import { test } from "node:test"; import assert from "node:assert/strict"; import { startFakeAnthropic, textTurn, thinkingBlock, toolUseBlock, turn, textBlock, } from "../../testing/llm/fakeAnthropic.mjs"; import { faultReply, jsonReply, reply, startFakeOllama } from "../../testing/llm/fakeOllama.mjs"; import { closeSchema, structuredAnswer, structuredPromptEstimate, StructuredAnswerError } from "./structured"; import { IMAGE_TOKEN_ESTIMATE, PromptTooLargeError, promptEstimate } from "./ollama"; import { execFileSync } from "node:child_process"; import { Meter } from "./meter"; import { providerOf } from "./config"; const schema = { type: "object", properties: { terms: { type: "array", items: { type: "string" } }, note: { type: "object", properties: { why: { type: "string" } } } }, required: ["terms"], }; test("providerOf: Claude → api, anything else → local", () => { assert.equal(providerOf("claude-sonnet-5-5"), "api"); assert.equal(providerOf("qwen3:8b"), "local"); }); test("closeSchema: additionalProperties false and every property required, nested", () => { const c = closeSchema(schema) as any; assert.equal(c.additionalProperties, false); assert.deepEqual(c.required, ["terms", "note"]); assert.equal(c.properties.note.additionalProperties, false); assert.deepEqual(c.properties.note.required, ["why"]); assert.equal((schema as any).additionalProperties, undefined); // not mutated }); test("Claude, a non-strict model: the answer tool forced", async () => { const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["oven"] })])] }); try { const meter = new Meter(); const out = await structuredAnswer<{ terms: string[] }>({ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, model: "claude-haiku-4-5", system: "Plan searches.", user: "Ovens?", schema, meter, }); assert.deepEqual(out, { terms: ["oven"] }); const body = api.requests[0]; assert.deepEqual(body.tool_choice, { type: "tool", name: "answer" }); assert.equal(body.tools[0].strict, undefined); assert.equal("temperature" in body, false); assert.ok(meter.usd > 0); } finally { await api.close(); } }); test("Claude, Sonnet 5.5: a strict tool with tool_choice auto; one re-ask, append-only after a thinking block", async () => { const api = await startFakeAnthropic({ turns: [ turn([thinkingBlock("hmm"), textBlock("I think ovens.")]), turn([toolUseBlock("answer", { terms: ["oven"], note: { why: "asked" } })]), ], }); try { const out = await structuredAnswer({ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, model: "claude-sonnet-5-5", system: "Plan searches.", user: "Ovens?", schema, }); assert.deepEqual(out, { terms: ["oven"], note: { why: "asked" } }); const [first, second] = api.requests; assert.deepEqual(first.tool_choice, { type: "auto" }); assert.equal(first.tools[0].strict, true); assert.equal(first.tools[0].input_schema.additionalProperties, false); assert.deepEqual(first.thinking, { type: "between_tools" }); assert.match(first.messages[0].content, /calling the `answer` tool/); // The re-ask appends the answer as it came (the fake checks the signature). assert.equal(second.messages.length, 3); assert.equal(second.messages[1].content[0].type, "thinking"); assert.match(second.messages[2].content, /Call the `answer` tool/); } finally { await api.close(); } }); test("Claude, Sonnet 5.5: no answer after the re-ask is an error", async () => { const api = await startFakeAnthropic({ turns: [textTurn("no"), textTurn("still no")] }); try { await assert.rejects( structuredAnswer({ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, model: "claude-sonnet-5-5", system: "s", user: "u", schema, }), StructuredAnswerError, ); assert.equal(api.requests.length, 2); } finally { await api.close(); } }); test("Claude: a model that refuses the forced tool_choice falls back to the strict way", async () => { const api = await startFakeAnthropic({ strictModels: ["claude-opus-5"], turns: [turn([toolUseBlock("answer", { terms: ["tile"] })])], }); try { const out = await structuredAnswer({ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key }, sleep: async () => {} } }, model: "claude-opus-5", system: "s", user: "u", schema, }); assert.deepEqual(out, { terms: ["tile"] }); assert.equal(api.requests.length, 2); assert.deepEqual(api.requests[1].tool_choice, { type: "auto" }); } finally { await api.close(); } }); test("ollama: format-constrained JSON; a GPU fault retried once; the meter counts tokens at $0", async () => { const ol = await startFakeOllama({ turns: [faultReply(), jsonReply({ terms: ["oven"] })] }); try { const meter = new Meter(); const out = await structuredAnswer({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen3:8b", system: "s", user: "u", schema, meter, }); assert.deepEqual(out, { terms: ["oven"] }); assert.equal(ol.requests.length, 2); assert.deepEqual(ol.requests[1].format, schema); assert.equal(ol.requests[1].think, false); assert.equal(meter.usd, 0); assert.equal(meter.summary().byModel["qwen3:8b"].calls, 1); } finally { await ol.close(); } }); test("ollama: an answer that is not JSON twice is an error; an oversized prompt is never sent", async () => { const ol = await startFakeOllama({ turns: [reply("prose"), reply("more prose")] }); try { const llm = { ollama: { baseUrl: ol.url } }; await assert.rejects(structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "u", schema }), /not JSON/); await assert.rejects( structuredAnswer({ llm, model: "qwen3:8b", system: "s", user: "w ".repeat(20_000), schema }), PromptTooLargeError, ); assert.equal(ol.requests.length, 2); } finally { await ol.close(); } }); test("a provider without its config is a clear error", async () => { await assert.rejects(structuredAnswer({ llm: {}, model: "qwen3:8b", system: "s", user: "u", schema }), /no ollama URL/); await assert.rejects(structuredAnswer({ llm: {}, model: "claude-sonnet-5", system: "s", user: "u", schema }), /no API config/); }); // ─── Images (release 30, the frame scan) ─── const tinyJpeg = () => execFileSync("ffmpeg", ["-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", "color=c=blue:s=64x36:d=1", "-frames:v", "1", "-c:v", "mjpeg", "-f", "image2pipe", "pipe:1"]).toString("base64"); test("Claude with images: image blocks before the text, in the one user turn", async () => { const api = await startFakeAnthropic({ turns: [turn([toolUseBlock("answer", { terms: ["chips"] })])] }); try { const data = tinyJpeg(); const out = await structuredAnswer<{ terms: string[] }>({ llm: { anthropic: { baseUrl: api.url, env: { ANTHROPIC_API_KEY: api.key } } }, model: "claude-haiku-4-5", system: "Read the frames.", user: "Two frames.", schema, images: [ { mediaType: "image/jpeg", data }, { mediaType: "image/jpeg", data }, ], }); assert.deepEqual(out, { terms: ["chips"] }); const content = api.requests[0].messages[0].content; assert.deepEqual(content.map((b: { type: string }) => b.type), ["image", "image", "text"]); assert.equal(content[0].source.media_type, "image/jpeg"); assert.equal(content[2].text, "Two frames."); } finally { await api.close(); } }); test("ollama with images: the user message's images, counted at a fixed cost in the estimate", async () => { const ol = await startFakeOllama({ models: ["qwen2.5vl:7b"], turns: [jsonReply({ terms: ["stack"] })] }); try { const data = tinyJpeg(); const out = await structuredAnswer<{ terms: string[] }>({ llm: { ollama: { baseUrl: ol.url } }, model: "qwen2.5vl:7b", system: "Read the frame.", user: "One frame.", schema, images: [{ mediaType: "image/jpeg", data }], }); assert.deepEqual(out, { terms: ["stack"] }); assert.deepEqual(ol.requests[0].messages[1].images, [data]); const est = structuredPromptEstimate({ system: "s", user: "u", schema, images: [{ mediaType: "image/jpeg", data }] }); assert.equal(est, structuredPromptEstimate({ system: "s", user: "u", schema }) + IMAGE_TOKEN_ESTIMATE); // The base64 itself is never counted as text. assert.ok(promptEstimate({ messages: [{ role: "user", content: "u", images: ["A".repeat(100_000)] }] }) < 2000); } finally { await ol.close(); } });