import {z} from 'zod' export type UsageRequest = {granularity: 'monthly' | 'yearly' | 'custom', date_start?: (string | null) | undefined, date_end?: (string | null) | undefined}; export type CreateApiLlmCostArgs = {cookie_name?: (string | null) | undefined, tenant_id?: number | undefined, body: UsageRequest}; export type CreateApiLlmCostOptions = {baseUrl?: string | undefined, APIKeyHeader?: string | undefined, fetch?: typeof fetch | undefined}; export const timeseriesPoint = z.object({date: z.string(), cost: z.number()}); export const timeseriesResponse = z.object({total_cost: z.number(), timeseries: z.record(z.string(), z.array(timeseriesPoint))}); 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 LLM cost metrics * * POST /llm/cost */ export const createApiLlmCost = async (args: CreateApiLlmCostArgs, options?: CreateApiLlmCostOptions) => { 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/cost${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(timeseriesResponse, await res.json()) };