From 845672540a65f1245feadfe29249fd0fc64eab61 Mon Sep 17 00:00:00 2001 From: David McKay Date: Tue, 1 Dec 2026 14:27:06 -0800 Subject: [PATCH] Cache the prompt prefix in the engines, hold the clearing boundary, drop the per-step snapshot Prompt caching. agent-langgraph-ts, agent-langgraph-agui and agent-mastra sent Claude no cache_control, and the model gateway passes the body through unchanged, so every step of a turn was billed in full. Measured on Anthropic's API through a gateway-style passthrough: a two-step tool turn sent 18,796 and 18,864 input tokens and read none from the cache. Each engine now marks the last tool, the system prompt and the conversation (top-level cache_control): the second step reads 18,792 tokens back (langgraph-ts), 13,920 (langgraph-agui) and 11,879 (mastra). A proxy that refuses the field is remembered for the process and asked again unmarked. OpenAI and Gemini are sent nothing new. Clearing hysteresis. Past 100,000 tokens the local rule in context-room.ts cleared all but the last ten results on every step, so each new result pushed one more out and the cached prefix changed on every step. It now clears the oldest results down to 60,000 and holds the boundary until the sent context passes 100,000 again, worked out from the thread alone so every run of a turn lands on the same boundary. A 200-step task now changes its prefix on a handful of steps instead of nearly all of them. Claude keeps Anthropic's own clearing, which measured live holds its prefix past the trigger. No MESSAGES_SNAPSHOT. agent-langgraph-ts ended every run with a snapshot of the whole thread, and every step of a long task is a run, so a turn streamed about N^2/2 messages back. The events already build every message a step adds in the caller's thread (text, calls, recall results, and Gemini's thought signature via REASONING_ENCRYPTED_VALUE), which the server and the browser apply with @ag-ui/client as they do for any agent that sends no snapshot. Tests now read the thread the caller holds after applying the events with @ag-ui/client itself. --- agent-langgraph-agui/src/main.py | 38 ++- agent-langgraph-agui/src/prompt_cache.py | 106 ++++++ agent-langgraph-agui/src/tool_runtime.py | 13 +- .../tests/test_prompt_cache.py | 207 ++++++++++++ .../tests/test_provider_boundaries.py | 5 +- agent-langgraph-ts/package-lock.json | 1 + agent-langgraph-ts/package.json | 1 + agent-langgraph-ts/src/context-room.ts | 163 ++++++++-- agent-langgraph-ts/src/models.ts | 42 +-- agent-langgraph-ts/src/prompt-cache.ts | 110 +++++++ agent-langgraph-ts/src/run.ts | 94 ++---- agent-langgraph-ts/test/context-room.test.ts | 145 ++++++++- agent-langgraph-ts/test/hand-back.test.ts | 25 +- agent-langgraph-ts/test/helpers.ts | 40 +++ agent-langgraph-ts/test/model-route.test.ts | 15 +- agent-langgraph-ts/test/no-snapshot.test.ts | 127 ++++++++ .../test/progress-reminder.test.ts | 15 +- .../test/progress-updates.test.ts | 35 +- .../test/prompt-cache.live.test.ts | 304 ++++++++++++++++++ agent-langgraph-ts/test/prompt-cache.test.ts | 156 +++++++++ .../test/thought-signatures.test.ts | 33 +- agent-mastra/src/mastra/index.test.ts | 125 ++++++- agent-mastra/src/mastra/index.ts | 14 +- agent-mastra/src/mastra/prompt-cache.ts | 140 ++++++++ 24 files changed, 1758 insertions(+), 196 deletions(-) create mode 100644 agent-langgraph-agui/src/prompt_cache.py create mode 100644 agent-langgraph-agui/tests/test_prompt_cache.py create mode 100644 agent-langgraph-ts/src/prompt-cache.ts create mode 100644 agent-langgraph-ts/test/no-snapshot.test.ts create mode 100644 agent-langgraph-ts/test/prompt-cache.live.test.ts create mode 100644 agent-langgraph-ts/test/prompt-cache.test.ts create mode 100644 agent-mastra/src/mastra/prompt-cache.ts diff --git a/agent-langgraph-agui/src/main.py b/agent-langgraph-agui/src/main.py index 391178d68e..b7b608aa6a 100644 --- a/agent-langgraph-agui/src/main.py +++ b/agent-langgraph-agui/src/main.py @@ -24,7 +24,7 @@ from langgraph.checkpoint.memory import MemorySaver from langgraph.graph import START, MessagesState, StateGraph -from . import chatgpt_images, chatgpt_models, progress_updates +from . import chatgpt_images, chatgpt_models, progress_updates, prompt_cache from .thought_signatures import SignedChatOpenAI, is_gemini, signed from .tool_runtime import ( ToolAwareAgent, @@ -366,20 +366,30 @@ async def answer(state: MessagesState): # Put in after the system turns are moved up, so a reminder stays where it was put. if form == progress_reminder.SYSTEM and places: model = progress_reminder.in_place(model) - try: - sent = progress_reminder.with_reminders(messages, places, form) - return {"messages": [await bind_tools(model).ainvoke(sent)]} - except Exception as error: - # A proxy that takes no system message mid-thread: reminded in the person's turn instead. - if not ( - form == progress_reminder.SYSTEM - and places - and progress_reminder.refuses_system_reminder(error) - ): + for _ in range(3): + # On Claude, the tools, the instructions and the conversation so far are marked for + # Anthropic's prompt cache, so each step reads what the step before it wrote. + cache = prompt_cache.caches_prompt(model) + asked = prompt_cache.with_cached_instructions(messages) if cache else messages + try: + sent = progress_reminder.with_reminders(asked, places, form) + return {"messages": [await bind_tools(model, cache).ainvoke(sent)]} + except Exception as error: + # A proxy that takes no cache mark: asked again unmarked, for good. + if cache and prompt_cache.refuses_prompt_cache(error): + prompt_cache.stop_prompt_cache(model) + continue + # A proxy that takes no system message mid-thread: reminded in the person's turn. + if ( + form == progress_reminder.SYSTEM + and places + and progress_reminder.refuses_system_reminder(error) + ): + progress_reminder.stop_system_reminders(model) + form = progress_reminder.TURN + continue raise - progress_reminder.stop_system_reminders(model) - sent = progress_reminder.with_reminders(messages, places, progress_reminder.TURN) - return {"messages": [await bind_tools(model).ainvoke(sent)]} + raise RuntimeError("The model refused every way this Bot knows to ask it.") except (AuthenticationError, PermissionDeniedError, _ChatGPTOAuthRefreshError) as error: # Typed provider boundary only. A callback or harness 401 is a different credential. A # 403 for an account out of credit (xAI answers so) is not a sign-in problem at all. diff --git a/agent-langgraph-agui/src/prompt_cache.py b/agent-langgraph-agui/src/prompt_cache.py new file mode 100644 index 0000000000..3b8bfb3cb2 --- /dev/null +++ b/agent-langgraph-agui/src/prompt_cache.py @@ -0,0 +1,106 @@ +"""Anthropic's prompt cache, for this Bot's Claude runs. + +Every model call of a turn sends the same tools, the same instructions and a conversation that only +grows. Anthropic reads a prompt's prefix back from its cache, at a tenth of the input price, only +where the request marks where the prefix ends (`cache_control`); nothing on the way adds a mark +(OpenBot's model gateway passes the body through as it came), so before this every step was billed +in full. + +WHERE THE MARKS GO, as Anthropic lays them out for an agent loop +(https://platform.claude.com/docs/en/build-with-claude/prompt-caching): +- The last tool. Tools lead the prefix and are the same on every step of a turn. +- The system prompt: the server's instructions, which are the same from run to run. +- The conversation, by the request's own top-level `cache_control`: Anthropic marks the last block + it can and moves the mark on as the conversation grows, so each step reads what the step before + it wrote. Three of the four marks a request may carry. + +Five minutes, the default: the steps of a turn start well inside that. + +A proxy in front of Claude that refuses the field is remembered for the life of the process and +asked again without it, as one that refuses a mid-thread system message is (progress_reminder.py). +""" + +from __future__ import annotations + +import re + +EPHEMERAL = {"type": "ephemeral"} + +# The addresses that refused a cache mark, kept for the life of the process. +_refused: set[str] = set() + + +def _address(model) -> str: + return str(getattr(model, "anthropic_api_url", None) or "https://api.anthropic.com").rstrip("/") + + +def caches_prompt(model) -> bool: + """Whether this model's requests carry the cache marks: Claude, at an address that took them.""" + try: + from langchain_anthropic import ChatAnthropic + except ImportError: + return False + return isinstance(model, ChatAnthropic) and _address(model) not in _refused + + +def stop_prompt_cache(model) -> None: + """Send this model's address no marks again, for the life of the process.""" + _refused.add(_address(model)) + + +def refuses_prompt_cache(error: BaseException) -> bool: + """A proxy in front of Claude that does not take a cache mark: a 4xx naming it.""" + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + status = getattr(error, "status_code", None) + if isinstance(status, int) and status < 500: + body = getattr(error, "body", None) + words = f"{error} {body if isinstance(body, (str, dict)) else ''}" + if re.search(r"cache[_-]control", words, re.IGNORECASE): + return True + error = error.__cause__ + return False + + +def cached_tools(tools) -> list[dict]: + """The run's tools in Anthropic's own shape, the last one marked as the end of the tools.""" + return [ + { + "name": tool.name, + "description": tool.description or "", + "input_schema": tool.parameters or {"type": "object", "properties": {}}, + **({"cache_control": dict(EPHEMERAL)} if index == len(tools) - 1 else {}), + } + for index, tool in enumerate(tools) + ] + + +def with_cached_instructions(messages): + """The messages with the last of the system turns that lead them marked as their end. + + Only the system turns at the very top are the instructions; the rest is the conversation, which + the top-level mark covers. An empty prompt can't carry the mark (the API refuses it). + """ + from langchain_core.messages import SystemMessage + + leading = 0 + while leading < len(messages) and isinstance(messages[leading], SystemMessage): + leading += 1 + if leading == 0: + return list(messages) + last = messages[leading - 1] + content = last.content + if isinstance(content, str): + if not content.strip(): + return list(messages) + blocks = [{"type": "text", "text": content, "cache_control": dict(EPHEMERAL)}] + elif isinstance(content, list) and content and isinstance(content[-1], dict): + blocks = [*content[:-1], {**content[-1], "cache_control": dict(EPHEMERAL)}] + else: + return list(messages) + return [ + *messages[: leading - 1], + last.model_copy(update={"content": blocks}), + *messages[leading:], + ] diff --git a/agent-langgraph-agui/src/tool_runtime.py b/agent-langgraph-agui/src/tool_runtime.py index 634cb49a27..73356cb6d8 100644 --- a/agent-langgraph-agui/src/tool_runtime.py +++ b/agent-langgraph-agui/src/tool_runtime.py @@ -598,8 +598,19 @@ def _text(content) -> str: return "" -def bind_tools(model): +def bind_tools(model, cache: bool = False): + """The model with the run's tools; with `cache`, marked for Anthropic's prompt cache. + + Marked, the tools go in Anthropic's own shape with the last one ending the cached tools, and the + request carries the top-level mark for the conversation (prompt_cache.py). + """ tools = current_tools().tools + if cache: + from .prompt_cache import EPHEMERAL, cached_tools + + if not tools: + return model.bind(cache_control=dict(EPHEMERAL)) + return model.bind_tools(cached_tools(tools), cache_control=dict(EPHEMERAL)) if not tools: return model return model.bind_tools( diff --git a/agent-langgraph-agui/tests/test_prompt_cache.py b/agent-langgraph-agui/tests/test_prompt_cache.py new file mode 100644 index 0000000000..833727d512 --- /dev/null +++ b/agent-langgraph-agui/tests/test_prompt_cache.py @@ -0,0 +1,207 @@ +"""Anthropic's prompt cache marks, as Claude receives them (prompt_cache.py). + +Every Claude request carries three marks: the last tool, the system prompt and the request's own +top-level mark for the conversation. No other provider is sent one, and a proxy that refuses the +field is asked again without it, for good. Read where it matters: the body that reached Anthropic at +its HTTP boundary, through the production AG-UI endpoint. + +The live test at the end measures it on Anthropic's own API: the second model call of a turn reads +the whole prefix back from the cache. It runs only with ANTHROPIC_API_KEY set. +""" + +import json +import os +import sys +from pathlib import Path +from uuid import uuid4 + +import httpx2 +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from src import prompt_cache +from test_model_choice import run, run_body +from test_progress_updates import ( # noqa: F401 (`environment` is this module's autouse fixture) + ANSWER_STEP, + FIRST_STEP, + TOOL_URL, + claude, + environment, + sse, +) + +EPHEMERAL = {"type": "ephemeral"} +LIVE_KEY = (os.environ.get("OPENBOT_LIVE_ANTHROPIC_KEY") or "").strip() + + +@pytest.fixture(autouse=True) +def fresh_refusals(): + prompt_cache._refused.clear() + yield + prompt_cache._refused.clear() + + +def weighing(model="claude-sonnet-5-5", content="Weigh crates 1 to 3 and tell me the total."): + body = run_body(model={"model": model}, tools=["weigh"], content=content) + body["messages"].insert( + 0, + { + "id": "standing-role:test-bot", + "role": "system", + "content": "You are Test Bot. Weigh what you are asked to, then add it up.", + }, + ) + body["forwardedProps"]["openbotDeploymentTools"] = ["weigh"] + return body + + +def marks(body): + found = [] + if body.get("cache_control"): + found.append("top-level") + for tool in body.get("tools") or []: + if tool.get("cache_control"): + found.append(f"tool:{tool['name']}") + system = body.get("system") + if isinstance(system, list): + found += ["system" for block in system if block.get("cache_control")] + for message in body.get("messages") or []: + if isinstance(message.get("content"), list): + found += ["message" for block in message["content"] if block.get("cache_control")] + return found + + +@pytest.mark.asyncio +async def test_every_claude_step_marks_the_tools_the_instructions_and_the_conversation(monkeypatch): + with claude(monkeypatch, [FIRST_STEP, ANSWER_STEP]) as requests: + await run(weighing()) + + assert len(requests) == 2, "a tool step and the answer, in one run" + for request in requests: + body = request["body"] + assert marks(body) == ["top-level", "tool:weigh", "system"] + assert body["cache_control"] == EPHEMERAL + assert "You are Test Bot." in body["system"][0]["text"] + + +@pytest.mark.asyncio +async def test_a_proxy_that_refuses_cache_control_is_asked_again_without_it_and_never_again( + monkeypatch, +): + requests = [] + original = httpx2.AsyncClient.send + + async def proxy(client, request, **kwargs): + if request.url.host != "anthropic.test": + return await original(client, request, **kwargs) + body = json.loads(request.content) + requests.append(body) + if "cache_control" in json.dumps(body): + return httpx2.Response( + 400, + json={ + "type": "error", + "error": { + "type": "invalid_request_error", + "message": "cache_control: Extra inputs are not permitted", + }, + }, + request=request, + ) + return httpx2.Response( + 200, + content=sse(body["model"], ANSWER_STEP, "end_turn"), + headers={"content-type": "text/event-stream"}, + request=request, + ) + + with claude(monkeypatch, []): + monkeypatch.setattr(httpx2.AsyncClient, "send", proxy) + first = await run(weighing()) + second = await run(weighing()) + + for events in (first, second): + assert events[-1]["type"] == "RUN_FINISHED", events[-1] + assert [bool(marks(body)) for body in requests] == [True, False, False] + + +@pytest.mark.asyncio +async def test_openai_is_sent_no_cache_marks(monkeypatch): + monkeypatch.setenv("BOT_PROVIDER", "openai") + monkeypatch.setenv("OPENAI_API_KEY", "sk-synthetic") + monkeypatch.setenv("OPENAI_BASE_URL", "http://openai.test/v1") + sent = [] + original = httpx2.AsyncClient.send + + async def openai(client, request, **kwargs): + if request.url.host != "openai.test": + return await original(client, request, **kwargs) + sent.append(request) + chunk = { + "id": "c", + "object": "chat.completion.chunk", + "created": 0, + "model": "gpt-5.2", + "choices": [{"index": 0, "delta": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}], + } + return httpx2.Response( + 200, + content=f"data: {json.dumps(chunk)}\n\ndata: [DONE]\n\n".encode(), + headers={"content-type": "text/event-stream"}, + request=request, + ) + + monkeypatch.setattr(httpx2.AsyncClient, "send", openai) + events = await run(weighing("gpt-5.2")) + assert events[-1]["type"] == "RUN_FINISHED", events[-1] + assert sent, "OpenAI was asked" + assert all(b"cache_control" not in request.content for request in sent) + + +@pytest.mark.asyncio +@pytest.mark.skipif(not LIVE_KEY, reason="OPENBOT_LIVE_ANTHROPIC_KEY is not set") +async def test_live_the_second_call_of_a_turn_reads_the_prefix_back(monkeypatch): + monkeypatch.setenv("ANTHROPIC_API_KEY", LIVE_KEY) + monkeypatch.delenv("ANTHROPIC_BASE_URL", raising=False) + usage = [] + original = httpx2.AsyncClient.send + + async def recorded(client, request, **kwargs): + response = await original(client, request, **kwargs) + if request.url.host != "api.anthropic.com": + return response + await response.aread() + for line in response.text.splitlines(): + if line.startswith("data:"): + event = json.loads(line[5:]) + if event.get("type") == "message_start": + usage.append(event["message"]["usage"]) + return response + + import httpx + + original_httpx = httpx.AsyncClient.send + + async def tool(client, request, **kwargs): + if request.url.host != "openbot.test": + return await original_httpx(client, request, **kwargs) + return httpx.Response(200, json={"text": "Crates: 12 kg, 14 kg, 16 kg."}, request=request) + + monkeypatch.setattr(httpx2.AsyncClient, "send", recorded) + monkeypatch.setattr(httpx.AsyncClient, "send", tool) + monkeypatch.setenv("OPENBOT_TOOL_URL", TOOL_URL) + body = weighing(content="Weigh crates 1 to 3 with the weigh tool, then tell me the total.") + # A built-in Bot's instructions are about ten thousand tokens; these are as long. + rules = "\n".join( + f"Rule {n}: when asked about topic {n}, answer plainly, cite the tool you used, and never " + "invent a figure the tools did not give you." + for n in range(1, 301) + ) + body["messages"][0]["content"] += f"\n{rules}\nRun {uuid4()}." + events = await run(body) + print("usage", json.dumps(usage)) + assert events[-1]["type"] == "RUN_FINISHED", events[-1] + assert len(usage) >= 2, usage + assert usage[0]["cache_creation_input_tokens"] > 5_000, usage + assert usage[1]["cache_read_input_tokens"] > 5_000, usage diff --git a/agent-langgraph-agui/tests/test_provider_boundaries.py b/agent-langgraph-agui/tests/test_provider_boundaries.py index 6ed512a1e9..c627f0e219 100644 --- a/agent-langgraph-agui/tests/test_provider_boundaries.py +++ b/agent-langgraph-agui/tests/test_provider_boundaries.py @@ -455,7 +455,10 @@ async def test_anthropic_answers_a_conversation_in_which_a_skill_was_picked( ) assert result["messages"][0].content == "anthropic proof" - assert captured[0]["body"]["system"] == "You are Ada, Analyst." + # One system prompt, marked as the end of the instructions for Anthropic's prompt cache. + assert captured[0]["body"]["system"] == [ + {"type": "text", "text": "You are Ada, Analyst.", "cache_control": {"type": "ephemeral"}} + ] assert captured[0]["body"]["messages"] == [ {"role": "user", "content": "Summarise the Q3 filing."}, {"role": "assistant", "content": "Revenue rose 4%."}, diff --git a/agent-langgraph-ts/package-lock.json b/agent-langgraph-ts/package-lock.json index 103a4f6286..071b5bd2c2 100644 --- a/agent-langgraph-ts/package-lock.json +++ b/agent-langgraph-ts/package-lock.json @@ -17,6 +17,7 @@ }, "devDependencies": { "@types/node": "22.20.5", + "rxjs": "7.8.1", "typescript": "5.9.3" }, "engines": { diff --git a/agent-langgraph-ts/package.json b/agent-langgraph-ts/package.json index a141033780..c0a208fc56 100644 --- a/agent-langgraph-ts/package.json +++ b/agent-langgraph-ts/package.json @@ -22,6 +22,7 @@ }, "devDependencies": { "@types/node": "22.20.5", + "rxjs": "7.8.1", "typescript": "5.9.3" } } diff --git a/agent-langgraph-ts/src/context-room.ts b/agent-langgraph-ts/src/context-room.ts index 3afc72f40c..c0868be236 100644 --- a/agent-langgraph-ts/src/context-room.ts +++ b/agent-langgraph-ts/src/context-room.ts @@ -9,10 +9,13 @@ * 1. On Claude, Anthropic clears old tool results on its side. Every request carries the edit and * its beta, and the whole history. A proxy in front of Claude that refuses the field is * remembered for the life of the process and gets rule 2 instead. - * 2. On every other provider the same rule runs here, before each model call: past 100,000 input - * tokens, every tool result but the last 10 becomes a short note naming its call, if that frees - * at least 20,000 tokens. `search_tools` results are never cleared, because they say which tools - * the Bot may call. Each call keeps a result, so no provider sees an orphan. + * 2. On every other provider the rule runs here, before each model call: past 100,000 input + * tokens, the oldest tool results become a short note naming their call until what is sent is + * down to 60,000, never the last 10, and only if that frees at least 20,000 tokens. Then the + * boundary holds until what is sent passes 100,000 again, so the provider's prompt cache is + * broken once per clearing rather than on every step (`heldClearing`). `search_tools` results + * are never cleared, because they say which tools the Bot may call. Each call keeps a result, so + * no provider sees an orphan. * 3. If the provider still refuses as too long, the same call is retried, cleared harder, up to * three times, and the stage that worked is where the rest of the run starts. A run is one step * and its recalls, since every other call ends it for the caller to answer, so the stage is @@ -28,8 +31,8 @@ */ import type { Tool } from "@ag-ui/core"; import { ChatAnthropic } from "@langchain/anthropic"; -import type { BaseChatModel } from "@langchain/core/language_models/chat_models"; import { ContextOverflowError } from "@langchain/core/errors"; +import type { BaseChatModel } from "@langchain/core/language_models/chat_models"; import { AIMessage, type BaseMessage, @@ -42,6 +45,11 @@ import { links, providerWords, statusOf } from "./errors.ts"; /** Past this many input tokens, old tool results are cleared. */ export const CLEAR_TRIGGER_TOKENS = 100_000; +/** + * Down to this many, and then the boundary is held until the trigger is passed again, so the prefix + * a provider caches changes once in a long stretch of steps instead of on every one. + */ +export const LOW_WATERMARK_TOKENS = 60_000; /** * The tool results that stay whole. Ten rather than Anthropic's default of three: a Bot is told to * batch about five reads at once, and a step must see the whole of its latest batch. @@ -198,48 +206,135 @@ function resultText(content: unknown): string { return JSON.stringify(content ?? ""); } +/** A result as its note: the same call, its words replaced. */ +function noteFor(result: ToolMessage): ToolMessage { + return new ToolMessage({ + ...(result.id ? { id: result.id } : {}), + content: clearedNote(result.tool_call_id), + tool_call_id: result.tool_call_id, + ...(result.name ? { name: result.name } : {}), + ...(result.status ? { status: result.status } : {}), + }); +} + +/** + * The tokens clearing each tool result would free, by its index: none for a result never cleared + * (`search_tools`) or one already as short as its note (or already cleared). + */ +function savings(messages: readonly BaseMessage[]): Map { + const names = callsById(messages); + const saved = new Map(); + for (const [index, message] of messages.entries()) { + if (message.getType() !== "tool") continue; + const result = message as ToolMessage; + const name = result.name ?? names.get(result.tool_call_id)?.name ?? ""; + if (NEVER_CLEARED.includes(name)) continue; + const size = sizeOf(result); + const gain = + tokensOf(size.chars, size.images) - + tokensOf(clearedNote(result.tool_call_id).length); + if (gain > 0) saved.set(index, gain); + } + return saved; +} + +function withNotes( + messages: readonly BaseMessage[], + cleared: ReadonlySet, +): readonly BaseMessage[] { + if (cleared.size === 0) return messages; + return messages.map((message, index) => + cleared.has(index) ? noteFor(message as ToolMessage) : message, + ); +} + +/** + * The tool results a step clears, with the boundary held still between clearings. + * + * Clearing changes what the provider has cached from the first cleared result on. FOUND IN THE + * WASTE AUDIT AFTER 1.2.7: past the trigger every step cleared all but the last `keep` results, so + * each new result pushed one more out, the prefix changed at a new place on every step and the cache + * from there on was written again, every step, for the rest of a long task. Now a step past the + * trigger clears the oldest results until what is sent is down to `low`, and then nothing more is + * cleared, and the prefix stays exactly as it was, until what is sent passes the trigger again. + * + * A run is one step and holds nothing from the steps before it, so the boundary is worked out from + * the thread alone: the thread is replayed message by message as it grew, clearing wherever the rule + * above would have, which lands on the same boundary on every step of a turn and moves it only when + * the trigger is passed again. + */ +function heldClearing( + messages: readonly BaseMessage[], + stage: Pick & { low: number }, + extraChars: number, +): Set { + const saved = savings(messages); + const results: number[] = []; + const cleared = new Set(); + /** The next result that may be cleared, in thread order. */ + let next = 0; + let sent = tokensOf(extraChars); + for (const [index, message] of messages.entries()) { + const size = sizeOf(message); + sent += tokensOf(size.chars, size.images); + if (message.getType() === "tool") results.push(index); + if (sent < stage.trigger) continue; + // The last `keep` results of the thread as it stood then stay whole. + const limit = Math.max(0, results.length - stage.keep); + let freed = 0; + let to = next; + const batch: number[] = []; + for (; to < limit && sent - freed > stage.low; to += 1) { + const at = results[to]; + const gain = at === undefined ? undefined : saved.get(at); + if (at === undefined || !gain) continue; + freed += gain; + batch.push(at); + } + // Clearing breaks the cache, so it is done only when it frees enough to be worth it. + if (batch.length === 0 || freed < stage.atLeast) continue; + for (const at of batch) cleared.add(at); + sent -= freed; + next = to; + } + return cleared; +} + /** - * The messages with every tool result but the last `keep` replaced by its note, once they pass - * `trigger` tokens and only if that frees `atLeast`. The same array when nothing is cleared. + * The messages with old tool results replaced by their notes, the same array when nothing is + * cleared. With a `trigger`: past it, the oldest results down to `low` tokens, the boundary then + * held until the trigger is passed again (`heldClearing`), each clearing only if it frees `atLeast`. + * Without one (a harder retry): every result but the last `keep`, if that frees `atLeast`. */ export function clearOldResults( messages: readonly BaseMessage[], - stage: Pick, + stage: Pick & { low?: number }, extraChars = 0, ): readonly BaseMessage[] { - if (stage.trigger > 0 && estimateTokens(messages, extraChars) < stage.trigger) - return messages; - const names = callsById(messages); + if (stage.trigger > 0) + return withNotes( + messages, + heldClearing( + messages, + { ...stage, low: stage.low ?? LOW_WATERMARK_TOKENS }, + extraChars, + ), + ); + const saved = savings(messages); const results: number[] = []; for (const [index, message] of messages.entries()) if (message.getType() === "tool") results.push(index); const kept = new Set(stage.keep > 0 ? results.slice(-stage.keep) : []); - const replaced = new Map(); + const cleared = new Set(); let freed = 0; for (const index of results) { - if (kept.has(index)) continue; - const result = messages[index] as ToolMessage; - const name = result.name ?? names.get(result.tool_call_id)?.name ?? ""; - if (NEVER_CLEARED.includes(name)) continue; - const note = clearedNote(result.tool_call_id); - const size = sizeOf(result); - const saved = tokensOf(size.chars, size.images) - tokensOf(note.length); - // A result already as short as its note (or already cleared) gains nothing. - if (saved <= 0) continue; - freed += saved; - replaced.set( - index, - new ToolMessage({ - ...(result.id ? { id: result.id } : {}), - content: note, - tool_call_id: result.tool_call_id, - ...(result.name ? { name: result.name } : {}), - ...(result.status ? { status: result.status } : {}), - }), - ); + const gain = saved.get(index); + if (kept.has(index) || !gain) continue; + freed += gain; + cleared.add(index); } - if (replaced.size === 0 || freed < stage.atLeast) return messages; - return messages.map((message, index) => replaced.get(index) ?? message); + if (freed < stage.atLeast) return messages; + return withNotes(messages, cleared); } function cutText(text: string): string { diff --git a/agent-langgraph-ts/src/models.ts b/agent-langgraph-ts/src/models.ts index 4a25291825..5959988693 100644 --- a/agent-langgraph-ts/src/models.ts +++ b/agent-langgraph-ts/src/models.ts @@ -34,6 +34,7 @@ import { withContextEditing } from "./context-room.ts"; import { HarnessRunError, MODEL_UNREACHABLE } from "./errors.ts"; import { PlanHarnessChatModel } from "./plan-model.ts"; import { withProgressUpdates } from "./progress-updates.ts"; +import { withPromptCache } from "./prompt-cache.ts"; import { ChatCompletionsWithSignatures } from "./thought-signatures.ts"; export type Env = Record; @@ -282,25 +283,28 @@ function thinksByDefault(model: string): boolean { function anthropicModel(model: string, run: RunModel, env: Env): BaseChatModel { const baseUrl = env.ANTHROPIC_BASE_URL?.trim() || undefined; // Anthropic clears old tool results on its side, so a long run stays inside the window - // (context-room.ts), and a model that writes progress updates between tool calls is asked for - // their text, so a long job shows its lines (progress-updates.ts); each unless a proxy at this - // address has already refused it. - return withContextEditing( - withProgressUpdates( - new ChatAnthropic({ - model, - apiKey: env.ANTHROPIC_API_KEY?.trim() || undefined, - maxRetries: retries(run), - ...(baseUrl ? { anthropicApiUrl: baseUrl } : {}), - ...(ANTHROPIC_EFFORTS.has(run.effort) - ? { outputConfig: { effort: run.effort as never } } - : {}), - // Said outright for a model that thinks adaptively anyway, so the request is the same. Left - // out, @langchain/anthropic checks its own default (`disabled`, which it never sends) against - // Opus 5's rule that disabled thinking can't run at xhigh or max, and throws before asking: - // a person who picked Opus 5.5 at Extra high got "The Bot stopped" and no answer. - ...(thinksByDefault(model) ? { thinking: { type: "adaptive" } } : {}), - }), + // (context-room.ts), a model that writes progress updates between tool calls is asked for + // their text, so a long job shows its lines (progress-updates.ts), and each step reads the + // prefix the step before it wrote from Anthropic's prompt cache (prompt-cache.ts); each unless a + // proxy at this address has already refused it. + return withPromptCache( + withContextEditing( + withProgressUpdates( + new ChatAnthropic({ + model, + apiKey: env.ANTHROPIC_API_KEY?.trim() || undefined, + maxRetries: retries(run), + ...(baseUrl ? { anthropicApiUrl: baseUrl } : {}), + ...(ANTHROPIC_EFFORTS.has(run.effort) + ? { outputConfig: { effort: run.effort as never } } + : {}), + // Said outright for a model that thinks adaptively anyway, so the request is the same. Left + // out, @langchain/anthropic checks its own default (`disabled`, which it never sends) against + // Opus 5's rule that disabled thinking can't run at xhigh or max, and throws before asking: + // a person who picked Opus 5.5 at Extra high got "The Bot stopped" and no answer. + ...(thinksByDefault(model) ? { thinking: { type: "adaptive" } } : {}), + }), + ), ), ); } diff --git a/agent-langgraph-ts/src/prompt-cache.ts b/agent-langgraph-ts/src/prompt-cache.ts new file mode 100644 index 0000000000..b5d4fb5106 --- /dev/null +++ b/agent-langgraph-ts/src/prompt-cache.ts @@ -0,0 +1,110 @@ +/** + * Anthropic's prompt cache, for this engine's Claude runs. + * + * Every step of a turn is a run of its own, and each sends the same tools, the same instructions and + * a conversation that only grows. Anthropic reads a prompt's prefix back from its cache, at a tenth + * of the input price, only where the request marks where the prefix ends (`cache_control`); nothing + * on the way adds a mark (OpenBot's model gateway passes the body through as it came). MEASURED ON + * ANTHROPIC'S API before this: a two-step tool turn with a built-in Bot's size of instructions sent + * 18,796 and 18,864 input tokens and read none of them from a cache (test/prompt-cache.live.test.ts). + * + * WHERE THE MARKS GO, as Anthropic lays them out for an agent loop + * (https://platform.claude.com/docs/en/build-with-claude/prompt-caching): + * - The last tool. Tools lead the prefix and are the same on every step of a turn. + * - The system prompt, which is OpenBot's instructions and nothing that changes from run to run + * (`modelMessages` in history.ts). With the tools before it, this holds across turns and threads + * of the same Bot. + * - The conversation, by the request's own top-level `cache_control`: Anthropic marks the last block + * it can and moves the mark on as the conversation grows, so each step reads what the step before + * it wrote. Three of the four marks a request may carry. The progress reminder + * (progress-reminder.ts) lands in the same place on every call, so it never moves the prefix. + * + * Five minutes, the default: the steps of a turn start well inside that, and a longer life costs + * twice the input price to write. + * + * Clearing old tool results (context-room.ts) changes the prefix, which is why it clears down to a + * low watermark and then holds the boundary still: the cache is broken once per clearing, not once + * per step. + * + * A proxy in front of Claude that refuses the field is remembered for the life of the process, as + * one that refuses context editing is, and asked again without it. + */ +import type { Tool } from "@ag-ui/core"; +import { ChatAnthropic } from "@langchain/anthropic"; +import type { BaseChatModel } from "@langchain/core/language_models/chat_models"; +import { type BaseMessage, SystemMessage } from "@langchain/core/messages"; +import { links, providerWords, statusOf } from "./errors.ts"; + +/** A five-minute cache entry, Anthropic's default. */ +export const EPHEMERAL = { type: "ephemeral" } as const; + +/** The addresses that refused a cache mark, kept for the life of the process. */ +const cacheRefused = new Set(); +/** The models whose requests carry the marks. */ +const caching = new WeakSet(); + +function addressOf(model: ChatAnthropic): string { + return model.apiUrl?.trim() || "https://api.anthropic.com"; +} + +/** A Claude model whose requests carry the cache marks, unless its address has refused them. */ +export function withPromptCache(model: ChatAnthropic): ChatAnthropic { + if (!cacheRefused.has(addressOf(model))) caching.add(model); + return model; +} + +/** Whether this model's requests are sent with the cache marks. */ +export function cachesPrompt(model: BaseChatModel): model is ChatAnthropic { + return model instanceof ChatAnthropic && caching.has(model); +} + +/** Send this model, and every later one at its address, without the marks. */ +export function stopPromptCache(model: BaseChatModel): void { + if (!(model instanceof ChatAnthropic)) return; + cacheRefused.add(addressOf(model)); + caching.delete(model); +} + +/** A proxy in front of Claude that does not take a cache mark: a 4xx naming it. */ +export function refusesPromptCache(error: unknown): boolean { + return links(error).some((link) => { + const status = statusOf(link); + return ( + status !== undefined && + status < 500 && + /cache[_-]control/i.test( + `${providerWords(link)} ${String(link.message ?? "")}`, + ) + ); + }); +} + +/** The step's tools in Anthropic's own shape, the last one marked as the end of the tools. */ +export function cachedTools(tools: readonly Tool[]) { + return tools.map((tool, index) => ({ + name: tool.name, + description: tool.description, + input_schema: tool.parameters ?? { type: "object", properties: {} }, + ...(index === tools.length - 1 ? { cache_control: EPHEMERAL } : {}), + })); +} + +/** + * The messages with the system prompt that leads them marked as the end of the instructions. + * Everything else is the same object; an empty prompt can't carry the mark (the API refuses it). + */ +export function withCachedInstructions( + messages: readonly BaseMessage[], +): BaseMessage[] { + const first = messages[0]; + if (first?.getType() !== "system") return [...messages]; + const text = typeof first.content === "string" ? first.content : undefined; + if (!text?.trim()) return [...messages]; + return [ + new SystemMessage({ + ...(first.id ? { id: first.id } : {}), + content: [{ type: "text", text, cache_control: EPHEMERAL }] as never, + }), + ...messages.slice(1), + ]; +} diff --git a/agent-langgraph-ts/src/run.ts b/agent-langgraph-ts/src/run.ts index 9b784522b3..a17bd517fa 100644 --- a/agent-langgraph-ts/src/run.ts +++ b/agent-langgraph-ts/src/run.ts @@ -21,6 +21,11 @@ * REASONING_ENCRYPTED_VALUE on the call, and `encryptedValue` on it in the snapshot, which the * caller returns unchanged with the call (https://docs.ag-ui.com/spec/draft/events/reasoning). * - Every run ends with RUN_FINISHED or one RUN_ERROR (`errors.ts`). + * - No closing MESSAGES_SNAPSHOT. Every message a step adds is already in the caller's thread from + * its events (TEXT_MESSAGE_*, TOOL_CALL_*, TOOL_CALL_RESULT, REASONING_ENCRYPTED_VALUE), and a + * snapshot is the whole thread: each step of a long task sent the whole conversation back, N²/2 + * messages over a turn of N steps (FOUND IN THE WASTE AUDIT AFTER 1.2.7). A caller that takes + * a run with no snapshot builds the same thread, as it does for any AG-UI agent that sends none. * * THE ONE OPENBOT EXTENSION: MODEL ROUTING. This engine has no model of its own, so the caller may * name one in `forwardedProps`, AG-UI's channel for what only the agent reads: `openbotModel`, @@ -100,6 +105,14 @@ import { showsProgressUpdates, stopProgressUpdates, } from "./progress-updates.ts"; +import { + cachedTools, + cachesPrompt, + EPHEMERAL, + refusesPromptCache, + stopPromptCache, + withCachedInstructions, +} from "./prompt-cache.ts"; import { signatureOf, signatureOfDelta, @@ -414,12 +427,22 @@ async function answer(state: StateType, config: RunnableConfig) { const sent = run.reminder ? withReminders(room, places, run.reminder) : room; + // On Claude, the tools, the instructions and the conversation so far are marked for Anthropic's + // prompt cache, so each step reads back what the step before it wrote (prompt-cache.ts). + const cached = cachesPrompt(run.model); const messages = run.model instanceof ChatGoogle ? signedSteps(forGemini(sent), run.model.model) - : sent; - const model = - offered.length && run.model.bindTools + : cached + ? withCachedInstructions(sent) + : sent; + const model = cachesPrompt(run.model) + ? offered.length + ? run.model.bindTools(cachedTools(run.tools), { + cache_control: EPHEMERAL, + }) + : run.model.withConfig({ cache_control: EPHEMERAL }) + : offered.length && run.model.bindTools ? run.model.bindTools(offered) : run.model; try { @@ -432,6 +455,11 @@ async function answer(state: StateType, config: RunnableConfig) { stopContextEditing(run.model); continue; } + // One that does not take a prompt cache mark: asked as before, unmarked. + if (cached && refusesPromptCache(error)) { + stopPromptCache(run.model); + continue; + } // One that does not take Claude's progress updates: asked as before, with no lines. if (run.progressUpdates && refusesProgressUpdates(error)) { stopProgressUpdates(run.model); @@ -536,56 +564,6 @@ export const graph = new StateGraph(State) .addConditionalEdges("tools", afterRecall, ["answer", END]) .compile(); -/** - * A message the graph added, as AG-UI carries it, for the run's closing snapshot: its words as they - * streamed, Claude's progress updates included where the run asked for them, so the snapshot keeps - * the lines the person saw. - */ -function asAgui( - message: BaseMessage, - progressUpdates: boolean, -): Message | undefined { - const type = message.getType(); - if (type === "ai") { - const ai = message as AIMessage; - const calls = ai.tool_calls ?? []; - return { - id: ai.id ?? randomUUID(), - role: "assistant", - content: progressUpdates ? progressWords(ai.content) : ai.text, - ...(calls.length - ? { - toolCalls: calls.map((call) => { - const sealed = signatureOf(call); - return { - id: call.id ?? "", - type: "function" as const, - function: { - name: call.name, - arguments: JSON.stringify(call.args ?? {}), - }, - ...(sealed ? { encryptedValue: sealed } : {}), - }; - }), - } - : {}), - } as Message; - } - if (type === "tool") { - const tool = message as ToolMessage; - return { - id: tool.id ?? randomUUID(), - role: "tool", - toolCallId: tool.tool_call_id, - content: - typeof tool.content === "string" - ? tool.content - : JSON.stringify(tool.content), - } as Message; - } - return undefined; -} - /** * The calls this run made and left for the caller, in the order the model made them: every call * with no result in the run. AG-UI's `pendingToolCallIds` must be exactly these. @@ -707,15 +685,9 @@ export async function runAgent( }, ); keepStage(input.threadId, run.room.stage); + // No MESSAGES_SNAPSHOT: the step's events already built every message it added, in the + // caller's thread (see the module comment). const all = final.messages as BaseMessage[]; - const added = all - .slice(thread.length) - .map((message) => asAgui(message, run.progressUpdates)) - .filter((message): message is Message => !!message); - emit({ - type: "MESSAGES_SNAPSHOT", - messages: [...(input.messages ?? []), ...added], - } as BaseEvent); const pending = pendingCalls(all.slice(thread.length)); emit({ type: "RUN_FINISHED", diff --git a/agent-langgraph-ts/test/context-room.test.ts b/agent-langgraph-ts/test/context-room.test.ts index 9abf0d99dd..c957887040 100644 --- a/agent-langgraph-ts/test/context-room.test.ts +++ b/agent-langgraph-ts/test/context-room.test.ts @@ -13,7 +13,14 @@ import assert from "node:assert/strict"; import { test } from "node:test"; import { fakeProvider, type Recorded, type Turn } from "./fake-provider.ts"; -import { conversation, type Event, run, types, withEngine } from "./helpers.ts"; +import { + conversation, + type Event, + run, + threadAfter, + types, + withEngine, +} from "./helpers.ts"; const RESULTS = 60; const RESULT_CHARS = 8_000; @@ -324,15 +331,17 @@ test("OpenAI: a conversation past the model's window keeps going, old results cl const first = provider.requests[0]!.body; const { whole, notes } = shape(first); - // The last ten results whole, the two search_tools results whole, every other one a note. + // The oldest results are notes, down to the low watermark each time the thread passed the + // trigger as it grew; the two search_tools results and everything since the last clearing are + // whole (context-room.ts, `heldClearing`). assert.deepEqual(whole, [ "call_0", "call_1", - ...Array.from({ length: 10 }, (_, i) => `call_${50 + i}`), + ...Array.from({ length: 20 }, (_, i) => `call_${40 + i}`), ]); assert.deepEqual( notes, - Array.from({ length: 48 }, (_, i) => `call_${2 + i}`), + Array.from({ length: 38 }, (_, i) => `call_${2 + i}`), ); // Every call still has its result, so no provider sees an orphan. assert.deepEqual( @@ -355,18 +364,17 @@ test("OpenAI: a conversation past the model's window keeps going, old results cl true, ); - // The next step, in the run that carries the turn on, clears again; the new result is whole. + // The next step, in the run that carries the turn on, holds the boundary: the same notes, so the + // prefix the provider cached is unchanged, and the new result whole. const second = shape(provider.requests[1]!.body); assert.ok(second.whole.includes("call_new")); - assert.equal(second.whole.length, 12); - - // Only what was sent was cut: the thread the run hands back is whole. - const snapshot = result.events.find( - (event) => event.type === "MESSAGES_SNAPSHOT", - )!; - const stored = (snapshot.messages as Block[]).filter( - (message) => message.role === "tool", - ); + assert.deepEqual(second.notes, notes); + assert.equal(second.whole.length, 23); + + // Only what was sent was cut: the thread the caller holds after the run is whole. + const stored = ( + (await threadAfter(input, result.events)) as unknown as Block[] + ).filter((message) => message.role === "tool"); assert.equal(stored.length, RESULTS); for (let i = 0; i < RESULTS; i += 1) assert.equal(stored[i]!.content, resultBody(i)); @@ -432,8 +440,8 @@ test("Claude behind a proxy that refuses context editing: cleared here instead, ), ); const { whole, notes } = shape(request.body); - assert.equal(whole.length, 12); - assert.equal(notes.length, 48); + assert.equal(whole.length, 22); + assert.equal(notes.length, 38); } } finally { await provider.close(); @@ -454,7 +462,7 @@ test("A smaller window: the refused call is retried cleared harder, and the run // run after the hand-back starts there and is not refused first: a long task carried on step // after step is refused once, not once a step. assert.equal(provider.requests.length, 3); - assert.equal(shape(provider.requests[0]!.body).whole.length, 12); + assert.equal(shape(provider.requests[0]!.body).whole.length, 22); const retried = shape(provider.requests[1]!.body); assert.deepEqual(retried.whole, [ "call_0", @@ -607,3 +615,106 @@ test("A Bot with no tools is not offered recall_earlier_results", async () => { await provider.close(); } }); + +/* + * THE CLEARING BOUNDARY HOLDS STILL BETWEEN CLEARINGS. Found in the waste audit after 1.2.7: past + * the trigger every step cleared all but the last ten results, so each new result pushed one more + * out and what the provider had cached changed on every step of a long task. A 200-step task, each + * step a run of its own as the server carries it on, with results from 1,000 to 12,000 characters: + * what one step sends is exactly the start of what the next sends, except on the few steps that + * clear, and each of those clears down to the low watermark. + */ +test("A 200-step task: the cleared prefix changes only when the trigger is passed again, not on every step", async () => { + const STEPS = 200; + const provider = await fakeProvider(() => ({ text: "ok" })); + const body = (i: number) => + JSON.stringify({ + page: i, + rows: Array.from({ length: 20 + ((i * 37) % 150) }, (_, row) => ({ + id: `row-${i}-${row}`, + etag: `${(i * 2654435761 + row * 40503) % 4294967296}`.padStart( + 10, + "0", + ), + status: row % 3 ? "open" : "closed", + })), + }); + const base = conversation(); + const thread: Record[] = [ + ...(base.messages as Record[]).slice(0, 2), + { id: "u1", role: "user", content: "Read every page of the register." }, + ]; + try { + await withEngine({ env: openAIEnv(provider.base) }, async (engine) => { + for (let i = 0; i < STEPS; i += 1) { + thread.push( + { + id: `a${i}`, + role: "assistant", + content: "", + toolCalls: [ + { + id: `call_${i}`, + type: "function", + function: { + name: "lookup", + arguments: JSON.stringify({ q: `page ${i}` }), + }, + }, + ], + }, + { + id: `t${i}`, + role: "tool", + toolCallId: `call_${i}`, + content: body(i), + }, + ); + const result = await run( + engine, + conversation({ + runId: `run-${i}`, + messages: [...thread], + tools: [LOOKUP], + forwardedProps: { openbotModel: OPENAI_MODEL }, + }), + ); + assert.equal(runEnd(result.events).type, "RUN_FINISHED"); + } + }); + assert.equal(provider.requests.length, STEPS); + const sent = provider.requests.map( + (request) => request.body.messages as Block[], + ); + const tokens = (messages: Block[]) => JSON.stringify(messages).length / 2.3; + let changed = 0; + for (let step = 1; step < STEPS; step += 1) { + const before = sent[step - 1]!; + const now = sent[step]!; + const kept = before.every( + (message, index) => + JSON.stringify(message) === JSON.stringify(now[index]), + ); + if (kept) continue; + changed += 1; + // A step that clears frees a stretch: what it sends is well under what the step before sent. + assert.ok( + tokens(now) < tokens(before) - 20_000, + `step ${step} cleared a stretch, not one result`, + ); + } + // The task passed the trigger many times over (about 1.4 million characters of results); the + // prefix changed only on the steps that cleared a stretch. + assert.ok( + JSON.stringify(sent.at(-1)).length < JSON.stringify(thread).length / 4, + ); + assert.ok(changed >= 3, `the task cleared ${changed} times`); + assert.ok(changed <= STEPS / 10, `the prefix changed on ${changed} steps`); + // The last ten results always went whole. + const last = shape(provider.requests.at(-1)!.body).results; + for (let i = STEPS - 10; i < STEPS; i += 1) + assert.equal(last.get(`call_${i}`), body(i)); + } finally { + await provider.close(); + } +}); diff --git a/agent-langgraph-ts/test/hand-back.test.ts b/agent-langgraph-ts/test/hand-back.test.ts index ea9ee063a4..bad23cad14 100644 --- a/agent-langgraph-ts/test/hand-back.test.ts +++ b/agent-langgraph-ts/test/hand-back.test.ts @@ -19,6 +19,7 @@ import { oldCallbackEnv, pendingOf, run, + threadAfter, tripwire, types, withEngine, @@ -325,12 +326,12 @@ test("Parallel calls hand back together, in one run end, in the order the model .sort(), ["call_a", "call_b", "call_c"], ); - // The snapshot holds the step's one assistant message, its three calls unanswered. - const snapshot = result.events.find( - (event) => event.type === "MESSAGES_SNAPSHOT", - )!; + // The caller's thread holds the step's one assistant message, its three calls unanswered. const last = ( - snapshot.messages as { role: string; toolCalls?: { id: string }[] }[] + (await threadAfter(conversation(), result.events)) as { + role: string; + toolCalls?: { id: string }[]; + }[] ).at(-1)!; assert.equal(last.role, "assistant"); assert.deepEqual( @@ -600,17 +601,19 @@ for (const [gemini, id] of [ encryptedValue: "SIGNATURE_MARKER", }, ); - const snapshot = first.events.find( - (event) => event.type === "MESSAGES_SNAPSHOT", - )!; + // The caller applies the event to the call in its own thread, with no snapshot. + const held = await threadAfter( + conversation({ tools: [weather], forwardedProps: props }), + first.events, + ); const call = ( - snapshot.messages as { + held as { toolCalls?: { id: string; encryptedValue?: string }[]; }[] ).at(-1)!.toolCalls![0]!; assert.equal(call.encryptedValue, "SIGNATURE_MARKER"); - // OpenBot answers it and sends the thread back, the call as the snapshot held it. + // OpenBot answers it and sends the thread back, the call as its thread holds it. const second = await run( base, conversation({ @@ -618,7 +621,7 @@ for (const [gemini, id] of [ tools: [weather], forwardedProps: props, messages: [ - ...(snapshot.messages as unknown[]), + ...(held as unknown[]), { id: "t-weather", role: "tool", diff --git a/agent-langgraph-ts/test/helpers.ts b/agent-langgraph-ts/test/helpers.ts index e25207e369..cb12f23c46 100644 --- a/agent-langgraph-ts/test/helpers.ts +++ b/agent-langgraph-ts/test/helpers.ts @@ -1,6 +1,13 @@ /** Drive the engine as the server does: a real HTTP AG-UI run against `createEngine`. */ import { createServer } from "node:http"; import type { AddressInfo } from "node:net"; +import { + AbstractAgent, + type BaseEvent, + type Message, + type RunAgentInput, +} from "@ag-ui/client"; +import { from, type Observable } from "rxjs"; import { createEngine, type ServerOptions } from "../src/server.ts"; export const TOKEN = "engine-test-token"; @@ -104,6 +111,39 @@ export const WEATHER_TOOL = { }, }; +/** An agent that plays back a run's recorded events, so @ag-ui/client applies them as it would. */ +class Playback extends AbstractAgent { + private readonly recorded: Event[]; + constructor(recorded: Event[], messages: Message[], threadId: string) { + super({ initialMessages: messages, threadId }); + this.recorded = recorded; + } + run(_: RunAgentInput): Observable { + return from(this.recorded as unknown as BaseEvent[]); + } +} + +/** + * The thread the caller holds after a run: the messages it sent, with the run's events applied by + * @ag-ui/client itself, as OpenBot's server and the browser apply them. + */ +export async function threadAfter( + input: Record, + recorded: Event[], +): Promise { + const agent = new Playback( + recorded, + structuredClone(input.messages as Message[]), + String(input.threadId), + ); + await agent.runAgent({ + runId: String(input.runId), + tools: [], + context: [], + }); + return agent.messages; +} + export function types(list: Event[]): string[] { return list.map((event) => event.type); } diff --git a/agent-langgraph-ts/test/model-route.test.ts b/agent-langgraph-ts/test/model-route.test.ts index 63f8f1fc8e..17da22fe11 100644 --- a/agent-langgraph-ts/test/model-route.test.ts +++ b/agent-langgraph-ts/test/model-route.test.ts @@ -19,7 +19,13 @@ import { fakeProvider, type Responder, } from "./fake-provider.ts"; -import { conversation, run, WEATHER_TOOL, withEngine } from "./helpers.ts"; +import { + conversation, + run, + threadAfter, + WEATHER_TOOL, + withEngine, +} from "./helpers.ts"; import { type Gateway, liveUpstreams, @@ -305,9 +311,10 @@ async function conversationAcross(legs: Leg[]) { "RUN_FINISHED", `leg ${index} on ${leg.side.model}: ${inspect(result.events.at(-1))}`, ); - const snapshot = result.events.findLast( - (event) => event.type === "MESSAGES_SNAPSHOT", - )?.messages as Record[]; + const snapshot = (await threadAfter( + ask({ runId: `run-leg-${index}`, messages: asked }), + result.events, + )) as unknown as Record[]; if (index === legs.length - 1) { assert.match(words(result.events), /pineapple/i); break; diff --git a/agent-langgraph-ts/test/no-snapshot.test.ts b/agent-langgraph-ts/test/no-snapshot.test.ts new file mode 100644 index 0000000000..ff70291845 --- /dev/null +++ b/agent-langgraph-ts/test/no-snapshot.test.ts @@ -0,0 +1,127 @@ +/** + * A STEP STREAMS WHAT IT ADDED, NOT THE WHOLE THREAD. Found in the waste audit after 1.2.7: every run + * ended with a MESSAGES_SNAPSHOT of the whole conversation, and every step of a long task is a run, + * so a turn of N steps streamed about N²/2 messages back to the server. The events already carry + * every message a step adds; the caller, applying them with @ag-ui/client as OpenBot's server and + * the browser do, holds the same thread the snapshot used to give it. + */ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { fakeProvider } from "./fake-provider.ts"; +import { + conversation, + pendingOf, + run, + threadAfter, + types, + WEATHER_TOOL, + withEngine, +} from "./helpers.ts"; + +const STEPS = 150; +const RESULT = (i: number) => + JSON.stringify({ + page: i, + rows: Array.from({ length: 40 }, (_, row) => ({ + id: `row-${i}-${row}`, + city: "Paris", + reading: (i * 31 + row) % 40, + })), + }); + +/** A long task's thread as the server sends a late step: 150 tool steps behind the latest. */ +function lateStep() { + const base = conversation(); + const messages: Record[] = [ + ...(base.messages as Record[]), + ]; + for (let i = 0; i < STEPS; i += 1) + messages.push( + { + id: `step-a${i}`, + role: "assistant", + content: i % 10 === 0 ? `Checked ${i} pages so far.` : "", + toolCalls: [ + { + id: `call_${i}`, + type: "function", + function: { + name: "get_weather", + arguments: JSON.stringify({ city: `Paris ${i}` }), + }, + }, + ], + }, + { + id: `step-t${i}`, + role: "tool", + toolCallId: `call_${i}`, + content: RESULT(i), + }, + ); + return conversation({ + messages, + tools: [WEATHER_TOOL], + forwardedProps: { openbotModel: { model: "gpt-5.2" } }, + }); +} + +test("A late step of a long task streams only its own messages, and the caller's thread is whole", async () => { + const provider = await fakeProvider(() => ({ + text: "One more page.", + calls: [{ id: "call_next", name: "get_weather", args: { city: "Lyon" } }], + })); + try { + const input = lateStep(); + const sent = JSON.stringify(input.messages).length; + const result = await withEngine( + { + env: { + BOT_PROVIDER: "openai", + OPENAI_API_KEY: "sk-test", + OPENAI_BASE_URL: `${provider.base}/v1`, + }, + }, + (base) => run(base, input), + ); + assert.equal(result.events.at(-1)!.type, "RUN_FINISHED"); + assert.deepEqual( + pendingOf(result.events), + ["call_next"], + JSON.stringify(types(result.events)), + ); + assert.ok(!types(result.events).includes("MESSAGES_SNAPSHOT")); + // What came back is the step, a few hundred bytes, not the thread of several hundred thousand. + const streamed = JSON.stringify(result.events).length; + assert.ok(sent > 300_000, `the thread is ${sent} characters`); + assert.ok(streamed < 5_000, `the step streamed ${streamed} characters`); + + // The caller's thread: everything it sent, unchanged, then the step's message, its words and + // its call. + const thread = (await threadAfter(input, result.events)) as { + id: string; + role: string; + content?: string; + toolCalls?: { + id: string; + function: { name: string; arguments: string }; + }[]; + }[]; + const asked = input.messages as { id: string }[]; + assert.equal(thread.length, asked.length + 1); + assert.deepEqual(thread.slice(0, asked.length), asked); + const step = thread.at(-1)!; + assert.equal(step.role, "assistant"); + assert.equal(step.content, "One more page."); + assert.deepEqual( + step.toolCalls?.map((call) => [ + call.id, + call.function.name, + JSON.parse(call.function.arguments), + ]), + [["call_next", "get_weather", { city: "Lyon" }]], + ); + } finally { + await provider.close(); + } +}); diff --git a/agent-langgraph-ts/test/progress-reminder.test.ts b/agent-langgraph-ts/test/progress-reminder.test.ts index 874de98dd1..1f934b2ff1 100644 --- a/agent-langgraph-ts/test/progress-reminder.test.ts +++ b/agent-langgraph-ts/test/progress-reminder.test.ts @@ -23,6 +23,7 @@ import { type Event, pendingOf, run, + threadAfter, WEATHER_TOOL, withEngine, } from "./helpers.ts"; @@ -119,9 +120,10 @@ async function runJob(job: Job): Promise<{ "RUN_FINISHED", `run ${runs}`, ); - snapshot = result.events.findLast( - (event) => event.type === "MESSAGES_SNAPSHOT", - )?.messages as Record[]; + snapshot = (await threadAfter( + { ...input, runId: `run-${runs}` }, + result.events, + )) as unknown as Record[]; const pending = pendingOf(result.events) ?? []; if (pending.length === 0) break; input = { @@ -301,9 +303,10 @@ test("A Claude proxy that refuses a system message mid-thread: the job carries o assert.equal(result.events.at(-1)?.type, "RUN_FINISHED"); const pending = pendingOf(result.events) ?? []; if (pending.length === 0) break; - const snapshot = result.events.findLast( - (event) => event.type === "MESSAGES_SNAPSHOT", - )?.messages as Record[]; + const snapshot = (await threadAfter( + { ...input, runId: `run-${runs}` }, + result.events, + )) as unknown as Record[]; input = { ...input, messages: [ diff --git a/agent-langgraph-ts/test/progress-updates.test.ts b/agent-langgraph-ts/test/progress-updates.test.ts index ce4d06d767..30134f5116 100644 --- a/agent-langgraph-ts/test/progress-updates.test.ts +++ b/agent-langgraph-ts/test/progress-updates.test.ts @@ -10,8 +10,14 @@ */ import assert from "node:assert/strict"; import { test } from "node:test"; -import { type Responder, fakeProvider } from "./fake-provider.ts"; -import { conversation, run, WEATHER_TOOL, withEngine } from "./helpers.ts"; +import { fakeProvider, type Responder } from "./fake-provider.ts"; +import { + conversation, + run, + threadAfter, + WEATHER_TOOL, + withEngine, +} from "./helpers.ts"; const BETA = "thinking-display-updates-2026-08-18"; const CONTEXT_EDITING_BETA = "context-management-2025-06-27"; @@ -122,11 +128,13 @@ test("A progress update is one line of the step's words before its call; an empt starts[0]!.messageId, events[at("TOOL_CALL_START")]!.parentMessageId, ); - // The run's snapshot keeps the line, so it is still there once the run ends. - const snapshot = events.findLast( - (event) => event.type === "MESSAGES_SNAPSHOT", - )?.messages as { role: string; content?: string; toolCalls?: unknown[] }[]; - const step = snapshot.at(-1)!; + // The caller's thread keeps the line, so it is still there once the run ends. + const thread = (await threadAfter(ask("claude-opus-5-5"), events)) as { + role: string; + content?: string; + toolCalls?: unknown[]; + }[]; + const step = thread.at(-1)!; assert.equal(step.role, "assistant"); assert.equal(step.content, LINE); assert.equal(step.toolCalls?.length, 1); @@ -149,10 +157,15 @@ test("A model not asked for progress updates shows no thinking, as before", asyn assert.ok( !result.events.some((event) => event.type.startsWith("TEXT_MESSAGE")), ); - const snapshot = result.events.findLast( - (event) => event.type === "MESSAGES_SNAPSHOT", - )?.messages as { content?: string }[]; - assert.equal(snapshot.at(-1)!.content, ""); + // The step is its call alone, with no words. + const thread = (await threadAfter(ask("claude-opus-5"), result.events)) as { + role: string; + content?: string; + toolCalls?: unknown[]; + }[]; + assert.equal(thread.at(-1)!.role, "assistant"); + assert.ok(!thread.at(-1)!.content); + assert.equal(thread.at(-1)!.toolCalls?.length, 1); } finally { await provider.close(); } diff --git a/agent-langgraph-ts/test/prompt-cache.live.test.ts b/agent-langgraph-ts/test/prompt-cache.live.test.ts new file mode 100644 index 0000000000..102c38392f --- /dev/null +++ b/agent-langgraph-ts/test/prompt-cache.live.test.ts @@ -0,0 +1,304 @@ +/** + * Anthropic's prompt cache, measured on Anthropic's real API: a two-step tool turn, sent the way + * OpenBot's model gateway sends it (`openbotModelRoute` via `anthropic`, the body passed through + * unchanged), must read the second step's prefix back from the cache. + * + * Runs only with OPENBOT_LIVE_ANTHROPIC_KEY set (it spends a few cents); skipped otherwise. The request-shape + * test in prompt-cache.test.ts holds the same rule in CI without a key. + */ +import assert from "node:assert/strict"; +import { createHash } from "node:crypto"; +import { + createServer, + type IncomingMessage, + type ServerResponse, +} from "node:http"; +import type { AddressInfo } from "node:net"; +import { test } from "node:test"; +import { conversation, run, WEATHER_TOOL, withEngine } from "./helpers.ts"; + +const KEY = process.env.OPENBOT_LIVE_ANTHROPIC_KEY?.trim(); +const MODEL = "claude-sonnet-5-5"; + +type Usage = { + input_tokens?: number; + cache_read_input_tokens?: number; + cache_creation_input_tokens?: number; +}; + +/** + * OpenBot's model gateway in miniature: `/anthropic/v1/messages` passed on to Anthropic byte for + * byte, as server/src/model-gateway forwards an API-key connection, with each answer's usage read + * off its `message_start`. + */ +async function passthrough() { + const usage: Usage[] = []; + const server = createServer( + async (request: IncomingMessage, response: ServerResponse) => { + const chunks: Buffer[] = []; + for await (const chunk of request) chunks.push(chunk as Buffer); + const path = (request.url ?? "/").replace(/^\/anthropic/, ""); + const headers: Record = { + "content-type": "application/json", + "anthropic-version": String( + request.headers["anthropic-version"] ?? "2023-06-01", + ), + "x-api-key": String(request.headers["x-api-key"] ?? ""), + }; + const authorization = request.headers.authorization; + if (authorization) headers.authorization = String(authorization); + if (!headers["x-api-key"]) delete headers["x-api-key"]; + const beta = request.headers["anthropic-beta"]; + if (beta) headers["anthropic-beta"] = String(beta); + const upstream = await fetch(`https://api.anthropic.com${path}`, { + method: request.method ?? "POST", + headers, + body: Buffer.concat(chunks), + }); + const text = await upstream.text(); + for (const line of text.split("\n")) { + if (!line.startsWith("data:")) continue; + const event = JSON.parse(line.slice(5).trim()) as { + type?: string; + message?: { usage?: Usage }; + }; + if (event.type === "message_start" && event.message?.usage) + usage.push(event.message.usage); + } + response.writeHead(upstream.status, { + "content-type": + upstream.headers.get("content-type") ?? "application/json", + }); + response.end(text); + }, + ); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const { port } = server.address() as AddressInfo; + return { + base: `http://127.0.0.1:${port}`, + usage, + close: () => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + }; +} + +/** A built-in Bot's instructions are about ten thousand tokens; these are as long. */ +function longRole(): string { + const rules: string[] = [ + "You are Test Bot. Use get_weather for any question about the weather, then answer in one sentence.", + ]; + for (let index = 1; index <= 300; index += 1) + rules.push( + `Rule ${index}: when a person asks about topic number ${index}, answer plainly, cite the tool you used, keep the reply short, and never invent a figure the tools did not give you.`, + ); + return rules.join("\n"); +} + +const EXTRA_TOOLS = Array.from({ length: 12 }, (_, index) => ({ + name: `lookup_record_${index}`, + description: `Look up one record in register ${index} by its id, and return its fields as JSON.`, + parameters: { + type: "object", + properties: { + id: { type: "string", description: "The record's id." }, + fields: { + type: "array", + items: { type: "string" }, + description: "Which fields to return; all when left out.", + }, + }, + required: ["id"], + }, +})); + +/** A long task's thread: `count` lookups, each answered with about 2,000 tokens of text. */ +function longTask(count: number, nonce: string) { + const messages: Record[] = [ + { + id: "standing-role:test-bot", + role: "system", + content: `${longRole()}\nRun ${nonce}.`, + }, + { id: "u1", role: "user", content: "Read every record in register 1." }, + ]; + for (let i = 0; i < count; i += 1) { + messages.push({ + id: `a${i}`, + role: "assistant", + content: "", + toolCalls: [ + { + id: `call_${i}`, + type: "function", + function: { + name: "lookup_record_1", + arguments: JSON.stringify({ id: `r${i}` }), + }, + }, + ], + }); + // Ids and digests, which tokenise as densely as real tool output does. + const rows = Array.from({ length: 60 }, (_, row) => { + const digest = createHash("sha256") + .update(`${nonce}:${i}:${row}`) + .digest("hex"); + return `{"record":"r${i}","row":${row},"etag":"${digest}","owner":"${digest.slice(0, 12)}"}`; + }).join("\n"); + messages.push({ + id: `t${i}`, + role: "tool", + toolCallId: `call_${i}`, + content: rows, + }); + } + return messages; +} + +test("a long Claude task past the clearing trigger reads its prefix back on every step", { + skip: !KEY && "OPENBOT_LIVE_ANTHROPIC_KEY is not set", +}, async () => { + const gateway = await passthrough(); + try { + const env = { OPENBOT_MODEL_GATEWAY_URL: gateway.base }; + const forwardedProps = { + openbotModel: { model: MODEL }, + openbotModelRoute: { via: "anthropic", token: KEY }, + }; + const nonce = `${Date.now()}-${Math.random()}`; + const tools = [WEATHER_TOOL, ...EXTRA_TOOLS]; + /** Each run's first model call: a run may also answer a recall itself and ask again. */ + const firsts: number[] = []; + await withEngine({ env }, async (base) => { + // Three steps of one task, each a run with one more result, as the server carries it on: + // about 110,000 tokens, past the trigger, so Anthropic clears old results on its side. + for (const count of [75, 76, 77]) { + firsts.push(gateway.usage.length); + const result = await run( + base, + conversation({ + runId: `run-${count}`, + messages: longTask(count, nonce), + tools, + forwardedProps, + }), + ); + assert.ok( + result.events.some((event) => event.type === "RUN_FINISHED"), + JSON.stringify( + result.events.filter((event) => event.type === "RUN_ERROR"), + ), + ); + } + }); + console.log("long task usage", JSON.stringify(gateway.usage)); + const total = (usage: Usage) => + (usage.input_tokens ?? 0) + + (usage.cache_read_input_tokens ?? 0) + + (usage.cache_creation_input_tokens ?? 0); + for (const step of [1, 2]) { + const before = gateway.usage[firsts[step - 1]!]!; + const now = gateway.usage[firsts[step]!]!; + // All the step before sent is read back; only the newest result is new. + assert.ok( + (now.cache_read_input_tokens ?? 0) >= total(before) - 50, + `step ${step + 1} reads back what step ${step} sent: ${JSON.stringify({ before, now })}`, + ); + } + } finally { + await gateway.close(); + } +}); + +test("a two-step tool turn reads its prefix back from Anthropic's cache on the second step", { + skip: !KEY && "OPENBOT_LIVE_ANTHROPIC_KEY is not set", +}, async () => { + const gateway = await passthrough(); + try { + const env = { OPENBOT_MODEL_GATEWAY_URL: gateway.base }; + const forwardedProps = { + openbotModel: { model: MODEL }, + openbotModelRoute: { via: "anthropic", token: KEY }, + }; + // A fresh thread each time, so no earlier run of this test warms the cache for it. + const nonce = `${Date.now()}-${Math.random()}`; + const messages = [ + { + id: "standing-role:test-bot", + role: "system", + content: `${longRole()}\nRun ${nonce}.`, + }, + { + id: "u1", + role: "user", + content: "What is the weather in Paris right now?", + }, + ]; + const tools = [WEATHER_TOOL, ...EXTRA_TOOLS]; + await withEngine({ env }, async (base) => { + const first = await run( + base, + conversation({ messages, tools, forwardedProps }), + ); + const start = first.events.find( + (event) => event.type === "TOOL_CALL_START", + ); + assert.ok( + start, + `the first step calls get_weather: ${JSON.stringify(first.events.filter((event) => event.type === "RUN_ERROR"))}`, + ); + const callId = String(start.toolCallId); + const second = await run( + base, + conversation({ + runId: "run-2", + messages: [ + ...messages, + { + id: "a1", + role: "assistant", + content: "", + toolCalls: [ + { + id: callId, + type: "function", + function: { + name: "get_weather", + arguments: JSON.stringify({ city: "Paris" }), + }, + }, + ], + }, + { + id: "t1", + role: "tool", + toolCallId: callId, + content: "Paris: 14 C, light rain.", + }, + ], + tools, + forwardedProps, + }), + ); + assert.ok( + second.events.some((event) => event.type === "RUN_FINISHED"), + "the second step finishes", + ); + }); + assert.equal(gateway.usage.length, 2); + const [one, two] = gateway.usage as [Usage, Usage]; + console.log("step usage", JSON.stringify(gateway.usage)); + assert.ok( + (one.cache_creation_input_tokens ?? 0) > 5_000, + `the first step writes the prefix to the cache: ${JSON.stringify(one)}`, + ); + assert.ok( + (two.cache_read_input_tokens ?? 0) > 5_000, + `the second step reads it back: ${JSON.stringify(two)}`, + ); + } finally { + await gateway.close(); + } +}); diff --git a/agent-langgraph-ts/test/prompt-cache.test.ts b/agent-langgraph-ts/test/prompt-cache.test.ts new file mode 100644 index 0000000000..9a7a2e410c --- /dev/null +++ b/agent-langgraph-ts/test/prompt-cache.test.ts @@ -0,0 +1,156 @@ +/** + * Anthropic's prompt cache marks, as Claude receives them (prompt-cache.ts): the last tool, the + * system prompt and the request's own top-level mark for the conversation, on every step; nothing on + * any other provider; and a proxy that refuses the field asked again without it, for good. + * + * test/prompt-cache.live.test.ts measures the same requests on Anthropic's own API, where the second + * step of a turn reads its whole prefix back from the cache. + */ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { always, fakeProvider } from "./fake-provider.ts"; +import { conversation, run, WEATHER_TOOL, withEngine } from "./helpers.ts"; + +const EPHEMERAL = { type: "ephemeral" }; + +type Block = { type?: string; text?: string; cache_control?: unknown }; + +/** Every cache mark in a request, by where it sits. */ +function marks(body: Record): string[] { + const found: string[] = []; + if (body.cache_control) found.push("top-level"); + for (const tool of (body.tools as { + name: string; + cache_control?: unknown; + }[]) ?? []) + if (tool.cache_control) found.push(`tool:${tool.name}`); + if (Array.isArray(body.system)) + for (const block of body.system as Block[]) + if (block.cache_control) found.push("system"); + for (const message of (body.messages as { content: unknown }[]) ?? []) + if (Array.isArray(message.content)) + for (const block of message.content as Block[]) + if (block.cache_control) found.push("message"); + return found; +} + +const claude = (base: string) => ({ + BOT_PROVIDER: "anthropic", + ANTHROPIC_API_KEY: "sk-ant-test", + ANTHROPIC_BASE_URL: base, +}); + +test("Claude: the last tool, the system prompt and the conversation are marked for the cache", async () => { + const provider = await fakeProvider(always({ text: "ok" })); + try { + await withEngine({ env: claude(provider.base) }, async (base) => { + const result = await run( + base, + conversation({ + tools: [WEATHER_TOOL], + forwardedProps: { openbotModel: { model: "claude-sonnet-5-5" } }, + }), + ); + assert.equal(result.events.at(-1)!.type, "RUN_FINISHED"); + }); + const { body } = provider.requests[0]!; + assert.deepEqual(marks(body), [ + "top-level", + "tool:recall_earlier_results", + "system", + ]); + assert.deepEqual(body.cache_control, EPHEMERAL); + // The instructions are the same words, now a block that carries the mark. + const system = body.system as Block[]; + assert.equal(system.length, 1); + assert.ok(system[0]!.text!.includes("STANDING_ROLE_MARKER")); + assert.deepEqual(system[0]!.cache_control, EPHEMERAL); + } finally { + await provider.close(); + } +}); + +test("Claude without tools: the system prompt and the conversation are marked", async () => { + const provider = await fakeProvider(always({ text: "ok" })); + try { + await withEngine({ env: claude(provider.base) }, async (base) => { + await run( + base, + conversation({ + forwardedProps: { openbotModel: { model: "claude-sonnet-5-5" } }, + }), + ); + }); + assert.deepEqual(marks(provider.requests[0]!.body), [ + "top-level", + "system", + ]); + } finally { + await provider.close(); + } +}); + +test("OpenAI is sent no cache marks: it caches a prefix by itself", async () => { + const provider = await fakeProvider(always({ text: "ok" })); + try { + const env = { + BOT_PROVIDER: "openai", + OPENAI_API_KEY: "sk-test", + OPENAI_BASE_URL: `${provider.base}/v1`, + }; + await withEngine({ env }, async (base) => { + await run( + base, + conversation({ + tools: [WEATHER_TOOL], + forwardedProps: { openbotModel: { model: "gpt-5.2" } }, + }), + ); + }); + assert.ok( + !JSON.stringify(provider.requests[0]!.body).includes("cache_control"), + ); + } finally { + await provider.close(); + } +}); + +// Last in this file: a refusal is remembered for the life of the process, by address. +test("a proxy that refuses cache_control is asked again without it, and never sent it again", async () => { + const provider = await fakeProvider((request) => + JSON.stringify(request.body).includes("cache_control") + ? { + status: 400, + body: { + type: "error", + error: { + type: "invalid_request_error", + message: "cache_control: Extra inputs are not permitted", + }, + }, + } + : { text: "ok" }, + ); + try { + await withEngine({ env: claude(provider.base) }, async (base) => { + for (const runId of ["run-1", "run-2"]) { + const result = await run( + base, + conversation({ + runId, + tools: [WEATHER_TOOL], + forwardedProps: { openbotModel: { model: "claude-sonnet-5-5" } }, + }), + ); + assert.equal(result.events.at(-1)!.type, "RUN_FINISHED"); + } + }); + // Refused once, asked again unmarked, and the second run was never marked. + assert.deepEqual( + provider.requests.map((request) => marks(request.body).length > 0), + [true, false, false], + ); + } finally { + await provider.close(); + } +}); diff --git a/agent-langgraph-ts/test/thought-signatures.test.ts b/agent-langgraph-ts/test/thought-signatures.test.ts index 9128fc7633..269447b261 100644 --- a/agent-langgraph-ts/test/thought-signatures.test.ts +++ b/agent-langgraph-ts/test/thought-signatures.test.ts @@ -13,14 +13,20 @@ * signature it gave, or with one it never gave. */ import assert from "node:assert/strict"; -import { inspect } from "node:util"; import { test } from "node:test"; +import { inspect } from "node:util"; import { type FakeProvider, fakeProvider, type Responder, } from "./fake-provider.ts"; -import { type Event, pendingOf, run, withEngine } from "./helpers.ts"; +import { + type Event, + pendingOf, + run, + threadAfter, + withEngine, +} from "./helpers.ts"; import { modelGateway } from "./model-gateway.ts"; const SEARCH = { @@ -50,9 +56,15 @@ function words(events: Event[]): string { .join(""); } -function snapshotOf(events: Event[]): Message[] { - return events.findLast((event) => event.type === "MESSAGES_SNAPSHOT")! - .messages as Message[]; +/** The thread the caller holds after a run that was sent `messages`, its events applied. */ +async function threadOf( + messages: Message[], + events: Event[], +): Promise { + return (await threadAfter( + { threadId: "thread-gemini", runId: "run", messages }, + events, + )) as unknown as Message[]; } function finished(events: Event[], label: string) { @@ -178,10 +190,10 @@ test("Gemini 3 behind the model gateway: a turn of two tool steps, one of them p const first = await ask("run-1", "gemini-3.5-flash", asked); finished(first, "step 1"); assert.deepEqual(pendingOf(first), ["function-call-1"]); - const afterFirst = snapshotOf(first); + const afterFirst = await threadOf(asked, first); - // Step 2: OpenBot answers the call and sends the thread back, as the snapshot held it. - const second = await ask("run-2", "gemini-3.5-flash", [ + // Step 2: OpenBot answers the call and sends the thread back, as its thread holds it. + const secondAsked: Message[] = [ ...afterFirst, { id: "t1", @@ -189,10 +201,11 @@ test("Gemini 3 behind the model gateway: a turn of two tool steps, one of them p toolCallId: "function-call-1", content: "search_tools found GitHub. Reading R-1.", }, - ]); + ]; + const second = await ask("run-2", "gemini-3.5-flash", secondAsked); finished(second, "step 2"); assert.deepEqual(pendingOf(second), ["function-call-2", "function-call-3"]); - const afterSecond = snapshotOf(second); + const afterSecond = await threadOf(secondAsked, second); // Step 3: both results back; Gemini answers in words. const third = await ask("run-3", "gemini-3.5-flash", [ diff --git a/agent-mastra/src/mastra/index.test.ts b/agent-mastra/src/mastra/index.test.ts index 4706367c6d..bb47ca3631 100644 --- a/agent-mastra/src/mastra/index.test.ts +++ b/agent-mastra/src/mastra/index.test.ts @@ -1139,7 +1139,11 @@ describe("OpenBot Mastra progress reminder", () => { "The person hasn't heard from you in a while: say in a few words what you're doing, then continue. If your instructions say nobody is watching this run, just continue."; const REMINDER_IN_TURN = `(A note from the app running this conversation, not a message from the person.) ${REMINDER}`; - type Sent = { messages: Record[]; beta: string | null }; + type Sent = { + messages: Record[]; + beta: string | null; + body: Record; + }; function sse(events: [string, unknown][]) { return events @@ -1254,7 +1258,7 @@ describe("OpenBot Mastra progress reminder", () => { // The shape @ag-ui/mastra gives a run's tools (`buildClientTools`). "const clientTools = { read_record: { id: 'read_record', description: 'Read one record of the ledger by its id.',", " inputSchema: { type: 'object', properties: { id: { type: 'string' } }, required: ['id'] } } };", - "let messages = [{ id: 'u1', role: 'user', content: 'Read the ledger from R1 to the end.' }];", + "let messages = [{ id: 'u1', role: 'user', content: (process.env.JOB_PREAMBLE ?? '') + 'Read the ledger from R1 to the end.' }];", "const chunks = [];", "const said = [];", "for (let run = 0; run <= steps; run += 1) {", @@ -1291,23 +1295,76 @@ describe("OpenBot Mastra progress reminder", () => { steps, lines = [], refuseSystem = false, + refuseCache = false, + live, + preamble = "", }: { model: string; steps: number; lines?: number[]; refuseSystem?: boolean; + refuseCache?: boolean; + /** Anthropic's own API with this key, each answer's usage recorded, instead of the script. */ + live?: { key: string; usage: Record[] }; + preamble?: string; }) { const sent: Sent[] = []; let step = 0; const provider = Bun.serve({ hostname: "127.0.0.1", port: 0, + idleTimeout: 120, async fetch(request) { const body = await request.json(); sent.push({ messages: body.messages, beta: request.headers.get("anthropic-beta"), + body, }); + if (live) { + const upstream = await fetch( + `https://api.anthropic.com${new URL(request.url).pathname}`, + { + method: "POST", + headers: { + "content-type": "application/json", + "anthropic-version": + request.headers.get("anthropic-version") ?? "2023-06-01", + ...(request.headers.get("anthropic-beta") + ? { "anthropic-beta": request.headers.get("anthropic-beta")! } + : {}), + "x-api-key": live.key, + }, + body: JSON.stringify(body), + }, + ); + const text = await upstream.text(); + for (const line of text.split("\n")) { + if (!line.startsWith("data:")) continue; + const event = JSON.parse(line.slice(5)); + if (event.type === "message_start") + live.usage.push(event.message.usage); + } + return new Response(text, { + status: upstream.status, + headers: { + "content-type": + upstream.headers.get("content-type") ?? "application/json", + }, + }); + } + // A proxy in front of Claude that does not take a prompt cache mark. + if (refuseCache && JSON.stringify(body).includes("cache_control")) + return Response.json( + { + type: "error", + error: { + type: "invalid_request_error", + message: "cache_control: Extra inputs are not permitted", + }, + }, + { status: 400 }, + ); // A proxy in front of Claude that does not take a system message mid-thread. if ( refuseSystem && @@ -1350,8 +1407,9 @@ describe("OpenBot Mastra progress reminder", () => { OPENAI_API_KEY: "", OPENAI_BASE_URL: "", JOB_STEPS: String(steps), + JOB_PREAMBLE: preamble, }, - 60_000, + live ? 120_000 : 60_000, ); if (exitCode !== 0) throw new Error(`job probe exited ${exitCode}\n${stdout}\n${stderr}`); @@ -1490,4 +1548,65 @@ describe("OpenBot Mastra progress reminder", () => { REMINDER_IN_TURN, ); }, 60_000); + + /* + * ANTHROPIC'S PROMPT CACHE. Every step of a job sends the same tools, the same instructions and a + * conversation that only grows, and Anthropic reads a prefix back from its cache only where the + * request marks it. Found in the waste audit after 1.2.7: this Bot marked none, so every step was + * billed in full. Every step now marks the last tool, the instructions, and the conversation by + * the request's own top-level mark (index.ts, `withPromptCache`). + */ + test("every Claude step marks the tools, the instructions and the conversation for Anthropic's prompt cache", async () => { + const { sent } = await runJob({ model: "claude-sonnet-5-5", steps: 3 }); + expect(sent).toHaveLength(4); + for (const { body } of sent) { + expect(body.cache_control).toEqual({ type: "ephemeral" }); + const tools = body.tools as { name: string; cache_control?: unknown }[]; + expect(tools.at(-1)?.cache_control).toEqual({ type: "ephemeral" }); + const system = body.system as { text: string; cache_control?: unknown }[]; + expect(system.at(-1)?.cache_control).toEqual({ type: "ephemeral" }); + expect(system.map((block) => block.text).join("")).toContain( + "Answer the question you are asked", + ); + } + }, 60_000); + + test("a Claude proxy that refuses cache_control: the job carries on unmarked, and is never sent a mark again", async () => { + const { sent, said } = await runJob({ + model: "claude-sonnet-5-5", + steps: 3, + refuseCache: true, + }); + const markedRequests = sent.map((request) => + JSON.stringify(request.body).includes("cache_control"), + ); + expect(markedRequests).toEqual([true, false, false, false, false]); + expect(said.at(-1)).toBe("All read."); + }, 60_000); + + // On Anthropic's own API, with OPENBOT_LIVE_ANTHROPIC_KEY set (a few cents): the second step reads back + // the prefix the first wrote. + const LIVE_KEY = process.env.OPENBOT_LIVE_ANTHROPIC_KEY?.trim(); + test.skipIf(!LIVE_KEY)( + "live: the second step of a job reads the first step's prefix back from Anthropic's cache", + async () => { + const usage: Record[] = []; + const rules = Array.from( + { length: 300 }, + (_, n) => + `Rule ${n + 1}: when asked about ledger section ${n + 1}, read it with read_record, cite the record, and never invent a figure.`, + ).join("\n"); + await runJob({ + model: "claude-sonnet-5-5", + steps: 1, + live: { key: LIVE_KEY!, usage }, + preamble: `${rules}\nRun ${crypto.randomUUID()}.\nUse read_record for each record, one at a time.\n`, + }); + console.log("usage", JSON.stringify(usage)); + expect(usage.length).toBeGreaterThanOrEqual(2); + expect(usage[0]!.cache_creation_input_tokens).toBeGreaterThan(5_000); + expect(usage[1]!.cache_read_input_tokens).toBeGreaterThan(5_000); + }, + 180_000, + ); }); diff --git a/agent-mastra/src/mastra/index.ts b/agent-mastra/src/mastra/index.ts index 6b10f2d8a8..34c36bb5b6 100644 --- a/agent-mastra/src/mastra/index.ts +++ b/agent-mastra/src/mastra/index.ts @@ -23,6 +23,7 @@ import { } from "../../../shared/model-providers"; import { signingFetch } from "./gemini-signatures"; import { progressReminder } from "./progress-reminder"; +import { withPromptCache } from "./prompt-cache"; import { withDefaultToolCallIndexes } from "./tool-call-index"; /** The providers this Bot can drive: the ones whose SDK modules it loads below. */ @@ -66,10 +67,15 @@ async function buildModel(runKey?: string) { const { createAnthropic } = await import("@ai-sdk/anthropic"); // Other harnesses accept an Anthropic origin; AI SDK expects the /v1 API prefix. const origin = (baseURL || "https://api.anthropic.com").replace(/\/+$/, ""); - return createAnthropic({ - baseURL: origin.endsWith("/v1") ? origin : `${origin}/v1`, - ...(key ? { apiKey: key } : {}), - })(model); + // Each step reads the prefix the step before it wrote from Anthropic's prompt cache + // (prompt-cache.ts). + return withPromptCache( + createAnthropic({ + baseURL: origin.endsWith("/v1") ? origin : `${origin}/v1`, + ...(key ? { apiKey: key } : {}), + })(model), + origin, + ); } const { createOpenAI } = await import("@ai-sdk/openai"); const compatible = diff --git a/agent-mastra/src/mastra/prompt-cache.ts b/agent-mastra/src/mastra/prompt-cache.ts new file mode 100644 index 0000000000..5dd68a2619 --- /dev/null +++ b/agent-mastra/src/mastra/prompt-cache.ts @@ -0,0 +1,140 @@ +/** + * Anthropic's prompt cache, for this Bot's Claude runs. + * + * Every step of a job sends the same tools, the same instructions and a conversation that only + * grows. Anthropic reads a prompt's prefix back from its cache, at a tenth of the input price, only + * where the request marks where the prefix ends (`cache_control`); nothing on the way adds a mark + * (OpenBot's model gateway passes the body through as it came), so every step was billed in full. + * + * WHERE THE MARKS GO, as Anthropic lays them out for an agent loop + * (https://platform.claude.com/docs/en/build-with-claude/prompt-caching), and as the AI SDK's + * Anthropic provider takes them (`providerOptions.anthropic.cacheControl`): + * - The last tool. Tools lead the prefix and are the same on every step of a job. + * - The last of the system messages that lead the prompt: the Bot's instructions. + * - The conversation, by the request's own top-level `cache_control`: Anthropic marks the last block + * it can and moves the mark on as the conversation grows, so each step reads what the step before + * it wrote. Three of the four marks a request may carry. + * + * Five minutes, the default: the steps of a job start well inside that. + * + * A wrapper around the model because a step's tools only exist in the call itself: Mastra builds + * them from the run's client tools on every call. A proxy in front of Claude that refuses the field + * is remembered for the life of the process and asked again unmarked. + */ + +const EPHEMERAL = { type: "ephemeral" } as const; + +/** The addresses that refused a cache mark, kept for the life of the process. */ +const refused = new Set(); + +type Options = { + tools?: Record[]; + prompt: Record[]; + providerOptions?: Record>; + [key: string]: unknown; +}; + +type Model = { + specificationVersion: string; + provider: string; + modelId: string; + supportedUrls: unknown; + doGenerate: (options: Options) => PromiseLike; + doStream: (options: Options) => PromiseLike; +}; + +function marked>(part: T): T { + const options = (part.providerOptions ?? {}) as Record< + string, + Record + >; + return { + ...part, + providerOptions: { + ...options, + anthropic: { ...(options.anthropic ?? {}), cacheControl: EPHEMERAL }, + }, + }; +} + +/** A tool Anthropic loads up front: the only kind the mark may go on. */ +function upFront(tool: Record): boolean { + const options = tool.providerOptions as + | Record> + | undefined; + return tool.type === "function" && options?.anthropic?.deferLoading !== true; +} + +/** One call with the marks in place; nothing else changes. */ +export function withCacheMarks(options: Options): Options { + const tools = options.tools ? [...options.tools] : undefined; + if (tools) { + const last = tools.findLastIndex(upFront); + const tool = tools[last]; + if (tool) tools[last] = marked(tool); + } + const prompt = [...options.prompt]; + const leading = prompt.findIndex((message) => message.role !== "system"); + const lastSystem = (leading < 0 ? prompt.length : leading) - 1; + const system = prompt[lastSystem]; + // An empty block can't carry the mark: the API refuses it. + if ( + system?.role === "system" && + typeof system.content === "string" && + system.content.trim() + ) + prompt[lastSystem] = marked(system); + return { + ...marked(options), + ...(tools ? { tools } : {}), + prompt, + }; +} + +/** A 4xx from a proxy in front of Claude naming the field. */ +function refusesCacheMarks(error: unknown): boolean { + for ( + let link = error as Record | undefined, depth = 0; + link && depth < 5; + link = link.cause as Record | undefined, depth += 1 + ) { + const status = Number(link.statusCode ?? link.status); + if ( + status >= 400 && + status < 500 && + /cache[_-]control/i.test( + `${String(link.message ?? "")} ${String(link.responseBody ?? "")}`, + ) + ) + return true; + } + return false; +} + +/** + * A Claude model whose every call carries the cache marks, unless `address` has refused them; a + * refusal is remembered and the same call asked again unmarked. + */ +export function withPromptCache(model: M, address: string): M { + const inner = model as unknown as Model; + const ask = + (method: "doGenerate" | "doStream") => + async (options: Options): Promise => { + if (refused.has(address)) return inner[method](options); + try { + return await inner[method](withCacheMarks(options)); + } catch (error) { + if (!refusesCacheMarks(error)) throw error; + refused.add(address); + return inner[method](options); + } + }; + return { + specificationVersion: inner.specificationVersion, + provider: inner.provider, + modelId: inner.modelId, + supportedUrls: inner.supportedUrls, + doGenerate: ask("doGenerate"), + doStream: ask("doStream"), + } as unknown as M; +}