|
| 1 | +# Copyright 2025 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +"""Context cache processor for LLM requests.""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import logging |
| 20 | +from typing import AsyncGenerator |
| 21 | +from typing import Optional |
| 22 | +from typing import TYPE_CHECKING |
| 23 | + |
| 24 | +from ...events.event import Event |
| 25 | +from ...models.cache_metadata import CacheMetadata |
| 26 | +from ._base_llm_processor import BaseLlmRequestProcessor |
| 27 | + |
| 28 | +if TYPE_CHECKING: |
| 29 | + from ...agents.invocation_context import InvocationContext |
| 30 | + from ...models.llm_request import LlmRequest |
| 31 | + |
| 32 | +logger = logging.getLogger('google_adk.' + __name__) |
| 33 | + |
| 34 | + |
| 35 | +class ContextCacheRequestProcessor(BaseLlmRequestProcessor): |
| 36 | + """Request processor that enables context caching for LLM requests. |
| 37 | +
|
| 38 | + This processor sets up context caching configuration for agents that have |
| 39 | + context caching enabled and finds the latest cache metadata from session |
| 40 | + events. The actual cache management is handled by the model-specific cache |
| 41 | + managers (e.g., GeminiContextCacheManager). |
| 42 | + """ |
| 43 | + |
| 44 | + async def run_async( |
| 45 | + self, invocation_context: 'InvocationContext', llm_request: 'LlmRequest' |
| 46 | + ) -> AsyncGenerator[Event, None]: |
| 47 | + """Process LLM request to enable context caching. |
| 48 | +
|
| 49 | + Args: |
| 50 | + invocation_context: Invocation context containing agent and session info |
| 51 | + llm_request: Request to process for caching |
| 52 | +
|
| 53 | + Yields: |
| 54 | + Event: No events are yielded by this processor |
| 55 | + """ |
| 56 | + agent = invocation_context.agent |
| 57 | + |
| 58 | + # Return early if no cache config |
| 59 | + if not invocation_context.context_cache_config: |
| 60 | + return |
| 61 | + |
| 62 | + # Set cache config to request |
| 63 | + llm_request.cache_config = invocation_context.context_cache_config |
| 64 | + |
| 65 | + # Find latest cache metadata from session events |
| 66 | + latest_cache_metadata = self._find_latest_cache_metadata( |
| 67 | + invocation_context, agent.name, invocation_context.invocation_id |
| 68 | + ) |
| 69 | + |
| 70 | + if latest_cache_metadata: |
| 71 | + llm_request.cache_metadata = latest_cache_metadata |
| 72 | + logger.debug( |
| 73 | + 'Found cache metadata for agent %s: invocations_used=%d, ' |
| 74 | + 'cached_contents=%d', |
| 75 | + agent.name, |
| 76 | + latest_cache_metadata.invocations_used, |
| 77 | + latest_cache_metadata.cached_contents_count, |
| 78 | + ) |
| 79 | + |
| 80 | + logger.debug('Context caching enabled for agent %s', agent.name) |
| 81 | + |
| 82 | + # This processor yields no events |
| 83 | + return |
| 84 | + yield # AsyncGenerator requires a yield in function body |
| 85 | + |
| 86 | + def _find_latest_cache_metadata( |
| 87 | + self, |
| 88 | + invocation_context: 'InvocationContext', |
| 89 | + agent_name: str, |
| 90 | + current_invocation_id: str, |
| 91 | + ) -> Optional[CacheMetadata]: |
| 92 | + """Find the latest cache metadata from session events. |
| 93 | +
|
| 94 | + Args: |
| 95 | + invocation_context: Context containing session with events |
| 96 | + agent_name: Name of agent to find cache metadata for |
| 97 | + current_invocation_id: Current invocation ID to compare for increment |
| 98 | +
|
| 99 | + Returns: |
| 100 | + Latest cache metadata for the agent (with updated invocations_used |
| 101 | + if needed), or None if not found |
| 102 | + """ |
| 103 | + if not invocation_context.session or not invocation_context.session.events: |
| 104 | + return None |
| 105 | + |
| 106 | + # Search events from most recent to oldest using index traversal |
| 107 | + events = invocation_context.session.events |
| 108 | + for i in range(len(events) - 1, -1, -1): |
| 109 | + event = events[i] |
| 110 | + if event.cache_metadata is not None and event.author == agent_name: |
| 111 | + |
| 112 | + cache_metadata = event.cache_metadata |
| 113 | + |
| 114 | + # Check if this is a different invocation - increment invocations_used |
| 115 | + if event.invocation_id and event.invocation_id != current_invocation_id: |
| 116 | + # Different invocation - increment invocations_used |
| 117 | + return cache_metadata.model_copy( |
| 118 | + update={'invocations_used': cache_metadata.invocations_used + 1} |
| 119 | + ) |
| 120 | + else: |
| 121 | + # Same invocation or no invocation_id - return as-is |
| 122 | + return cache_metadata |
| 123 | + |
| 124 | + return None |
| 125 | + |
| 126 | + |
| 127 | +# Create processor instance for use in flows |
| 128 | +request_processor = ContextCacheRequestProcessor() |
0 commit comments