// One JSON answer matching a schema, on either provider (release 27; the // stopgap's claude_api.chat_json and local_sweep.chat). // // Claude: a single tool `answer` carries the schema. Most models are forced to // call it. A strict model (no forced tool_choice) gets a STRICT tool with a // closed schema and tool_choice auto plus an instruction, and is re-asked once // if it answers without calling it. A non-strict model whose forced call is // refused (a 400 naming tool_choice) falls back to the strict way. // ollama: constrained decoding through `format`, retried once on a GPU fault or // an answer that is not JSON. A prompt over the cap is refused, never sent. import { extractJsonObject } from "../parseStdoutJson"; import { AnthropicClient, AnthropicError, isStrictModel, toolUsesOf, type ContentBlock, type MessagesResponse, } from "./anthropic"; import { anthropicConfigOf, ollamaConfigOf, providerOf, type LlmConfig } from "./config"; import { CallSlot, lazyKeyRedactor, recordModelCall } from "./callLog-server"; import type { Meter, Usage } from "./meter"; import { ollamaChat, OllamaError, PromptTooLargeError, promptEstimate } from "./ollama"; export const ANSWER_TOOL = "answer"; const ASK = "Answer by calling the `answer` tool."; const REASK = "Call the `answer` tool with your answer now."; export class StructuredAnswerError extends Error { constructor(message: string) { super(message); this.name = "StructuredAnswerError"; } } // Strict tool use: `additionalProperties: false` on every object and every // property required. export function closeSchema(schema: T): T { if (Array.isArray(schema)) return schema.map((s) => closeSchema(s)) as T; if (!schema || typeof schema !== "object") return schema; const out: Record = {}; for (const [k, v] of Object.entries(schema as Record)) out[k] = closeSchema(v); if (out.type === "object") { out.additionalProperties = false; out.required = Object.keys((out.properties as Record) ?? {}); } return out as T; } // An image the model reads with the question (release 30, the frame scan): // base64 bytes and their media type. Claude gets image blocks before the // text; ollama gets the user message's `images`. export type AnswerImage = { mediaType: "image/jpeg" | "image/png"; data: string }; type Opts = { llm: LlmConfig; model: string; system: string; user: string; schema: object; images?: AnswerImage[]; meter?: Meter; signal?: AbortSignal; maxTokens?: number; // The model log (./callLog.ts): the call's phase and label, and a slot the // caller says through what code did with the answer. call?: StructuredCallMeta; }; export type StructuredCallMeta = { phase?: string; label?: string; slot?: CallSlot }; // What one structured answer cost, summed over its attempts, and the text it // last sent (the model log's record). type Spent = { tokensIn: number; tokensOut: number; any: boolean; sent: string; redact?: (s: string) => string }; const spend = (s: Spent, u: Usage | undefined) => { if (!u) return; const n = (v: unknown) => (typeof v === "number" && Number.isFinite(v) ? v : 0); s.tokensIn += n(u.input_tokens) + n(u.cache_creation_input_tokens) + n(u.cache_read_input_tokens); s.tokensOut += n(u.output_tokens); s.any = true; }; export async function structuredAnswer(o: Opts): Promise { const route = providerOf(o.model); const spent: Spent = { tokensIn: 0, tokensOut: 0, any: false, sent: o.user, redact: lazyKeyRedactor(o.llm.anthropic) }; const t0 = Date.now(); const images = o.images?.length ? `\n\n[${o.images.length} image${o.images.length === 1 ? "" : "s"} sent with this prompt]` : ""; const record = (answer: unknown, error?: unknown) => recordModelCall( { ...(o.call?.phase ? { phase: o.call.phase } : {}), ...(o.call?.label ? { label: o.call.label } : {}), model: o.model, route, system: o.system, prompt: spent.sent + images, answer, seconds: (Date.now() - t0) / 1000, ...(spent.any ? { tokensIn: spent.tokensIn, tokensOut: spent.tokensOut } : {}), ...(error !== undefined ? { error: (error as Error)?.message ?? String(error) } : {}), ...(spent.redact ? { redact: spent.redact } : {}), }, o.call?.slot, ); try { const out = route === "api" ? await claudeAnswer(o, spent) : await localAnswer(o, spent); record(out); return out; } catch (err) { record(null, err); throw err; } } async function claudeAnswer(o: Opts, spent: Spent): Promise { const client = new AnthropicClient(anthropicConfigOf(o.llm, o.model)); const configured = spent.redact; spent.redact = (s) => client.redactText(configured ? configured(s) : s); const strict = isStrictModel(o.model); try { return await claudeTry(client, o, strict, spent); } catch (err) { if (!strict && err instanceof AnthropicError && err.status === 400 && /tool_choice/.test(err.message)) return claudeTry(client, o, true, spent); throw err; } } async function claudeTry(client: AnthropicClient, o: Opts, strict: boolean, spent: Spent): Promise { const tool = { name: ANSWER_TOOL, description: "Give the answer.", input_schema: strict ? closeSchema(o.schema) : o.schema, ...(strict ? { strict: true } : {}), }; const text = strict ? `${o.user}\n\n${ASK}` : o.user; spent.sent = text; let messages: { role: string; content: string | ContentBlock[] }[] = [ { role: "user", content: o.images?.length ? [ ...o.images.map((img) => ({ type: "image", source: { type: "base64", media_type: img.mediaType, data: img.data } })), { type: "text", text }, ] : text, }, ]; let res: MessagesResponse | undefined; for (let attempt = 0; attempt < (strict ? 2 : 1); attempt++) { res = await client.messages( { model: o.model, max_tokens: o.maxTokens ?? 4096, system: o.system, messages, tools: [tool], tool_choice: strict ? { type: "auto" } : { type: "tool", name: ANSWER_TOOL }, }, { meter: o.meter, signal: o.signal }, ); spend(spent, res.usage); const call = toolUsesOf(res).find((b) => b.name === ANSWER_TOOL); if (call && call.input && typeof call.input === "object") return call.input as T; // Append-only: the re-ask follows the answer as it came. messages = [...messages, { role: "assistant", content: res.content }, { role: "user", content: REASK }]; } throw new StructuredAnswerError(`${o.model}: no structured answer (stop_reason ${res?.stop_reason ?? "none"})`); } // What a local structuredAnswer's prompt is estimated at — the very request // localAnswer sends (its messages and its format), counted as ollamaChat // counts it against the cap (release 28 Q3: a caller fits its text first). export function structuredPromptEstimate(o: { system: string; user: string; schema: object; images?: AnswerImage[] }): number { return promptEstimate({ messages: [ { role: "system", content: o.system }, { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) }, ], format: o.schema, }); } async function localAnswer(o: Opts, spent: Spent): Promise { const cfg = ollamaConfigOf(o.llm, o.model); let last = ""; for (let attempt = 0; attempt < 2; attempt++) { let reply: Awaited>; try { reply = await ollamaChat(cfg, { model: o.model, messages: [ { role: "system", content: o.system }, { role: "user", content: o.user, ...(o.images?.length ? { images: o.images.map((i) => i.data) } : {}) }, ], format: o.schema, signal: o.signal, }); } catch (err) { if (err instanceof PromptTooLargeError || o.signal?.aborted) throw err; if (!(err instanceof OllamaError) || (err.status !== undefined && err.status < 500)) throw err; last = err.message; continue; } o.meter?.add(o.model, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); spend(spent, { input_tokens: reply.promptTokens, output_tokens: reply.evalTokens }); const content = reply.message.content ?? ""; const value = content.trim() ? extractJsonObject(content) : null; if (value !== null && typeof value === "object") return value as T; last = content.trim() ? "the answer is not JSON" : "an empty answer"; } throw new StructuredAnswerError(`${o.model}: no structured answer (${last})`); }