Repository navigation
feat: forward cached_content into generate_content - #4889
Merged
Merged
Conversation
Adds a cached_content field on ChatGoogle (and a per-call kwarg on ainvoke) that gets threaded into the GenerateContentConfigDict before each generate_content call. This lets callers point Gemini at an explicit CachedContent resource (e.g. "cachedContents/abc123") instead of relying on implicit caching, which is constrained by the ~5-minute TTL window. Token accounting already pulls cached_content_token_count from response.usage_metadata into ChatInvokeUsage.prompt_cached_tokens, so the savings show up in usage stats without further work. Cache creation itself (client.caches.create) is left to the caller — this PR only adds the forwarding hook so explicit caching becomes opt-in usable. A follow-up can wire agent-side cache lifecycle if useful.
Agent Task Evaluation Results: 2/2 (100%)View detailed results
Check the evaluate-tasks job for detailed task execution logs. |
MagMueller
added a commit
that referenced
this pull request
May 23, 2026
## Summary - Revert #4889 (`ChatGoogle.cached_content` field and per-call `cached_content` forwarding). - Remove the now-unused cached-content unit test. ## Why Cloud explicit caching does not need the OSS convenience API: the gateway injects `cached_content` through a copied `ChatGoogle.config` dict on its request-local model. Keeping the public field/kwarg exposes a sharp edge because Gemini rejects cachedContent calls that also send live `system_instruction`, which normal `ChatGoogle` messages can still do. ## Tests - `uv run pytest tests/ci/models/test_llm_google.py -q` - `uv run pre-commit run --all-files` <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Reverts `ChatGoogle` `cached_content` forwarding to Gemini and removes the field and per-call passthrough. This avoids Gemini errors when `cachedContent` is sent with live `system_instruction`; the gateway still injects caching, so the obsolete unit test is removed. <sup>Written for commit 22939a2. Summary will update on new commits. <a href="https://cubic.dev/pr/browser-use/browser-use/pull/4900?utm_source=github">Review in cubic</a></sup> <!-- End of auto-generated description by cubic. -->
pull Bot
pushed a commit
to forgotDj/browser-use
that referenced
this pull request
May 23, 2026
browser-use#4889)" This reverts commit 5a745a8, reversing changes made to 640360e.
r266-tech
pushed a commit
to r266-tech/browser-use
that referenced
this pull request
May 26, 2026
…er-use#4889) ## Context Closes part of browser-use#4887 (item browser-use#4 — explicit CachedContent support). Gemini's implicit context cache is great for the steady-state of an agent loop but has a ~5-minute TTL and is per-call best-effort. For long sessions (or sessions that go quiet for >5 minutes and resume), explicit `CachedContent` is the deterministic alternative: you create a named cache once with the prefix, then reference it on subsequent calls and Google bills the cached portion at the discounted rate, period. The wrapper in `browser_use/llm/google/chat.py` already parses `cached_content_token_count` out of `response.usage_metadata` into `ChatInvokeUsage.prompt_cached_tokens`, so the savings are visible — it just had no way to *send* a cache reference. ## Change - New `cached_content: str | None = None` field on `ChatGoogle`. - New `cached_content` kwarg on `ainvoke()` — overrides the instance default for one call. - When set, threads into `config['cached_content']` before all three `generate_content` calls (string output, native JSON, fallback JSON). Per-call kwarg takes precedence over the instance default, so you can pin a cache for the whole session and still override per-call when needed. ## What's NOT in this PR - Cache creation (`client.caches.create(...)`) is left to the caller. That gives users full control over TTL, contents, and lifecycle without coupling the LLM wrapper to agent-state decisions. - Agent-side automatic cache lifecycle (create on first step, reuse on subsequent steps, refresh near TTL) is an obvious follow-up but a separate design discussion — it touches `agent/service.py` and depends on what the agent considers its "stable prefix." ## Usage ```python from google.genai import types from google import genai client = genai.Client(api_key=...) cache = await client.aio.caches.create( model='gemini-2.5-flash', config=types.CreateCachedContentConfig( contents=[...prefix turns...], system_instruction='...', ttl='3600s', ), ) llm = ChatGoogle(model='gemini-2.5-flash', cached_content=cache.name) # Every ainvoke() now references that cache. # Per-call override: await llm.ainvoke(messages, cached_content='cachedContents/other') ``` ## Test plan - [x] New unit test `test_cached_content_threaded_into_config` — verifies the kwarg flows into `generate_content`'s `config` dict, the per-call kwarg overrides the instance default, and when unset the key is absent (`pytest tests/ci/models/test_llm_google.py`). - [x] Existing google tests still pass. - [ ] Real-API smoke test against a Gemini model with an actual `cachedContents/...` resource (requires API key + paid quota — not in CI). <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Adds explicit Gemini CachedContent support to `ChatGoogle` by forwarding a `cached_content` name into all `generate_content` calls. Addresses browser-use#4887 (item 4) to enable deterministic cache reuse with discounted billing. - **New Features** - Add `cached_content` on `ChatGoogle` with per-call override via `ainvoke(..., cached_content=...)`. - Thread to `config['cached_content']` for all paths; omit when unset. - Cache creation is caller-managed; usage already counts `prompt_cached_tokens`. - **Migration** - No breaking changes; behavior is unchanged when `cached_content` is unset. - To adopt: create a Gemini cache and pass its name via `ChatGoogle(cached_content=...)` or `ainvoke(..., cached_content=...)`. <sup>Written for commit ac5ff6d. Summary will update on new commits. <a href="https://cubic.dev/pr/browser-use/browser-use/pull/4889?utm_source=github">Review in cubic</a></sup> <!-- End of auto-generated description by cubic. -->
r266-tech
pushed a commit
to r266-tech/browser-use
that referenced
this pull request
May 26, 2026
browser-use#4889)" This reverts commit 5a745a8, reversing changes made to 640360e.
r266-tech
pushed a commit
to r266-tech/browser-use
that referenced
this pull request
May 26, 2026
## Summary - Revert browser-use#4889 (`ChatGoogle.cached_content` field and per-call `cached_content` forwarding). - Remove the now-unused cached-content unit test. ## Why Cloud explicit caching does not need the OSS convenience API: the gateway injects `cached_content` through a copied `ChatGoogle.config` dict on its request-local model. Keeping the public field/kwarg exposes a sharp edge because Gemini rejects cachedContent calls that also send live `system_instruction`, which normal `ChatGoogle` messages can still do. ## Tests - `uv run pytest tests/ci/models/test_llm_google.py -q` - `uv run pre-commit run --all-files` <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Reverts `ChatGoogle` `cached_content` forwarding to Gemini and removes the field and per-call passthrough. This avoids Gemini errors when `cachedContent` is sent with live `system_instruction`; the gateway still injects caching, so the obsolete unit test is removed. <sup>Written for commit 22939a2. Summary will update on new commits. <a href="https://cubic.dev/pr/browser-use/browser-use/pull/4900?utm_source=github">Review in cubic</a></sup> <!-- End of auto-generated description by cubic. -->
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Context
Closes part of #4887 (item #4 — explicit CachedContent support).
Gemini's implicit context cache is great for the steady-state of an agent loop but has a ~5-minute TTL and is per-call best-effort. For long sessions (or sessions that go quiet for >5 minutes and resume), explicit
CachedContentis the deterministic alternative: you create a named cache once with the prefix, then reference it on subsequent calls and Google bills the cached portion at the discounted rate, period.The wrapper in
browser_use/llm/google/chat.pyalready parsescached_content_token_countout ofresponse.usage_metadataintoChatInvokeUsage.prompt_cached_tokens, so the savings are visible — it just had no way to send a cache reference.Change
cached_content: str | None = Nonefield onChatGoogle.cached_contentkwarg onainvoke()— overrides the instance default for one call.config['cached_content']before all threegenerate_contentcalls (string output, native JSON, fallback JSON).Per-call kwarg takes precedence over the instance default, so you can pin a cache for the whole session and still override per-call when needed.
What's NOT in this PR
client.caches.create(...)) is left to the caller. That gives users full control over TTL, contents, and lifecycle without coupling the LLM wrapper to agent-state decisions.agent/service.pyand depends on what the agent considers its "stable prefix."Usage
Test plan
test_cached_content_threaded_into_config— verifies the kwarg flows intogenerate_content'sconfigdict, the per-call kwarg overrides the instance default, and when unset the key is absent (pytest tests/ci/models/test_llm_google.py).cachedContents/...resource (requires API key + paid quota — not in CI).Summary by cubic
Adds explicit Gemini CachedContent support to
ChatGoogleby forwarding acached_contentname into allgenerate_contentcalls. Addresses #4887 (item 4) to enable deterministic cache reuse with discounted billing.New Features
cached_contentonChatGooglewith per-call override viaainvoke(..., cached_content=...).config['cached_content']for all paths; omit when unset.prompt_cached_tokens.Migration
cached_contentis unset.ChatGoogle(cached_content=...)orainvoke(..., cached_content=...).Written for commit ac5ff6d. Summary will update on new commits. Review in cubic