ADK 智能体上下文压缩的两种触发策略

ADK 在智能体运行中累积用户指令、检索数据、工具响应等上下文,数据增长会拉长处理时间。文章介绍基于令牌量与滑动窗口两种压缩策略,并说明压缩配置项的含义与触发时机。

## 为性能压缩代理上下文[¶](<https://adk.dev/context/compaction/#compress-agent-context-for-performance>) 支持于 ADKPython v1.16.0Go v2.3.0Java v0.2.0 TypeScript v0.6.0Kotlin v0.7.0 中 当一个ADK特工运行时,它收集 *上下文* 信息,包括用户指令,检索数据,工具响应,以及生成的内容。随着此上下文数据的大小增加,代理处理时间通常也会增加。越来越多的数据被发送到代理使用的基因化的AI模型,增加处理时间并减缓响应速度。ADK Contaction 特性旨在通过总结旧会话历史(包括指令、输入和模型响应)来减少代理运行时的背景大小。通过保持紧凑的上下文窗口,这一过程 **优化延缓性,降低成本** 同时确保代理人能够保持基本的近期互动。 压缩自动运行,以您在 `EventsCompactionConfig`。在通过 SingleFlow 的模型调用之前,先检查基于托肯的压缩件。 `CompactionRequestProcessor`,然后再次在 `Runner` 在每次引用之后。滑动的窗口紧凑在 `Runner` 在每次引用完成之后。 ## 选择策略[¶](<https://adk.dev/context/compaction/#choose-your-strategy>) 您可以使用下列策略管理您的会话数据: `EventsCompactionConfig`: - **基于托肯(小学)**: 触发器根据实际消耗的令牌数量进行清理。 这对于无法预测的工作量来说是一个绝对的安全网, 就像用户粘贴大量代码块或上传大文件时一样。 - **滑动窗口( 回合制)**: 在固定次数的对讲转折后进行触发清理。 这对经常的、可预测的文本聊天很有用 。 如果您配置了两种压缩策略, 系统会优先排序基于符号的压缩。 当会话长度超过您定义的符号阈值时, 系统会触发基于符号的压缩, 并跳过该方向的滑动窗口压缩 。 ## 基于托肯的压缩[¶](<https://adk.dev/context/compaction/#token-based-compaction>) 基于托肯的收缩触发了基于令牌或数据量的上下文管理,而不是事件或转折的次数. ### 配置设置[¶](<https://adk.dev/context/compaction/#configuration-settings>) 在代理工作流程中添加基于令牌的压缩 `EventsCompactionConfig` 设置到 App 对象。您必须指定以下内容: - **`token_threshold`**: 自动触发尾部保留紧固物一旦到达的令牌的安全限制. - **`event_retention_size`**: 触发紧凑时, 以“ raw” 未压缩格式保存的最近事件/ 交互次数。 这保持了即时对话上下文和代名解析度 。 要在您的项目中执行基于符号的压缩, 请使用以下配置 : PythonGo ``` # 1. Correct the import path to use the google.adk namespace from google.adk.apps.app import App, EventsCompactionConfig from google.adk.agents import Agent # 2. Initialize your root agent (required for App setup) root_agent = Agent( name="my_root_agent", description="Main coordinating agent for the workflow." ) # 3. Token-based configuration: Activates the priority/pre-call layer compaction_config = EventsCompactionConfig( token_threshold=4000, # Triggers compaction when actual token count exceeds this event_retention_size=5 # Number of recent raw events to keep intact when token limit is hit ) # 4. Register with required name and root_agent fields, and the config object app = App( name="my_compacting_agent_app", root_agent=root_agent, events_compaction_config=compaction_config ) ``` ``` import ( "google.golang.org/adk/v2/runner" "google.golang.org/adk/v2/session/compaction" ) // Set both fields, or runner.New returns an error. r, err := runner.New(runner.Config{ AppName: "my_compacting_agent_app", Agent: rootAgent, SessionService: sessionService, Compaction: &compaction.Config{ TokenThreshold: 4000, // Compact once the prompt reaches this many tokens. EventRetentionSize: 5, // Number of recent raw events to keep intact. }, }) ``` ## 滑动窗口紧凑[¶](<https://adk.dev/context/compaction/#sliding-window-compaction>) 上下文压缩特性使用 a *滑动窗口* 收集和总结代理工作流程数据的方法 [会话](<https://adk.dev/sessions/session/>)。当您在代理服务器中配置此功能时,当它在本会话中达到特定数量的新引用阈值时,它会汇总来自旧事件的数据。 ``` # (Optional) Invocation-based, sliding window as supplementary setting compaction_config = EventsCompactionConfig( compaction_interval=10, # Number of new invocations between standard compactions overlap_size=2, # Number of prior invocations to retain as overlapping context ) ``` ## 配置上下文压缩[¶](<https://adk.dev/context/compaction/#configure-context-compaction>) 在代理工作流程中添加上下文收缩, 在 App 对象( Python/ Java/ Kotlin) 中添加事件收缩配置设置, 通过配置 `contextCompactors` 编辑 `LlmAgent` (TypeScript),或设置 `Compaction` 作为配置的一部分,您必须指定压缩间隔和重叠大小(Python/Java)、压缩间隔和可选择的重叠大小(Go),或符号阈值和事件保留大小(TypeScript/Kotlin/Go),如下样码所示: PythonJavaTypeScriptKotlinGo ``` from google.adk.apps.app import App from google.adk.apps.app import EventsCompactionConfig app = App( name='my-agent', root_agent=root_agent, events_compaction_config=EventsCompactionConfig( compaction_interval=3, # Trigger compaction every 3 new invocations. overlap_size=1 # Include last invocation from the previous window. ), ) ``` ``` import com.google.adk.apps.App; import com.google.adk.summarizer.EventsCompactionConfig; App app = App.builder() .name("my-agent") .rootAgent(rootAgent) .eventsCompactionConfig(EventsCompactionConfig.builder() .compactionInterval(3) // Trigger compaction every 3 new invocations. .overlapSize(1) // Include last invocation from the previous window. .build()) .build(); ``` ``` import {Gemini, LlmAgent, LlmSummarizer, TokenBasedContextCompactor} from '@google/adk'; const agent = new LlmAgent({ name: 'my-agent', model: 'gemini-flash-latest', contextCompactors: [ new TokenBasedContextCompactor({ tokenThreshold: 1000, // Trigger compaction when session exceeds 1000 tokens. eventRetentionSize: 1, // Keep at least 1 raw event (overlap). summarizer: new LlmSummarizer({ llm: new Gemini({model: 'gemini-flash-latest'}), }), }), ], }); ``` ``` import com.google.adk.kt.apps.App import com.google.adk.kt.summarizer.EventsCompactionConfig // tokenThreshold and eventRetentionSize must be set together; either alone throws. // Kotlin also accepts the compactionInterval/overlapSize pair used in the other tabs. val app = App( appName = "my-agent", rootAgent = rootAgent, eventsCompactionConfig = EventsCompactionConfig( tokenThreshold = 1000, // Compact when the last prompt exceeds 1000 tokens. eventRetentionSize = 1, // Keep at least 1 raw event. ), ) ``` ``` import ( "google.golang.org/adk/v2/runner" "google.golang.org/adk/v2/session/compaction" ) // Compaction is set on the runner rather than on an App object. r, err := runner.New(runner.Config{ AppName: "my-agent", Agent: rootAgent, SessionService: sessionService, Compaction: &compaction.Config{ CompactionInterval: 3, // Trigger compaction every 3 new invocations. OverlapSize: 1, // Include last invocation from the previous window. }, }) ``` 配置后, ADK `Runner` 每次会话达到所配置的间隔或符号阈值时,都会处理压缩过程。 ## 上下文压缩实例[¶](<https://adk.dev/context/compaction/#example-of-context-compaction>) 如果你准备好了 `compaction_interval` 3号卫星和 `overlap_size` 到 1 , 事件数据在引用完成 3 , 6 , 9 等时进行压缩. 重叠设置会增加第二次摘要压缩的大小, 以及之后的每次摘要, 如图 1 所示. ![上下文压缩示例示例](<https://adk.dev/assets/context-compaction.svg>) **图1.** 以3的间隔和1的重叠来说明事件压缩配置. 有了这个示例配置,上下文压缩任务发生如下: 1. **使用 3 完成**: 所有 3 引用被压缩成摘要 2. **使用 6 完成**: 引用 3 到 6 被压缩,包括 1 前引用的重叠 3. **使用 9 完成**: 引用 6 到 9 被压缩,包括 1 前引用的重叠 ## 配置设置[¶](<https://adk.dev/context/compaction/#configuration-settings_1>) 此特性的配置设置可以控制事件数据被压缩的频率, 以及代理工作流程运行时保留多少数据。 您可以选择配置压缩器对象 。 - **`compaction_interval`**: 设置已完成的新用户启动的引用次数,这些引用会触发前一个事件数据的压缩。必须大于 `0`,并必须与 `overlap_size`. - **`overlap_size`**:设定在新压缩的上下文集中包含多少以前压缩的引用. - **`summarizer`**: (可选)定义一个概括对象,包括一个用于归纳的特定AI模型。 [定义摘要](<https://adk.dev/context/compaction/#define-summarizer>). ### 定义摘要[¶](<https://adk.dev/context/compaction/#define-summarizer>) 您可以通过定义摘要来自定义上下文压缩的过程。 `LlmEventSummarizer` (Python、Java和Kotlin), `LlmSummarizer` (TypeScript) 或 (中文(简体) ). `LLMSummarizer` (Go) 类允许您指定一个特定的模型进行归纳。 以下代码示例演示了如何定义和配置自定义摘要 : PythonJavaTypeScriptKotlinGo ``` from google.adk.apps.app import App, EventsCompactionConfig from google.adk.apps.llm_event_summarizer import LlmEventSummarizer from google.adk.models import Gemini # Define the AI model to be used for summarization: summarization_llm = Gemini(model="gemini-flash-latest") # Create the summarizer with the custom model: my_summarizer = LlmEventSummarizer(llm=summarization_llm) # Configure the App with the custom summarizer and compaction settings: app = App( name='my-agent', root_agent=root_agent, events_compaction_config=EventsCompactionConfig( compaction_interval=3, overlap_size=1, summarizer=my_summarizer, ), ) ``` ``` import com.google.adk.apps.App; import com.google.adk.models.Gemini; import com.google.adk.summarizer.EventsCompactionConfig; import com.google.adk.summarizer.LlmEventSummarizer; // Define the AI model to be used for summarization: Gemini summarizationLlm = Gemini.builder() .model("gemini-flash-latest") .build(); // Create the summarizer with the custom model: LlmEventSummarizer mySummarizer = new LlmEventSummarizer(summarizationLlm); // Configure the App with the custom summarizer and compaction settings: App app = App.builder() .name("my-agent") .rootAgent(rootAgent) .eventsCompactionConfig(EventsCompactionConfig.builder() .compactionInterval(3) .overlapSize(1) .summarizer(mySummarizer) .build()) .build(); ``` ``` import {Gemini, LlmAgent, LlmSummarizer, TokenBasedContextCompactor} from '@google/adk'; // Define the AI model to be used for summarization: const summarizationLlm = new Gemini({model: 'gemini-flash-latest'}); // Create the summarizer with the custom model: const mySummarizer = new LlmSummarizer({llm: summarizationLlm}); // Configure the agent with the custom summarizer and compaction settings: const agent = new LlmAgent({ name: 'my-agent', model: 'gemini-flash-latest', contextCompactors: [ new TokenBasedContextCompactor({ tokenThreshold: 1000, eventRetentionSize: 1, summarizer: mySummarizer, }), ], }); ``` ``` import com.google.adk.kt.apps.App import com.google.adk.kt.models.Gemini import com.google.adk.kt.summarizer.EventsCompactionConfig import com.google.adk.kt.summarizer.LlmEventSummarizer // Define the AI model to be used for summarization: val summarizationLlm = Gemini(name = "gemini-flash-latest") // Create the summarizer with the custom model: val mySummarizer = LlmEventSummarizer(model = summarizationLlm) // Configure the App with the custom summarizer and compaction settings: val app = App( appName = "my-agent", rootAgent = rootAgent, eventsCompactionConfig = EventsCompactionConfig( compactionInterval = 3, overlapSize = 1, summarizer = mySummarizer, ), ) ``` ``` import ( "google.golang.org/adk/v2/model/gemini" "google.golang.org/adk/v2/runner" "google.golang.org/adk/v2/session/compaction" ) // Define the AI model to be used for summarization: summarizationLLM, err := gemini.NewModel(ctx, "gemini-flash-latest", nil) // Create the summarizer with the custom model: mySummarizer, err := compaction.NewLLMSummarizer(compaction.LLMSummarizerConfig{ Model: summarizationLLM, }) // Configure the runner with the custom summarizer and compaction settings: r, err := runner.New(runner.Config{ AppName: "my-agent", Agent: rootAgent, SessionService: sessionService, Compaction: &compaction.Config{ CompactionInterval: 3, OverlapSize: 1, Summarizer: mySummarizer, }, }) ``` 您可以通过修改压缩器的总结来进一步完善压缩器。 在 Python、 Java 和 Kotlin 中, 将快捷模板自定义于 `LlmEventSummarizer` - 财产是 `prompt_template` 在 Python 中,以及 `promptTemplate` 在 Java 和 Kotlin 中。在 TypeScript 中,自定义 `prompt` 打开 `LlmSummarizer`在 Go 中,设置 `PromptTemplate` 打开 `LLMSummarizerConfig`;必须包含 `{conversation_history}` 占位符。详细情况见 [`LlmEventSummarizer` 代码](<https://github.com/google/adk-python/blob/main/src/google/adk/apps/llm_event_summarizer.py#L60>) 或 时 间 [`LlmSummarizer` 代码](<https://github.com/google/adk-js/blob/main/core/src/context/summarizers/llm_summarizer.ts>).

查看原始来源