Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 24 additions & 14 deletions agent-langgraph-agui/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down
106 changes: 106 additions & 0 deletions agent-langgraph-agui/src/prompt_cache.py
Original file line number Diff line number Diff line change
@@ -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:],
]
13 changes: 12 additions & 1 deletion agent-langgraph-agui/src/tool_runtime.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
207 changes: 207 additions & 0 deletions agent-langgraph-agui/tests/test_prompt_cache.py
Original file line number Diff line number Diff line change
@@ -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
Loading