Skip to content

feat: forward cached_content into generate_content - #4889

Merged
sauravpanda merged 2 commits into
mainfrom
prompt-cache/gemini-cached-content
May 23, 2026
Merged

sauravpanda merged 2 commits into
mainfrom
prompt-cache/gemini-cached-content

Conversation

@sauravpanda

@sauravpanda sauravpanda commented May 23, 2026 •

Copy link
Copy Markdown
Contributor

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 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

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

  • 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).
  • 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).

Summary by cubic

Adds explicit Gemini CachedContent support to ChatGoogle by forwarding a cached_content name into all generate_content calls. Addresses #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=...).

Written for commit ac5ff6d. Summary will update on new commits. Review in cubic

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.
@github-actions

github-actions Bot commented May 23, 2026 •

Copy link
Copy Markdown

Agent Task Evaluation Results: 2/2 (100%)

View detailed results
Task Result Reason
browser_use_pip ✅ Pass Skipped - API key not available (fork PR or missing secret)
amazon_laptop ✅ Pass Skipped - API key not available (fork PR or missing secret)

Check the evaluate-tasks job for detailed task execution logs.

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No issues found across 2 files

Re-trigger cubic

@sauravpanda
sauravpanda merged commit 5a745a8 into main May 23, 2026
98 checks passed
@sauravpanda
sauravpanda deleted the prompt-cache/gemini-cached-content branch May 23, 2026 01:40
@sauravpanda sauravpanda changed the title feat(llm/google): forward cached_content into generate_content feat: forward cached_content into generate_content May 23, 2026
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
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
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. -->
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.

1 participant