import {z} from 'zod' export type JsonNode = Record; export type FunctionCallView = {name?: string | undefined, arguments?: string | undefined}; export type ToolCallView = {id?: string | undefined, type?: string | undefined, function?: FunctionCallView | undefined}; export type MessageView = {role?: string | undefined, content?: JsonNode | undefined, tool_calls?: Array | undefined, tool_call_id?: string | undefined, name?: string | undefined}; export type FunctionDefView = {name?: string | undefined, description?: string | undefined, parameters?: JsonNode | undefined}; export type ToolView = {type?: string | undefined, function?: FunctionDefView | undefined}; export type StreamOptionsView = {include_usage?: boolean | undefined}; export type ChatCompletionRequestView = {model?: string | undefined, messages?: Array | undefined, tools?: Array | undefined, tool_choice?: JsonNode | undefined, response_format?: JsonNode | undefined, stream?: boolean | undefined, stream_options?: StreamOptionsView | undefined, temperature?: number | undefined, max_tokens?: number | undefined, top_p?: number | undefined, stop?: Array | undefined, n?: number | undefined}; export type CreateApiApiInferenceV1ChatCompletionsArgs = {siteId?: string | undefined, body: ChatCompletionRequestView}; export type CreateApiApiInferenceV1ChatCompletionsOptions = {baseUrl: string, fetch?: typeof fetch | undefined}; export const jsonNode = z.object({}); export const functionCallView = z.object({name: z.string().optional(), arguments: z.string().optional()}); export const toolCallView = z.object({id: z.string().optional(), type: z.string().optional(), function: functionCallView.optional()}); export const messageView = z.object({role: z.string().optional(), content: jsonNode.optional(), tool_calls: z.array(toolCallView).optional(), tool_call_id: z.string().optional(), name: z.string().optional()}); export const choiceView = z.object({index: z.number().int().optional(), message: messageView.optional(), finish_reason: z.string().optional()}); export const usageView = z.object({prompt_tokens: z.number().int().optional(), total_tokens: z.number().int().optional()}); export const chatCompletionView = z.object({id: z.string().optional(), object: z.string().optional(), created: z.number().int().optional(), model: z.string().optional(), choices: z.array(choiceView).optional(), usage: usageView.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 /api/inference/v1/chat/completions */ export const createApiApiInferenceV1ChatCompletions = async (args: CreateApiApiInferenceV1ChatCompletionsArgs, options: CreateApiApiInferenceV1ChatCompletionsOptions) => { const {baseUrl, 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.siteId != null) query.append("siteId", String(args.siteId)) const url = `${baseUrl.replace(/\/+$/, '')}/api/inference/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(chatCompletionView, await res.json()) };