import {z} from 'zod' 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 GenerateRequest = {model: string, prompt?: string | undefined, suffix?: string | undefined, images?: Array | undefined, format?: (string | Record) | undefined, system?: string | undefined, stream?: boolean | undefined, think?: (boolean | 'high' | 'medium' | 'low' | 'max') | undefined, raw?: boolean | undefined, keep_alive?: (string | number) | undefined, options?: ModelOptions | undefined, logprobs?: boolean | undefined, top_logprobs?: number | undefined}; export type CreateApiApiGenerateArgs = {body: GenerateRequest}; export type CreateApiApiGenerateOptions = {baseUrl?: string | undefined, fetch?: typeof fetch | undefined}; 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 generateResponse = z.object({model: z.string().optional(), created_at: z.string().optional(), response: z.string().optional(), thinking: z.string().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 response * * POST /api/generate */ export const createApiApiGenerate = async (args: CreateApiApiGenerateArgs, options?: CreateApiApiGenerateOptions) => { 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/generate${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(generateResponse, await res.json()) };