import {z} from 'zod' export type UsageRequest = {granularity: 'monthly' | 'yearly' | 'custom', date_start?: (string | null) | undefined, date_end?: (string | null) | undefined}; export type CreateApiLlmTokensArgs = {cookie_name?: (string | null) | undefined, tenant_id?: number | undefined, body: UsageRequest}; export type CreateApiLlmTokensOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const tokensPerModel = z.object({llm_model: z.string(), duration: z.string(), total_tokens_count: z.number(), prompt_token_count: z.number(), completion_token_count: z.number(), total_requests: z.number()}); export const tokenTimeseriesPoint = z.object({date: z.string(), value: z.number()}); export const tokenTimeseriesPerModel = z.object({llm_model: z.string(), timeseries: z.record(z.string(), z.array(tokenTimeseriesPoint))}); export const tokensTimeseriesResponse = z.object({total_prompt_tokens: z.number(), total_completion_tokens: z.number(), total_requests: z.number(), total_tokens: z.number(), tokens_per_model: z.array(tokensPerModel), timeseries_per_model: z.array(tokenTimeseriesPerModel)}); 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 }; /** * Get token usage metrics * * POST /llm/tokens */ export const createApiLlmTokens = async (args: CreateApiLlmTokensArgs, options?: CreateApiLlmTokensOptions) => { const {baseUrl = "https://api.your-domain.com", fetch: fetchFn = fetch, APIKeyHeader} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args.cookie_name != null) query.append("cookie_name", String(args.cookie_name)) if (args.tenant_id != null) query.append("tenant_id", String(args.tenant_id)) if (APIKeyHeader !== undefined) headers.set("X-API-KEY", APIKeyHeader) const url = `${baseUrl.replace(/\/+$/, '')}/llm/tokens${query.size > 0 ? `?${query}` : ''}` const res = await fetchFn(url, {method: "POST", headers, body: JSON.stringify(args.body)}) if (!res.ok) throw new Error(`Request failed with status ${res.status}`, {cause: {status: res.status, body: await res.text()}}) return validateResponse(tokensTimeseriesResponse, await res.json()) };