// A local model on ollama (release 27): `/api/chat` with tools or a `format` // schema, and the unload. The stopgap's local_sweep.chat and agentloop's local // loop, with Q0's limits for the 8 GB card (2026-10-11): // - `num_ctx` is clamped to 12k; // - the prompt is estimated and REFUSED over 8k tokens before it is sent (a // 13.8k prompt hung the GPU); // - `done: false` is a GPU fault, never an answer; // - one JSON answer (`stream: false`), `think: false` on thinking models // unless the caller asks for thinking. // `digestApps.ts`'s `ollamaDirect` is the digest's own call and is left as it is. import { LOCAL_ONLY_WHY, LocalOnlyError, assertLocalOnlyAllowsEndpoint, assertLocalOnlyAllowsOllamaModel, isLocalOnly, showNamesRemote } from "./localOnly"; export type OllamaConfig = { baseUrl: string; numCtx?: number; promptCapTokens?: number; fetch?: typeof fetch; temperature?: number; // One request's timeout (default 15 minutes: a cold load plus a long answer). timeoutMs?: number; }; export type OllamaToolCall = { function: { name: string; arguments: Record } }; export type OllamaMessage = { role: string; content: string; tool_calls?: OllamaToolCall[]; tool_name?: string; thinking?: string; [k: string]: unknown; }; export type OllamaTool = { type: "function"; function: { name: string; description: string; parameters: Record }; }; export const NUM_CTX_MAX = 12_288; export const PROMPT_CAP_TOKENS = 8_000; // Q0's estimate: 3.5 characters a token, over the JSON of what is sent — on the // safe side of ollama's own count for English transcripts. export const CHARS_PER_TOKEN = 3.5; export function estimateTokens(v: unknown): number { const s = typeof v === "string" ? v : (JSON.stringify(v ?? "") ?? ""); return Math.ceil(s.length / CHARS_PER_TOKEN); } // An image a vision model reads (release 30, the frame scan) is counted at a // fixed cost, not by its base64: a 1280-px frame is about a thousand tokens to // a vision model, and its base64 would read as tens of thousands. export const IMAGE_TOKEN_ESTIMATE = 1_200; // What a chat request is estimated at: its messages (each message's `images` // at IMAGE_TOKEN_ESTIMATE apiece), tools and format. export function promptEstimate(req: { messages: unknown[]; tools?: unknown[]; format?: unknown }): number { let images = 0; const messages = req.messages.map((m) => { if (!m || typeof m !== "object" || !Array.isArray((m as { images?: unknown }).images)) return m; const { images: imgs, ...rest } = m as { images: unknown[] }; images += imgs.length; return rest; }); return estimateTokens([messages, req.tools ?? null, req.format ?? null]) + images * IMAGE_TOKEN_ESTIMATE; } export function numCtxOf(cfg: OllamaConfig): number { const v = cfg.numCtx ?? NUM_CTX_MAX; return Math.max(512, Math.min(NUM_CTX_MAX, Math.floor(v))); } export function promptCapOf(cfg: OllamaConfig): number { const v = cfg.promptCapTokens ?? PROMPT_CAP_TOKENS; return Math.max(256, Math.min(PROMPT_CAP_TOKENS, Math.floor(v))); } // Models with a reasoning mode, which take `think`; ollama refuses `think` on // the others, so it is sent only to these unless the caller sets it. const THINKING_MODELS = /^(qwen3|qwq|deepseek-r1|gpt-oss|magistral|cogito)/; export class OllamaError extends Error { readonly status: number | undefined; constructor(message: string, status?: number) { super(message); this.name = "OllamaError"; this.status = status; } } export class OllamaFaultError extends OllamaError { constructor(model: string) { super(`${model} answered done:false (a GPU fault) — not an answer`); this.name = "OllamaFaultError"; } } export class PromptTooLargeError extends OllamaError { readonly estimate: number; readonly cap: number; constructor(estimate: number, cap: number) { super(`prompt ~${estimate} tokens is over the ${cap}-token cap — not sent`); this.name = "PromptTooLargeError"; this.estimate = estimate; this.cap = cap; } } const base = (cfg: OllamaConfig) => cfg.baseUrl.replace(/\/+$/, ""); // LOCAL ONLY's ollama check (./localOnly.ts), the one every ollama caller // asks before it sends anything (this module's chat and unload, the digest's // ollama-direct): a no-op without the flag. With it: the server's host must // be on this machine, the name must not be a cloud tag, and — once per server // and model per process, before the first prompt — the server's own // /api/show must not name a remote host (a cloud model behind a local // alias). A show that cannot be read refuses: the check fails closed. const SHOWN_KEY = Symbol.for("archilyzer.localOnly.shown"); function shownCache(): Map { const g = globalThis as unknown as Record | undefined>; return (g[SHOWN_KEY] ??= new Map()); } export async function assertLocalOllama(baseUrl: string, model: string, fetchImpl: typeof fetch = fetch, o: { show?: boolean } = {}): Promise { if (!isLocalOnly()) return; const b = baseUrl.replace(/\/+$/, ""); assertLocalOnlyAllowsEndpoint(b, "the ollama server"); assertLocalOnlyAllowsOllamaModel(model); if (o.show === false) return; const key = `${b} ${model}`; if (shownCache().has(key)) return; let show: unknown; try { const res = await fetchImpl(`${b}/api/show`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model }), signal: AbortSignal.timeout(15_000), }); if (!res.ok) throw new Error(`/api/show answered ${res.status}`); show = await res.json(); } catch (e) { throw new LocalOnlyError(`${LOCAL_ONLY_WHY}: could not confirm that "${model}" runs on this machine (${(e as Error).message}) — refused`); } if (showNamesRemote(show)) throw new LocalOnlyError(`${LOCAL_ONLY_WHY}: "${model}" is served from a remote host (its /api/show says so) — refused`); shownCache().set(key, true); } /** Forget what /api/show said (tests). */ export function resetLocalOllamaChecks(): void { shownCache().clear(); } // ollama returns tool-call arguments as an object; some models send a string. function normalizeMessage(m: Partial | undefined): OllamaMessage { const out: OllamaMessage = { ...(m ?? {}), role: m?.role ?? "assistant", content: m?.content ?? "" }; if (Array.isArray(m?.tool_calls) && m.tool_calls.length) { out.tool_calls = m.tool_calls.map((c) => { let args: unknown = c?.function?.arguments ?? {}; if (typeof args === "string") { try { args = JSON.parse(args); } catch { args = {}; } } return { function: { name: String(c?.function?.name ?? ""), arguments: args && typeof args === "object" && !Array.isArray(args) ? (args as Record) : {}, }, }; }); } else delete out.tool_calls; return out; } export async function ollamaChat( cfg: OllamaConfig, req: { model: string; messages: object[]; tools?: object[]; format?: object; think?: boolean; signal?: AbortSignal; }, ): Promise<{ message: OllamaMessage; promptTokens: number; evalTokens: number }> { // LOCAL ONLY (./localOnly.ts): a model server not on this machine, or an // ollama cloud model (by name, then by what /api/show says), is refused // before the request. await assertLocalOllama(base(cfg), req.model, cfg.fetch ?? fetch); const cap = promptCapOf(cfg); const estimate = promptEstimate(req); if (estimate > cap) throw new PromptTooLargeError(estimate, cap); const think = req.think ?? (THINKING_MODELS.test(req.model) ? false : undefined); const body = { model: req.model, stream: false, ...(think !== undefined ? { think } : {}), messages: req.messages, ...(req.tools?.length ? { tools: req.tools } : {}), ...(req.format ? { format: req.format } : {}), options: { num_ctx: numCtxOf(cfg), ...(cfg.temperature !== undefined ? { temperature: cfg.temperature } : {}), }, }; const timeout = AbortSignal.timeout(cfg.timeoutMs ?? 900_000); const signal = req.signal ? AbortSignal.any([req.signal, timeout]) : timeout; let res: Response; try { res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/chat`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), signal, }); } catch (err) { if (req.signal?.aborted) throw err; throw new OllamaError(`ollama request failed (${base(cfg)}): ${(err as Error)?.message ?? String(err)}`); } if (!res.ok) { const text = await res.text().catch(() => ""); let detail = text; try { detail = (JSON.parse(text) as { error?: string }).error ?? text; } catch { // keep the text } throw new OllamaError(`ollama returned ${res.status}: ${detail.slice(0, 300) || res.statusText}`, res.status); } const out = (await res.json()) as { message?: Partial; done?: boolean; prompt_eval_count?: number; eval_count?: number; }; if (!out.done) throw new OllamaFaultError(req.model); return { message: normalizeMessage(out.message), promptTokens: typeof out.prompt_eval_count === "number" ? out.prompt_eval_count : estimate, evalTokens: typeof out.eval_count === "number" ? out.eval_count : 0, }; } // Frees the card: `keep_alive: 0` with nothing to answer. export async function unloadOllama(cfg: OllamaConfig, model: string): Promise { // LOCAL ONLY: nothing is sent to a server that is not on this machine. await assertLocalOllama(base(cfg), model, cfg.fetch ?? fetch, { show: false }); const res = await (cfg.fetch ?? fetch)(`${base(cfg)}/api/generate`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model, keep_alive: 0 }), signal: AbortSignal.timeout(30_000), }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new OllamaError(`ollama unload of ${model} returned ${res.status}: ${text.slice(0, 300)}`, res.status); } await res.body?.cancel().catch(() => {}); } // ─── Tools, both ways ─── export function toOllamaTools( tools: { name: string; description: string; inputSchema: Record }[], descriptionChars = 600, ): OllamaTool[] { return tools.map((t) => ({ type: "function", function: { name: t.name, description: t.description.slice(0, descriptionChars), parameters: t.inputSchema }, })); } export function toolCallsOf(message: OllamaMessage): { name: string; input: Record }[] { return (message.tool_calls ?? []).map((c) => ({ name: c.function.name, input: c.function.arguments })); }