import {z} from 'zod' export type AICompletionMetadataResource = {transactionId: string, traceId?: string | undefined, model: string, responseQualityScore?: number | undefined, modelSource?: string | undefined, inputTokenCount: number, outputTokenCount: number, reasoningTokenCount?: number | undefined, cacheCreationTokenCount?: number | undefined, cacheReadTokenCount?: number | undefined, totalTokenCount: number, stopReason: 'END' | 'END_SEQUENCE' | 'TIMEOUT' | 'TOKEN_LIMIT' | 'COST_LIMIT' | 'COMPLETION_LIMIT' | 'ERROR', inputTokenCost?: number | undefined, outputTokenCost?: number | undefined, totalCost?: number | undefined, costType: 'AI', requestTime: string, completionStartTime: string, timeToFirstToken?: number | undefined, isStreamed: boolean, responseTime: string, requestDuration: number, mediationLatency?: number | undefined, provider: string, taskType?: string | undefined, subscriberCredentialName?: string | undefined, subscriberCredential?: string | undefined, subscriberEmail?: string | undefined, subscriberId?: string | undefined, organizationId?: string | undefined, subscriptionId?: string | undefined, productId?: string | undefined, agent?: string | undefined, operationType?: ('CHAT' | 'GENERATE' | 'EMBED' | 'CLASSIFY' | 'SUMMARIZE' | 'TRANSLATE' | 'OTHER') | undefined, systemFingerprint?: string | undefined, temperature?: number | undefined, errorReason?: string | undefined}; export type CreateApiV2AiCompletionsArgs = {body: AICompletionMetadataResource}; export type CreateApiV2AiCompletionsOptions = {baseUrl?: string | undefined, xApiKey?: string | undefined, fetch?: typeof fetch | undefined}; export const link = z.object({href: z.string().optional(), hreflang: z.string().optional(), title: z.string().optional(), type: z.string().optional(), deprecation: z.string().optional(), profile: z.string().optional(), name: z.string().optional(), templated: z.boolean().optional()}); export const links = z.record(z.string(), link); export const meteringResponseResource = z.object({object: z.string(), label: z.string(), created: z.string().optional(), updated: z.string().optional(), id: z.string(), signature: z.string(), _links: links.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 }; /** * Meter an LLM completion * * POST /v2/ai/completions */ export const createApiV2AiCompletions = async (args: CreateApiV2AiCompletionsArgs, options?: CreateApiV2AiCompletionsOptions) => { const {baseUrl = "https://api.revenium.io/meter", fetch: fetchFn = fetch, xApiKey} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (xApiKey !== undefined) headers.set("x-api-key", xApiKey) const url = `${baseUrl.replace(/\/+$/, '')}/v2/ai/completions${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(meteringResponseResource, await res.json()) };