import {z} from 'zod' export type ChatMessage = {role: string, content?: (string | Array<{[key: string]: unknown}> | null) | undefined, name?: (string | null) | undefined, tool_calls?: (Array | null) | undefined, tool_call_id?: (string | null) | undefined, reasoning_content?: (string | null) | undefined}; export type ChatCompletionRequest = {model: string, messages: Array, system?: (string | Array<{[key: string]: unknown}> | null) | undefined, temperature?: (number | null) | undefined, max_tokens?: (number | null) | undefined, response_format?: ({[key: string]: unknown} | null) | undefined, stop?: (Array | string | null) | undefined, stream?: boolean | undefined, extra_headers?: ({[key: string]: string} | null) | undefined, extra_body?: ({[key: string]: unknown} | null) | undefined, reasoning?: ({[key: string]: unknown} | null) | undefined, store?: boolean | undefined, metadata?: ({[key: string]: unknown} | null) | undefined, top_p?: (number | null) | undefined, n?: (number | null) | undefined, presence_penalty?: (number | null) | undefined, frequency_penalty?: (number | null) | undefined, logit_bias?: ({[key: string]: unknown} | null) | undefined, user?: (string | null) | undefined, seed?: (number | null) | undefined, tools?: (Array | null) | undefined, tool_choice?: (string | {[key: string]: unknown} | null) | undefined, schema?: (Array | {[key: string]: unknown} | null) | undefined, task_type?: (string | null) | undefined, include_confidence?: boolean | undefined, include_spans?: boolean | undefined, threshold?: number | undefined}; export type CreateApiV1ChatCompletionsArgs = {body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl: string, ApiKeyAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const chatCompletionChoice = z.object({index: z.number().int().optional(), message: z.record(z.string(), z.unknown()).optional(), finish_reason: z.string().nullable().optional()}); export const promptTokensDetails = z.object({cached_tokens: z.number().int().optional(), cache_write_tokens: z.number().int().optional()}); export const chatCompletionUsage = z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional(), prompt_tokens_details: promptTokensDetails.nullable().optional()}); export const fastinoExtension = z.object({inference_id: z.string().nullable().optional()}); export const chatCompletionResponse = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string(), choices: z.array(chatCompletionChoice), usage: chatCompletionUsage, x_fastino: fastinoExtension.nullable().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 }; /** * Chat Completions * * POST /v1/chat/completions * * Also accepts auth: BearerAuth */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options: CreateApiV1ChatCompletionsOptions) => { const {baseUrl, fetch: fetchFn = fetch, ApiKeyAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (ApiKeyAuth !== undefined) headers.set("X-API-Key", ApiKeyAuth) 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()) };