import {z} from 'zod' export type ChatCompletionRequest = {model: string, messages: Array<{role: 'system' | 'user' | 'assistant' | 'tool', content: unknown, name?: string | undefined, tool_calls?: Array> | undefined, tool_call_id?: string | undefined}>, temperature?: number | undefined, top_p?: number | undefined, max_tokens?: number | undefined, max_completion_tokens?: number | undefined, stream?: boolean | undefined, stop: unknown, presence_penalty?: number | undefined, frequency_penalty?: number | undefined, user?: string | undefined, response_format?: Record | undefined, seed?: number | undefined, tools?: Array> | undefined, tool_choice: unknown}; export type CreateApiV1ChatCompletionsArgs = {'X-Provider-Key': string, traceparent?: string | undefined, body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const chatCompletionResponse = z.object({id: z.string(), object: z.literal("chat.completion"), created: z.number().int(), model: z.string(), choices: z.array(z.object({index: z.number().int().optional(), message: z.object({role: z.string().optional(), content: z.string().nullable().optional(), tool_calls: z.array(z.object({})).optional()}).optional(), finish_reason: z.enum(["stop", "length", "tool_calls", "content_filter", "null"]).nullable().optional()})), usage: z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}).optional(), system_fingerprint: 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 }; /** * OpenAI-compatible chat completions with policy enforcement * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "https://agent.getaxonflow.com", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Provider-Key'] != null) headers.set("X-Provider-Key", String(args['X-Provider-Key'])) if (args.traceparent != null) headers.set("traceparent", String(args.traceparent)) 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(chatCompletionResponse, await res.json()) };