在ADK应用层配置Gemini上下文缓存

介绍在ADK的App对象上通过ContextCacheConfig启用上下文缓存,复用跨请求的指令与数据以减少重复发送的token。说明最小token阈值、TTL与复用次数等参数含义,并给出通过CacheMetadata判断缓存是否生效的方法。

## 用双子座缓存上下文[¶](<https://adk.dev/context/caching/#context-caching-with-gemini>) 支持于 ADKPython v1.15.0Java v0.1.0Kotlin v0.7.0 在与代理商合作完成任务时,您可能想要在多个代理商请求中重复使用扩展指令或大组数据到基因AI模型中. 将每个代理商请求的这一数据重排是缓慢的,效率低下的,并且可能很昂贵. 使用基因AI模型中上下文缓存特性可以显著加快响应速度,并降低每个请求发送给模型的令牌数量. ADK上下文缓存功能允许您使用支持它的基因化的AI模型缓存数据,包括Gemini 2.0和更高的模型. 本文解释如何配置和使用此功能. 实验 那个... `ContextCacheConfig` 类是实验性的,它的API或行为可能在未来的释放中发生改变。在 Python 中,构建一个发出警告;在 Kotlin 中,它需要 `@OptIn(ExperimentalContextCachingFeature::class)`. ## 配置上下文缓存[¶](<https://adk.dev/context/caching/#configure-context-caching>) 您在 ADK 配置上下文缓存功能 `App` 对象关卡,将您的代理件包起来。使用 `ContextCacheConfig` 分类以配置这些设置,如下代码样本所示: PythonJavaKotlin ``` from google.adk import Agent from google.adk.apps.app import App from google.adk.agents.context_cache_config import ContextCacheConfig root_agent = Agent( name='my_caching_agent', # configure an agent using Gemini 2.0 or higher ) # Create the app with context caching configuration app = App( name='my-caching-agent-app', root_agent=root_agent, 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 ), ) ``` ``` import com.google.adk.agents.BaseAgent; import com.google.adk.agents.ContextCacheConfig; import com.google.adk.apps.App; import java.time.Duration; // Create the app with context caching configuration App app = App.builder() .name("my-caching-agent-app") .rootAgent(rootAgent) .contextCacheConfig( new ContextCacheConfig( 5, /* cache_intervals (max invocations) */ Duration.ofMinutes(10), /* ttl */ 2048 /* min_tokens */)) .build(); ``` ``` import com.google.adk.kt.agents.ContextCacheConfig import com.google.adk.kt.agents.LlmAgent import com.google.adk.kt.annotations.ExperimentalContextCachingFeature import com.google.adk.kt.apps.App import com.google.adk.kt.models.Gemini import com.google.adk.kt.types.HttpOptions import kotlin.time.Duration.Companion.minutes import kotlin.time.Duration.Companion.seconds val rootAgent = LlmAgent( name = "my_caching_agent", // configure an agent using Gemini 2.0 or higher model = Gemini(name = "gemini-flash-latest"), ) // Create the app with context caching configuration @OptIn(ExperimentalContextCachingFeature::class) val app = App( appName = "my-caching-agent-app", rootAgent = rootAgent, contextCacheConfig = ContextCacheConfig( // Gemini applies its own minimum cacheable size, which varies by model minTokens = 8192, ttl = 10.minutes, // Store for up to 10 minutes cacheIntervals = 5, // Refresh after 5 uses // On timeout the create fails and the request proceeds uncached. createHttpOptions = HttpOptions(timeout = 10.seconds), ), ) ``` ## 配置设置[¶](<https://adk.dev/context/caching/#configuration-settings>) 那个... `ContextCacheConfig` 类有以下设置来控制您的代理服务器的缓存工作。当您配置这些设置时,它们适用于您的应用程序中的所有代理服务器。 - **`min_tokens`** (int): 允许缓存所需的最小的令牌数量。 此设置允许您避免对极小请求的缓存管理费, 因为执行好处可以忽略不计。 ADK 将设置与先前请求的快速令牌计数相比较, 因此会话中的第一个请求永远不会缓存。 默认为 `0`. - **`ttl_seconds`** (int): 以秒计缓存的 time-to-live( TTL) 。 此设置决定缓存内容在刷新前存储时间。 必须大于 `0`。默认为 `1800` (30分钟). - **`cache_intervals`** (int): 在同一缓存内容过期前可以使用的最大次数。 此设置允许您控制缓存更新的频率, 即使 TTL 尚未过期 。 必须是在两者之间 `1` 财务报告和财务报告 `100`。默认为 `10`. - **`create_http_options`** (HttpOptions):用于缓存创建呼叫的HTTP选项,它允许您设置一个超时。如果调用时间过期,则失败,请求不会缓存。在 Python 和 Kotlin 中可用;默认为零 。 ## 检查是否正在使用缓存[¶](<https://adk.dev/context/caching/#check-whether-the-cache-is-being-used>) 在ADKKotlin v0.6.0中支持过 当缓存被启用时,由LLM响应支持的事件可以携带一个 `CacheMetadata` 当缓存被禁用时, 以及当调用没有生成缓存信息时, 请在读取之前先检查它。 当它有两个状态: a **活动缓存**时, `cacheName`, `expireTime` 财务报告和财务报告 `invocationsUsed` 都准备好了,还有... **fingerprint-only** 州,三者皆为无效. ``` /** Reports whether the context cache was used for the LLM call behind [event]. */ fun logCacheUse(event: Event) { // Null when caching is disabled, and on any event whose LLM call produced // no cache information. val cache = event.cacheMetadata ?: return if (!cache.isActive) { // Fingerprint-only: ADK measured the cacheable prefix but no cache is in // use. That is the first turn, a prefix that changed since the last turn, // or a cache ADK did not create -- most often because the cacheable // prefix was below minTokens. println("Not cached yet; fingerprinted ${cache.contentsCount} contents.") return } println("Cache ${cache.cacheName} reused ${cache.invocationsUsed} time(s).") if (cache.expireSoon) { // Advisory only. ADK goes on reusing the cache until it actually expires, // so this is a heads-up for your own code, not a prediction about the // next turn. println("Cache is at or near expiry.") } } ``` `expireSoon` 表示缓存在大约两分钟内过期, 或者已经过期 。 它是您自己的代码的信号, 而不是 ADK 的行为 : ADK 持续重用缓存直到它实际上过期 。 `expireTime`,已经运行过去 `cacheIntervals`,或缓存的前缀更改。 Token 计数没有开始 `CacheMetadata`; 从 `LlmResponse.usageMetadata`. ## 今后的步骤[¶](<https://adk.dev/context/caching/#next-steps>) 关于如何充分利用和测试上下文缓存特征,请参见以下样本: - [`cache_analysis`](<https://github.com/google/adk-python/tree/main/contributing/samples/context_management/cache_analysis>):一个代码样本,可以演示如何分析上下文缓存的性能. 如果您使用时需要您提供整个会话中使用的指令,请考虑使用 `static_instruction` 用于代理的参数,允许您修改基因模型的系统指令。详情请参见此样本代码: - [`static_instruction`](<https://github.com/google/adk-python/tree/main/contributing/samples/context_management/static_instruction>):使用静态指令执行数字宠物代理.

查看原始来源