import {z} from 'zod' export type GetApiApiopsProjectsProjectNameApiProxiesApiProxyNameUsageArgs = {projectName: string, apiProxyName: string, from?: string | undefined, to?: string | undefined, model?: string | undefined, environmentName?: string | undefined}; export type GetApiApiopsProjectsProjectNameApiProxiesApiProxyNameUsageOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const scope = z.object({type: z.enum(["ORGANIZATION", "CONSUMER", "APPLICATION", "API_CLIENT", "API_PROXY"]).optional(), key: z.string().optional(), name: z.string().optional()}); export const period = z.object({from: z.string().optional(), to: z.string().optional(), effectiveFrom: z.string().optional(), effectiveTo: z.string().optional(), timeZone: z.string().optional()}); export const filters = z.object({model: z.string().optional(), environmentName: z.string().optional(), environmentApplied: z.boolean().optional()}); export const totals = z.object({tokenInput: z.number().int().optional(), tokenOutput: z.number().int().optional(), tokenCached: z.number().int().optional(), tokenTotal: z.number().int().optional(), costUsd: z.number().optional(), requests: z.number().int().optional(), failedRequests: z.number().int().optional()}); export const modelRow = z.object({provider: z.string().optional(), model: z.string().optional(), tokenInput: z.number().int().optional(), tokenOutput: z.number().int().optional(), tokenCached: z.number().int().optional(), tokenTotal: z.number().int().optional(), costUsd: z.number().optional(), requests: z.number().int().optional()}); export const ai = z.object({dataSource: z.enum(["ROLLUP_DAILY", "TRAFFIC_LOG"]).optional(), granularity: z.enum(["DAY", "EXACT"]).optional(), freshness: z.enum(["hourly", "near-real-time"]).optional(), totals: totals.optional(), byModel: z.array(modelRow).optional()}); export const traffic = z.object({dataSource: z.string().optional(), totalRequests: z.number().int().optional(), successfulRequests: z.number().int().optional(), blockedRequests: z.number().int().optional(), erroredRequests: z.number().int().optional(), successRatePercent: z.number().optional(), avgTimeMs: z.number().optional()}); export const childRow = z.object({key: z.string().optional(), name: z.string().optional(), tokenTotal: z.number().int().optional(), costUsd: z.number().optional(), requests: z.number().int().optional(), usagePercent: z.number().optional()}); export const children = z.object({type: z.enum(["CONSUMER", "API_CLIENT"]).optional(), items: z.array(childRow).optional(), total: z.number().int().optional(), truncated: z.boolean().optional()}); export const dimension = z.object({type: z.enum(["MODEL", "PROVIDER"]).optional(), ref: z.string().optional()}); export const budget = z.object({family: z.enum(["AI_TOKEN", "AI_COST", "REQUEST_QUOTA"]).optional(), unit: z.enum(["TOKENS", "USD", "REQUESTS"]).optional(), window: z.enum(["ONE_HOUR", "ONE_DAY", "ONE_MONTH"]).optional(), dimension: dimension.optional(), limit: z.number().optional(), consumed: z.number().optional(), remaining: z.number().optional(), usagePercent: z.number().optional(), windowStartsAt: z.string().optional(), resetsAt: z.string().optional(), assignmentKey: z.string().optional(), planKey: z.string().optional(), source: z.enum(["TYPED", "LEGACY_BUDGET", "POLICY"]).optional()}); export const apiOpsUsageReportDTO = z.object({scope: scope.optional(), period: period.optional(), filters: filters.optional(), ai: ai.optional(), aiLicensed: z.boolean().optional(), traffic: traffic.optional(), children: children.optional(), budgets: z.array(budget).optional(), budgetsAsOf: z.string().optional(), partial: z.boolean().optional(), unavailableEnvironments: z.array(z.string()).optional(), notes: z.array(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 }; /** * Usage of one API proxy * * GET /apiops/projects/{projectName}/api-proxies/{apiProxyName}/usage */ export const getApiApiopsProjectsProjectNameApiProxiesApiProxyNameUsage = async (args: GetApiApiopsProjectsProjectNameApiProxiesApiProxyNameUsageArgs, options?: GetApiApiopsProjectsProjectNameApiProxiesApiProxyNameUsageOptions) => { const {baseUrl = "http://167.86.118.166:32080", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('accept', "application/json") if (args.from != null) query.append("from", String(args.from)) if (args.to != null) query.append("to", String(args.to)) if (args.model != null) query.append("model", String(args.model)) if (args.environmentName != null) query.append("environmentName", String(args.environmentName)) const url = `${baseUrl.replace(/\/+$/, '')}/apiops/projects/${encodeURIComponent(String(args.projectName))}/api-proxies/${encodeURIComponent(String(args.apiProxyName))}/usage${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(apiOpsUsageReportDTO, await res.json()) };