AI Coding Agents
Deterministic prompt serialization for caching
Deterministic prompt serialization for caching means preparing the reusable part of every API request with the same tool order, JSON encoding, text line endings, and image bytes. Put per-request values after the reusable boundary, then hash the frozen prefix before each send and raise an explicit error when an unchanged conversation unexpectedly produces different bytes.
Normalize at the last boundary you control
Run normalization on every call, including tool continuations, resume, streaming requests and retries. Build the provider request from normalized values and inspect what the adapter actually sends. A hash of the application’s message list alone misses drift in discovered tools, options, and any instructions the adapter adds. For an existing integration, start with one captured request from each path and identify the common point where the final provider body is assembled.
Choose what the cache should reuse first. On the Claude API, tools precede system instructions and messages. In OpenAI’s rendered context, tools, developer messages and multimodal history can contribute, and eligible cache boundaries depend on the model and mode. As of November 30, 2026, both guides make matching the complete prefix through the boundary central to reuse. Stable request construction gives you control over the client’s contribution to that prefix. Anthropic prompt caching · OpenAI prompt caching
| Input | Normalization rule | Check before sending |
|---|---|---|
| Discovered tools | Resolve duplicate names using the existing tool policy, then sort the final list by name. | Reverse discovery order and compare the ordered list and schema bytes. |
| Application-owned schema JSON | Sort object keys recursively and use fixed separators for JSON you render. Keep array order except for collections, such as this tool list, that you deliberately normalize. | Build the same schema with a different insertion order and compare the serialized form. |
| Application-owned instruction text | Choose a newline convention before taking the initial snapshot. Preserve meaningful indentation and spaces. | Compare the fixture built from different line endings. |
| Reusable image input | Reuse the same encoded asset and keep its position and image options fixed. | Compare asset bytes and the outgoing image block in a replay. |
| Time, trace IDs and fresh context | Keep operational values in application logs. Append model-visible values after the stable boundary. | Change the values and confirm that the frozen prefix digest agrees. |
| Assistant content and tool results | Save and replay sent blocks unchanged. | Compare the overlapping history between turns, including request reconstruction after resume. |
Apply canonical JSON to content you construct, especially tool input schemas and any JSON rendered as prompt text. Anthropic diagnostics explicitly identifies nondeterministic input_schema serialization as a source of tools_changed. Its caching guide also warns about key order in replayed tool_use blocks. Keep received assistant blocks intact. Run any formatting of application-generated tool results before their first send, then replay the resulting representation. Anthropic cache diagnostics · Anthropic prompt caching
If you cache the tools separately on Claude, attach cache_control after sorting, on the last non-deferred tool in the final array. A tool with defer_loading: true sits outside the initial rendered prefix, and marking that definition returns a 400. In the shuffled-discovery test, verify that the outgoing marker still lands on the last non-deferred tool. Tool use with prompt caching · Anthropic tool search
Normalize template line endings once when constructing the original instructions and preserve the same form on replay. Restrict this to text your application owns, since changing whitespace inside a code sample, literal or saved result can change what the model receives. Treat an image similarly. Save the exact representation you intend to replay instead of recreating it from a source file each turn. In a request that includes a reusable image, make the image block part of the comparison. Anthropic includes images in its exact matching rule. Azure also specifies that the detail setting for images must stay the same across requests. Anthropic prompt caching · Azure OpenAI prompt caching
Compute a digest of the frozen prefix
The examples use a local array containing the final tool definitions and the system text. This is an illustrative fingerprint format for a single client, with unique final tool names assumed after duplicate resolution. It captures only these two layers. Use the returned tool list and text to construct the request, then verify schema ordering on the provider-bound path. The digest checks the client’s stable inputs. The provider computes its own cache match.
Illustrative Python:
import hashlib
import json
def prepare_prefix(tools, system_text, expected=None):
ordered_tools = sorted(tools, key=lambda tool: tool["name"])
system_text = system_text.replace("\r\n", "\n").replace("\r", "\n")
encoded = json.dumps(
[ordered_tools, system_text],
sort_keys=True, separators=(",", ":"), ensure_ascii=False, allow_nan=False,
).encode("utf-8")
digest = hashlib.sha256(encoded).hexdigest()
if expected is not None and digest != expected:
raise ValueError("Frozen prompt prefix changed")
return json.loads(encoded)[0], system_text, digest
Illustrative TypeScript for a Node client. The type represents JSON values and assumes numbers are finite and strings are valid Unicode.
import { createHash } from "node:crypto"
type Json = null | boolean | number | string | Json[] | { [key: string]: Json }
type Tool = { name: string; [key: string]: Json }
function canonical(value: Json): string {
if (Array.isArray(value)) return "[" + value.map(canonical).join(",") + "]"
if (value === null || typeof value !== "object") return JSON.stringify(value)
const entries = Object.keys(value).sort().map(
(key) => JSON.stringify(key) + ":" + canonical(value[key]),
)
return "{" + entries.join(",") + "}"
}
function preparePrefix(tools: Tool[], systemText: string, expected?: string) {
const orderedTools = [...tools].sort(
(a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0,
)
const text = systemText.replace(/\r\n?/g, "\n")
const digest = createHash("sha256")
.update(canonical([orderedTools, text])).digest("hex")
if (expected !== undefined && digest !== expected) {
throw new Error("Frozen prompt prefix changed")
}
return { orderedTools, toolsJson: canonical(orderedTools), text, digest }
}
Use the digest from the first confirmed send as the expected value on the next turn. Extend the comparison to the frozen reference blocks, image bytes and prompt-affecting options your adapter owns. If you cache a growing message history, save the prior endpoint and compare the prefix through that endpoint on the next call. Hashing the entire new history against the entire old one would flag every legitimate append. When an intentional model change, tool upgrade or compaction changes the expected prefix, record the transition and establish the new baseline explicitly.
These examples define stable encoding within each runtime. If Python creates a baseline and TypeScript validates it, define one encoding contract for strings, numbers and key ordering and test shared fixtures before comparing their digests. Within either runtime, a hash of a canonical view can hide changes in the transmitted JSON if the SDK serializes a different view. Inspect the body or test the adapter’s output from shuffled inputs. Preserve marked block boundaries when you pass the request through a gateway.
Preserve the normalized form through the adapter
The Python example returns tools reconstructed with sorted object keys. The TypeScript example also exposes the serialized array for a transport that can use it directly. When the SDK owns serialization, use a wire-level fixture to verify that supplying normalized definitions produces a stable schema. Treat this as an end-to-end property of the request builder. A test that stops at preparePrefix can pass even when the next adapter step rebuilds a schema with keys inserted in a different order. Keep the JSON separator rule for strings your application renders, such as JSON inside a tool result. A stable string approved for replay should stay exactly as it was sent.
Save a check for each layer when a single digest is hard to debug. Start with the resolved list of tool names in the order sent. Next record an application-side digest per tool schema and per stable text block. For replayed history, compare the count and content of the blocks through the previous endpoint. Keep the last verified prefix for the comparison and append new content after it. That will help distinguish a moved tool from a schema edit, or a moved history block from a text rewrite. You can record the differing position and component name without including prompt text in routine logs.
Release a changed instruction template or tool schema as an explicit prefix revision. For sessions that should keep the old prefix, continue using their original definitions until the planned transition. If a session must take the revision immediately, build a fresh baseline and expect a write at the new boundary. When a digest changes unexpectedly, surface the error before sending. Automatically accepting the new digest would mask the same drift that the per-turn check is meant to catch.
Compare first calls across user turns
MCP tool discovery can appear stable during an agent loop and still drift between user turns. In OpenClaw PR #58037, opened March 31, 2026 and merged April 4, 2026, the author identified an unsorted collection of tools in the per-turn runtime. The change kept the first-server-wins collision policy in the collection step, then sorted the surviving tool names with localeCompare. OpenClaw PR #58037
PrimusClaw PR #155, opened October 28, 2026 and merged October 29, 2026, describes a related failure. The first request of each user turn received a newly ordered tool list. Subsequent requests inside that turn reused the same list. The change sorts schemas by name in code-unit order across servers to remove its dependence on the pod’s ICU data. The TypeScript example uses < and > for the same reason. The table shows the project’s own before-and-after measurement over three consecutive turns with a real gateway, Claude Sonnet 5.5 and 81 tools from two default MCP servers. Use the pattern to design a replay test for your client. PrimusClaw PR #155
| First request of user turn | Before, tokens read / written | After, tokens read / written |
|---|---|---|
| Turn 2 | 0 / 21,400 | 21,236 / 172 |
| Turn 3 | 0 / 21,426 | 21,236 / 198 |
Test the bytes and the provider usage
- Build a realistic fixture. Include discovered tools, fixed instructions, a prior assistant tool call and its tool result. Choose a stable prefix at or above the model minimum and a boundary that writes it. Separate fresh user text and model-visible per-request values from that known reusable part.
- Exercise equivalent assembly paths. Feed the fixture through a second tool discovery order and a different schema insertion order. Compare the complete normalized tools and frozen digest. Repeat with a reconnect or resume path if it rebuilds the tool list.
- Exercise a real change. Edit an early tool description and verify that the digest check fails loudly. Attach the first changed component in the error or local trace so an operator can tell a changed tool from a rebuilt system template.
- Compare two calls through the ordinary route. Send a warmable prefix, then send an appended turn within the relevant lifetime. On Claude, compare
cache_read_input_tokensandcache_creation_input_tokens. In OpenAI’s Responses API, checkcached_tokensunderusage.input_tokens_detailsand trackcache_write_tokensthere for GPT-5.6 and later. Earlier models roundcached_tokensdown to a multiple of 128, so use that rounding in the expected count. If the client digest agrees and billed reads stay low, inspect expiry, provider options, the forwarded request and the actual cache boundary. Anthropic prompt caching · OpenAI prompt caching
Repeat the same comparison with a real schema update as a positive control. On the earlier fixture, shuffling discovery order should preserve the digest through the previous endpoint. On the revised fixture, an intentional schema edit should produce a detectable change. Exercise both cases before using provider usage alone as your regression signal. That way, a provider-side hit on a shorter prefix cannot make a request-construction regression look like success.
Put the check on the path that drifts
- If only the first call of a user turn drifts, trace MCP tool ordering across separate listings and freeze the resolved array.
- If a hash fails, use a prefix diff to locate the first difference. Check other silent cache busters when the serialized content agrees.
- If the normalized prefix stays stable, confirm Anthropic breakpoint placement or the applicable provider boundary, then measure cache reads and writes across both user turns and tool continuations.
Sources
- Cache diagnostics (Anthropic, accessed 2026-11-30)
- Prompt caching (Anthropic, accessed 2026-11-30)
- Tool use with prompt caching (Anthropic, accessed 2026-11-30)
- Tool search (Anthropic, accessed 2026-11-30)
- Prompt caching (OpenAI, accessed 2026-11-30)
- Prompt caching in Azure OpenAI (Microsoft, accessed 2026-11-30)
- OpenClaw PR #58037 (GitHub, accessed 2026-11-30)
- PrimusClaw PR #155 (GitHub, accessed 2026-11-30)
Interactive report
- The Cache Breakers: The agent sends another ordinary-looking request. A timestamp, a shuffled tool list, or a model switch just changed what the API can reuse. See what each edit puts on the invoice.
How this note was produced
Drafted with AI assistance from committed ByteCosts pricing snapshots and deterministic cost formulas. Figures are grounded in the linked sources (last updated 2026-11-30). Read our editorial & automation policy, inspect the methodology, or report a discrepancy.
Deterministic prompt serialization for caching. ByteCosts. Updated 2026-11-30. https://bytecosts.com/blog/deterministic-prompt-serialization-cache/