ADK 会话对象与存储后端的选择
ADK 用 Session 对象封装单条对话线程的标识与事件历史,由 SessionService 负责创建和读取,并提供内存、Vertex AI 与关系数据库三种存储实现,其中数据库实现用两级锁保证并发写入的一致性。
## 会话:跟踪个别对话[¶](<https://adk.dev/sessions/session/#session-tracking-individual-conversations>) 支持于 ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0Kotlin v0.1.0 中 A `Session` 代表一个用户和您的代理商之间的单个对话线程。 就像您不会从零开始每条短信一样, 代理商需要关于当前互动的背景 。 `Session` ADK中的对象是专门用来跟踪和管理这些单个的对话线程的. ## `Session` 对象[¶](<https://adk.dev/sessions/session/#session-objects>) 当用户开始与您的代理交互时, `SessionService` 创建一个 `Session` 对象( C)`google.adk.sessions.Session`。这个物体作为容器,与它有关。 *一个特定的聊天线索*。这里是它的关键属性: - **识别( E)`id`, `appName`, `userId`):** 谈话专用标签. - `id`: 一个唯一的标识符 *此具体内容* 对话框线程, 以后检索它所必需的。 一个 SessionService 对象可以处理多个 `Session`(s). 本字段确定我们指的是哪个特定会话对象,例如 " test_id_modification " 。 - `app_name`: 确定该对话属于哪个代理程序。 例如, " id_modifier_workflow " 。 - `userId`:将对话链接到特定用户。 - **历史( A)`events`):** 所有相互作用的时间顺序(`Event` 对象 – 用户消息,代理响应,工具动作)在此特定线程中发生. - **开会国( C)`state`):** 一个存储临时相关数据的地方 *仅限* 用于此特定且持续的对话。在互动过程中,这可作为代理人的抓图。我们将涵盖如何使用和管理 `state` 详细情况见下一节。 - **活动跟踪(`lastUpdateTime`):** 一个时间戳,表示此对话线中最后一次发生事件的时间 。 ### 示例:检查会话属性[¶](<https://adk.dev/sessions/session/#example-examining-session-properties>) 以下代码示例说明如何列出存储在会话对象中的各种值: PythonTypeScriptGoJavaKotlin ``` 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) ``` *(**说明:** 上面显示的状态只是初始状态. 州更新是通过事件进行的,如州一节所讨论的. )* ## 届会周期[¶](<https://adk.dev/sessions/session/#session-lifecycle>)  以下为简化流程: `Session` 财务报告和财务报告 `SessionService` 在对话时一起工作: 1. **开始或恢复 :** 您的应用程序需要使用 `SessionService` 改为: `create_session` (用于新聊天)或使用已有会话 ID. 2. **提供的背景:** 那个... `Runner` 获得合适的 `Session` 对象来自适当的服务方法,使代理机能够访问相应的会话 `state` 财务报告和财务报告 `events`. 3. **代理处理 :** 用户会以查询方式提示代理商。代理商会分析查询和可能的会话 `state` 财务报告和财务报告 `events` 历史来决定对策。 4. **响应状态更新( S) :** 代理生成一个响应( 并有可能在 `state`)。该 `Runner` 包此为 `Event`. 5. **保存交互 :** 那个... `Runner` 电话 `sessionService.append_event(session, event)` 与 `session` 和新项目 `event` 作为参数。服务添加 `Event` 更新会议记录 `state` 根据活动内的信息进行存储。 `last_update_time` 也得到更新。 6. **准备下一个 :** 代理回复到用户。 更新 `Session` 现保存于 `SessionService`,为下一个回合做好准备(该回合将依次重启循环的1,通常随着当前会话的继续). 7. **结束对话 :** 谈话结束后,您的申请会打来 `sessionService.delete_session(...)` 如果不再需要,则清理存储的会话数据。 这一周期突出地说明了如何开展以下活动: `SessionService` 通过管理历史和与每个历史相关的状态,确保对话的连续性 `Session` 对象。 ## A. 管理会议与 `SessionService`[¶](<https://adk.dev/sessions/session/#managing-sessions-with-a-sessionservice>) 如上所述,你通常不创建或管理 `Session` 对象。相反,您使用 **`SessionService`**本服务是负责您谈话整个生命周期的中央管理者。 其核心职责包括: - **开始新对话 :** 创建新 `Session` 当用户开始交互时,对象。 - **恢复现有对话:** 获取特定 `Session` (使用它的 ID) 这样,代理可以继续它离开的地方. - **保存进度 :** 增加新的互动(`Event` 对象)到会话历史。这也是会话通过的机制。 `state` 更新( 更多在 `State` 页:1 - **列出对话内容 :** 为特定用户和应用程序查找活动会话线索 。 - **正在清理 :** 删除 `Session` 当对话完成或不再需要时,对象及其相关数据。 ## `SessionService` 执行情况[¶](<https://adk.dev/sessions/session/#sessionservice-implementations>) ADK 提供了不同的 `SessionService` ,允许您选择最适合您的需要的存储后端 : ### `InMemorySessionService`[¶](<https://adk.dev/sessions/session/#inmemorysessionservice>) - **如何运作:** 将所有会话数据直接存储在应用程序的内存中. - **持久性 :** 无。 **如果应用程序重新启动, 所有的对话数据都会丢失 。** - **要求:** 没有额外的。 - **最佳服务:** 快速开发,局部测试,实例,以及不需要长期持久性的情景. PythonTypeScriptGoJavaKotlin ``` from google.adk.sessions import InMemorySessionService session_service = InMemorySessionService() ``` ``` import { InMemorySessionService } from "@google/adk"; const sessionService = new InMemorySessionService(); ``` ``` import "google.golang.org/adk/v2/session" inMemoryService := session.InMemoryService() ``` ``` import com.google.adk.sessions.InMemorySessionService; InMemorySessionService exampleSessionService = new InMemorySessionService(); ``` ``` import com.google.adk.kt.sessions.InMemorySessionService val sessionService = InMemorySessionService() ``` ### `VertexAiSessionService`[¶](<https://adk.dev/sessions/session/#vertexaisessionservice>) 支持于 ADKPython v0.1.0Go v0.1.0Java v0.1.0Kotlin v0.7.0 - **如何运作:** 通过API使用Google云代理平台基础设施呼叫会话管理. - **持久性 :** 是的,数据是通过可靠和可扩展的方式管理的。 [代理运行时间](<https://adk.dev/deploy/agent-runtime/>). - **要求:** - 谷歌云项目. - 那个... `gcp` 额外, 安装于 `pip install google-adk[gcp]`. - 可用此配置的 Google 云存储桶 [步骤](<https://cloud.google.com/vertex-ai/docs/pipelines/configure-project#storage>). - 一个代理运行时资源名称/ ID , 可以在之后设置 [教程](<https://adk.dev/deploy/agent-runtime/>). - 如果您没有Google Cloud项目, 您想要尝试 VertexAiSessionService , 请看 [代理平台快捷模式](<https://adk.dev/integrations/express-mode/>). - **最佳服务:** 在Google Cloud上部署的可扩展生产应用程序,特别是在与其他代理平台功能整合时. PythonGoJavaKotlin ``` # 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)) } ``` 关于连接到Google Cloud的更多信息,请见ADK代理商 [连接到 Google 云和代理平台](<https://adk.dev/get-started/google-cloud/>). ### `DatabaseSessionService`[¶](<https://adk.dev/sessions/session/#databasesessionservice>) 在 ADKPython v0.1.0Go v0.1.0中支持 - **如何运作:** 连接到关系数据库(如PostgreSQL,MySQL,SQLite),将会话数据持续存储在表格中. - **持久性 :** 是的,数据在应用程序重新启动后幸存。 - **要求:** 一个已配置的数据库。在 Python 中,也可以是 `db` 额外, 安装于 `pip install google-adk[db]`在 Go 中,一个 [GORM](<https://gorm.io/>) 用于数据库的驱动程序。 - **最佳服务:** 应用程序需要可靠,持续的存储,你管理自己。 PythonGo ``` 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 会话服务不创建或更新其表格。 call `database.AutoMigrate` 每次应用程序启动时, 在它为流量服务之前。 它会创建缺失的表格和列, 并且不丢弃已有的表格和列, 因此一个数据库在 ADK 升级后会继续工作 。 它还可以更改现有列的类型, 以匹配 ADK 的预期。 如果您自己管理计划而不是运行 `AutoMigrate`中,在部署介绍它们的 ADK 发布之前添加新的列。否则,请写到该表格中失败。 #### 货币和锁定[¶](<https://adk.dev/sessions/session/#concurrency-and-locking>) 在Python语中, `DatabaseSessionService` 通过双层锁定架构,确保同时运行期间的数据完整性: - **程序内锁定 :** 服务使用内部的、在流程中的锁进行序列化 `append_event` 当多个请求试图在同一进程内同时更新同一会话时,这可以防止种族条件。 - **行级锁定 :** 对于PostgreSQL,MySQL,以及MariaDB,服务使用行级锁定(通过) `SELECT ... FOR UPDATE`当多个进程或复制者试图同时更新同一会话时,防止种族条件. Async 驱动程序要求 在皮森语中 `DatabaseSessionService` 使用 SQLite 时,您必须使用 `sqlite+aiosqlite` 改为 `sqlite` 在连接字符串中。对于其他数据库(PostgreSQL, MySQL),请确保您正在使用一个协同驱动程序,例如 `asyncpg` 为PostgreSQL, `aiomysql` 用于MySQL. ADK Python v1.22.0中的会话数据库变换方案 会话数据库的计划在 ADK Python v1.22.0 中更改,它需要迁移会话数据库。更多信息请参见 [会话数据库计划迁移](<https://adk.dev/sessions/session/migrate/>). ## 解决问题会话错误[¶](<https://adk.dev/sessions/session/#troubleshoot-session-errors>) 执行期间,ADK可以提出具体的例外,以帮助您识别配置或状态问题. ### `SessionNotFoundError`[¶](<https://adk.dev/sessions/session/#sessionnotfounderror>) 当一个运行者试图访问或执行活动会话存储中不存在的会话时, 升起。 继承来自 `ValueError` 用于后向兼容性。 - **常见原因:** 无效、过期或缺失 `session_id`; 在创建之前运行一个会话。 - **如何解决:** 确保会话首先通过 `create_session(...)`,或构造 `Runner` 与 `auto_create_session=True`.
查看原始来源