import {z} from 'zod' export type ToolCall = {function?: ({name: string, description?: string | undefined, arguments?: Record | undefined}) | undefined}; export type ChatMessage = {role: 'system' | 'user' | 'assistant' | 'tool', content: string, images?: Array | undefined, tool_calls?: Array | undefined}; export type ToolDefinition = {type: 'function', function: {name: string, description?: string | undefined, parameters: Record}}; export type ModelOptions = {seed?: number | undefined, temperature?: number | undefined, top_k?: number | undefined, top_p?: number | undefined, min_p?: number | undefined, stop?: (string | Array) | undefined, num_ctx?: number | undefined, num_predict?: number | undefined} | {[key: string]: unknown}; export type ChatRequest = {model: string, messages: Array, tools?: Array | undefined, format?: ('json' | Record) | undefined, options?: ModelOptions | undefined, stream?: boolean | undefined, think?: (boolean | 'high' | 'medium' | 'low' | 'max') | undefined, keep_alive?: (string | number) | undefined, logprobs?: boolean | undefined, top_logprobs?: number | undefined}; export type CreateApiApiChatArgs = {body: ChatRequest}; export type CreateApiApiChatOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; export const toolCall = z.object({function: z.object({name: z.string(), description: z.string().optional(), arguments: z.object({}).optional()}).optional()}); export const tokenLogprob = z.object({token: z.string().optional(), logprob: z.number().optional(), bytes: z.array(z.number().int()).optional()}); export const logprob = z.object({token: z.string().optional(), logprob: z.number().optional(), bytes: z.array(z.number().int()).optional(), top_logprobs: z.array(tokenLogprob).optional()}); export const chatResponse = z.object({model: z.string().optional(), created_at: z.string().optional(), message: z.object({role: z.literal("assistant").optional(), content: z.string().optional(), thinking: z.string().optional(), tool_calls: z.array(toolCall).optional(), images: z.array(z.string()).optional()}).optional(), done: z.boolean().optional(), done_reason: z.string().optional(), total_duration: z.number().int().optional(), load_duration: z.number().int().optional(), prompt_eval_count: z.number().int().optional(), prompt_eval_duration: z.number().int().optional(), eval_count: z.number().int().optional(), eval_duration: z.number().int().optional(), logprobs: z.array(logprob).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 }; /** * Generate a chat message * * POST /api/chat */ export const createApiApiChat = async (args: CreateApiApiChatArgs, options?: CreateApiApiChatOptions) => { const {baseUrl = "http://localhost:11434", fetch: fetchFn = fetch} = options ?? {} const query = new URLSearchParams() const headers = new Headers() headers.set('content-type', "application/json") headers.set('accept', "application/json") const url = `${baseUrl.replace(/\/+$/, '')}/api/chat${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(chatResponse, await res.json()) };