会话:追踪用户之间的个别对话记录¶
A Session 这代表用户与您的代理之间的单次对话记录。就像您不会每次发送短信时都从头开始编写内容一样,代理也需要了解当前对话的上下文信息,以便能够更好地进行交流。 Session ADK(Application Development Kit)中的这个对象是专门为跟踪和管理这些单独的对话线程而设计的。
Session 对象¶
当用户开始与您的智能助手(agent)进行交互时, SessionService 创建一个
Session `object`(对象)google.adk.sessions.Session该对象充当一个“容器”,用于存储与该对象相关的所有内容。 一个特定的聊天线程以下是它的关键属性:
- **识别信息(Identification)**
id,appName,userId): 用于标识对话内容的唯一标签。id:一个用于唯一标识该对象的标识符。 这个特定的(thing) 对话线程(conversation thread)对于后续的数据检索非常重要。一个 SessionService 对象可以处理多个(multiple)对话线程。Session(s). 该字段用于标识我们正在引用的是哪个特定的会话对象。例如:“test_id_modification”。app_name用于标识此次对话所属的代理应用程序。例如:“id_modifier_workflow”。userId:将对话与特定用户关联起来。
- 历史记录(History)
events): 所有交互行为的按时间顺序排列的记录……)Event这些对象(包括用户消息、代理的响应以及工具执行的操作)都发生在这个特定的线程中。 - 会话状态(Session State)
state): 一个用于存储相关临时数据的地方。 只有;仅仅 这与当前正在进行的对话相关。在交互过程中,这个工具相当于代理(agent)的“临时记事本”(scratchpad)。接下来,我们将介绍如何使用和管理这个工具。state具体细节将在下一节中详细说明。 - 活动跟踪(Activity Tracking)
lastUpdateTime): 一个时间戳,用于表示该对话线程中某个事件最后一次发生的时间。
示例:检查会话属性¶
以下代码示例展示了如何列出存储在 `session` 对象中的各种值:
from google.adk.sessions import InMemorySessionService, Session
# Create a simple session to examine its properties
temp_service = InMemorySessionService()
example_session = await temp_service.create_session(
app_name="my_app",
user_id="example_user",
state={"initial_key": "initial_value"} # State can be initialized
)
print(f"--- Examining Session Properties ---")
print(f"ID (`id`): {example_session.id}")
print(f"Application Name (`app_name`): {example_session.app_name}")
print(f"User ID (`user_id`): {example_session.user_id}")
print(f"State (`state`): {example_session.state}") # Note: Only shows initial state here
print(f"Events (`events`): {example_session.events}") # Initially empty
print(f"Last Update (`last_update_time`): {example_session.last_update_time:.2f}")
print(f"---------------------------------")
# Clean up (optional for this example)
await temp_service.delete_session(app_name=example_session.app_name,
user_id=example_session.user_id, session_id=example_session.id)
print("The final status of temp_service - ", temp_service)
import { InMemorySessionService } from "@google/adk";
// Create a simple session to examine its properties
const tempService = new InMemorySessionService();
const exampleSession = await tempService.createSession({
appName: "my_app",
userId: "example_user",
state: {"initial_key": "initial_value"} // State can be initialized
});
console.log("--- Examining Session Properties ---");
console.log(`ID ('id'): ${exampleSession.id}`);
console.log(`Application Name ('appName'): ${exampleSession.appName}`);
console.log(`User ID ('userId'): ${exampleSession.userId}`);
console.log(`State ('state'): ${JSON.stringify(exampleSession.state)}`); // Note: Only shows initial state here
console.log(`Events ('events'): ${JSON.stringify(exampleSession.events)}`); // Initially empty
console.log(`Last Update ('lastUpdateTime'): ${exampleSession.lastUpdateTime}`);
console.log("---------------------------------");
// Clean up (optional for this example)
const finalStatus = await tempService.deleteSession({
appName: exampleSession.appName,
userId: exampleSession.userId,
sessionId: exampleSession.id
});
console.log("The final status of temp_service - ", finalStatus);
appName := "my_go_app"
userID := "example_go_user"
initialState := map[string]any{"initial_key": "initial_value"}
// Create a session to examine its properties.
createResp, err := inMemoryService.Create(ctx, &session.CreateRequest{
AppName: appName,
UserID: userID,
State: initialState,
})
if err != nil {
log.Fatalf("Failed to create session: %v", err)
}
exampleSession := createResp.Session
fmt.Println("\n--- Examining Session Properties ---")
fmt.Printf("ID (`ID()`): %s\n", exampleSession.ID())
fmt.Printf("Application Name (`AppName()`): %s\n", exampleSession.AppName())
// To access state, you call Get().
val, _ := exampleSession.State().Get("initial_key")
fmt.Printf("State (`State().Get()`): initial_key = %v\n", val)
// Events are initially empty.
fmt.Printf("Events (`Events().Len()`): %d\n", exampleSession.Events().Len())
fmt.Printf("Last Update (`LastUpdateTime()`): %s\n", exampleSession.LastUpdateTime().Format("2006-01-02 15:04:05"))
fmt.Println("---------------------------------")
// Clean up the session.
err = inMemoryService.Delete(ctx, &session.DeleteRequest{
AppName: exampleSession.AppName(),
UserID: exampleSession.UserID(),
SessionID: exampleSession.ID(),
})
if err != nil {
log.Fatalf("Failed to delete session: %v", err)
}
fmt.Println("Session deleted successfully.")
import com.google.adk.sessions.InMemorySessionService;
import com.google.adk.sessions.Session;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ConcurrentHashMap;
String sessionId = "123";
String appName = "example-app"; // Example app name
String userId = "example-user"; // Example user id
ConcurrentMap<String, Object> initialState = new ConcurrentHashMap<>(Map.of("newKey", "newValue"));
InMemorySessionService exampleSessionService = new InMemorySessionService();
// Create Session
Session exampleSession = exampleSessionService.createSession(
appName, userId, initialState, Optional.of(sessionId)).blockingGet();
System.out.println("Session created successfully.");
System.out.println("--- Examining Session Properties ---");
System.out.printf("ID (`id`): %s%n", exampleSession.id());
System.out.printf("Application Name (`appName`): %s%n", exampleSession.appName());
System.out.printf("User ID (`userId`): %s%n", exampleSession.userId());
System.out.printf("State (`state`): %s%n", exampleSession.state());
System.out.println("------------------------------------");
// Clean up (optional for this example)
var unused = exampleSessionService.deleteSession(appName, userId, sessionId);
import com.google.adk.kt.sessions.InMemorySessionService
import com.google.adk.kt.sessions.SessionKey
val sessionId = "123"
val appName = "example-app"
val userId = "example-user"
val initialState = mapOf("newKey" to "newValue")
val sessionService = InMemorySessionService()
// Create Session
val exampleSession = sessionService.createSession(
key = SessionKey(appName, userId, sessionId),
state = initialState
)
println("Session created successfully.")
println("--- Examining Session Properties ---")
println("ID (`id`): ${exampleSession.key.id}")
println("Application Name (`appName`): ${exampleSession.key.appName}")
println("User ID (`userId`): ${exampleSession.key.userId}")
println("State (`state`): ${exampleSession.state}")
println("------------------------------------")
// Clean up (optional for this example)
sessionService.deleteSession(exampleSession.key)
(注意: 上面显示的状态只是初始状态。状态的更新是通过事件来实现的,这一点在“状态”(State)部分的讨论中已经提到过。
会话生命周期(Session Lifecycle)¶

以下是该过程的简化流程: Session 和 SessionService 在对话过程中,双方可以“共同努力”(即互相配合、共同完成任务或解决问题)。
- 开始或继续: 您的应用程序需要使用该功能/服务。
SessionService要么……要么……create_session(用于新建聊天会话)或使用现有的会话 ID。 - 提供的上下文信息: The
Runner获取相应的(内容或信息)Session该对象来自相应的服务方法,使代理能够访问相应的会话(Session)。state和events. - 代理处理(Agent Processing): 用户向代理提交一个查询请求。代理会分析该查询请求,以及可能相关的会话数据(session information)。
state和events历史数据(history)用于确定响应结果(response)。 - 响应与状态更新: 代理会生成一个响应(并且可能会标记需要更新的数据)。
state). TheRunner将此内容打包为一个……Event. - “保存交互记录”(Save Interaction): The
Runner调用(functions/methods)sessionService.append_event(session, event)使用(或借助)……session还有这个新的……event将这些参数作为输入值。该服务会对其进行处理(或:该服务会使用这些参数来执行相应的操作)。Event将相关内容添加到历史记录中,并更新会话的相关信息。state根据事件中的信息,该会话被存储在相应的存储系统中。last_update_time这些内容也会被更新。 - 准备好迎接下一个阶段了: 代理的响应会发送给用户。系统已经完成了更新。
Session现在该数据由……存储。SessionService准备进入下一个环节……(这会使整个流程重新从第一步开始,通常会继续当前会话中的对话。) - 结束对话: 当对话结束时,您的应用程序会发起相应的调用。
sessionService.delete_session(...)如果不再需要存储的会话数据,就需要将其清除。
这个周期重点展示了……(即这个周期如何突出某种现象或趋势)。 SessionService 通过管理与每个用户会话相关联的历史记录和状态,确保会话的连续性。 Session `object.`
使用 [该工具/方法] 管理会话 SessionService¶
如上所述,通常情况下你并不需要创建或管理这些内容。 Session 对象可以直接使用。
相反,你应该使用……(此处应填写具体的方法或工具)。 SessionService该服务充当中央管理器,负责管理您所有对话会话的整个生命周期。
其核心职责包括:
- 开启新的对话: 正在创建新的内容(或资源)。
Session当用户开始进行交互时,系统会生成相应的对象。 - 恢复现有的对话: 检索特定的……
Session(使用其 ID),以便代理能够从上次停止的地方继续执行任务。 - 保存进度: 添加新的交互记录……)
Event(对象)被添加到会话的历史记录中。这也是会话管理机制的一部分。state会得到更新(更多细节将在……中提供)。State(section)。 - 列出对话记录: 查找特定用户和应用程序的活跃会话线程。
- 清理工作: 删除
Session当对话结束时,或者这些数据不再被需要时,系统会删除相关对象及其关联的数据。
SessionService 实现方式(implementations)¶
ADK 提供了多种不同的功能/选项。 SessionService 这些实现方案允许您根据自己的需求选择最适合的存储后端服务。
InMemorySessionService¶
- 工作原理: 将所有会话数据直接存储在应用程序的内存中。
- 持久性(Persistence): 无。 如果应用程序重新启动,所有对话数据都会丢失。
- 需要: 没有任何额外的内容。
- 最适合: 适用于快速开发、本地测试的场景;同时也提供了相关示例和用例,这些场景并不需要数据的长期保存(即不需要数据的持久化存储)。
VertexAiSessionService¶
- 工作原理: 通过 API 使用 Google Cloud Agent Platform 的基础设施; 同时需要执行会话管理相关的操作。
- 持久性(Persistence): 是的。数据通过相关系统得到可靠且可扩展的管理。 代理(Agent) 运行时(Runtime).
- 需要:
- 一个 Google Cloud 项目。
- The
gcp“extra”:随软件一起安装的附加组件或功能。pip install google-adk[gcp]. - 这是一个 Google Cloud 存储桶,可以通过此配置进行相关设置。 步骤(Step).
- 这是一个代理运行时(Agent Runtime)资源的名称/ID,可以按照以下方式对其进行配置: 教程.
- 如果您没有 Google Cloud 项目,但想要尝试使用 `VertexAiSessionService`,请参阅…… Agent Platform Express 模式(Mode).
- 最适合: 部署在 Google Cloud 上的可扩展生产级应用程序, 尤其是在与其他 Agent Platform 功能集成时。
# Requires: pip install google-adk[gcp]
# Plus GCP setup and authentication
from google.adk.sessions import VertexAiSessionService
PROJECT_ID = "your-gcp-project-id"
LOCATION = "us-central1"
# The app_name used with this service should be the Reasoning Engine ID or name
REASONING_ENGINE_APP_NAME = "projects/your-gcp-project-id/locations/us-central1/reasoningEngines/your-engine-id"
session_service = VertexAiSessionService(project=PROJECT_ID, location=LOCATION)
# Use REASONING_ENGINE_APP_NAME when calling service methods, e.g.:
# session = await session_service.create_session(app_name=REASONING_ENGINE_APP_NAME, ...)
import "google.golang.org/adk/v2/session/vertexai"
// Before running, ensure your environment is authenticated:
// gcloud auth application-default login
sessionService, err := vertexai.NewSessionService(ctx, vertexai.VertexAIServiceConfig{
ProjectID: "your-gcp-project-id",
Location: "us-central1",
// The numeric reasoning engine ID.
ReasoningEngine: "1234567890",
})
if err != nil {
log.Fatal(err)
}
// Please look at the set of requirements above, consequently export the following in your bashrc file:
// export GOOGLE_CLOUD_PROJECT=my_gcp_project
// export GOOGLE_CLOUD_LOCATION=us-central1
// export GOOGLE_API_KEY=my_api_key
import com.google.adk.sessions.VertexAiSessionService;
import java.util.UUID;
String sessionId = UUID.randomUUID().toString();
String reasoningEngineAppName = "123456789";
String userId = "u_123"; // Example user id
ConcurrentMap<String, Object> initialState = new
ConcurrentHashMap<>(); // No initial state needed for this example
VertexAiSessionService sessionService = new VertexAiSessionService();
Session mySession =
sessionService
.createSession(reasoningEngineAppName, userId, initialState, Optional.of(sessionId))
.blockingGet();
VertexAiSessionService 该功能仅在 ADK Kotlin 中可用(仅适用于 JVM 环境),在 Android 平台上不可使用。请通过服务器端的代理程序来使用该功能。
import com.google.adk.kt.sessions.SessionKey
import com.google.adk.kt.sessions.VertexAiSessionService
import kotlinx.coroutines.runBlocking
// The reasoning engine is pinned here, at construction. In the other tabs
// the engine is chosen per call, through `app_name`; in Kotlin `appName`
// is never parsed for it and is only a label on the session.
val sessionService =
VertexAiSessionService(
project = "your-gcp-project-id",
location = "us-central1",
// The bare numeric engine id. A full
// "projects/.../reasoningEngines/..." resource name is rejected;
// project and location are separate arguments.
reasoningEngineId = "1234567890",
)
// Session methods are suspend functions; `runBlocking` here is the
// counterpart of the Java tab's `.blockingGet()`.
val mySession = runBlocking {
// A null id lets the service assign one.
sessionService.createSession(SessionKey("example-app", "u_123", id = null))
}
有关如何从 ADK 代理连接到 Google Cloud 的更多信息,请参阅…… 连接到 Google Cloud 和 Agent Platform。.
DatabaseSessionService¶
- 工作原理: 该功能用于连接到关系型数据库(例如 PostgreSQL、MySQL、SQLite),并将会话数据持久地存储在数据库的表中。
- 持久性(Persistence): 是的。数据在应用程序重启后仍然会保留下来。
- 需要: 一个已配置的数据库。在 Python 中也是如此。
db`extra` (与软件一起)被安装了pip install google-adk[db]在 Go 语言中,一个……(In Go, a……) GORM 这是用于连接您的数据库的驱动程序。 - 最适合: 需要可靠且持久的数据存储解决方案的应用程序——这些存储方案由用户自己管理。
from google.adk.sessions import DatabaseSessionService
# Example using a local SQLite file:
# Note: The implementation requires an async database driver.
# For SQLite, use 'sqlite+aiosqlite' instead of 'sqlite' to ensure async compatibility.
db_url = "sqlite+aiosqlite:///./my_agent_data.db"
session_service = DatabaseSessionService(db_url=db_url)
import (
"log"
"github.com/glebarez/sqlite"
"gorm.io/gorm"
"google.golang.org/adk/v2/session/database"
)
// Example using a local SQLite file. Any GORM dialector works, for
// example gorm.io/driver/postgres for PostgreSQL.
sessionService, err := database.NewSessionService(sqlite.Open("my_agent_data.db"), &gorm.Config{})
if err != nil {
log.Fatal(err)
}
// Creates the tables and adds any columns a newer ADK release needs.
// Run it every time the application starts.
if err := database.AutoMigrate(sessionService); err != nil {
log.Fatal(err)
}
运行 AutoMigrate 在每次系统启动时(即每次应用程序开始运行时)
Go 语言的会话(session)服务本身不会创建或更新任何数据库表。相关操作需要通过其他方式来完成。
database.AutoMigrate 每次您的应用程序启动时,在开始处理用户请求之前,系统会自动创建缺失的表和列,同时不会删除现有的表或列。因此,即使在升级 ADK 后添加了新的列,数据库仍能继续正常运行。此外,系统还可以更改现有列的数据类型,以使其符合 ADK 的要求。如果您自己负责管理数据库架构(而不是依赖自动化的工具或流程),则需要手动执行这些操作。 AutoMigrate在部署 ADK 之前,需要添加这些新列;只有在新版本发布后,这些更改才会生效。否则,尝试向该表写入数据时会失败。
并发与锁机制(Concurrency and Locking)¶
在 Python 中, DatabaseSessionService 通过双层锁定架构,在并发操作期间确保数据的完整性:
- 进程内锁定(In-Process locking): 该服务使用一个内部的、在进程内部的锁机制来确保数据序列化的正确性(即防止数据在传输或存储过程中被意外修改)。
append_event这些请求属于同一个会话(session);这样做可以避免“竞态条件”(race condition)的发生。当多个请求在同一进程内同时尝试更新同一个会话时,竞态条件可能会导致数据不一致或系统错误。 - 行级锁定(Row-Level locking): 对于 PostgreSQL、MySQL 和 MariaDB,该服务使用行级锁定(通过……实现)。
SELECT ... FOR UPDATE)以防止竞态条件(race conditions)的发生。当多个进程或副本尝试同时更新同一个会话(session)时,这种机制可以避免数据不一致或系统错误。
异步驱动程序的要求(Async driver requirement)
在 Python 中, DatabaseSessionService 需要一个异步数据库驱动程序。
在使用 SQLite 时,必须使用相应的异步驱动程序。 sqlite+aiosqlite 而不是 sqlite 请在您的连接字符串中包含该驱动程序的名称。对于其他数据库(如 PostgreSQL、MySQL),请确保您使用的是支持异步操作的驱动程序(例如相应的驱动程序版本)。 asyncpg 对于 PostgreSQL:
aiomysql 适用于 MySQL 的代码。
在 ADK Python v1.22.0 中,会话数据库(Session database)的架构发生了变更。
在 ADK Python v1.22.0 中,会话数据库的架构发生了变化,因此需要迁移现有的会话数据库。有关更多详细信息,请参阅…… 会话数据库模式迁移.
排查会话错误(Session Errors)¶
在执行过程中,ADK 可以抛出特定的异常,以帮助您识别配置或状态方面的问题。
SessionNotFoundError¶
当运行者尝试访问或执行一个在活动会话存储中不存在的会话时,会触发此异常。该异常继承自……(此处应填写异常的父类名称)。 ValueError 为了保持向后兼容性(即确保旧版本的应用程序仍能正常运行)。
- 常见原因: 无效的、已过期的或缺失的
session_id在会话尚未被创建之前就尝试运行它。 - 如何解决: 首先需要确保会话(session)已经存在。
create_session(...)或者构建这个……Runner使用(with)auto_create_session=True.