Context cache size gate ignores function call/response parts, so caches.create still fails with 400 INVALID_ARGUMENT in tool loops

Offen
#8,225 6 Kommentare 0 Reaktionen 1 zugewiesene Person Auf GitHub ansehen

Maintainer antworten meist innerhalb von 3 Tagen

@surajksharma07 arbeitet bereits daran.

Seit 18.11.2026.

  • #8234 von @karthik-0306 — offen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Beschreibung

🔴 Required Information

Describe the Bug:
GeminiContextCacheManager checks the size of the cacheable prefix before it calls caches.create, so that it never sends a cache below the model's minimum. That check was added in #6137 to fix #5847. It works by scaling the real token count of the previous prompt (cacheable_contents_token_count) by the prefix's share of an estimate. The estimate comes from _estimate_request_tokens, which only counts part.text:

for content in contents:
  for part in content.parts or []:
    if part.text:
      total_chars += len(part.text)

function_call, function_response and inline_data parts count as zero. In an agent that uses tools, these are often most of the prompt, so the share comes out wrong in both directions:

  1. Overestimate, so the 400 is back. In a tool loop, the newest content is usually the tool's function_response (role user). It falls outside the cached prefix but is invisible to the estimate. If it's large, the prefix's share comes out close to 1, the gate passes a prefix far below the minimum, and caches.create fails with 400 INVALID_ARGUMENT. This is the failure #6137 was meant to prevent.
  2. Underestimate, so caching never turns on. When large tool results sit inside the prefix and the uncached tail is text, the prefix's share is underestimated. A prefix that is above the minimum gets rejected, and agents that use tools heavily get no caching.

Steps to Reproduce:

  1. pip install google-adk
  2. Run this script. It calls the manager directly with a mocked client, so it needs no API key:
import asyncio
from unittest import mock
from google.genai import types
from google.adk.agents.context_cache_config import ContextCacheConfig
from google.adk.models.cache_metadata import CacheMetadata
from google.adk.models.gemini_context_cache_manager import GeminiContextCacheManager
from google.adk.models.llm_request import LlmRequest

big = "lorem ipsum " * 10000  # ~120k chars of tool output
contents = [
    types.Content(role="user", parts=[types.Part(text="Summarize the doc at x")]),
    types.Content(role="model", parts=[types.Part(function_call=types.FunctionCall(name="fetch_doc", args={"url": "x"}))]),
    types.Content(role="user", parts=[types.Part(function_response=types.FunctionResponse(name="fetch_doc", response={"result": big}))]),
]
req = LlmRequest(
    model="gemini-3-flash",
    contents=contents,
    config=types.GenerateContentConfig(system_instruction="You are a helpful agent."),
    cache_config=ContextCacheConfig(min_tokens=0),
)
req.cacheable_contents_token_count = 30_050  # real count reported for the previous prompt

client = mock.MagicMock()
client.vertexai = False
client.aio.caches.create = mock.AsyncMock(side_effect=Exception("400 INVALID_ARGUMENT"))
mgr = GeminiContextCacheManager(client)

n = mgr._find_count_of_contents_to_cache(contents)  # 2: user text + function_call
print("estimated prefix tokens:", mgr._estimate_cacheable_prefix_tokens(req, n))
req.cache_metadata = CacheMetadata(fingerprint=mgr._generate_cache_fingerprint(req, n), contents_count=n)
asyncio.run(mgr.handle_context_caching(req))
print("caches.create calls:", client.aio.caches.create.await_count)

Expected Behavior:
The cacheable prefix (a short user message and one function call, about 10 real tokens) is estimated well below the 4,096-token minimum for Gemini 3, so caches.create is never called.

Observed Behavior:

Failed to create cache: 400 INVALID_ARGUMENT
estimated prefix tokens: 30050
caches.create calls: 1

The whole 120k-character tool result is credited to the prefix, so the gate passes and the API rejects the cache.

Environment Details:

  • ADK Library Version: 2.14.1 (main @ c74df83c0)
  • Desktop OS: Windows 11 (the bug isn't OS-specific)
  • Python Version: 3.11

Model Information:

  • Are you using LiteLLM: No
  • Which model is being used: gemini-3-flash (any model that _minimum_cache_tokens covers: gemini-2.5-, gemini-3)

🟡 Optional Information

Regression:
No. The gate has used a text-only estimate since it was introduced in #6137.

Proposed fix:
Count the payloads of non-text parts in _estimate_request_tokens: the JSON size of function_call.args and function_response.response (plus the function name), and a rough size for inline_data and file_data. Then the prefix's share reflects what is actually sent. Add regression tests for both directions: a large function_response in the uncached tail must not pass the gate, and a large one in the prefix must not block it. I'm happy to send a PR.

Vorherrschende Sprache
Python
Sterne
22.3k
Forks
4.4k
Ø Merge
1 T. 2 Std.
Gemergte PRs (30 T.)
6

Entwicklungsumgebung

Erste Schritte

  1. Lesen Sie das ganze Issue und danach den Beitragsleitfaden des Projekts.
  2. Schreiben Sie ins Issue, dass Sie es übernehmen — das erspart doppelte Arbeit.
  3. Forken Sie das Repository und arbeiten Sie in einem Branch.
  4. Öffnen Sie einen Pull Request, der die Issue-Nummer nennt.

Mehr aus google/adk-python

Alle Issues in google/adk-python

Ähnliche Issues

Weitere Issues zu Python

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.