import {z} from 'zod' export type ChatCompletionRequest = {model: string, messages: Array>, tools?: Array | undefined, max_completion_tokens?: number | undefined, max_tokens?: number | undefined, stream?: boolean | undefined, stream_options?: ({include_usage?: boolean | undefined}) | undefined, response_format?: Record | undefined, user?: string | undefined, agentlab?: ({schema_version: unknown, tool_calling?: boolean | undefined, vision?: boolean | undefined, structured_output?: boolean | undefined, minimum_context_tokens?: number | undefined}) | undefined} | {[key: string]: unknown}; export type CreateApiV1ChatCompletionsArgs = {'X-AgentLab-Routing'?: ('auto' | 'auto:cost' | 'auto:balanced' | 'auto:quality') | undefined, 'Idempotency-Key'?: string | undefined, body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, bearer?: string | undefined, fetch?: typeof fetch | undefined}; export const createApiV1ChatCompletionsResponse = z.record(z.string(), z.unknown()); 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 }; /** * OpenAI Chat Completions * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://api.agentlab.cresclab.com", fetch: fetchFn = fetch, bearer} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-AgentLab-Routing'] != null) headers.set("X-AgentLab-Routing", String(args['X-AgentLab-Routing'])) if (args['Idempotency-Key'] != null) headers.set("Idempotency-Key", String(args['Idempotency-Key'])) if (bearer !== undefined) headers.set('authorization', `Bearer ${bearer}`) const url = `${baseUrl.replace(/\/+$/, '')}/v1/chat/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(createApiV1ChatCompletionsResponse, await res.json()) };