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

未關閉
#8,225 6 則留言 0 個 reaction 已指派 1 人 在 GitHub 檢視

維護者通常 3 天內回覆

@surajksharma07 已經在處理了。

開始於 2026年11月18日。

  • #8234 來自 @karthik-0306 —— 未關閉

評估

這個 Issue 還沒有評估資料。

描述

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

主要語言
Python
星號
22.3k
分支
4.4k
平均合併
1 天 2 小時
30 天內合併 PR
6

環境準備

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

google/adk-python 的其他 Issue

查看 google/adk-python 的全部 Issue

相似的 Issue

更多 Python Issue

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。