Memory

Session State

Session State 在 ADK 里面的储存方式是 Python dict,保存对话时的信息,并且只要 session 存在,可以 cross multiple conversation 生效. 同时,Agents 和 Tools 也可以读写这个 Session State

那么 Agents 是如何与 State 交互的呢?对于 Tools 而言,如果在定义函数的时候,在最后添加一个参数 tool_context: ToolContext,那么 Tools 就可以通过 tool_context.state 来访问 Session State 以提供运行时读写 Session State. 对于 Agent 而言,他可以自动读写 Session State(由 ADK 控制),然而其输出结果默认不会记录在 Session State 里,这时我们可以在 Agent() class 定义的时候指定 output_key="xxx",这样 ADK 就会把 Agent 最后一次的输出结果保存到 session.state["xxx"].

初始化一个 Session State

初始化一个 Session State 其实很简单,在 constructor 里加上 state=... 参数即可.

以下的示例中,我们为 Agent 实现摄氏度与华氏度的输出.

Initialization
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from google.adk.sessions import InMemorySessionService

# 创建一个 SessionService 负责管理(这个程序的)所有 sessions
session_service_stateful = InMemorySessionService()

SESSION_ID_STATEFUL = "session_state_demo_001"
USER_ID_STATEFUL = "user_state_demo"
initial_state = {
"user_preference_temperature_unit": "Celsius"
}

# 创建一个 session
session_stateful = await session_service_stateful.create_session(
app_name=APP_NAME, # Use the consistent app name
user_id=USER_ID_STATEFUL,
session_id=SESSION_ID_STATEFUL,
state=initial_state # <<< Initialize state during creation
)

在 Tool 里访问 session

下面的示例代码在 get_weather_stateful() 函数里直接将摄氏度与华氏度转化写好了.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# 在函数定义的时候,一定要加上 :ToolContext 参数!
def get_weather_stateful(city: str, tool_context: ToolContext) -> dict:
# 从 tool_context (即 session) 获取
preferred_unit = tool_context.state.get(
"user_preference_temperature_unit",
"Celsius"
) # Default to Celsius

city_normalized = city.lower().replace(" ", "")

mock_weather_db = {
"newyork": {"temp_c": 25, "condition": "sunny"},
"london": {"temp_c": 15, "condition": "cloudy"},
"tokyo": {"temp_c": 18, "condition": "light rain"},
}

if city_normalized in mock_weather_db:
data = mock_weather_db[city_normalized]
temp_c = data["temp_c"]
condition = data["condition"]

# Format temperature based on state preference
if preferred_unit == "Fahrenheit":
temp_value = (temp_c * 9/5) + 32 # Calculate Fahrenheit
temp_unit = "°F"
else: # Default to Celsius
temp_value = temp_c
temp_unit = "°C"

report = f"The weather in {city.capitalize()} is {condition} with a temperature of {temp_value:.0f}{temp_unit}."
result = {"status": "success", "report": report}
print(f"--- Tool: Generated report in {preferred_unit}. Result: {result} ---")

# Example of writing back to state (optional for this tool)
tool_context.state["last_city_checked_stateful"] = city
print(f"--- Tool: Updated state 'last_city_checked_stateful': {city} ---")

return result
else:
# Handle city not found
error_msg = f"Sorry, I don't have weather information for '{city}'."
print(f"--- Tool: City '{city}' not found. ---")

return {"status": "error", "error_message": error_msg}