The use of a specific tool severely degrades prompt caching.
** Please make sure you read the contribution guide and file the issues in the right place. ** Contribution guide.
Describe the bug The phenomena observed so far are as follows:
When using load_artifacts_tool or preload_memory_tool, these tools generate prompts to guide the LLM.
The problem is that these tools generate dynamic content within those prompts.
load_artifacts
You have a list of artifacts: {json.dumps(artifact_names)}
preload_memory
<PAST_CONVERSATIONS>
{full_memory_text}
</PAST_CONVERSATIONS>
This is where the problem arises.
These tools use append_instructions, which appends their results to the top-level system_prompt.
Example:
system_instruction"
// omitted
You have a list of artifacts:
["test.txt"]
When the user asks questions about any of the artifacts, you should call the
`load_artifacts` function to load the artifact. Always call load_artifacts
before answering questions related to the artifacts, regardless of whether the
artifacts have been loaded before. Do not depend on prior answers about the
artifacts.
The following content is from your previous conversations with the user.
They may be useful for answering the user's current query.
<PAST_CONVERSATIONS>
Time: 2025-10-20T21:15:13.686996
user: hi
</PAST_CONVERSATIONS>
"
This behavior corrupts all forms of prompt caching, and in the case of explicit caching, it results in severe cost inefficiencies.
As with how both static_instruction and instruction operate in the agent, these prompts should instead be appended to the bottom of the prompt.
One concern is that moving them to the bottom may cause the LLM to become confused about context. However, I believe this issue could be mitigated by making this behavior optional or by issuing a warning when prompt caching is enabled together with these tools.
To Reproduce Using load_artifacts, preload_memory (always)
I’m ready to contribute to fixing this issue.
It seemed simple, but it seems like a significant change to the current ADK structure. Are there any patches planned?
Tool is reflected after request_processors have completed processing, so it is not possible to create dynamic instructions in Tool definition using any method with small changes.
@UlookEE The issue occurs because load_artifacts_tool and preload_memory_tool use append_instructions() to add dynamic content (timestamps, artifact lists) to system_instruction, which invalidates Gemini's prompt cache on every request.
The fix is to append this dynamic context as user messages instead: replace llm_request.append_instructions([content]) with llm_request.contents.append(Content(role='user', parts=[Part(text=content)])) in both tools.
This keeps system_instruction static while moving dynamic data to the bottom, preserving cache hits and reducing costs significantly. Thanks!
@surajksharma07
First of all, thank you for your kind reply.
You're right — using your proposed solution does make Prompt Caching work. My earlier belief that it was impossible was mistaken. However, upon deeper analysis, the fundamental issues can be summarized as follows:
- In
base_llm_flow,_preprocess_asyncprocessesrequest_processors. - Within
request_processors,contents[0]is used to create adynamic_instruction, which is then placed at an appropriate position. - (In the currently proposed solution) this result is appended to the end of
contentsas an additionaldynamic_instruction.
From my perspective, this solution has the following problems:
1. The solution lacks “coherence” (or natural consistency).
To clarify, let's define the content that should come after the cached portion (and therefore doesn’t need caching) as dynamic_instruction.
First, if we solve the issue in this way, new tool developers are likely to be confused.
At first glance, the end of contents seems like an appropriate place to insert the dynamic_instruction.
However, to verify whether that location is indeed correct, the user must analyze the internal structure of the ADK in detail.
Whether the last element of contents contains the user’s message depends on the implementation of base_llm_flow.
So, one must deeply inspect the code to know where exactly to insert their code.
In reality, the end of contents is where the user’s message is inserted.
Thus, if the tool’s instruction is appended there, the dynamic_instruction will appear after the user’s message — resulting in an incomplete LLM call.
(I’m not criticizing your explanation — I’m saying this behavior is simply confusing.)
2. There’s a high chance users will insert the prompt in an incorrect position.
As seen in issue google/adk-python#3269, this approach increases the likelihood that users will place prompts in inappropriate locations.
3. Dynamic contents from agents and tools all get appended separately.
Since both the agent’s dynamic_instruction and each tool’s dynamic content are appended individually,
they all exist as separate “content” entries.
This can make the LLM interpret them as if multiple turns of dialogue have passed, leading to unintended behavior.
Root Cause Analysis
I believe the recurring issues with dynamic_instruction stem from a design flaw in the Context Caching Instruction mechanism.
The process where _InstructionsLlmRequestProcessor identifies dynamic_instruction and inserts it into contents,
and _ContentLlmRequestProcessor then rebuilds contents from it, seems more like a “makeshift workaround” than a deliberate design.
This likely arose because GenerateContentConfig includes only system_instruction but not dynamic_instruction.
To respect the design of that class, this layered logic was introduced.
It would have worked well if tool_processing didn’t exist —
but since it does, there’s now no global space for agents, tools, or later dynamic_instruction consumers to share a consistent final context.
In my view, this is a core design issue.
It would be better to fix it promptly in beginning — for example, by creating a subclass of GenerateContentConfig
that includes a dedicated space for dynamic or cached instructions.
That said, as a contributor, I may not fully understand every part of the system. If this analysis turns out to be unnecessary, please feel free to close the issue.
Thank you.
@UlookEE You're absolutely right - I reviewed the code and your architectural analysis is spot on.
The current approach with _InstructionsLlmRequestProcessor and _ContentLlmRequestProcessor using heuristic repositioning is indeed fragile, and your concern about instructions ending up after user messages is valid.
This needs a proper architectural fix with dedicated dynamic_instruction support rather than the makeshift workaround.
Let me loop in @xuanyang15 and the team to discuss the proper solution path you've outlined - this is beyond a simple fix and needs design consideration.
Thanks!
@xuanyang15 Please have a look into it.
@seanzhou1023 Could you please help with this issue?
This issue has been automatically marked as stale because it has not had recent activity for 7 days after a maintainer requested clarification. It will be closed if no further activity occurs within 7 days.
@UlookEE @surajksharma07 Hi there! I've been following this discussion and it's been really helpful. I'm running into a similar friction point and did some digging, but I'm struggling to understand the architectural intent behind separating static_instruction vs. instruction if the latter is just appended as a user message.
Specifically, I’m trying to wrap my head around how appending dynamic instructions to the end of contents preserves the cache for multi-turn conversations. Wouldn't the pattern below result in a cache miss on the second turn?
Scenario:
Request 1: [static_sys] + [user_msg_1] + [dynamic_instruction_A] -> Cache Creates Fingerprint A
Request 2: [static_sys] + [user_msg_1] + [agent_response] + [user_msg_2] + [dynamic_instruction_B]
My Assumption: Since Request 2 replaces the tail end of Fingerprint A (dynamic_instruction_A) with agent_response, wouldn't the prefix match fail immediately after user_msg_1, causing a Cache MISS?
I feel like I might be missing a piece of the puzzle regarding how the history is constructed relative to that dynamic tail. Any clarification would be appreciated!
@mohannaguru-design
I have mainly analyzed Anthropic’s context caching in detail, so some parts of my understanding may differ slightly from the actual implementation.
You are correct. However, as far as I know, LLM providers offer the following types of solutions to address this issue:
Implicit Caching
- Detects and caches content that appears repeatedly.
- If
[static_sys] + [user_msg_1]continue to repeat across requests, caching will be applied there, meaning the cache may never reach[dynamic_instruction_A]. (This likely depends on the caching algorithm used by each LLM provider.)
Explicit Caching
- Allows users to specify the exact point up to which caching should be applied.
- In this scenario, the agent would determine the caching point by comparing the likelihood that the call up to
user_msg_1will be reused versus the cost of cache write/read. (In this case, caching atuser_msg_1, and then caching up touser_msg_2in the next call, seems optimal.) - If everything up to
[dynamic_instruction_A]is cached, cache misses may occur. However, in Claude’s case, even if some parts miss, it can still hit matching chunks and save tokens.
@UlookEE Thanks for the detailed breakdown!
I'm currently working specifically with Gemini's Explicit Caching, and it appears the implementation diverges significantly from the checkpoint-based model (like Claude's) that you described.
Unlike Claude, which allows for granular checkpoints (partial hits), Gemini's explicit cache functions more like an immutable snapshot. It seems to operate on an "all-or-nothing" prefix match basis. Once a cache is created via the ADK using the config below, it is effectively a frozen object:
context_cache_config=ContextCacheConfig(
min_tokens=2048, # Minimum tokens to trigger caching
ttl_seconds=600, # Store for up to 10 minutes
cache_intervals=5, # Refresh after 5 uses (Snapshots the current state)
)
The Compatibility Issue:
Because Gemini requires us to "snapshot" the history periodically (controlled by cache_intervals), the current ADK design seems fundamentally incompatible with dynamic instructions.
If we simply append a dynamic_instruction to the content list, the ADK will inevitably bake that transient instruction into the cached snapshot when the interval triggers. This effectively "poisons" the cache for subsequent turns, as the prefix will no longer match the new request (which won't have that specific dynamic instruction in the history).
My Question for the Team:
If we proceed with your suggested architectural improvement (adding a dedicated dynamic_instruction slot), wouldn't we also need to modify the cache processor to explicitly exclude this slot from the cache creation?
It seems we need a strict separation of "Cached Context" (System + History) vs. "Transient Context" (Dynamic Instructions) to make explicit caching work with Gemini.
Does that assessment align with your understanding?
@surajksharma07
@mohannaguru-design You're absolutely correct about the Gemini caching incompatibility.
Your assessment is spot-on: Gemini's snapshot-based explicit caching operates fundamentally differently from Claude's checkpoint model.
When cache_intervals triggers a snapshot, it freezes the entire content array including any dynamic instructions we've appended, which then poisons future cache lookups as you described.
This validates @UlookEE's original point that we need proper architectural support rather than the append-to-contents workaround. Here's what the fix should look like:
Architectural Solution:
We need to separate the request structure into three distinct layers that the cache processor understands:
- Cached Layer (system_instruction + static content): Never changes, always cached
- History Layer (conversation turns): Partially cached based on intervals
- Transient Layer (dynamic instructions): Excluded from cache creation
The cache processor would need to:
# In cache creation logic
cached_content = [
system_instruction,
...conversation_history # Up to cache_intervals
]
# Explicitly exclude dynamic_instruction slot from snapshot
# At request time, merge cached + transient
full_request = cached_content + dynamic_instructions + current_user_message
This means:
- Adding a dedicated
dynamic_instructionfield toGenerateContentConfig(as @UlookEE suggested) - Modifying the cache processor to skip this field when creating snapshots
- Tools would populate this field instead of using
append_instructions()
The key insight: For Gemini's all-or-nothing caching to work, we can't just move where we append - we need the cache system to know what not to cache.
The architectural redesign is more critical than we initially thought - it's not just about cache efficiency, it's about fundamental compatibility with Gemini's caching model.
@UlookEE - your proposed GenerateContentConfig subclass with dedicated dynamic instruction space is exactly what's needed here.
Team is looking more into it. Thanks!
I have mainly analyzed Anthropic’s context caching in detail, so some parts of my understanding may differ slightly from the actual implementation.
Hi @UlookEE, we are also using Anthropic models via vertex-ai and want to leverage context caching. But as per my understanding ADK currently supports only gemini models- source. Wanted to understand if you are able to use anthropic models in adk for context caching or your analysis is independent of adk
@maheshwaritanay
I haven't analyzed GCP’s Anthropic Claude in detail, but after briefly reviewing the official documentation, it appears that prompt caching is not supported. (Since a KV-cache–based prompt caching structure would likely require additional mechanisms, I assume it differs somewhat from simply supporting LLM usage.)
I am using Claude through LiteLLM, and LiteLLM allows control over the context delivered to the LLM before each call. Through this, it becomes possible to manage features such as prompt caching and dynamic instruction—which are currently impossible to implement in ADK—with relatively little concern.
However, since this approach deviates to some extent from ADK’s built-in control mechanisms, some level of inaccuracy may occur in areas such as OTel observability.
https://docs.cloud.google.com/vertex-ai/generative-ai/docs/partner-models/claude/prompt-caching?hl=ko
It is possible.
I haven’t tested it yet, but it seems like you can adjust the cache control options in a before LLM callback.
Since Claude only supports explicit caching, you must make sure to place your cache points in the right locations.
Checked against latest ADK (post v1.23.0): the core issue is still present.
While the team added static_instruction support at the agent level (separating static vs dynamic instructions), both load_artifacts_tool and preload_memory_tool still use append_instructions() with dynamic content — artifact lists and timestamped conversation history still get injected into system_instruction, invalidating prompt cache on every call.
No tool-level API for cache-aware dynamic content exists yet.
the architectural groundwork is there but the two offending tools haven't been updated.
We hit this in production on a multi-tenant Gemini shopping assistant (ADK + AG-UI on Cloud Run), and I can confirm it's still present on main (v2.3.0) — preload_memory_tool still calls append_instructions([...]), so the recalled-memory block lands in system_instruction.
Why it's especially bad with memory. PreloadMemoryTool selects memories by the current user query, so the injected block changes every turn. GeminiContextCacheManager._generate_cache_fingerprint hashes the entire system_instruction (+ tools + first-N contents), and handle_context_caching runs in google_llm.py after _preprocess_async — tools' process_llm_request run after the request processors (base_llm_flow.py), so the per-turn memory block is part of the fingerprint. Net effect: on any memory-enabled channel the explicit cache is rebuilt every turn. In one ~16-turn session we measured ~75% of prompt tokens re-billed at full price (only the implicit cache helped, and it goes cold during the 1–2 min inter-turn reading/typing pause).
static_instruction doesn't cover this case. It's documented as constant, no-placeholder content set at construction time. For a multi-tenant agent the stable system prompt is per-request (brand / persona / locale vary by channel via an instruction provider), so it can't live in static_instruction without pushing the large per-channel persona into the uncached tail — strictly worse. So the byte-stable prefix has to come from the dynamic instruction (→ system_instruction), which means tools have no first-class place to put post-cache dynamic content, exactly as @UlookEE described.
Interim workaround (matches @surajksharma07's suggestion). In a PreloadMemoryTool subclass we call super().process_llm_request(...), then diff system_instruction before/after and relocate the appended block to a trailing user content (inserted before the last user batch, mirroring _add_instructions_to_user_content). Using the before/after delta rather than string-matching the memory wording means it auto-no-ops the day the tool appends to contents itself. The same is needed for load_artifacts_tool.
Request: make this first-tier. A tool-accessible "dynamic instruction" slot (post-cache — e.g. a dedicated region of contents, or an LlmRequest API) so preload_memory_tool / load_artifacts_tool — and third-party tools — can add per-turn content without invalidating the explicit and implicit cache. The static_instruction groundwork is a great start, but as noted the two built-in tools still defeat caching out of the box on the most common setup (memory on). Happy to send a PR for the two tools if a minimal contents-append fix is acceptable while the larger design lands.