Skip to content

Mark prompt cache breakpoints on Anthropic, Vertex and Bedrock Claude requests - #3419

Open
Podwarden wants to merge 5 commits into
webbrain-one:mainfrom
Podwarden:prompt-caching
Open

Podwarden wants to merge 5 commits into
webbrain-one:mainfrom
Podwarden:prompt-caching

Conversation

@Podwarden

Copy link
Copy Markdown

Part of #3418: the caching findings. The Helicone default model is left for a separate change.

Anthropic and Bedrock cache a prompt prefix only when the request carries a cache mark. Today no request does, so every step of an Act run pays the full input price again for the system prompt (about 12,000 tokens, an estimate), the tools and the history it sent a few seconds earlier.

What this changes:

  • Anthropic API and Vertex: AnthropicProvider._prepareRequestBody adds two cache_control breakpoints, one on the system prompt (covers tools and system) and one on the last cacheable block of the last message (covers the history and moves forward each step). The system string becomes a single text block with the same text. Thinking blocks and empty text blocks are skipped. Message objects are copied, not mutated, so PDF document blocks in the agent's history are not changed.
  • Claude subscription: only the history breakpoint. Its system prompt stays the same plain string, so the preamble it needs is untouched; the history mark still caches the tools and system in front of it.
  • Bedrock: a cachePoint block after the system text, only for the Claude models the Bedrock prompt-caching guide lists for explicit caching (Opus 4.5 to 4.8, Sonnet 4.6, Haiku 4.5 and the 5 family), since a request must carry only cache controls the model supports. Other models, and inference-profile ARNs, are sent as before.
  • Not changed: Anthropic-compatible servers on a custom base URL (they may reject the field), and request bodies whose configured fields already place a cache_control mark (their breakpoints and TTLs are kept).
  • Same change in src/chrome and src/firefox, a CHANGELOG line under Unreleased, and a new test file test/provider-prompt-caching.mjs added to npm run test:anthropic.
Input Expected Before After
Agent step: system string, tools, last message a tool result Marks on system and on the tool result No marks 2 marks (test)
Last user message holds a PDF document block shared with history Mark on a copy, history object unchanged No marks Copy marked, original untouched (test)
Last message ends with an empty text block Mark on the last non-empty block No marks Mark on the previous block (test)
Last message holds only a thinking block No mark No marks No marks (test)
Configured body already has cache_control with ttl 1h Kept as configured 1 mark 1 mark, unchanged (test)
A tool_use input with a key named cache_control Still marked No marks 2 marks (test)
Custom base URL (Anthropic-compatible proxy) No marks, system stays a string No marks No marks (test)
Claude subscription System string unchanged, history marked No marks 1 mark (test)
Vertex Claude Same 2 marks, anthropic_version kept No marks 2 marks (test)
Bedrock, listed Claude model (Sonnet 4.6, Opus 4.5, Haiku 4.5, 5.x) System cachePoint None Present (test)
Bedrock, Claude Sonnet 4, 3.7 Sonnet, Opus 4.1, Llama, inference-profile ARN No cachePoint None None (test)

How to check: run two steps of one task on the Anthropic provider and look at usage. cache_creation_input_tokens should be about the prompt size on step 1 and cache_read_input_tokens about the same on step 2 (the app already forwards both). We could not run it against the live APIs, so this is not verified end to end, including the Claude subscription and Vertex paths.

Tests: npm run test:anthropic with the new file, plus the provider, improver, pdf-read and network-lifecycle suites, exits 0 with the patch (257 tests), as the same suites do on the clean base (239 tests). The Playwright UI suites were not run.

This was found by leanprompt, our open-source set of skills for working with LLMs safely and efficiently, while we ran it on public repositories. The numbers above are estimates from reading the code, not measurements, so please treat them as a starting point. The suggested fix was written with an AI coding assistant and checked by hand.

… requests

Anthropic and Bedrock cache a prompt prefix only when the request carries a
cache mark. Add a cache_control breakpoint at the end of the system prompt
and at the last block of the last message for Anthropic's API and Vertex,
the history breakpoint alone for the Claude subscription (its system string
is unchanged), and a system cachePoint on Bedrock for the Claude models it
lists for explicit caching. Custom Anthropic-compatible base URLs and
request bodies that already place cache_control are left alone.

Refs webbrain-one#3418

Signed-off-by: PodWarden <info@podwarden.com>
@vercel

vercel Bot commented Nov 29, 2026

Copy link
Copy Markdown

@Podwarden is attempting to deploy a commit to the esokullu's projects Team on Vercel.

A member of the Team first needs to authorize it.

@esokullu

esokullu commented Nov 29, 2026 •

Copy link
Copy Markdown
Collaborator

Thanks for the PR and for flagging this — really appreciate the thorough write-up and test matrix! Overall the approach looks solid: block-level cache_control breakpoints on system and the last cacheable message block, preserving user-configured cache_control and custom baseUrl proxies, avoiding mutation of shared history blocks (PDF documents / signed thinking replay), and keeping Chrome/Firefox in parity.

A couple of blocking issues to address before merging, plus a few smaller suggestions:

Blocking

  1. Breaks existing test in test/run.js (test/run.js:128114)
    In anthropic (${label}): custom request body enables thinking and non-streaming preserves it:

    assert.deepEqual(requestBody.messages, [{ role: 'user', content: 'Inspect it.' }]);

    Because _applyPromptCaching wraps the last message's string content into [{ type: 'text', text: 'Inspect it.', cache_control: { type: 'ephemeral' } }], node test/run.js (npm run test:shard:tail) will fail on both Chrome and Firefox. Please update that assertion and verify node test/run.js passes.

  2. BEDROCK_CACHE_MODEL misses claude-sonnet-5 (and claude-haiku-5 / claude-sonnet-4-5)
    In src/{chrome,firefox}/src/providers/aws-bedrock.js:

    const BEDROCK_CACHE_MODEL = /claude-(?:opus-4-[5-8]|sonnet-4-6|haiku-4-5|opus-5|(?:opus|sonnet|haiku)-5-5|fable-5|mythos-5)(?![0-9])/i;

    This does not match anthropic.claude-sonnet-5 (or us.anthropic.claude-sonnet-5-...), even though:

    • The PR description intends to cover "the 5 family", and Bedrock supports explicit prompt caching on Claude Sonnet 5 (as well as Claude Sonnet 4.5 / claude-sonnet-4-5).
    • anthropic.claude-sonnet-5 is the documented example/seed Bedrock model in src/chrome/src/providers/manager.js:818-830 and test/improver-providers.mjs:317.
    • Also, opus-5(?![0-9]) already matches opus-5-5, so opus in (?:opus|sonnet|haiku)-5-5 is redundant.

    Simplifying the 5-family branch to (?:opus|sonnet|haiku|fable|mythos)-5 (and sonnet-4-[56] if Sonnet 4.5 should be included) and adding anthropic.claude-sonnet-5 to test/provider-prompt-caching.mjs would fix this cleanly.

Suggestions / Minor

  • Bedrock conversation history caching (messages): On Anthropic/Vertex this caches both system and the growing history (messages.at(-1)), while on Bedrock it only adds { cachePoint: { type: 'default' } } to payload.system. Multi-step Act runs accumulate large page reads / tool results in messages; adding a second { cachePoint: { type: 'default' } } to the last message's content array on Bedrock (Converse supports up to 4 cache points across toolConfig, system, and messages) would match the Anthropic/Vertex savings. (If intentionally deferred, a short note in the comment helps.)
  • Subclass hook instead of this.name === 'anthropic-oauth': _applyPromptCaching checks this.name === 'anthropic-oauth' inside AnthropicProvider while using a polymorphic method for _supportsPromptCaching(). A matching _shouldCacheSystemPrompt() hook (true on base, false on AnthropicOAuthProvider) would be cleaner, and AnthropicOAuthProvider._supportsPromptCaching() is redundant since its baseUrl is hardcoded to https://api.anthropic.com.
  • Wire-level test coverage: test/provider-prompt-caching.mjs invokes _prepareRequestBody() directly via a helper. Adding at least one chat() / chatStream() test with mocked fetch (including extraBody: { cache_control: { type: 'ephemeral', ttl: '1h' } }) would also cover the _mergeConfiguredRequestBody → _applyPromptCaching path end to end.

Thanks again for the contribution!

…oint, OAuth hook, wire test

- test/run.js: the custom-body chat test now expects the cache mark on the
  last message.
- Bedrock: match the whole Claude 5 family (Sonnet 5 included) and add a
  second cachePoint at the end of the last message.
- _shouldCacheSystemPrompt() hook replaces the provider-name check; drop
  the redundant OAuth _supportsPromptCaching().
- chat() test with a mocked fetch, including extraBody cache_control ttl.

Signed-off-by: PodWarden <info@podwarden.com>
@Podwarden

Podwarden commented Nov 29, 2026 via email

Copy link
Copy Markdown
Author

@Podwarden

Copy link
Copy Markdown
Author

Thanks for the fast and careful review. Pushed c0cab45 addressing all of it:

  • test/run.js: updated the custom-body assertion to expect the cache mark on the last message. anthropic (chrome|firefox): custom request body enables thinking and non-streaming preserves it now passes. In my environment node test/run.js ends 2587 passed, 5 failed, and the same 5 fail on clean main (locale coverage, Hebrew RTL, the API-key settings warning, Unsloth defaults), so they look environmental, not from this PR.
  • Bedrock models: took your simplified 5-family branch, so anthropic.claude-sonnet-5 and claude-haiku-5 now match, with tests. I left Sonnet 4.5 out only because the Bedrock prompt-caching guide we checked doesn't list it; if you know it works there, it's a one-word change.
  • Bedrock history: added the second cachePoint at the end of the last message, so Act runs cache page reads and tool results there too.
  • OAuth: replaced the name check with a _shouldCacheSystemPrompt() hook and dropped the redundant _supportsPromptCaching() override.
  • Wire-level test: chat() with a mocked fetch, including extraBody: { cache_control: { type: 'ephemeral', ttl: '1h' } }.

One question: we published the audit this came from at https://lmwarden.com/leanprompt/audits/webbrain-one__webbrain/. Are you OK with it staying up? When this merges we'll mark it fixed and link this PR the same day. If you'd rather it came down, say so and we'll remove it.

To re-check after merging: npx leanprompt install, then /leanprompt audit in your coding agent. It's free and open source. And since WebBrain already runs local models (Companion, llama.cpp), you might find LM Warden useful too. It's our open-source self-hosted gateway for serving models on your own GPUs: https://github.com/Podwarden/lm-warden

Updated regex for BEDROCK_CACHE_MODEL to align with AWS guidelines and support additional model IDs.
Updated BEDROCK_CACHE_MODEL regex for explicit prompt caching and model ID acceptance.
@esokullu

Copy link
Copy Markdown
Collaborator

Thanks for the quick update, Ingvar! AWS’s Sonnet 4.5 model card confirms explicit caching even though the summary table omits it. I pushed the Bedrock matcher and regression tests: Sonnet 4.5 and Haiku 5.5 are covered, and plain Haiku 5 is left out since I couldn’t verify it. npm run test:anthropic passed all 24 tests locally. I haven’t tested against live Bedrock.

And yes, the audit can stay up. Once this lands, a link to the PR on the audit page would be great. I’m leaving the PR open for now.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants