Public: anyone can read this; the crew can change it.

Talk on a local model: a cut prompt is said, reasoning effort is a setting, tool calls written as text are retried (#16410) #16430

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

fix/backends-1b → main 0 commits

  • Merged. fix/backends-1b was merged into main as 24c9325.

Review

Sign in to review this change.
3 files changed +190 −10
docs/features/openai-runner.md +18
@@ -15,6 +15,11 @@ read for these, and a secret cannot be named `OPENAI_*`):
1515 - `OPENAI_BASE_URL` is the endpoint's base, `http://` or `https://`, for example `https://api.openai.com/v1`.
1616 - `OPENAI_MODEL` names the model, unless the run names one.
1717 - `OPENAI_API_KEY` is sent as a bearer token; leave it unset for an endpoint that needs none.
18 - `OPENAI_REASONING_EFFORT` is sent as `reasoning_effort`: `none`, `minimal`, `low`, `medium` or `high`.
19 Unset, nothing is sent and the model thinks as it does by default. Any other word ends the run as an
20 error naming the five. Which is fastest depends on the model and its server: on Ollama 0.40, qwen3:4b
21 at `low` answered a short question in 321 tokens (20 s on a MacBook), while `none` only hid its
22 thinking channel and it thought in the answer instead (2,170 tokens).
1823
1924 Without a base URL and a model a run ends as an error saying so. Read it as the run's result.
2025
@@ -48,6 +53,19 @@ turn on a model the price table does not know has no cost to state, so none is s
4853 (never $0); a crew run keeps the dearest row so its budget holds. Pinned by
4954 `test/openai-talk.test.ts`.
5055
56 **A local model** (Ollama, LM Studio, llama.cpp's server): Talk's prompt and its tools come to about
57 7,000 tokens before the history, so the model needs a context of **32,768 tokens or more**. Ollama's
58 default is 4,096, of which it reads about half of a longer prompt, without an error; set
59 `OLLAMA_CONTEXT_LENGTH=32768` where `ollama serve` runs (its `/v1` endpoint takes no context size per
60 request), and point the forge at it with `OPENAI_BASE_URL=http://127.0.0.1:11434/v1`. A prompt the
61 endpoint read less than half of is said once in the turn and the run log, naming that setting, so a
62 cut prompt never passes quietly. A small model that writes a tool call out as text (`<function-call>…`,
63 `<tool_call>…`, or a JSON object naming a function) instead of calling it has run nothing: it is told
64 so and gets the one retry a call with broken arguments gets, and its text is never kept as the answer.
65 Measured with qwen3:4b on a MacBook (2026-11-25): a tool question, a held close and a follow-up from
66 the history all answered right, at 70 to 220 seconds a turn, most of it thinking, which
67 `OPENAI_REASONING_EFFORT=low` shortens.
68
5169 **A picked subscription is what the run spends** (#15198). When the forge picks an account for the run,
5270 its token goes to that account's gateway (`<gateway>/v1/chat/completions`, through the forge's door for
5371 a crew run), never to `OPENAI_BASE_URL` with the operator's key. An account with no gateway (a bare
src/crew/openai_runner.ts +71 −5
@@ -7,7 +7,8 @@
77 *
88 * Configuration, from the forge's own environment alone, never the run's (a
99 * granted secret is in the run's): `OPENAI_BASE_URL`, `OPENAI_API_KEY`, and
10 * the model name (`AgentRun.model`, else `OPENAI_MODEL`). A run on a picked
10 * the model name (`AgentRun.model`, else `OPENAI_MODEL`), and the reasoning
11 * effort asked for (`OPENAI_REASONING_EFFORT`, sent as `reasoning_effort`). A run on a picked
1112 * subscription (`AgentRun.account`, #15198) spends that account instead: its
1213 * token, sent to its gateway's `/v1`; an account with no gateway is refused,
1314 * never quietly paid for with the operator's key. The endpoint's redirects
@@ -364,6 +365,9 @@ function modelOf(model: string | undefined, get: (k: string) => string): string
364365 return /^(opus|sonnet|haiku)$/i.test(model) && configured !== "" ? configured : model;
365366 }
366367
368 /** The reasoning efforts an endpoint may be asked for (`reasoning_effort`); unset, none is sent. */
369 const EFFORTS = /^(none|minimal|low|medium|high)$/;
370
367371 /** Why a picked account without a gateway does not run here. */
368372 export const NO_GATEWAY = "the picked subscription has no gateway, and this runner reaches a model only through an OpenAI-compatible one; it does not spend the forge's own key on another account's run";
369373
@@ -375,19 +379,59 @@ export const NO_GATEWAY = "the picked subscription has no gateway, and this runn
375379 * sent to. A picked account's base is the forge's (`AgentRun.account`: the
376380 * door it opened, or the gateway the account names), never a granted one.
377381 */
378 export function settings(run: AgentRun, config: Record<string, string | undefined>): { base: string; key: string; model: string } | { refused: string } {
382 export function settings(run: AgentRun, config: Record<string, string | undefined>): Settings | { refused: string } {
379383 const get = (k: string) => config[k] ?? "";
380384 const model = modelOf(run.model, get);
385 // A setting of the connection, not of the run: a granted secret never names it.
386 const reasoningEffort = get("OPENAI_REASONING_EFFORT").trim().toLowerCase();
387 if (reasoningEffort !== "" && !EFFORTS.test(reasoningEffort)) return { refused: "OPENAI_REASONING_EFFORT is none, minimal, low, medium or high" };
388 const effort = reasoningEffort === "" ? {} : { reasoningEffort };
381389 const account = run.account;
382390 if (account !== undefined) {
383391 const base = baseUrl(() => account.base ?? "");
384392 if (base === "") return { refused: NO_GATEWAY };
385393 if (model === "") return { refused: "a model name is required" };
386 return { base: `${base}/v1`, key: account.token, model };
394 return { base: `${base}/v1`, key: account.token, model, ...effort };
387395 }
388396 const base = baseUrl(get);
389397 if (base === "" || model === "") return { refused: "OPENAI_BASE_URL (http/https) and a model name are required" };
390 return { base, key: get("OPENAI_API_KEY"), model };
398 return { base, key: get("OPENAI_API_KEY"), model, ...effort };
399 }
400
401 /** Where a run's model is reached and how it is asked (`settings`). */
402 export interface Settings { base: string; key: string; model: string; reasoningEffort?: string }
403
404 /**
405 * Said once in a run whose endpoint read far less of a prompt than was sent: a server that keeps
406 * a context smaller than the prompt (Ollama's default is 4,096 tokens, half kept for the answer)
407 * cuts it without an error, and the model then answers without its tools or the history.
408 */
409 export function cutLine(read: number, sent: number): string {
410 return `The model's endpoint read ${read.toLocaleString("en-US")} tokens of a prompt of about ${sent.toLocaleString("en-US")}, so it answered without part of it. Give the model a context of 32,768 tokens or more (Ollama: OLLAMA_CONTEXT_LENGTH=32768).`;
411 }
412
413 /** About how many tokens a prompt is: four characters to a token, which no tokenizer is far from. */
414 function tokensAbout(messages: readonly Message[], tools: unknown): number {
415 return Math.round((JSON.stringify(messages).length + JSON.stringify(tools).length) / 4);
416 }
417
418 /**
419 * Whether a reply is only a tool call written out as text (`<function-call>…`, `<tool_call>…`, or a
420 * JSON object naming a function and its arguments): a small model's way of calling when it does
421 * not use the tools field, which would otherwise end the turn with the call shown as the answer.
422 */
423 export function callAsText(text: string): boolean {
424 const body = text.trim().replace(/^```(?:json)?\s*([\s\S]*?)\s*```$/, "$1").trim();
425 if (/^<\/?(function[-_ ]?calls?|tool[-_ ]?calls?)\b/i.test(body)) return true;
426 if (!body.startsWith("{")) return false;
427 try {
428 const parsed: unknown = JSON.parse(body);
429 if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return false;
430 const o = parsed as Record<string, unknown>;
431 return ("name" in o || "function" in o) && ("arguments" in o || "parameters" in o);
432 } catch {
433 return false;
434 }
391435 }
392436
393437 export async function runOpenAI(run: AgentRun, config: Record<string, string | undefined> = process.env): Promise<AgentOutcome> {
@@ -413,6 +457,7 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
413457 { role: "user", content: run.prompt },
414458 ];
415459 let malformed = 0;
460 let warned = false;
416461 try {
417462 const link = run.mcp === undefined ? undefined : await openMcp(run.mcp, run.env, signal);
418463 if (link !== undefined && "refused" in link) {
@@ -425,7 +470,7 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
425470 const res = await fetch(`${cfg.base}/chat/completions`, {
426471 method: "POST",
427472 headers: { "content-type": "application/json", ...(cfg.key ? { authorization: `Bearer ${cfg.key}` } : {}) },
428 body: JSON.stringify({ model: cfg.model, messages, tools, stream: true, stream_options: { include_usage: true } }),
473 body: JSON.stringify({ model: cfg.model, messages, tools, stream: true, stream_options: { include_usage: true }, ...(cfg.reasoningEffort === undefined ? {} : { reasoning_effort: cfg.reasoningEffort }) }),
429474 redirect: "error",
430475 signal,
431476 });
@@ -434,6 +479,7 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
434479 run.log(`! ${result}`);
435480 return done(false, res.status === 429 ? "rate_limited" : "error");
436481 }
482 const sent = tokensAbout(messages, tools);
437483 const answer = await readAnswer(res, run.onDelta);
438484 if ("error" in answer) {
439485 result = answer.error;
@@ -447,6 +493,26 @@ export async function runOpenAI(run: AgentRun, config: Record<string, string | u
447493 tokensOut += usage.completion_tokens ?? 0;
448494 costUsd = priced ? costOf(price, tokensIn, tokensOut) : 0;
449495 run.onUsage?.({ tokensIn, tokensOut, ...(priced ? { costUsd } : {}) });
496 if (!warned && contextTokens > 0 && contextTokens < sent / 2) {
497 warned = true;
498 const line = cutLine(contextTokens, sent);
499 run.log(`! ${line}`);
500 run.onSaid?.({ kind: "text", text: line });
501 }
502 // A call written as text ran nothing: the model is told so and gets the one retry a call
503 // with broken arguments gets, never its text kept as the answer.
504 if (!message.tool_calls?.length && message.content && callAsText(message.content)) {
505 messages.push({ role: "assistant", content: message.content });
506 messages.push({ role: "user", content: "That reply was a tool call written as text, so nothing ran. Call the tool through the tools you were given, or answer in words." });
507 run.log(`! a tool call written as text: ${message.content.slice(0, 200)}`);
508 malformed++;
509 if (malformed > 1) {
510 result = "the model wrote its tool calls as text twice in a row";
511 run.log(`! ${result}`);
512 return done(false, "error");
513 }
514 continue;
515 }
450516 messages.push({ role: "assistant", content: message.content ?? null, ...(message.tool_calls?.length ? { tool_calls: message.tool_calls } : {}) });
451517 if (message.content) {
452518 result = message.content;
test/openai-talk.test.ts +101 −5
@@ -5,6 +5,9 @@
55 * Through Talk itself (`say`) a message is answered, a held tool comes back `needs_confirm` to the
66 * model and to the dock, the stored turns ride along with the next message, a model with no price
77 * costs nothing (never a guess), and a call whose arguments are not JSON is mended once.
8 * A small local model's ways of failing (Ollama, qwen3:4b, 2026-11-25) are pinned too: a prompt
9 * its endpoint cut short is said once, a tool call written as text gets the one retry, and the
10 * reasoning effort setting reaches the endpoint.
811 */
912 import {
1013 afterAll,
@@ -22,12 +25,14 @@ import { listTurns, openConversation } from "../src/core/conversations.ts";
2225 import { createUser, type User } from "../src/core/users.ts";
2326 import { useRunner } from "../src/crew/agent_runner.ts";
2427 import { say, type ConversationOptions } from "../src/crew/conversation.ts";
25 import { openaiRunner } from "../src/crew/openai_runner.ts";
28 import { callAsText, openaiRunner } from "../src/crew/openai_runner.ts";
2629 import { serve, type Servers } from "../src/http/server.ts";
30 import { readRunLog } from "../src/runs/log.ts";
2731
2832 type Body = {
2933 model: string;
3034 stream?: boolean;
35 reasoning_effort?: string;
3136 messages: { role: string; content: string | null; tool_call_id?: string }[];
3237 tools: { function: { name: string } }[];
3338 };
@@ -38,10 +43,17 @@ const sse = (chunks: readonly object[]): Response =>
3843 `${chunks.map((c) => `data: ${JSON.stringify(c)}\n\n`).join("")}data: [DONE]\n\n`,
3944 { headers: { "content-type": "text/event-stream" } },
4045 );
46 /**
47 * The prompt tokens the canned endpoint reports: as many as it was sent (four characters to a
48 * token), unless a test has it cut the prompt as a small context would.
49 */
50 let reads: number | undefined;
51 const promptTokens = (): number =>
52 reads ?? Math.round(JSON.stringify(bodies.at(-1) ?? {}).length / 4);
4153 const text = (...pieces: string[]): Response =>
4254 sse([
4355 ...pieces.map((p) => ({ choices: [{ delta: { content: p } }] })),
44 { choices: [], usage: { prompt_tokens: 120, completion_tokens: 8 } },
56 { choices: [], usage: { prompt_tokens: promptTokens(), completion_tokens: 8 } },
4557 ]);
4658 /** A tool call sent in pieces: its name first, its arguments split across two chunks. */
4759 const toolCall = (name: string, args: string): Response => {
@@ -80,7 +92,7 @@ const toolCall = (name: string, args: string): Response => {
8092 },
8193 ],
8294 },
83 { choices: [], usage: { prompt_tokens: 100, completion_tokens: 20 } },
95 { choices: [], usage: { prompt_tokens: promptTokens(), completion_tokens: 20 } },
8496 ]);
8597 };
8698
@@ -124,11 +136,12 @@ beforeAll(async () => {
124136 return (answers.shift() ?? (() => text("(nothing more)")))();
125137 },
126138 });
127 for (const k of ["OPENAI_BASE_URL", "OPENAI_MODEL", "OPENAI_API_KEY"])
139 for (const k of ["OPENAI_BASE_URL", "OPENAI_MODEL", "OPENAI_API_KEY", "OPENAI_REASONING_EFFORT"])
128140 kept[k] = process.env[k];
129141 process.env["OPENAI_BASE_URL"] = `http://127.0.0.1:${String(model.port)}/v1`;
130142 process.env["OPENAI_MODEL"] = "local-llama";
131143 delete process.env["OPENAI_API_KEY"];
144 delete process.env["OPENAI_REASONING_EFFORT"];
132145 useRunner(openaiRunner);
133146 app = createApp({ dataDir: dir, port: 0 });
134147 servers = await serve(app);
@@ -159,8 +172,15 @@ afterAll(async () => {
159172 beforeEach(() => {
160173 answers = [];
161174 bodies.length = 0;
175 reads = undefined;
162176 });
163177
178 const lastRun = (): { tokens_in: number; tokens_out: number } =>
179 app.db
180 .query<{ tokens_in: number; tokens_out: number }, []>(
181 "SELECT tokens_in, tokens_out FROM conversation_run ORDER BY rowid DESC LIMIT 1",
182 )
183 .get()!;
164184 const runCost = (): number =>
165185 app.db
166186 .query<
@@ -260,9 +280,85 @@ describe("Talk on an OpenAI-compatible endpoint", () => {
260280 try {
261281 answers = [() => text("Priced.")];
262282 await turn("what does it cost?");
263 expect(runCost()).toBeCloseTo((120 * 0.15 + 8 * 0.6) / 1_000_000, 12);
283 const { tokens_in, tokens_out } = lastRun();
284 expect(tokens_out).toBe(8);
285 expect(runCost()).toBeCloseTo((tokens_in * 0.15 + tokens_out * 0.6) / 1_000_000, 12);
264286 } finally {
265287 process.env["OPENAI_MODEL"] = "local-llama";
266288 }
267289 });
290
291 test("a prompt the endpoint cut short is said once, in the thread and the run log, and the turn still answers", async () => {
292 // Ollama at its default context reads about 2,048 tokens of a far longer prompt, without an error.
293 reads = 2050;
294 answers = [
295 () => toolCall("mcp__forge__issues", JSON.stringify({ repo: "alice/shop" })),
296 () => text("No issues."),
297 ];
298 const turns = await turn("which issues are open?");
299 const said = turns.filter((t) => t.role === "agent" && t.text.includes("OLLAMA_CONTEXT_LENGTH=32768"));
300 expect(said.length).toBe(1);
301 expect(said[0]!.text).toContain("read 2,050 tokens of a prompt of about");
302 expect(turns.at(-1)).toMatchObject({ role: "agent", text: "No issues." });
303 const run = app.db.query<{ id: string }, []>("SELECT id FROM conversation_run ORDER BY rowid DESC LIMIT 1").get()!;
304 const log = readRunLog(dir, run.id).lines.filter((l) => l.startsWith("! The model's endpoint read 2,050 tokens"));
305 expect(log.length).toBe(1);
306
307 // A prompt read whole says nothing.
308 reads = undefined;
309 answers = [() => text("Fine.")];
310 const after = await turn("and now?");
311 expect(after.filter((t) => t.text.includes("OLLAMA_CONTEXT_LENGTH")).length).toBe(1);
312 });
313
314 test("a reply that is only a tool call written as text runs nothing, is not kept as the answer, and gets the one retry", async () => {
315 const written = '<function-call>\n{"function": "mcp__forge__issues", "arguments": {"repo": "alice/shop"}}\n</function-call>';
316 answers = [() => text(written), () => text("Three are open.")];
317 let turns = await turn("what is open in alice/shop?");
318 const told = bodies[1]!.messages.at(-1)!;
319 expect(told).toMatchObject({ role: "user" });
320 expect(told.content).toContain("written as text, so nothing ran");
321 expect(turns.at(-1)).toMatchObject({ role: "agent", text: "Three are open." });
322 expect(turns.some((t) => t.text.includes("<function-call>"))).toBe(false);
323
324 answers = [() => text(written), () => text('```json\n{"name": "mcp__forge__issues", "arguments": {}}\n```')];
325 bodies.length = 0;
326 turns = await turn("again");
327 expect(bodies.length).toBe(2);
328 expect(turns.at(-1)).toMatchObject({ role: "agent", failed: true });
329 });
330
331 test("the reasoning effort setting reaches the endpoint; unset it is not sent; a word it does not know refuses the turn", async () => {
332 answers = [() => text("Plain.")];
333 await turn("quick one");
334 expect(bodies[0]).not.toHaveProperty("reasoning_effort");
335
336 process.env["OPENAI_REASONING_EFFORT"] = "None";
337 try {
338 answers = [() => text("Quick.")];
339 bodies.length = 0;
340 await turn("quicker");
341 expect(bodies[0]).toMatchObject({ reasoning_effort: "none" });
342
343 process.env["OPENAI_REASONING_EFFORT"] = "maximum";
344 bodies.length = 0;
345 const turns = await turn("fastest");
346 expect(bodies.length).toBe(0);
347 expect(turns.at(-1)).toMatchObject({ role: "agent", failed: true });
348 } finally {
349 delete process.env["OPENAI_REASONING_EFFORT"];
350 }
351 });
352 });
353
354 describe("callAsText", () => {
355 test("names a tool call written out as text, and nothing else", () => {
356 expect(callAsText('<function-call>{"function":"x","arguments":{}}</function-call>')).toBe(true);
357 expect(callAsText('<tool_call>\n{"name":"x","arguments":{}}\n</tool_call>')).toBe(true);
358 expect(callAsText('{"name":"mcp__forge__issues","parameters":{"repo":"a/b"}}')).toBe(true);
359 expect(callAsText('```json\n{"name":"x","arguments":{}}\n```')).toBe(true);
360 expect(callAsText("Three issues are open: #1, #2 and #3.")).toBe(false);
361 expect(callAsText('{"repo":"alice/shop","open":3}')).toBe(false);
362 expect(callAsText("I would call <function-call> here, but no.")).toBe(false);
363 });
268364 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs