跳转到内容

使用 Gemini 实现上下文缓存(Context caching)

在 ADK 中得到支持。Python v1.15.0Java v0.1.0Kotlin v0.7.0

在与代理协作完成任务时,您可能希望将一些扩展后的指令或大量数据重复用于多个代理对生成式 AI 模型的请求中。每次请求时都重新发送这些数据不仅效率低下,而且成本较高。利用生成式 AI 模型中的上下文缓存功能,可以显著加快响应速度,并减少每次请求时需要发送给模型的数据量(即“令牌”数量)。

ADK Context Caching 功能允许您使用支持该功能的生成式 AI 模型(包括 Gemini 2.0 及更高版本的模型)来缓存请求数据。本文档介绍了如何配置和使用该功能。

实验性的(Experimental)

The ContextCacheConfig 该类仍处于实验阶段,其 API 或行为可能会在未来的版本中发生变化。在 Python 中,使用该类会触发警告;而在 Kotlin 中,则需要特别处理(即需要编写相应的代码来确保兼容性)。 @OptIn(ExperimentalContextCachingFeature::class).

配置上下文缓存

您可以在 ADK 中配置上下文缓存功能。 App 在对象级别(object level)进行封装;该封装层会包裹你的代理(agent)。请使用相应的工具或方法来实现这一功能。 ContextCacheConfig 用于配置这些设置的类,如下代码示例所示:

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),
            ),
    )

配置设置

The ContextCacheConfig 该类包含以下设置,用于控制代理的缓存机制。一旦您配置了这些设置,它们将适用于应用程序中的所有代理。

  • min_tokens (int):启用缓存所需的最小令牌数量。此设置可帮助您避免对那些请求量非常小、且性能提升几乎可以忽略不计的请求进行缓存处理,从而避免不必要的开销。ADK 会将当前设置的令牌数量与上一次请求的令牌数量进行比较;因此,会话中的第一个请求永远不会被缓存。默认值为…… 0.
  • ttl_seconds (int):缓存的有效期(TTL),单位为秒。 此设置决定了缓存内容在被刷新之前会保留多长时间。该值必须大于 0。 0默认值为: 1800 (30分钟后)。
  • cache_intervals (int):相同缓存内容在过期前可以被使用的最大次数。此设置允许您控制缓存的更新频率,即使缓存的有效期(TTL)尚未到期。该值必须介于……和……之间。 1 和 100默认值为: 10.
  • create_http_options (HttpOptions):用于缓存创建请求的 HTTP 配置选项,允许您设置超时时间。如果请求超时,该请求将失败,并且后续请求将不会被缓存。该选项在 Python 和 Kotlin 中均可用;默认值为“无”(即不设置超时时间)。

检查是否正在使用缓存。

在 ADK 中得到支持。Kotlin v0.6.0

当缓存功能被启用时,由大型语言模型(LLM)生成的响应所支持的事件可以携带某些信息(或数据)。 CacheMetadata 报告缓存对该请求所做的处理。当缓存功能被禁用时,该值为空;当请求没有产生任何缓存相关信息时,该值同样为空。因此,在读取该值之前请先进行检查。如果该值存在,它有两种可能的状态: active cache……其中 cacheName, expireTime 和 invocationsUsed 所有准备工作都已经完成,接下来就可以开始了。 仅支持指纹识别(fingerprint-only) `state` 的值为 `null`,同时这三个字段(`state` 以及与之相关的其他两个字段)也都为 `null`。

/** 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 counts are not on” 的意思是:当前系统尚未启用对令牌(Token)数量的统计功能。 CacheMetadata;从……中读取它们 LlmResponse.usageMetadata.

下一步骤

有关如何使用和测试上下文缓存功能的完整实现方法,请参阅以下示例:

  • cache_analysis: 一个代码示例,演示了如何分析上下文缓存(context caching)的性能。

如果您的使用场景需要提供在整个会话期间都适用的指令,那么可以考虑使用……(此处应填写具体的工具或方法名称)。 static_instruction 这是一个用于代理的参数,它允许你修改生成模型的系统指令。有关更多详细信息,请参阅以下示例代码: