// A fake ollama for the generation tests (release 27): `/api/chat` with tools // or a `format` schema, `/api/tags`, `/api/ps`, and the unload call // (`keep_alive: 0`). No test talks to a real ollama or touches the GPU. // // const ol = await startFakeOllama({ turns: [jsonReply({ terms: ["oven"] })] }); // … point the client at ol.url … // ol.requests every /api/chat body, in order // ol.unloads the models unloaded with keep_alive 0 // await ol.close() // // What it enforces, because the GPU does (Q0, 2026-10-11): a request over the // prompt cap (8k tokens, estimated at 4 chars a token) or with `options.num_ctx` // over 12k is refused with a 400 "fake: …", so a client that would hang the // card fails its test instead. `stream: true` is refused: the clients here read // one JSON answer. A scripted `faultReply()` answers `done: false` — what a GPU // fault looks like — which a client must read as a failure, not an answer. // A message's `images` (release 30) must be base64 of an image; each counts // IMAGE_TOKENS against the cap. // // A scripted turn is a reply (helpers below) or a function (body, ctx) → reply. // When the script runs out the server answers 500 "fake: script exhausted". import http from "node:http"; import { imageSize } from "./fakeAnthropic.mjs"; export const PROMPT_CAP_TOKENS = 8192; export const NUM_CTX_CAP = 12288; const tok = (v) => Math.ceil(JSON.stringify(v ?? "").length / 4); // A vision model's image (release 30): counted at a fixed cost, not its base64. export const IMAGE_TOKENS = 1200; // Every message's `images`, decoded: {bytes, width, height}. export function imagesOf(body) { const out = []; for (const m of Array.isArray(body?.messages) ? body.messages : []) for (const d of Array.isArray(m.images) ? m.images : []) { const bytes = Buffer.from(String(d), "base64"); out.push({ bytes, ...(imageSize(bytes) ?? { width: 0, height: 0 }) }); } return out; } // What ollama refuses: an `images` entry that is not base64 of an image. export function imageProblem(body) { for (const [i, m] of (Array.isArray(body?.messages) ? body.messages : []).entries()) { if (m.images === undefined) continue; if (!Array.isArray(m.images)) return `messages.${i}.images: not a list`; for (const d of m.images) { if (typeof d !== "string" || !d || /[^A-Za-z0-9+/=]/.test(d)) return `messages.${i}.images: not base64`; if (!imageSize(Buffer.from(d, "base64"))) return `messages.${i}.images: not an image`; } } return null; } const promptTokensOf = (body) => { let images = 0; const messages = (body.messages ?? []).map((m) => { if (!Array.isArray(m?.images)) return m; images += m.images.length; const { images: _drop, ...rest } = m; return rest; }); return tok([messages, body.tools ?? null, body.format ?? null]) + images * IMAGE_TOKENS; }; export const reply = (content, extra = {}) => ({ message: { role: "assistant", content }, done: true, ...extra }); // A `format`-schema answer: the content is the JSON text. export const jsonReply = (value) => reply(JSON.stringify(value)); // Tool calls, as ollama returns them (arguments an object, not a string). export const toolCallsReply = (calls, content = "") => ({ message: { role: "assistant", content, tool_calls: calls.map((c) => ({ function: { name: c.name, arguments: c.arguments ?? {} } })), }, done: true, }); export const faultReply = () => ({ message: { role: "assistant", content: "" }, done: false }); export const errorReply = (status, error) => ({ __error: { status, error } }); export async function startFakeOllama(opts = {}) { const models = opts.models ?? ["qwen3:8b", "qwen2.5:7b"]; const promptCap = opts.promptCapTokens ?? PROMPT_CAP_TOKENS; const numCtxCap = opts.numCtxCap ?? NUM_CTX_CAP; const script = [...(opts.turns ?? [])]; const requests = []; const unloads = []; const shows = []; const loaded = new Set(); const send = (res, status, payload) => { res.writeHead(status, { "content-type": "application/json" }); res.end(JSON.stringify(payload)); }; const server = http.createServer((req, res) => { let raw = ""; req.on("data", (c) => (raw += c)); req.on("end", async () => { if (req.method === "GET" && req.url === "/api/tags") return send(res, 200, { models: models.map((name) => ({ name, model: name })) }); if (req.method === "GET" && req.url === "/api/ps") return send(res, 200, { models: [...loaded].map((name) => ({ name, model: name })) }); // /api/show (what local only asks before a model's first prompt): a // model in `opts.remote` answers as ollama's cloud models do, with a // remote_host. Asked, never counted in `requests`. if (req.method === "POST" && req.url === "/api/show") { let name = ""; try { name = JSON.parse(raw).model ?? ""; } catch { // falls through to not found } shows.push(name); if (!models.includes(name)) return send(res, 404, { error: `model "${name}" not found` }); const remote = (opts.remote ?? []).includes(name); return send(res, 200, { details: { format: "gguf", family: "qwen2" }, ...(remote ? { remote_host: "https://ollama.com:443", remote_model: name } : {}) }); } if (req.method !== "POST" || (req.url !== "/api/chat" && req.url !== "/api/generate")) return send(res, 404, { error: `fake: no route ${req.method} ${req.url}` }); let body; try { body = JSON.parse(raw); } catch { return send(res, 400, { error: "fake: body is not JSON" }); } if (!models.includes(body.model)) return send(res, 404, { error: `model "${body.model}" not found` }); // The unload: keep_alive 0 with nothing to answer. const empty = req.url === "/api/generate" ? !body.prompt : !Array.isArray(body.messages) || body.messages.length === 0; if ((body.keep_alive === 0 || body.keep_alive === "0") && empty) { unloads.push(body.model); loaded.delete(body.model); return send(res, 200, { model: body.model, done: true, done_reason: "unload" }); } if (req.url === "/api/generate") return send(res, 400, { error: "fake: only the unload call on /api/generate" }); requests.push(body); if (body.stream !== false) return send(res, 400, { error: "fake: stream must be false" }); const numCtx = body.options?.num_ctx; if (typeof numCtx === "number" && numCtx > numCtxCap) return send(res, 400, { error: `fake: num_ctx ${numCtx} is over the ${numCtxCap} cap` }); const bad = imageProblem(body); if (bad) return send(res, 400, { error: `fake: ${bad}` }); const promptTokens = promptTokensOf(body); if (promptTokens > promptCap) return send(res, 400, { error: `fake: prompt ~${promptTokens} tokens is over the ${promptCap} cap` }); let next = script.shift(); if (next === undefined) return send(res, 500, { error: "fake: script exhausted" }); if (typeof next === "function") next = await next(body, { requests }); if (next.__error) return send(res, next.__error.status, { error: next.__error.error }); loaded.add(body.model); send(res, 200, { model: body.model, created_at: "2026-10-13T00:00:00Z", prompt_eval_count: promptTokens, eval_count: tok(next.message), done_reason: next.done ? "stop" : undefined, ...next, }); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); const { port } = server.address(); return { url: `http://127.0.0.1:${port}`, requests, unloads, shows, loaded: () => [...loaded], push: (...turns) => script.push(...turns), remaining: () => script.length, close: () => new Promise((r) => server.close(() => r())), }; }