repositories / pi-ext
pi-ext
bugabingas pi extensions
owned by admin
extensions/quota/src/providers/zai.ts
Rawimport { fetchJson } from "../http.ts";
import {
amount,
epoch,
finite,
label,
list,
object,
percent,
windowBucket,
} from "../parse.ts";
import type { ProviderQuota, QuotaBucket, QuotaProvider } from "../types.ts";
export function parseZai(data: unknown, cn = false): ProviderQuota {
const d = object(object(data)["data"]);
const buckets: QuotaBucket[] = [];
const occurrences = new Map<string, number>();
for (const raw of list(d["limits"])) {
const limit = object(raw);
const unit = finite(limit["unit"]);
const type = label(limit["type"]) ?? "quota";
const base = `${type}:${unit ?? "unknown"}:${finite(limit["number"]) ?? 1}`;
const occurrence = occurrences.get(base) ?? 0;
occurrences.set(base, occurrence + 1);
const count = finite(limit["number"]);
const n = count !== undefined && count > 0 ? count : undefined;
const duration =
unit === 3
? (n ?? 5) * 3600000
: unit === 6
? (n ?? 1) * 604800000
: undefined;
const title =
unit === 3
? `${n ?? 5}h`
: unit === 6
? n === undefined || n === 1
? "Weekly"
: `${n} weeks`
: unit === 5
? n === undefined || n === 1
? "Monthly"
: `${n} months`
: `Quota ${unit ?? "unknown"}`;
const value = amount(
type === "CREDIT_LIMIT" ? "credits" : "unknown",
finite(limit["currentValue"]),
finite(limit["usage"]),
finite(limit["remaining"]),
);
const reported = finite(limit["percentage"]);
if (value.state === "measured" && reported !== undefined)
value.usedPercent = Math.min(100, Math.max(0, reported));
const scope =
type === "CREDIT_LIMIT" ? undefined : type.replaceAll("_", " ");
buckets.push(
windowBucket(
`${base}:${occurrence}`,
title,
value.state === "unknown" ? percent(reported) : value,
duration,
epoch(limit["nextResetTime"]),
scope,
),
);
}
return {
provider: cn ? "zai-coding-cn" : "zai",
name: cn ? "Zai CN" : "Zai",
buckets,
observedAt: Date.now(),
};
}
function provider(cn: boolean): QuotaProvider {
return {
name: cn ? "Zai CN" : "Zai",
async fetch(key) {
const data = await fetchJson(
`https://${cn ? "open.bigmodel.cn" : "api.z.ai"}/api/monitor/usage/quota/limit`,
{ headers: { Authorization: key, "Content-Type": "application/json" } },
);
if (object(data)["success"] !== true)
throw new Error("Zai quota unavailable");
return parseZai(data, cn);
},
};
}
export const zai: QuotaProvider = provider(false);
export const zaiCn: QuotaProvider = provider(true);