import {z} from 'zod' export type ContentPart = {type: 'text' | 'image_url', text?: string | undefined, image_url?: ({url: string, detail?: ('auto' | 'low' | 'high') | undefined}) | undefined}; export type ToolCallReference = {index?: number | undefined, id?: string | undefined, type?: 'function' | undefined, function: {name: string, arguments?: string | undefined}}; export type ChatCompletionMessage = {role: 'system' | 'user' | 'assistant' | 'tool' | 'developer', content?: (string | Array) | undefined, name?: string | undefined, tool_call_id?: string | undefined, tool_calls?: Array | undefined}; export type ChatCompletionRequest = {model?: string | undefined, messages: Array, stream?: boolean | undefined, stream_options?: ({include_usage?: boolean | undefined}) | undefined, temperature?: number | undefined, top_p?: number | undefined, max_tokens?: number | undefined, stop?: (string | Array) | undefined}; export type CreateApiV1ChatCompletionsArgs = {'X-Conversation-Id'?: string | undefined, body: ChatCompletionRequest}; export type CreateApiV1ChatCompletionsOptions = {baseUrl?: string | undefined, bearerAuth?: string | undefined, fetch?: typeof fetch | undefined}; export const contentPart = z.object({type: z.enum(["text", "image_url"]), text: z.string().optional(), image_url: z.object({url: z.string(), detail: z.enum(["auto", "low", "high"]).optional()}).optional()}); export const toolCallReference = z.object({index: z.number().int().optional(), id: z.string().optional(), type: z.literal("function").optional(), function: z.object({name: z.string(), arguments: z.string().optional()})}); export const chatCompletionMessage = z.object({role: z.enum(["system", "user", "assistant", "tool", "developer"]), content: z.union([z.string(), z.array(contentPart)]).optional(), name: z.string().optional(), tool_call_id: z.string().optional(), tool_calls: z.array(toolCallReference).optional()}); export const chatCompletionChoice = z.object({index: z.number().int(), message: chatCompletionMessage, finish_reason: z.enum(["stop", "tool_calls", "error", "length"]).optional()}); export const chatCompletionUsage = z.object({prompt_tokens: z.number().int().optional(), completion_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}); export const chatCompletionResponse = z.object({id: z.string(), object: z.literal("chat.completion"), created: z.number().int(), model: z.string(), choices: z.array(chatCompletionChoice), usage: chatCompletionUsage.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 }; /** * Create a chat completion. * * POST /v1/chat/completions */ export const createApiV1ChatCompletions = async (args: CreateApiV1ChatCompletionsArgs, options?: CreateApiV1ChatCompletionsOptions) => { const {baseUrl = "http://127.0.0.1:8083", fetch: fetchFn = fetch, bearerAuth} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") if (args['X-Conversation-Id'] != null) headers.set("X-Conversation-Id", String(args['X-Conversation-Id'])) if (bearerAuth !== undefined) headers.set('authorization', `Bearer ${bearerAuth}`) 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()) };