状态:会话的临时存储区(即“Scratchpad”)¶
在每个……内部 Session (我们的对话记录), state “attribute”可以被视为代理在进行特定交互时的专用“临时记录本”(即用于存储交互过程中产生的各种信息或数据的临时存储空间)。 session.events 保存了所有的历史记录(即所有发生过的事件或数据)。 session.state 代理程序在这里存储和更新所需的动态详细信息。 在……期间;当……的时候 这次谈话(the conversation)。
“What is” 是一个常见的英语疑问句,用于询问某事物的名称、性质或功能。例如:“What is this book?”(这本书叫什么?) session.state?¶
从概念上讲, session.state 它是一个用于存储键值对(key-value pairs)的集合(可以是字典或 Map)。它的设计目的是为了保存代理需要记住或跟踪的信息,从而确保当前的对话能够顺利进行。
- “个性化互动”(Personalize Interaction): 请记住之前提到的用户偏好设置(例如:
'user_preference_theme': 'dark'). - 跟踪任务进度: 跟踪多步骤流程中的各个环节(例如:
'booking_step': 'confirm_payment'). - **收集信息:** 生成列表或摘要(例如:
'shopping_cart_items': ['book', 'pen']). - 做出明智的决策: 存储会影响下一次响应的标志或值(例如:
'user_is_authenticated': True).
……的主要特征是: State¶
-
数据结构:可序列化的键值对(Serializable Key-Value Pairs)
- 数据被存储为……
key: value. - Keys: 始终使用字符串(Always use strings)
str请使用清晰的名称(例如:)。'departure_city','user:language_preference'). - 值: 必须;务必 `serializable`这意味着它们可以很容易地被保存和加载。
SessionService. 在特定的编程语言(Python/Go/Java/TypeScript)中,应坚持使用基本的数据类型,例如字符串(strings)、数字(numbers)、布尔值(booleans),以及包含其他元素的简单列表(lists)或字典(dictionaries)。 只有;仅仅 这些是基本的数据类型。(具体细节请参阅 API 文档。) - ⚠️ 避免使用复杂的对象: 请不要存储无法序列化的对象。 (自定义类实例、函数、连接等)可以直接存储在状态(state)中。如果需要,可以存储简单的标识符(identifiers),而复杂的对象则可以存储在其他地方,并在需要时再将其检索出来。
- 数据被存储为……
-
可变性:它会发生变化。
- 该文件的内容包括:
state这些内容预计会随着对话的进展而发生变化。
- 该文件的内容包括:
-
持久性(Persistence):取决于……
SessionService-
应用程序重新启动后,该状态是否能够保持不变,取决于您所选择的服务类型。
-
InMemorySessionService: 数据不具有持久性(即数据不会被长期保存)。 在重新启动后,系统状态(State)会丢失。 DatabaseSessionService/VertexAiSessionService: 持久性(Persistent)。 状态数据能够被可靠地保存下来。
-
注意:
这些基本类型(primitives)的具体参数或方法名称可能会因所使用的 SDK 语言的不同而略有差异(例如: session.state['current_intent'] = 'book_flight' 在 Python 中,context.State().Set("current_intent", "book_flight") 在 Go 语言中, session.state().put("current_intent", "book_flight) 在 Java 中,或者 context.state.set("current_intent", "book_flight") (适用于 TypeScript)。详情请参阅该语言特定的 API 文档。
使用前缀来组织状态:范围(即状态所属的上下文)非常重要。¶
状态键(state keys)前缀决定了它们的作用范围(scope)以及数据持久化(persistence)行为,尤其是在使用持久化服务(persistent services)的情况下。
-
无前缀(会话状态):
- 范围(Scope): 具体来说: current `session`(会话)
id). - 持久性(Persistence): 只有在该条件下才会被保留(或持续存在)。
SessionService具有持久性;即数据或状态会在系统关闭后仍然保留。)Database,VertexAI). - 使用场景: 跟踪当前任务的进展情况(例如:
'current_booking_step'),以及用于此次交互的临时标志(例如,'needs_clarification'). - 示例:
session.state['current_intent'] = 'book_flight'
- 范围(Scope): 具体来说: current `session`(会话)
-
user:前缀(用户状态):- 范围(Scope): 与……相关联;受……影响
user_id在多个用户之间共享;被多个用户共同使用。 所有 该用户的所有会话(在同一时间段内)app_name). - 持久性(Persistence): 坚持到底;不放弃
Database或者VertexAI. (由……存储)InMemory但在重新启动后,问题又再次出现了(即问题仍然存在)。 - 使用场景: 用户偏好设置(例如:
'user:theme'),个人资料信息(例如:'user:name'). - 在没有会话(session)的情况下进行阅读: 在 Python 中,
await session_service.get_user_state(app_name=..., user_id=...)返回用户范围内的键(user-scoped keys)。user:前缀已被删除,因此你可以在会话创建之前就阅读这些内容。VertexAiSessionService这是一个例外:它总是会引发(某种错误或问题)。NotImplementedError这是因为 Agent Runtime API 并不会独立于会话(session)来暴露用户状态(user state)。因此,需要通过会话来遍历所有用户会话(enumerate sessions with)。list_sessions然后调用(该函数/方法)。get_session相反,应该显示在每个结果上。 - 示例:
session.state['user:preferred_language'] = 'fr'
- 范围(Scope): 与……相关联;受……影响
-
app:前缀(应用状态):- 范围(Scope): 与……相关联;受……影响
app_name在多个用户之间共享;被多个用户共同使用。 所有 该应用程序的用户信息及会话数据。 - 持久性(Persistence): 坚持到底;不放弃
Database或者VertexAI. (由……存储)InMemory但在重新启动后,问题又再次出现了(即问题仍然存在)。 - 使用场景: 全局设置(例如:
'app:api_endpoint'),以及共享的模板(shared templates)。 - 示例:
session.state['app:global_discount_code'] = 'SAVE10'
- 范围(Scope): 与……相关联;受……影响
-
temp:前缀(临时调用状态):- 范围(Scope): 仅适用于当前情况(或:特定于当前环境/需求)。 调用(即程序中执行某段代码的行为) (从代理接收用户输入到生成该输入的最终输出的全部过程。)
- 持久性(Persistence): 数据不具有持久性(即数据不会被长期保存)。 在调用完成后会被丢弃,不会被传递到下一次调用中。
- 使用场景: 在单次调用过程中,用于存储中间计算结果、标志值,以及在工具之间传递的数据。
- **何时不应使用:** 对于那些需要在多次调用之间保持不变的信息(例如用户偏好设置、对话历史记录的摘要或累积的数据),可以使用这种存储方式。
- 示例:
session.state['temp:raw_api_response'] = {...}
次级代理(Sub-Agents)与调用上下文(Invocation Context)
当上级代理(parent agent)调用下级代理(sub-agent)时(例如,通过某种通信方式或接口进行调用), SequentialAgent 或者 ParallelAgent当它完成自己的任务后,就会继续执行接下来的步骤(或:当它完成自己的功能后,就会继续执行后续的操作)。 InvocationContext 该请求会被转发给子代理(sub-agent)。这意味着整个代理调用链(agent call chain)都会使用相同的调用 ID(invocation ID),从而也会使用相同的处理逻辑或结果。 temp: `state.`
代理(Agent)的视角: 您的代理代码会与……(该系统/服务)进行交互。 combined 通过单一方式实现状态转换(或:通过单一步骤完成状态更新) session.state `collection`(类型为 `dict` 或 `Map`)。 SessionService 根据前缀(prefixes),负责从相应的底层存储系统中获取或合并数据(即状态信息)。
在代理指令中访问会话状态¶
在使用(某个工具或方法)时…… LlmAgent 在处理实例时,您可以使用简单的模板语法直接将会话状态值注入到代理的指令字符串中。这样一来,您就可以生成具有动态性且能够理解上下文的指令,而无需完全依赖自然语言指令。
使用 {key} 模板设计(Templating)¶
要从会话状态中获取某个值,需要将所需状态变量的键放在大括号 `{}` 中: {key}该框架会自动将此占位符替换为相应的值。 session.state 在将指令传递给大型语言模型(LLM)之前。
示例:
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."
}
重要注意事项¶
- **键的存在性检查:** 确保你在指令字符串中引用的键确实存在于 `session.state` 中。如果该键不存在,代理程序会抛出错误。如果你需要使用一个可能存在于 `session.state` 中、也可能不存在的键,可以在键的后面加上问号(?),例如:`{topic?}`。
- 数据类型:与键关联的值应该是一个字符串,或者是一种可以轻松转换为字符串的数据类型。
- `Literal Curly Braces: The`
{key}该语法可以匹配任何有效的 Python 标识符(这些标识符必须位于单层大括号 `{}` 内)。如果你在指令中确实需要使用大括号(例如用于 JSON 格式化或模板语法),请使用相应的特殊符号或方法来表示这些大括号。InstructionProvider该函数应返回一个值,而不是一个字符串(详见下文)。
f-字符串(f-string)和双大括号(double braces)
一些 ADK 示例在指令中使用了 Python 的 f-strings(格式化字符串),例如: f"Topic: {{initial_topic}}". The {{ 和 }} 在那些例子中…… Python 中 f-string 的转义机制这不是 ADK 语法;在运行时,Python 会自动进行转换。 {{initial_topic}} 给……;发送到…… {initial_topic}ADK 会将这个值视为一个普通的状态变量占位符(placeholder)。如果你没有使用 f-strings(字符串格式化功能),则需要使用单大括号({ })来表示变量。 {key} 直接地。
使用 InstructionProvider 为了获得完全的控制权¶
在某些情况下,您可能需要完全控制指令字符串的内容;例如,当您的指令中包含实际的 curly braces(大括号,例如在 JSON 数据或模板语法中)时,这些 curly braces 否则会被解释为状态变量的占位符。
为了实现这一目标,需要提供一个相应的函数。 instruction 该参数应该是一个数值(即数字),而不是字符串。这个函数被称为……(函数的具体名称在这里没有给出)。 InstructionProvider当你使用某个工具或功能时…… InstructionProvider在这种情况下,ADK 将会…… 不;并非 尝试注入状态变量(state variables),返回的字符串将原样传递给模型(model)。
The InstructionProvider `function receives a` ReadonlyContext 你可以使用这个对象来访问会话状态或其他上下文信息(如果需要动态生成指令的话)。
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 这是一个“效用函数”(utility function),仅此而已。 {key} 所有与有效状态变量名称匹配的占位符将被替换;其他文本(包括那些与有效标识符不匹配的 curly braces(大括号))将保持原样。
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();
直接喷射技术的好处
- **Clarity(清晰度):** 明确指出指令中的哪些部分是动态的,并且这些部分的值取决于会话状态(session state)。
- 可靠性:避免依赖大型语言模型(LLM)来正确解读自然语言指令,从而确保系统能够正确地访问所需的数据或状态。
- 可维护性:简化了指令字符串的编写方式,降低了在更新状态变量名称时出现错误的风险。
与其他状态访问方法的关系
这种直接注入的方法是专门为 LlmAgent 指令设计的。有关其他状态访问方法的更多信息,请参阅以下部分。
状态更新的方式:推荐的方法¶
修改状态的正确方法
当您需要更改会话状态时,正确且最安全的方法是…… 直接修改 state “object on the” 这个短语在语法上并不完整,可能是一个拼写错误或者是一个特定的术语/短语。如果它是一个拼写错误,那么正确的表达可能是 “an object on the table”(桌子上的一个物体)或者 “an object located on the surface”(位于某个表面上的物体)。如果它是一个特定的术语/短语,那么需要更多的上下文信息才能准确理解其含义。 Context 提供给你的函数(例如: callback_context.state['my_key'] = 'new_value'这被视为“直接的状态操控”,只不过是以正确的方式进行的;因为该框架会自动跟踪这些变化。
这与直接修改该内容的方式有着本质上的区别。 state 在……的时候;当……的情况下 Session 从……中检索到的对象。 SessionService (e.g., my_session.state['my_key'] = 'new_value'). 你应该避免这样做。这种方法会绕过 ADK 的事件跟踪机制,因此可能导致数据丢失。本页末尾的“警告”部分提供了关于这一重要区别的更多详细信息。
“State should” 的意思是:“国家应该……”;这里的 “State” 指的是国家或政府,而 “should” 表示一种建议或期望。 总是;一直 在添加新内容的过程中,该内容会自动得到更新。 Event 通过该方式可以访问会话历史记录(session history)。 session_service.append_event()这样可以确保所有的更改都被记录下来,数据的持久性得到正确保障,并且更新操作是线程安全的(即多个线程可以同时执行更新操作而不会导致数据不一致)。
1. 简单的方法: output_key (用于代理的文本回复)
这是将代理的最终文本响应直接保存到状态中的最简单方法。在定义你的……(此处内容不完整) LlmAgent请指定…… output_key:
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该功能会应用“delta”值(即变化量)。
2. 标准方法: EventActions.state_delta (用于复杂的更新操作)
对于更复杂的场景(例如更新多个键、非字符串类型的值,或针对特定范围的操作),…… user: 或者 app:(或者那些与代理生成的最终文本没有直接关联的更新),你需要手动构建这些内容。 state_delta 在……范围内;在……时间内 EventActions.
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. 通过(Via) CallbackContext 或者 ToolContext (推荐用于回调函数和工具)
(注意:在 Python 和 TypeScript 中,……) CallbackContext 和 ToolContext 这些内容被统一成了一个整体。 Context 在 Python 中,这两个名称仍然可以作为该类型的别名来使用。
在代理回调(agent callbacks)中修改状态(modifying state within agent callbacks),例如: before_agent_callback 和 after_agent_callback在工具函数内部进行相关操作时,最好使用……(此处应填写具体的方法或工具名称)。 state ……的属性 CallbackContext 或者 ToolContext 该数据被提供给您的函数(function)。
callback_context.state['my_key'] = my_valuetool_context.state['my_key'] = my_value
这些上下文对象(context objects)是专门为管理其各自执行范围内的状态变化而设计的。当你对这些对象进行修改时…… context.stateADK框架确保这些更改能够被自动捕获,并正确地路由到相应的目标位置。 EventActions.state_delta 该差值(delta)是由回调函数或工具生成的。随后,这个差值会被进一步处理。 SessionService 当事件被添加到系统中时,会确保其数据得到妥善的持久化处理(即长期保存)并能够被有效追踪。
这种方法抽象掉了手动创建的过程(即避免了用户需要手动完成某些步骤的需求)。 EventActions 和 state_delta 对于回调函数和工具中常见的状态更新场景而言,这样的代码结构会让代码更加清晰、易于维护,并且出错的可能性也会更低。
有关上下文对象(context objects)的更详细信息,请参阅…… 上下文文档(Context documentation).
# 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 Does:
- 添加(the)
Event给……;发送到……session.events. - 读取(数据)
state_delta来自该事件的actions. - 将这些更改应用到由该系统管理的状态中。
SessionService根据服务类型,正确处理前缀以及数据的持久化(即数据的存储方式)。 - 更新会话的(相关内容)。
last_update_time. - 当服务支持时,会将同时对同一会话进行的更新操作序列化(即按顺序处理这些更新)。
DatabaseSessionService每次会话都会获取一个锁(即每个用户会话都会被分配一个唯一的锁标识符),同时……InMemorySessionService不适用于多线程环境(即使用多个线程时可能会引发安全问题)。
⚠️ 关于直接修改状态的警告¶
请避免直接修改…… session.state 一个集合(字典/映射)…… Session 直接从……获取的对象。 SessionService (例如,通过……) session_service.get_session() 或者 session_service.create_session()) outside 属于代理调用的受管理生命周期的一部分(即,不是通过其他方式)。 CallbackContext 或者 ToolContext例如,像这样的代码: retrieved_session = await session_service.get_session(...); retrieved_session.state['key'] = value 这确实是个问题(is problematic)。
状态变更(State modifications) 在……范围内;在……时间内 使用的回调函数或工具 CallbackContext.state 或者 ToolContext.state 这些方法确实是确保变更被跟踪的正确方式,因为这些上下文对象负责与事件系统进行必要的集成。
为什么强烈不建议直接进行修改(即在特定上下文之外进行修改)?
- 绕过事件记录功能(Bypasses Event History): 该更改没有被记录为……(即:该更改没有被正式记录在相关系统中)。
Event这样一来,系统的可审计性(即系统数据是否能够被独立、客观地验证和审查)就会受到影响。 - 会破坏数据持久性(即数据在系统关闭后仍能被保留的状态)。 通过这种方式进行的更改 很可能不会被保存下来。 由……制作;由……提供
DatabaseSessionService或者VertexAiSessionService他们依赖于……append_event用于触发保存操作。 - **不支持线程安全(Not Thread-Safe):** 这可能导致“竞争条件”(race conditions)以及数据更新丢失的问题。
- 忽略时间戳(Timestamps)和逻辑判断(Logic): 不会更新。
last_update_time或者触发相关的事件逻辑。
推荐: 请坚持通过以下方式来更新状态: output_key, EventActions.state_delta (在手动创建事件时),或者通过修改现有事件来实现。 state 属于……的财产 CallbackContext 或者 ToolContext 当对象位于其各自的作用域内时,这些方法可以正常工作。这些方法确保了状态管理的可靠性、可追踪性以及持久性(即状态在程序运行过程中不会被意外修改)。可以直接使用这些方法来访问对象。 session.state (来自……) SessionService(仅用于已检索到的会话) “reading” `state.`
状态设计最佳实践总结¶
- 极简主义(Minimalism): 仅存储必要的、动态变化的数据。
- 序列化(Serialization): 使用基本的可序列化数据类型。
- 描述性键(Descriptive Keys)与前缀(Prefixes): 请使用清晰的名称和合适的前缀。)
user:,app:,temp:(可以包含一个或多个值,也可以不包含任何值。) - 浅层结构(Shallow Structures): 尽可能避免使用深度嵌套的结构。
- 标准更新流程: 依赖;依靠
append_event.