Repository navigation
Description
Context
Gemini's implicit context caching matches calls that share a byte-stable prefix in system_instruction and the conversation up to a chunk boundary. When the prefix matches and exceeds the per-model token minimum (~1024 tokens for Flash family), Google bills the matching portion at the discounted cache-read rate. For long-running agents this can move a meaningful share of input tokens to the cheaper line item — but only if the prefix actually stays byte-stable across steps.
Working through some real agent runs, a few patterns in the current prompt construction tend to burst the cacheable prefix earlier than necessary. Filing this as a list of things that would make the agent friendlier to implicit caching (and would also enable cleaner adoption of Gemini's explicit CachedContent API later).
None of these are urgent for correctness — the agent behaves the same either way. They're prompt-stability hygiene that compounds nicely when traffic volume is high.
Suggested changes, ordered by expected impact
1. Make the per-step transcript append-only
Each step's running history block should be a strict byte-prefix of the next step's:
- Step N's transcript = Step N-1's transcript + one new appended entry
- No re-summarization, no compaction, no reordering of earlier entries
- No mutation of earlier entries when a later step succeeds/fails
- No timestamps embedded inside individual entries
If this property holds, the cache extends through the conversation portion at every step. Today, small rewrites of earlier entries (or any field that gets toggled on/off based on later state) burst the cache from that byte onward — and that loss compounds the longer the run goes.
Things to audit in the agent loop:
- Is the history rendered from a structured log each step? Make sure serialization is deterministic and emits the older entries byte-identical to what was emitted last step.
- Are there conditional fields (e.g. "recently_failed_action: ...") that appear in some steps and not others mid-run? Move them out of the prefix or always emit (empty when unset).
2. Avoid placeholder data blocks in the system prompt templates
The system prompts in browser_use/agent/system_prompts/ include placeholder blocks like:
<user_request>Ultimate objective. Specific tasks: ...</user_request>
<browser_state>Elements: [index]<type>text</type>. ...</browser_state>
<file_system>...</file_system>
These contain template descriptions of what those tags carry, not actual data — so they don't break cache today (the descriptions are static across calls). But:
- They couple the system prompt's structure to per-step data shapes. If anything later lets actual per-step content leak into these blocks, cache silently dies.
- They invite confusion: a reader sees
<user_request>...</user_request>in the system and assumes that's where the user request belongs at runtime, when in practice it arrives in a user turn.
Prefer prose references: "The user's request will be provided in the next message." / "Browser state arrives in subsequent user messages." Keep the actual data flow in user messages (which it already is).
3. Strip per-step metadata from anything that should be prefix-stable
Anything that varies per call inside a prefix-stable message kills cache from that byte onward. Things worth auditing for:
datetime.now()/time.time()formatted into a message- Step counters in human-readable form ("Step 7 of 50") — fine at the end of the message, broken if inside the prefix
- Run IDs, session IDs, agent UUIDs printed into any block
- Random samples or hashes (e.g. element-id allocations that get renumbered between steps)
For each: either move to the end of the message, or strip entirely if the LLM doesn't need it.
4. Optional: support explicit CachedContent for long sessions
For agent runs longer than the implicit-cache TTL window (~5 min, model-dependent), explicit CachedContent deterministically caches whatever you reference:
- On the first step of a session, call
client.caches.create(model=..., contents=[system + first user turn], ttl=\"3600s\")and stash the cache name on the agent state. - On subsequent steps, pass
cached_content=<cache_name>togenerate_contentinstead of resending the prefix.
The wrapper in browser_use/llm/google/chat.py would need a path to forward cached_content (and the usage parser already pulls cached_content_token_count). This is opt-in by nature — users who want it would enable it on the agent.
Expected impact
#1 is the biggest lever because the conversation grows every step and is where most of the prompt token volume lives. #2 and #3 are hygiene that prevent future regressions. #4 is the only one that requires a small API surface change but it removes implicit-cache TTL as a variable for long sessions.
Happy to put up draft PRs for any of these if useful — flagging here first so it can be triaged against whatever else is in flight on the prompt side.
Activity
[-]Make agent prompt cache-friendly for Gemini implicit caching (~30-40pp hit-rate lift)[/-][+]Make agent prompts cache-friendly for Gemini implicit caching[/+]agent(history): freeze HistoryItem + lock byte-prefix property (#4890)
agent(prompts): move per-step metadata out of <agent_state> into a ta…
feat(llm/google): forward cached_content into generate_content (#4889)
agent(history): freeze HistoryItem + lock byte-prefix property (brows…
agent(prompts): move per-step metadata out of <agent_state> into a ta…
feat(llm/google): forward cached_content into generate_content (brows…
scosemicolon commentedon May 28, 2026
One concrete way to make this easier to maintain would be a snapshot test around prompt prefix stability.
For example, render the prompt for step N and step N+1 from a deterministic fake agent history, then assert:
That catches the expensive class of regressions where the prompt still looks semantically equivalent to a human, but a small reordering or rewritten earlier entry destroys Gemini implicit cache reuse. It would also make an eventual explicit
CachedContentmode easier to reason about, because the cache boundary is already visible in tests.IgorGanapolsky commentedon Jul 22, 2026
Reliability note
Production automation failures usually reduce to a contract issue before a model/prompt issue:
If you have one failing execution + expected vs actual, reply with stack/version and I will send a free root-cause checklist.
chiruu12 commentedon Jul 27, 2026
Item 1 is the part still outstanding. I measured the rendered user message on main: with default settings the byte-stable prefix grows as expected (~2.7KB by step 4) and then collapses to 96 bytes on the step compaction fires. With max_history_items set it sits at about 108 bytes, and the count inside
<sys>[... N previous steps omitted...]</sys>changes it again on every step after that.I can pick this up. One thing first: tests/ci/test_history_item_byte_stable.py was removed in 51598ef. Do you want prefix-stability coverage back as part of this, or was that cut on purpose?
perf(agent): keep the agent-history transcript append-only between ev…
perf(agent): keep the agent-history transcript append-only between ev…
test(agent): use tmp_path, tighten the cap check, drop a coupled asse…
github-actions commentedon Sep 26, 2026
👋 This issue has been automatically marked as stale because it hasn't had activity for 60 days.
⚡ We've made significant progress recently! Please test with the latest version of browser-use to see if this issue has been resolved. If the issue persists, please let us know by commenting below.
To keep this issue open:
pinnedlabel if this is an important long-term issueThis will be automatically closed in 14 days if no further activity occurs.
Thanks for contributing to browser-use! 🤖 If you have questions, join our Discord.
github-actions commentedon Oct 10, 2026
🔒 This issue was automatically closed because it was stale for 14 days with no activity.
Don't worry! If this issue is still relevant:
We appreciate your contribution to browser-use! 🤖