Coverage for app / services / prompt_cache.py: 90%
72 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2Provider prompt caching for the answering agent.
4Both providers bill a repeated prompt prefix at a fraction of the input rate,
5and an agent call is mostly prefix: its tool definitions (several thousand
6tokens), its instructions and the platform's standards are the same on every
7call — every turn of every conversation, every iteration of its tool loop,
8every case of an evaluation. Two things kept any of it from being reused:
9every system prompt started with a timestamp to the minute, and per-request
10content (knowledge, memory, the plan) sat in the middle of it. The answering
11agent's system message is now stable — per-request context travels in the
12task message, after the history — and this module marks it:
14* **Anthropic** caches only what is marked. The system message becomes one
15 text block with ``cache_control``: tools precede the system prompt, so the
16 breakpoint caches both. A prefix below the model's minimum cacheable
17 length is simply not cached, at no cost.
18* **OpenAI** caches any prefix of 1,024 tokens or more on its own;
19 ``prompt_cache_key`` routes requests that share one to the same cache. The
20 key is a hash of the model, the system message and the tool names, so
21 calls that can share a prefix share a key.
23* **Bedrock** (``ChatBedrockConverse``) takes an explicit ``cachePoint``
24 block, which langchain-aws passes through as it stands; an Anthropic
25 ``cache_control`` on a text block is dropped there. The block goes after
26 the system text, so the stable prefix — tools, then system — is cached and
27 the task after it is not, as on Anthropic. Only Claude takes it: OpenAI's
28 models on Bedrock cache on their own terms, and get nothing.
30Other providers (and test doubles) get neither: an unknown request field is
31a 400 waiting to happen.
33**Beyond the system prompt** (cost-control plan, B1.1). A turn re-sends the
34conversation so far, and a tool loop re-sends the turn so far every round.
35Two more breakpoints let both be read from cache, on the providers that
36cache only what is marked (Anthropic, and Claude on Bedrock):
38* **The end of the history** (``mark_last``): the next turn's request starts
39 with this one's history, so it reads that prefix — two messages longer
40 each turn — instead of paying for all of it again.
41* **The tail of every tool-loop round** (``tail_options``): the next round
42 reads everything before it. On Anthropic's API this is its top-level
43 ``cache_control``, placed by the API at the request's last block; on
44 Bedrock langchain-aws expands the same kwarg into ``cachePoint`` blocks at
45 the last message and the tools array.
47So a request carries at most four breakpoints — system, history, tail and
48(on Bedrock) tools — the most either provider accepts. A write costs a
49little more than a plain input token (1.25× on Anthropic) and a read a
50tenth, so a mark pays for itself once its prefix is read again; one that is
51never read is a small loss. Each is to be kept only where measurement shows
52reads outweigh writes (``docs/guides/agent-graph-review.md#cost-levers``).
53"""
55from __future__ import annotations
57import hashlib
58from typing import Any
60from langchain_core.messages import AIMessage, BaseMessage, HumanMessage, SystemMessage
62from app.services.structured_output import provider_model
64#: Anthropic's ephemeral cache: five minutes, refreshed on every hit.
65EPHEMERAL = {"type": "ephemeral"}
68#: Bedrock's cache marker, appended after the system text.
69CACHE_POINT = {"cachePoint": {"type": "default"}}
72def _provider(llm: Any) -> str:
73 return (provider_model(llm)[0] or "").lower()
76def _bedrock_vendor(llm: Any) -> str | None:
77 """The vendor a Bedrock client serves, or None for any other client.
79 By class rather than by the meter's provider: a catalogue model served
80 through Bedrock is metered as its vendor's (``anthropic``) but takes
81 Bedrock's request."""
82 if type(llm).__name__ != "ChatBedrockConverse":
83 return None
84 from app.services.inference_routes import bedrock_vendor
86 return bedrock_vendor(str(getattr(llm, "model_id", "") or ""))
89def system_message(llm: Any, text: str) -> SystemMessage:
90 """``text`` as the system message, marked for caching where the provider
91 caches only what is marked."""
92 vendor = _bedrock_vendor(llm)
93 if vendor is not None:
94 if vendor == "anthropic" and text:
95 return SystemMessage(content=[{"type": "text", "text": text}, CACHE_POINT])
96 return SystemMessage(content=text)
97 if _provider(llm) == "anthropic" and text:
98 return SystemMessage(
99 content=[{"type": "text", "text": text, "cache_control": EPHEMERAL}]
100 )
101 return SystemMessage(content=text)
104#: The most cache breakpoints a request may carry (Anthropic and Bedrock).
105MAX_BREAKPOINTS = 4
108def marks_breakpoints(llm: Any) -> str | None:
109 """``anthropic`` or ``bedrock`` for a client that caches only what is
110 marked — Anthropic's own API, or Claude on Bedrock — else None."""
111 vendor = _bedrock_vendor(llm)
112 if vendor is not None:
113 return "bedrock" if vendor == "anthropic" else None
114 return "anthropic" if _provider(llm) == "anthropic" else None
117def tail_options(llm: Any) -> dict[str, Any]:
118 """Options that cache a request up to its last block, so the next call
119 that extends it — the next tool-loop round — reads it back. Nothing for
120 a provider that caches on its own or not at all."""
121 return {"cache_control": dict(EPHEMERAL)} if marks_breakpoints(llm) else {}
124def _marked(llm: Any, message: BaseMessage) -> BaseMessage:
125 family = marks_breakpoints(llm)
126 content = message.content
127 if isinstance(content, str):
128 if not content:
129 return message
130 blocks: list[Any] = [{"type": "text", "text": content}]
131 elif isinstance(content, list) and content:
132 blocks = [dict(b) if isinstance(b, dict) else b for b in content]
133 else:
134 return message
135 if family == "bedrock":
136 blocks.append(dict(CACHE_POINT))
137 else:
138 last = blocks[-1]
139 if not (isinstance(last, dict) and last.get("type") == "text"):
140 return message
141 last["cache_control"] = dict(EPHEMERAL)
142 return message.model_copy(update={"content": blocks})
145def mark_last(llm: Any, messages: list[BaseMessage]) -> list[BaseMessage]:
146 """``messages`` (the conversation so far) with a breakpoint after the
147 last one, where the provider caches only what is marked: the next turn
148 starts with the same history and reads it from cache. A copy — the
149 history a caller holds is not changed — and the messages unchanged for
150 any other provider, or when the last is not plain text."""
151 if not messages or marks_breakpoints(llm) is None:
152 return list(messages)
153 last = messages[-1]
154 if not isinstance(last, (HumanMessage, AIMessage)) or getattr(
155 last, "tool_calls", None
156 ):
157 return list(messages)
158 return [*messages[:-1], _marked(llm, last)]
161def request_options(
162 llm: Any, system_text: str, tool_names: list[str]
163) -> dict[str, Any]:
164 """Request options that route a call to the cache its prefix lives in:
165 ``prompt_cache_key`` for OpenAI, nothing for anyone else — Bedrock
166 included, whose Converse API would refuse the unknown field."""
167 if _bedrock_vendor(llm) is not None or _provider(llm) != "openai":
168 return {}
169 _, model = provider_model(llm)
170 material = "\x1f".join([model, system_text, *sorted(tool_names)])
171 return {
172 "prompt_cache_key": "chainr-"
173 + hashlib.sha256(material.encode()).hexdigest()[:24]
174 }
177def cached_system(
178 llm: Any, messages: list[BaseMessage], tool_names: list[str]
179) -> tuple[list[BaseMessage], dict[str, Any]]:
180 """A structured call's messages with its system message marked for
181 caching, and the request options that route it to its cache — for a
182 call whose system prompt is the same on every turn (triage, the quality
183 check), so its second and later calls read it back."""
184 if not messages or not isinstance(messages[0], SystemMessage):
185 return list(messages), {}
186 text = text_of(messages[0].content)
187 return (
188 [system_message(llm, text), *messages[1:]],
189 request_options(llm, text, tool_names),
190 )
193def text_of(content: Any) -> str:
194 """A message's text whether it is a string or content blocks (a cached
195 system message is a block list)."""
196 if isinstance(content, str):
197 return content
198 if isinstance(content, list):
199 # Only the text: a cache marker or other non-text block is not part
200 # of what the model is told.
201 return "\n".join(
202 str(block["text"]) if isinstance(block, dict) else str(block)
203 for block in content
204 if not isinstance(block, dict) or "text" in block
205 )
206 return str(content or "")