ADK会话状态作为对话临时存储的机制
ADK在各语言版本中为每个Session提供state属性,以键值对形式存放对话期间需要动态更新的信息,与保存完整历史的events区分开,用于个性化交互和跟踪多轮任务进度。
## 状态: 会话剪辑板[¶](<https://adk.dev/sessions/state/#state-the-sessions-scratchpad>) 支持于 ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0Kotlin v0.1.0 中 内 `Session` (我们的谈话线), **`state`** 属性可以像代理人的专用抓图来进行特定的交互。虽然 `session.events` 拥有完整的历史, `session.state` 代理存储和更新所需的动态细节的地方 *期间* 谈话。 ## 何谓 `session.state`?[¶](<https://adk.dev/sessions/state/#what-is-sessionstate>) 从概念上来说, `session.state` 是一个收藏( 词典或地图) , 持有密钥值对 。 它旨在提供代理机需要调用或跟踪的信息, 以使当前对话有效 : - **个性化交互 :** 记住前面提到的用户偏好(例如, `'user_preference_theme': 'dark'`). - **音轨任务进度 :** 在多回合进程中保持对步骤的跟踪(例如, `'booking_step': 'confirm_payment'`). - **累积信息:** 建立列表或摘要(例如, `'shopping_cart_items': ['book', 'pen']`). - **作出知情决定:** 存储影响下一个响应的旗帜或值(例如, `'user_is_authenticated': True`). ### 关键特征 `State`[¶](<https://adk.dev/sessions/state/#key-characteristics-of-state>) 1. **结构:可序列键值对等** - 数据存储为 `key: value`. - **密钥 :** 总是字符串( E)`str`。使用明确的名称(例如, `'departure_city'`, `'user:language_preference'`). - **数值 :** 一定是这样 **可序列化**。这意味着它们很容易被保存和装入。 `SessionService`。坚持特定语言(Python/Go/Java/ TypeScript)中的基本类型,如字符串、数字、布尔语、以及包含简单的列表或词典。 *仅限* 这些基本类型。 (详细情况见API文档)。 - **QQ 避免复杂对象 :** **不存储非串行对象** 直接在状态中保存简单的标识符, 并获取其它复杂的对象 。 2. **变异性:它会改变** - 报告的内容 `state` 预计随着对话的发展,对话将发生变化。 3. **持久性:取决于 `SessionService`** - 状态是否幸存应用程序重新启动取决于您选择的服务 : - `InMemorySessionService`: **不执着.** 状态在重启时丢失 。 - `DatabaseSessionService` / `VertexAiSessionService`: **坚持不懈。** 国家得到可靠保存。 说明 原始人的具体参数或方法名称可能因SDK语言(例如,)而略有不同. `session.state['current_intent'] = 'book_flight'` 在蟒蛇中,`context.State().Set("current_intent", "book_flight")` 继续前进 `session.state().put("current_intent", "book_flight)` 在爪哇语中,或 `context.state.set("current_intent", "book_flight")` 在TypeScript中). 详见语言专用的API文档. ### 有前缀的组织国:范围事项[¶](<https://adk.dev/sessions/state/#organizing-state-with-prefixes-scope-matters>) 状态密钥上的前缀定义了它们的范畴和持久性行为,特别是在持久性服务中: - **无前缀( 会议国) :** - **范围:** 具体内容: *当前* 届会`id`). - **持久性 :** 只有在 `SessionService` 具有持久性( E)`Database`, `VertexAI`). - **使用大小写 :** 跟踪当前任务的进展情况(例如: `'current_booking_step'`),用于此交互作用的临时旗帜(例如, `'needs_clarification'`). - **示例:** `session.state['current_intent'] = 'book_flight'` - **`user:` 前缀( 用户状态 ) :** - **范围:** 被绑在床上 `user_id`,共享 *全部( E)* 用于该用户的会话(在同一段内) `app_name`). - **持久性 :** 持续使用 `Database` 或 时 间 `VertexAI`. (由 `InMemory` 但是在重新启动时丢失). - **使用大小写 :** 用户偏好(例如, `'user:theme'`),简介细节(例如, `'user:name'`). - **无会话阅读 :** 在皮森语中 `await session_service.get_user_state(app_name=..., user_id=...)` 返回带有下列内容的用户范围密钥: `user:` 前缀剥离,所以可以在会话存在前读取。 `VertexAiSessionService` 是个例外: 总是会增加 `NotImplementedError`,因为代理 Runtime API 并不独立于会话显示用户状态。 `list_sessions` 打电话 `get_session` 以每个结果代替。 - **示例:** `session.state['user:preferred_language'] = 'fr'` - **`app:` 前缀( App 状态) :** - **范围:** 被绑在床上 `app_name`,共享 *全部( E)* 该应用程序的用户和会话。 - **持久性 :** 持续使用 `Database` 或 时 间 `VertexAI`. (由 `InMemory` 但是在重新启动时丢失). - **使用大小写 :** 全球设置(例如, `'app:api_endpoint'`),共享模板. - **示例:** `session.state['app:global_discount_code'] = 'SAVE10'` - **`temp:` 前缀(临时召集国):** - **范围:** 具体针对当前 **援引** (从接受用户输入的代理到为该输入生成最终产出的整个过程). - **持久性 :** **不执着.** 引用完成后弃置,不结转至下一部. - **使用大小写 :** 将中间计算、旗子或数据存储在单一引用范围内的工具调用之间。 - **不使用时 :** 对于必须贯穿不同引用的信息,例如用户偏好、对话历史摘要或累积数据。 - **示例:** `session.state['temp:raw_api_response'] = {...}` 子代理人和援引背景 当父代理人调用子代理人(例如使用) `SequentialAgent` 或 时 间 `ParallelAgent`),它通过它的 `InvocationContext` 这意味着整个代理电话链 共享相同的引用 ID , 并因此相同 `temp:` 状态。 **探员怎么看的?** 您的代理代码与 *合计* 状态通过单数 `session.state` 收藏(数字/地图)。 `SessionService` 手柄从基于前缀的正确基础存储中获取/合并状态。 ### 在代理指令中访问会话状态[¶](<https://adk.dev/sessions/state/#accessing-session-state-in-agent-instructions>) 工作时 `LlmAgent` 实例中,您可以使用简单的调试语法直接将会话状态值注入代理指令字符串中。这使得您可以创建动态和上下文感知指令,而无需完全依赖自然语言指令。 #### 使用( E) `{key}` 调情[¶](<https://adk.dev/sessions/state/#using-key-templating>) 要从会话状态中注入一个值, 请将想要的状态变量的密钥包含在卷曲框中 : `{key}`。框架将自动替换该占位符,其值对应来自 `session.state` 在将指令传递给LLM之前. **示例:** PythonTypeScriptGoJavaKotlin ``` from google.adk.agents import LlmAgent story_generator = LlmAgent( name="StoryGenerator", model="gemini-flash-latest", instruction="""Write a short story about a cat, focusing on the theme: {topic}.""" ) # Assuming session.state['topic'] is set to "friendship", the LLM # will receive the following instruction: # "Write a short story about a cat, focusing on the theme: friendship." ``` ``` import { LlmAgent } from "@google/adk"; const storyGenerator = new LlmAgent({ name: "StoryGenerator", model: "gemini-flash-latest", instruction: "Write a short story about a cat, focusing on the theme: {topic}." }); // Assuming session.state['topic'] is set to "friendship", the LLM // will receive the following instruction: // "Write a short story about a cat, focusing on the theme: friendship." ``` ``` func main() { ctx := context.Background() sessionService := session.InMemoryService() // 1. Initialize a session with a 'topic' in its state. _, err := sessionService.Create(ctx, &session.CreateRequest{ AppName: appName, UserID: userID, SessionID: sessionID, State: map[string]any{ "topic": "friendship", }, }) if err != nil { log.Fatalf("Failed to create session: %v", err) } // 2. Create an agent with an instruction that uses a {topic} placeholder. // The ADK will automatically inject the value of "topic" from the // session state into the instruction before calling the LLM. model, err := gemini.NewModel(ctx, modelID, nil) if err != nil { log.Fatalf("Failed to create Gemini model: %v", err) } storyGenerator, err := llmagent.New(llmagent.Config{ Name: "StoryGenerator", Model: model, Instruction: "Write a short story about a cat, focusing on the theme: {topic}.", }) if err != nil { log.Fatalf("Failed to create agent: %v", err) } r, err := runner.New(runner.Config{ AppName: appName, Agent: agent.Agent(storyGenerator), SessionService: sessionService, }) if err != nil { log.Fatalf("Failed to create runner: %v", err) } ``` ``` import com.google.adk.agents.LlmAgent; LlmAgent storyGenerator = LlmAgent.builder() .name("StoryGenerator") .model(geminiModel) .instruction("Write a short story about a cat, focusing on the theme: " + topic) .build(); // Assuming session.state().put("topic", "friendship"), the LLM // will receive the following instruction: // "Write a short story about a cat, focusing on the theme: friendship." ``` ``` fun instructionTemplating(model: Gemini) { val storyGenerator = LlmAgent( name = "StoryGenerator", model = model, instruction = Instruction( "Write a short story about a cat, focusing on the theme: {topic}.", ), ) // Assuming session.state["topic"] is set to "friendship", the LLM // will receive the following instruction: // "Write a short story about a cat, focusing on the theme: friendship." } ``` #### 重要考虑[¶](<https://adk.dev/sessions/state/#important-considerations>) - Key 存在: 确保您在指令字符串中引用的密钥存在于会话中. state。 如果缺少密钥, 代理将丢出一个错误。 要使用可能存在或可能不存在的密钥, 您可以在密钥( 如 {topic?}) 后添加一个问号 (? ) 。 - 数据类型(Data Type):与密钥相关的值应为字符串或可以轻松转换成字符串的类型. - 字形曲线带: `{key}` 语法匹配单曲括号内任何有效的 Python 标识符。 如果您在指令中需要字母缩写, 如用于 JSON 格式化或调制语法, 请使用一个 `InstructionProvider` 函数代替字符串(见下文)。 f-弦和双牙架 一些ADK的例子在指令中使用了Python f-strings,例如: `f"Topic: {{initial_topic}}"`。该数字 `{{` 财务报告和财务报告 `}}` 这些例子包括: **Python f - string 逃逸( Python f - string 逃逸)**,而不是 ADK 语法。运行时, Python 转换 `{{initial_topic}}` 改为: `{initial_topic}`,然后将 ADK 作为普通状态变量占位符处理。如果您不使用 f- 字符串,请使用单个括号 `{key}` 直接来. #### 使用( E) `InstructionProvider` 用于全控[¶](<https://adk.dev/sessions/state/#using-instructionprovider-for-full-control>) 在某些情况下,你可能需要对指令字符串的完全控制——例如,当你的指令包含字面的卷曲括号(如JSON例,诱导语法),否则会解释为状态可变的占位符. 为了实现这一点,向 `instruction` 参数而不是字符串。此函数称为 `InstructionProvider`。当您使用 `InstructionProvider`,ADK将 **没有** 尝试注入状态变量,返回的字符串将会作为-is传递给模型。 那个... `InstructionProvider` 函数收到一个 `ReadonlyContext` 对象,如果需要动态构建指令,您可以用它来访问会话状态或其他背景信息。 PythonTypeScriptGoJavaKotlin ``` from google.adk.agents import LlmAgent from google.adk.agents.readonly_context import ReadonlyContext # This is an InstructionProvider def my_instruction_provider(context: ReadonlyContext) -> str: # No state injection occurs — curly braces are treated as literal text. return 'Format your output as JSON: {"city": "<name>", "population": <number>}' agent = LlmAgent( model="gemini-flash-latest", name="template_helper_agent", instruction=my_instruction_provider ) ``` ``` import { LlmAgent, ReadonlyContext } from "@google/adk"; // This is an InstructionProvider function myInstructionProvider(context: ReadonlyContext): string { // No state injection occurs — curly braces are treated as literal text. return 'Format your output as JSON: {"city": "<name>", "population": <number>}'; } const agent = new LlmAgent({ model: "gemini-flash-latest", name: "template_helper_agent", instruction: myInstructionProvider }); ``` ``` // 1. This InstructionProvider returns a static string. // Because it's a provider function, the ADK will not attempt to inject // state, and the instruction will be passed to the model as-is, // preserving the literal braces. func staticInstructionProvider(ctx agent.ReadonlyContext) (string, error) { return "This is an instruction with {{literal_braces}} that will not be replaced.", nil } ``` ``` import com.google.adk.agents.Instruction; import com.google.adk.agents.LlmAgent; import com.google.adk.agents.ReadonlyContext; import io.reactivex.rxjava3.core.Single; // This is an Instruction.Provider Instruction.Provider myInstructionProvider = new Instruction.Provider( (ReadonlyContext context) -> { // No state injection occurs — curly braces are treated as literal text. return Single.just("Format your output as JSON: {\"city\": \"<name>\", \"population\": <number>}"); } ); LlmAgent agent = LlmAgent.builder() .model("gemini-flash-latest") .name("template_helper_agent") .instruction(myInstructionProvider) .build(); ``` ``` fun instructionProvider(model: Gemini) { // This is an Instruction.Provider val myInstructionProvider = Instruction { context: ReadonlyContext -> // No state injection occurs — curly braces are treated as literal text. Content( parts = listOf( Part( text = "Format your output as JSON: {\"city\": \"<name>\", \"population\": <number>}", ), ), ) } val agent = LlmAgent( model = model, name = "template_helper_agent", instruction = myInstructionProvider, ) } ``` 如果你们都想使用 `InstructionProvider` *财务报告和财务报告* 将状态插入到您的指令中,您可以使用 `inject_session_state` 工具函数。仅限 `{key}` 匹配有效状态变量名称的占位符将被替换;其他文本(包括不匹配有效标识符的卷套)将被留为原样。 PythonGoJava ``` from google.adk.agents import LlmAgent from google.adk.agents.readonly_context import ReadonlyContext from google.adk.utils import instructions_utils async def my_dynamic_instruction_provider(context: ReadonlyContext) -> str: template = "This is a {adjective} instruction. Use JSON like: {\"key\": \"value\"}." # This will inject the 'adjective' state variable. # The JSON braces are left alone because their content is not a valid identifier. return await instructions_utils.inject_session_state(template, context) agent = LlmAgent( model="gemini-flash-latest", name="dynamic_template_helper_agent", instruction=my_dynamic_instruction_provider ) ``` ``` // 2. This InstructionProvider demonstrates how to manually inject state // while also preserving literal braces. It uses the instructionutil helper. func dynamicInstructionProvider(ctx agent.ReadonlyContext) (string, error) { template := "This is a {adjective} instruction with {{literal_braces}}." // This will inject the 'adjective' state variable but leave the literal braces. return instructionutil.InjectSessionState(ctx, template) } ``` ``` import com.google.adk.agents.Instruction; import com.google.adk.agents.LlmAgent; import com.google.adk.agents.ReadonlyContext; import com.google.adk.utils.InstructionUtils; import io.reactivex.rxjava3.core.Single; Instruction.Provider myDynamicInstructionProvider = new Instruction.Provider( (ReadonlyContext context) -> { String template = "This is a " + adjective + " instruction. Use JSON like: {\"key\": \"value\"}."; // This will inject the 'adjective' state variable. // The JSON braces are left alone because their content is not a valid identifier. return InstructionUtils.injectSessionState(context.invocationContext(), template); } ); LlmAgent agent = LlmAgent.builder() .model("gemini-flash-latest") .name("dynamic_template_helper_agent") .instruction(myDynamicInstructionProvider) .build(); ``` **直接注射的好处** - 清晰度:明确指令的哪些部分是动态的,基于会话状态. - 可靠性:避免依赖LLM正确解释自然语言指令以访问状态. - 可维护性:简化指令字符串,减少更新状态变量名称时出现错误的风险. **与其他国家接触方法的关系** 这种直接注射方法是LlmAgent指令所特有的. 有关其他状态访问方法的更多信息,请参见下一节. ### 国家如何更新:建议的方法[¶](<https://adk.dev/sessions/state/#how-state-is-updated-recommended-methods>) 修改状态的正确方式 当您需要更改会话状态时,最正确和最安全的方法是 **直接修改 `state` 对象 `Context`** 用于您的职能(例如, `callback_context.state['my_key'] = 'new_value'`),这被认为是以正确的方式"直接状态操纵",因为框架会自动跟踪这些变化. 这与直接修改 `state` 时间轴: `Session` 对象从 `SessionService` (e.g., `my_session.state['my_key'] = 'new_value'`). **你该避免这样**,因为它绕过 ADK 的事件跟踪并可能导致数据丢失。本页末尾的“警告”部分对这一重要区分有更详细的信息。 国家应 **永远** 作为增加一项内容的一部分更新 `Event` ưμ㼯A `session_service.append_event()`。这确保了对变化进行跟踪,持久性工作正确,更新是安全的。 **1. 简便之路: `output_key` (用于代理文本回复)** 这是将代理端的最终文本响应直接保存到状态的最简单的方法。当定义您时, `LlmAgent`中,指定 `output_key`: PythonTypeScriptGoJava ``` from google.adk.agents import LlmAgent from google.adk.sessions import InMemorySessionService, Session from google.adk.runners import Runner from google.genai.types import Content, Part # Define agent with output_key greeting_agent = LlmAgent( name="Greeter", model="gemini-flash-latest", # Use a valid model instruction="Generate a short, friendly greeting.", output_key="last_greeting" # Save response to state['last_greeting'] ) # --- Setup Runner and Session --- app_name, user_id, session_id = "state_app", "user1", "session1" session_service = InMemorySessionService() runner = Runner( agent=greeting_agent, app_name=app_name, session_service=session_service ) session = await session_service.create_session(app_name=app_name, user_id=user_id, session_id=session_id) print(f"Initial state: {session.state}") # --- Run the Agent --- # The agent uses the output_key to put its response into the event's # state_delta; the Runner hands that event to append_event, which # applies the delta to the session state. user_message = Content(parts=[Part(text="Hello")]) for event in runner.run(user_id=user_id, session_id=session_id, new_message=user_message): if event.is_final_response(): print(f"Agent responded.") # Response text is also in event.content # --- Check Updated State --- updated_session = await session_service.get_session(app_name=app_name, user_id=user_id, session_id=session_id) print(f"State after agent run: {updated_session.state}") # Expected output might include: {'last_greeting': 'Hello there! How can I help you today?'} ``` ``` import { LlmAgent, Runner, InMemorySessionService, isFinalResponse } from "@google/adk"; import { Content } from "@google/genai"; // Define agent with outputKey const greetingAgent = new LlmAgent({ name: "Greeter", model: "gemini-flash-latest", instruction: "Generate a short, friendly greeting.", outputKey: "last_greeting" // Save response to state['last_greeting'] }); // --- Setup Runner and Session --- const appName = "state_app"; const userId = "user1"; const sessionId = "session1"; const sessionService = new InMemorySessionService(); const runner = new Runner({ agent: greetingAgent, appName: appName, sessionService: sessionService }); const session = await sessionService.createSession({ appName, userId, sessionId }); console.log(`Initial state: ${JSON.stringify(session.state)}`); // --- Run the Agent --- // Runner handles calling appendEvent, which uses the outputKey // to automatically create the stateDelta. const userMessage: Content = { parts: [{ text: "Hello" }] }; for await (const event of runner.runAsync({ userId, sessionId, newMessage: userMessage })) { if (isFinalResponse(event)) { console.log("Agent responded."); // Response text is also in event.content } } // --- Check Updated State --- const updatedSession = await sessionService.getSession({ appName, userId, sessionId }); console.log(`State after agent run: ${JSON.stringify(updatedSession?.state)}`); // Expected output might include: {"last_greeting":"Hello there! How can I help you today?"} ``` ``` // 1. GreetingAgent demonstrates using `OutputKey` to save an agent's // final text response directly into the session state. func greetingAgentExample(sessionService session.Service) { fmt.Println("--- Running GreetingAgent (output_key) Example ---") ctx := context.Background() modelGreeting, err := gemini.NewModel(ctx, modelID, nil) if err != nil { log.Fatalf("Failed to create Gemini model for greeting agent: %v", err) } greetingAgent, err := llmagent.New(llmagent.Config{ Name: "Greeter", Model: modelGreeting, Instruction: "Generate a short, friendly greeting.", OutputKey: "last_greeting", }) if err != nil { log.Fatalf("Failed to create greeting agent: %v", err) } r, err := runner.New(runner.Config{ AppName: appName, Agent: agent.Agent(greetingAgent), SessionService: sessionService, }) if err != nil { log.Fatalf("Failed to create runner: %v", err) } // Run the agent userMessage := genai.NewContentFromText("Hello", "user") for event, err := range r.Run(ctx, userID, sessionID, userMessage, agent.RunConfig{}) { if err != nil { log.Printf("Agent Error: %v", err) continue } if isFinalResponse(event) { if event.LLMResponse.Content != nil { fmt.Printf("Agent responded with: %q\n", textParts(event.LLMResponse.Content)) } else { fmt.Println("Agent responded.") } } } // Check the updated state resp, err := sessionService.Get(ctx, &session.GetRequest{AppName: appName, UserID: userID, SessionID: sessionID}) if err != nil { log.Fatalf("Failed to get session: %v", err) } lastGreeting, _ := resp.Session.State().Get("last_greeting") fmt.Printf("State after agent run: last_greeting = %q\n\n", lastGreeting) } ``` ``` import com.google.adk.agents.LlmAgent; import com.google.adk.agents.RunConfig; import com.google.adk.events.Event; import com.google.adk.runner.Runner; import com.google.adk.sessions.InMemorySessionService; import com.google.adk.sessions.Session; import com.google.genai.types.Content; import com.google.genai.types.Part; import java.util.List; import java.util.Optional; public class GreetingAgentExample { public static void main(String[] args) { // Define agent with output_key LlmAgent greetingAgent = LlmAgent.builder() .name("Greeter") .model("gemini-2.5-flash") .instruction("Generate a short, friendly greeting.") .description("Greeting agent") .outputKey("last_greeting") // Save response to state['last_greeting'] .build(); // --- Setup Runner and Session --- String appName = "state_app"; String userId = "user1"; String sessionId = "session1"; InMemorySessionService sessionService = new InMemorySessionService(); Runner runner = Runner.builder() .agent(greetingAgent) .appName(appName) .sessionService(sessionService) .build(); Session session = sessionService.createSession(appName, userId, null, sessionId).blockingGet(); System.out.println("Initial state: " + session.state().entrySet()); // --- Run the Agent --- // Runner handles calling appendEvent, which uses the output_key // to automatically create the stateDelta. Content userMessage = Content.builder().parts(List.of(Part.fromText("Hello"))).build(); // RunConfig is needed for runner.runAsync in Java RunConfig runConfig = RunConfig.builder().build(); for (Event event : runner.runAsync(userId, sessionId, userMessage, runConfig).blockingIterable()) { if (event.finalResponse()) { System.out.println("Agent responded."); // Response text is also in event.content } } // --- Check Updated State --- Session updatedSession = sessionService.getSession(appName, userId, sessionId, Optional.empty()).blockingGet(); assert updatedSession != null; System.out.println("State after agent run: " + updatedSession.state().entrySet()); // Expected output might include: {'last_greeting': 'Hello there! How can I help you today?'} } } ``` 在幕后,特工们自己使用 `output_key` 将回复写入 `state_delta` 会 议 日 程 和 议 程 `EventActions` 以它所产的果实盟誓, `Runner` 然后将事件传递给 `SessionService`'s `append_event`,它应用三角洲。 **2. 标准方式 : `EventActions.state_delta` (用于复杂更新)** 对于更为复杂的情景(更新多个键,非字符串值,具体范围如: `user:` 或 时 间 `app:`,或者更新不直接与代理商最后文本绑定),您手动构造 `state_delta` 内部 `EventActions`. PythonTypeScriptGoJavaKotlin ``` from google.adk.sessions import InMemorySessionService, Session from google.adk.events import Event, EventActions from google.genai.types import Part, Content import time # --- Setup --- session_service = InMemorySessionService() app_name, user_id, session_id = "state_app_manual", "user2", "session2" session = await session_service.create_session( app_name=app_name, user_id=user_id, session_id=session_id, state={"user:login_count": 0, "task_status": "idle"} ) print(f"Initial state: {session.state}") # --- Define State Changes --- current_time = time.time() state_changes = { "task_status": "active", # Update session state "user:login_count": session.state.get("user:login_count", 0) + 1, # Update user state "user:last_login_ts": current_time, # Add user state "temp:validation_needed": True # Add temporary state (will be discarded) } # --- Create Event with Actions --- actions_with_update = EventActions(state_delta=state_changes) # This event might represent an internal system action, not just an agent response system_event = Event( invocation_id="inv_login_update", author="system", # Or 'agent', 'tool' etc. actions=actions_with_update, timestamp=current_time # content might be None or represent the action taken ) # --- Append the Event (This updates the state) --- await session_service.append_event(session, system_event) print("`append_event` called with explicit state delta.") # --- Check Updated State --- updated_session = await session_service.get_session(app_name=app_name, user_id=user_id, session_id=session_id) print(f"State after event: {updated_session.state}") # Expected: {'user:login_count': 1, 'task_status': 'active', 'user:last_login_ts': <timestamp>} # Note: 'temp:validation_needed' is NOT present. ``` ``` import { InMemorySessionService, createEvent, createEventActions } from "@google/adk"; // --- Setup --- const sessionService = new InMemorySessionService(); const appName = "state_app_manual"; const userId = "user2"; const sessionId = "session2"; const session = await sessionService.createSession({ appName, userId, sessionId, state: { "user:login_count": 0, "task_status": "idle" } }); console.log(`Initial state: ${JSON.stringify(session.state)}`); // --- Define State Changes --- const currentTime = Date.now(); const stateChanges = { "task_status": "active", // Update session state "user:login_count": (session.state["user:login_count"] as number || 0) + 1, // Update user state "user:last_login_ts": currentTime, // Add user state "temp:validation_needed": true // Add temporary state (will be discarded) }; // --- Create Event with Actions --- const actionsWithUpdate = createEventActions({ stateDelta: stateChanges, }); // This event might represent an internal system action, not just an agent response const systemEvent = createEvent({ invocationId: "inv_login_update", author: "system", // Or 'agent', 'tool' etc. actions: actionsWithUpdate, timestamp: currentTime // content might be null or represent the action taken }); // --- Append the Event (This updates the state) --- await sessionService.appendEvent({ session, event: systemEvent }); console.log("`appendEvent` called with explicit state delta."); // --- Check Updated State --- const updatedSession = await sessionService.getSession({ appName, userId, sessionId }); console.log(`State after event: ${JSON.stringify(updatedSession?.state)}`); // Expected: {"user:login_count":1,"task_status":"active","user:last_login_ts":<timestamp>} // Note: 'temp:validation_needed' is NOT present. ``` ``` // 2. manualStateUpdateExample demonstrates creating an event with explicit // state changes (a "state_delta") to update multiple keys, including // those with user- and temp- prefixes. func manualStateUpdateExample(sessionService session.Service) { fmt.Println("--- Running Manual State Update (EventActions) Example ---") ctx := context.Background() s, err := sessionService.Get(ctx, &session.GetRequest{AppName: appName, UserID: userID, SessionID: sessionID}) if err != nil { log.Fatalf("Failed to get session: %v", err) } retrievedSession := s.Session // Define state changes loginCount, _ := retrievedSession.State().Get("user:login_count") newLoginCount := 1 if lc, ok := loginCount.(int); ok { newLoginCount = lc + 1 } stateChanges := map[string]any{ "task_status": "active", "user:login_count": newLoginCount, "user:last_login_ts": time.Now().Unix(), "temp:validation_needed": true, } // Create an event with the state changes systemEvent := session.NewEvent(ctx, "inv_login_update") systemEvent.Author = "system" systemEvent.Actions.StateDelta = stateChanges // Append the event to update the state if err := sessionService.AppendEvent(ctx, retrievedSession, systemEvent); err != nil { log.Fatalf("Failed to append event: %v", err) } fmt.Println("`append_event` called with explicit state delta.") // Check the updated state updatedResp, err := sessionService.Get(ctx, &session.GetRequest{AppName: appName, UserID: userID, SessionID: sessionID}) if err != nil { log.Fatalf("Failed to get session: %v", err) } taskStatus, _ := updatedResp.Session.State().Get("task_status") loginCount, _ = updatedResp.Session.State().Get("user:login_count") lastLogin, _ := updatedResp.Session.State().Get("user:last_login_ts") temp, err := updatedResp.Session.State().Get("temp:validation_needed") // This should fail or be nil fmt.Printf("State after event: task_status=%q, user:login_count=%v, user:last_login_ts=%v\n", taskStatus, loginCount, lastLogin) if err != nil { fmt.Printf("As expected, temp state was not persisted: %v\n\n", err) } else { fmt.Printf("Unexpected temp state value: %v\n\n", temp) } } ``` ``` import com.google.adk.events.Event; import com.google.adk.events.EventActions; import com.google.adk.sessions.InMemorySessionService; import com.google.adk.sessions.Session; import java.time.Instant; import java.util.Optional; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class ManualStateUpdateExample { public static void main(String[] args) { // --- Setup --- InMemorySessionService sessionService = new InMemorySessionService(); String appName = "state_app_manual"; String userId = "user2"; String sessionId = "session2"; ConcurrentMap<String, Object> initialState = new ConcurrentHashMap<>(); initialState.put("user:login_count", 0); initialState.put("task_status", "idle"); Session session = sessionService.createSession(appName, userId, initialState, sessionId).blockingGet(); System.out.println("Initial state: " + session.state().entrySet()); // --- Define State Changes --- long currentTimeMillis = Instant.now().toEpochMilli(); // Use milliseconds for Java Event ConcurrentMap<String, Object> stateChanges = new ConcurrentHashMap<>(); stateChanges.put("task_status", "active"); // Update session state // Retrieve and increment login_count Object loginCountObj = session.state().get("user:login_count"); int currentLoginCount = 0; if (loginCountObj instanceof Number) { currentLoginCount = ((Number) loginCountObj).intValue(); } stateChanges.put("user:login_count", currentLoginCount + 1); // Update user state stateChanges.put("user:last_login_ts", currentTimeMillis); // Add user state (as long milliseconds) stateChanges.put("temp:validation_needed", true); // Add temporary state // --- Create Event with Actions --- EventActions actionsWithUpdate = EventActions.builder().stateDelta(stateChanges).build(); // This event might represent an internal system action, not just an agent response Event systemEvent = Event.builder() .invocationId("inv_login_update") .author("system") // Or 'agent', 'tool' etc. .actions(actionsWithUpdate) .timestamp(currentTimeMillis) // content might be None or represent the action taken .build(); // --- Append the Event (This updates the state) --- sessionService.appendEvent(session, systemEvent).blockingGet(); System.out.println("`appendEvent` called with explicit state delta."); // --- Check Updated State --- Session updatedSession = sessionService.getSession(appName, userId, sessionId, Optional.empty()).blockingGet(); assert updatedSession != null; System.out.println("State after event: " + updatedSession.state().entrySet()); // Expected: {'user:login_count': 1, 'task_status': 'active', 'user:last_login_ts': <timestamp_millis>} // Note: 'temp:validation_needed' is NOT present because InMemorySessionService's appendEvent // applies delta to its internal user/app state maps IF keys have prefixes, // and to the session's own state map (which is then merged on getSession). } } ``` ``` fun main() = runBlocking { // --- Constants --- val appName = "state_example_app" val userId = "state_user" val model = Gemini(name = "gemini-flash-latest") // --- Services --- val sessionService = InMemorySessionService() // --- 1. Instruction Templating --- // Inject state values into agent instructions using {key} syntax. val templateAgent = LlmAgent( name = "TemplateAgent", model = model, instruction = Instruction( "Greet the user and mention their favorite color: {favorite_color}.", ), ) // --- 2. State Updates in Callbacks --- // Update state directly in a callback using context.updateState() val logTurnCallback = AfterAgentCallback { context -> val turnCount = context.state["turn_count"] as? Int ?: 0 context.updateState("turn_count", turnCount + 1) println("Turn #$turnCount logged in callback.") CallbackChoice.Continue(Unit) } val callbackAgent = LlmAgent( name = "CallbackAgent", model = model, instruction = Instruction("Answer concisely."), afterAgentCallbacks = listOf(logTurnCallback), ) // --- 3. Manual State Updates via EventActions --- println("--- Manual State Update ---") val sessionId = "manual_session" val sessionKey = SessionKey(appName, userId, sessionId) val session = sessionService.createSession( key = sessionKey, state = mapOf("favorite_color" to "blue", "turn_count" to 0), ) val stateUpdateEvent = Event( invocationId = "manual_update", author = "system", actions = EventActions( stateDelta = mutableMapOf("user:preferred_language" to "en"), ), timestamp = System.currentTimeMillis(), ) val unused = sessionService.appendEvent(session, stateUpdateEvent) val updatedSession = sessionService.getSession(sessionKey) println("Updated State: ${updatedSession?.state}") // --- 4. Running with Templating --- println("\n--- Running with Templating ---") val runner = InMemoryRunner( agent = templateAgent, appName = appName, sessionService = sessionService, ) val userMessage = Content.fromText(Role.USER, "Hello!") runner.runAsync( userId = userId, sessionId = sessionId, newMessage = userMessage, ).collect { event -> event.content?.parts?.forEach { part -> if (!part.text.isNullOrBlank()) { println("Agent Response: ${part.text}") } } } } ``` **3. 维雅 `CallbackContext` 或 时 间 `ToolContext` (建议召回和工具)** *(注:在Python和TypeScript中, `CallbackContext` 财务报告和财务报告 `ToolContext` 统一为单一 `Context` 类型,在 Python 中,这两个名称仍可作为它的别名使用。 )* 在代理调用中修改状态, 例如 `before_agent_callback` 财务报告和财务报告 `after_agent_callback`,或者在工具函数范围内,最好使用 `state` 属性 `CallbackContext` 或 时 间 `ToolContext` 为您提供功能。 - `callback_context.state['my_key'] = my_value` - `tool_context.state['my_key'] = my_value` 这些上下文对象专门设计用于管理各自执行范围内的状态变化。当您修改时 `context.state`中,ADK框架确保这些变化自动被捕获并正确引导到 `EventActions.state_delta` 对于由调用或工具生成的事件,此三角洲由 `SessionService` 当事件随附时,确保适当的持久性和跟踪性。 这种方法将手动创建 `EventActions` 财务报告和财务报告 `state_delta` 对于大多数常见的状态更新情景 在召回和工具, 使您的代码更清洁 并且较少容易出错。 有关上下文对象的更详尽细节,请参见: [背景资料](<https://adk.dev/context/>). PythonTypeScriptGoJavaKotlin ``` # In an agent callback or tool function from google.adk.agents.callback_context import CallbackContext # or, equivalently: from google.adk.tools.tool_context import ToolContext def my_callback_or_tool_function(context: CallbackContext, # Or ToolContext # ... other parameters ... ): # Update existing state count = context.state.get("user_action_count", 0) context.state["user_action_count"] = count + 1 # Add new state context.state["temp:last_operation_status"] = "success" # State changes are automatically part of the event's state_delta # ... rest of callback/tool logic ... ``` ``` // In an agent callback or tool function import { Context } from "@google/adk"; function myCallbackOrToolFunction( context: Context, // ... other parameters ... ) { // Update existing state const count = context.state.get("user_action_count", 0); context.state.set("user_action_count", count + 1); // Add new state context.state.set("temp:last_operation_status", "success"); // State changes are automatically part of the event's stateDelta // ... rest of callback/tool logic ... } ``` ``` // 3. contextStateUpdateExample demonstrates the recommended way to modify state // from within a tool function using the provided `agent.Context`. func contextStateUpdateExample(sessionService session.Service) { fmt.Println("--- Running Context State Update (ToolContext) Example ---") ctx := context.Background() // Define the tool that modifies state updateActionCountTool, err := functiontool.New( functiontool.Config{Name: "update_action_count", Description: "Updates the user action count in the state."}, func(actx agent.Context, args struct{}) (struct{}, error) { s, err := actx.State().Get("user_action_count") if err != nil { log.Printf("could not get user_action_count: %v", err) } newCount := 1 if c, ok := s.(int); ok { newCount = c + 1 } if err := actx.State().Set("user_action_count", newCount); err != nil { log.Printf("could not set user_action_count: %v", err) } if err := actx.State().Set("temp:last_operation_status", "success from tool"); err != nil { log.Printf("could not set temp:last_operation_status: %v", err) } fmt.Println("Tool: Updated state via agent.Context.") return struct{}{}, nil }, ) if err != nil { log.Fatalf("Failed to create tool: %v", err) } // Define an agent that uses the tool modelTool, err := gemini.NewModel(ctx, modelID, nil) if err != nil { log.Fatalf("Failed to create Gemini model for tool agent: %v", err) } toolAgent, err := llmagent.New(llmagent.Config{ Name: "ToolAgent", Model: modelTool, Instruction: "Use the update_action_count tool.", Tools: []tool.Tool{updateActionCountTool}, }) if err != nil { log.Fatalf("Failed to create tool agent: %v", err) } r, err := runner.New(runner.Config{ AppName: appName, Agent: agent.Agent(toolAgent), SessionService: sessionService, }) if err != nil { log.Fatalf("Failed to create runner: %v", err) } // Run the agent to trigger the tool userMessage := genai.NewContentFromText("Please update the action count.", "user") for _, err := range r.Run(ctx, userID, sessionID, userMessage, agent.RunConfig{}) { if err != nil { log.Printf("Agent Error: %v", err) } } // Check the updated state resp, err := sessionService.Get(ctx, &session.GetRequest{AppName: appName, UserID: userID, SessionID: sessionID}) if err != nil { log.Fatalf("Failed to get session: %v", err) } actionCount, _ := resp.Session.State().Get("user_action_count") fmt.Printf("State after tool run: user_action_count = %v\n", actionCount) } ``` ``` // In an agent callback or tool method import com.google.adk.agents.CallbackContext; // or ToolContext // ... other imports ... public class MyAgentCallbacks { public void onAfterAgent(CallbackContext callbackContext) { // Update existing state Integer count = (Integer) callbackContext.state().getOrDefault("user_action_count", 0); callbackContext.state().put("user_action_count", count + 1); // Add new state callbackContext.state().put("temp:last_operation_status", "success"); // State changes are automatically part of the event's state_delta // ... rest of callback logic ... } } ``` ``` fun myCallbackFunction(context: CallbackContext) { // Update existing state using updateState helper val count = context.state["user_action_count"] as? Int ?: 0 context.updateState("user_action_count", count + 1) // Add new state context.updateState("temp:last_operation_status", "success") } suspend fun myToolFunction( context: ToolContext, args: Map<String, Any>, ) { // Access state via context.context.state val count = context.context.state["user_action_count"] as? Int ?: 0 // Update state via context.actions.stateDelta context.actions.stateDelta["user_action_count"] = count + 1 context.actions.stateDelta["temp:last_operation_status"] = "success" } ``` **什麽? `append_event` 是否:** - 添加 `Event` 改为: `session.events`. - 读取 `state_delta` 从活动 `actions`. - 将这些更改应用到由 . `SessionService`,根据服务类型正确处理前缀和持久性。 - 更新会话 `last_update_time`. - 序列化同步更新到服务所支持的同一会话: `DatabaseSessionService` 每节锁,而 `InMemorySessionService` 无法安全地进行多线性使用。 ### ⚠️ 关于直接改变国家的警告[¶](<https://adk.dev/sessions/state/#a-warning-about-direct-state-modification>) 避免直接修改 `session.state` a 上的收藏(词典/地图) `Session` 直接从 `SessionService` (例如,通过 `session_service.get_session()` 或 时 间 `session_service.create_session()`) *外部* 代理人的受管寿命周期(即不通过 `CallbackContext` 或 时 间 `ToolContext`。例如,代码像 `retrieved_session = await session_service.get_session(...); retrieved_session.state['key'] = value` 有问题。 国家修改 *内部* 使用回调或工具 `CallbackContext.state` 或 时 间 `ToolContext.state` 这是确保跟踪变化的正确方法,因为这些上下文对象处理与事件系统的必要整合。 **为何强烈不鼓励直接修改(情况之外):** 1. **旁证事件历史 :** 变化没有记录为 `Event`,失去可审计性。 2. **打破持久性 :** 以这种方式作出的改变 **将可能保存 NOT** 由 `DatabaseSessionService` 或 时 间 `VertexAiSessionService`。他们依赖 `append_event` 以触发储蓄。 3. **不是线索- 安全 :** 可以导致比赛条件和失去更新. 4. **忽略时间戳/ 日志 :** 没有更新 `last_update_time` 或触发相关的事件逻辑。 **建议:** 坚持通过更新状态 `output_key`, `EventActions.state_delta` (当手动创建事件时),或通过修改 `state` 财产 `CallbackContext` 或 时 间 `ToolContext` 这些方法确保可靠、可追踪和持续的国家管理。使用直接访问 `session.state` (从a) `SessionService`-检索到的会话) *读取* 状态。 ### 国家设计概述的最佳做法[¶](<https://adk.dev/sessions/state/#best-practices-for-state-design-recap>) - **最小化 :** 仅存储必不可少的动态数据. - **序列化 :** 使用基本,可序列的类型. - **描述密钥( P) :** 使用清晰的名称和适当的前缀( E)`user:`, `app:`, `temp:`,或无). - **浅层结构 :** 尽可能避免深筑巢穴. - **标准更新流程 :** 继续说 `append_event`.
查看原始来源