import {z} from 'zod' export type GetApiV1ConsoleUsageApikeysStatsArgs = {scope?: string | undefined, startTime?: string | undefined, endTime?: string | undefined}; export type GetApiV1ConsoleUsageApikeysStatsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const usageV1APIKeyStatItem = z.object({apiKeyId: z.string().optional(), apiKeyName: z.string().optional(), billedMicros: z.string().optional(), completionTokens: z.string().optional(), failedCount: z.string().optional(), promptTokens: z.string().optional(), requestCount: z.string().optional(), successCount: z.string().optional(), teamId: z.string().optional(), totalTokens: z.string().optional()}); export const usageV1ListAPIKeyStatsReply = z.object({endTime: z.string().optional(), items: z.array(usageV1APIKeyStatItem).optional(), startTime: z.string().optional()}); export const validateResponse = async ( schema: { readonly '~standard': { readonly validate: (value: unknown) => ({ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }) | Promise<{ readonly value: Output; readonly issues?: undefined } | { readonly issues: ReadonlyArray<{ readonly message: string; readonly path?: ReadonlyArray | undefined }> }> } }, value: unknown ): Promise => { const result = await schema['~standard'].validate(value) if (result.issues !== undefined) { const detail = result.issues .map(({ message, path }) => path?.length ? `${path.map((segment) => String(typeof segment === 'object' ? segment.key : segment)).join('.')}: ${message}` : message ) .join('; ') throw new Error(`Response does not match the schema: ${detail}`, { cause: { issues: result.issues } }) } return result.value }; /** * ListAPIKeyStats 按 API Key 维度汇总计费/用量统计。 * * GET /v1/console/usage/apikeys/stats */ export const getApiV1ConsoleUsageApikeysStats = async (args: GetApiV1ConsoleUsageApikeysStatsArgs, options: GetApiV1ConsoleUsageApikeysStatsOptions) => { const {baseUrl, fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.scope != null) query.append("scope", String(args.scope)) if (args.startTime != null) query.append("startTime", String(args.startTime)) if (args.endTime != null) query.append("endTime", String(args.endTime)) const url = `${baseUrl.replace(/\/+$/, '')}/v1/console/usage/apikeys/stats${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "GET", headers}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(usageV1ListAPIKeyStatsReply, await res.json()) };