区分会话短期状态与长期记忆服务

资料说明会话的events与state只覆盖单次对话,而MemoryService提供可检索的长期知识库,支持把完整会话写入记忆并按查询检索片段,并对比了三种Python ADK实现及其适用场景。

## 记忆:长期知识 `MemoryService`[¶](<https://adk.dev/sessions/memory/#memory-long-term-knowledge-with-memoryservice>) 支持于 ADKPython v0.1.0TypeScript v0.2.0Go v0.1.0Java v0.1.0Kotlin v0.1.0 中 期间a `Session` 跟踪历史( T)`events`)和临时数据(`state`)在一次谈话中,代理人可能需要回顾过去互动中的信息。 **长期知识** 页:1 **`MemoryService`** 来玩吧,这样想想: - **`Session` / `State`:** 这是你在一个特定聊天时的短期记忆. - **长期知识`MemoryService`)**:这是一个可以搜索的档案或代理商可查询的知识库,可能包含来自许多过去聊天或其他来源的信息. ## 那个... `MemoryService` 角色[¶](<https://adk.dev/sessions/memory/#the-memoryservice-role>) 那个... `BaseMemoryService` (或 减) `Service` in Go)中定义了管理这个可搜索的长期知识库的接口。它支持这些操作: - **获取信息:** - **`add_session_to_memory`**: 需要完成一个 `Session` 并添加相关信息到长期知识库中。这种方法对于自动捕捉对话的本质是理想的。 - **`add_events_to_memory`**: 附加一个事件三角形( 例如最近转弯) 而不重新摄入整个会话 。 如果您要通过长期会话写入记忆部分, 则有用 。 - **`add_memory`**: 添加明示 `MemoryEntry` 对象直接切入内存。这种方法可以使您得到精细的控制,并且有助于从其他来源注入特定事实。 - **搜索信息( I)`search_memory`):** 让代理人(通常通过 `Tool`)查询知识库,并检索基于搜索查询的相关片段或上下文. `add_events_to_memory` 财务报告和财务报告 `add_memory` 服务是可选的,并非每个服务机构都会执行,所以确认您选择的服务在依赖它们之前会支持它们。 ## 选择正确的内存服务[¶](<https://adk.dev/sessions/memory/#choose-the-right-memory-service>) Python ADK号三号舰 `MemoryService` 执行。请使用下表来决定哪个最适合您的代理。 | **特性** | **InMemoryMemoryService** | **VertexAiMemoryBankService** | **VertexAiRagMemoryService** | | --- | --- | --- | --- | | **持久性** | 无, 数据在重新启动时丢失 | 是,由代理平台管理 | 是,储存在知识引擎中 | | **主使用大小写** | 原型化,局部发展,以及简单的测试. | 从用户对话中建立有意义的、不断发展的记忆。 | 矢量搜索检索 整个谈话程序, 或者与其它RAG索引的内容。 | | **内存提取** | 存储完整对白 | 摘录 [有意义的信息](<https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/memory-bank/generate-memories>) 从对话中,用LLM驱动的现有记忆来整合它. | 存储完整对白, 由 [知识引擎](<https://cloud.google.com/vertex-ai/generative-ai/docs/rag-engine/rag-overview>). | | **搜索能力** | 基本关键字匹配 。 | 高级语义搜索. | 矢量相似性搜索在知识引擎上. | | **设置复杂度** | 没有,是默认的 | 低,需要一个 [代理运行时间](<https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/memory-bank/overview>) 在代理平台上。 | 中度。 要求( M) [知识引擎](<https://cloud.google.com/vertex-ai/generative-ai/docs/rag-engine/manage-your-rag-corpus>). | | **依赖关系** | 无。 | 谷歌云项目,代理平台 API | Google云项目,知识引擎,代理平台SDK(可选安装). | | **什么时候用?** | 当您想要搜索多个会话的聊天历史时, 请查看原型 。 | 当你想要你的经纪人记住 并从过去的互动中吸取教训时 | 当您已经拥有 RAG 基础设施时, 或想要从原始谈话记录获取 。 | 您总是可以导入 `VertexAiRagMemoryService` 从 `google.adk.memory`但它的建造升起 `ImportError` 除非代理平台 SDK 安装在 `pip install google-adk[gcp]`。内存库和RAG支持的内存记录在 [记忆库](<https://adk.dev/sessions/memory/#memory-bank>) 财务报告和财务报告 [RAG 内存](<https://adk.dev/sessions/memory/#rag-memory>) 现列于下。 ## `InMemoryMemoryService`[¶](<https://adk.dev/sessions/memory/#inmemorymemoryservice>) 那个... `InMemoryMemoryService` 将会话信息存储在应用程序的内存中,并进行基本的关键字匹配以进行搜索。它不需要设置,而且最适合不要求持久性的原型和简单的测试方案。 PythonTypeScriptGoJavaKotlin ``` from google.adk.memory import InMemoryMemoryService memory_service = InMemoryMemoryService() ``` ``` import { InMemoryMemoryService } from '@google/adk'; const memoryService = new InMemoryMemoryService(); ``` ``` import ( "google.golang.org/adk/v2/memory" "google.golang.org/adk/v2/session" ) // Services must be shared across runners to share state and memory. sessionService := session.InMemoryService() memoryService := memory.InMemoryService() ``` ``` import com.google.adk.memory.InMemoryMemoryService; InMemoryMemoryService memoryService = new InMemoryMemoryService(); ``` ``` fun instantiateMemoryService() { val memoryService = InMemoryMemoryService() } ``` **示例: 添加和搜索内存** 这个例子表明,使用下列方法的基本流量: `InMemoryMemoryService` 简洁。 PythonTypeScriptGoJavaKotlin ``` import asyncio from google.adk.agents import LlmAgent from google.adk.sessions import InMemorySessionService, Session from google.adk.memory import InMemoryMemoryService # Import MemoryService from google.adk.runners import Runner from google.adk.tools import load_memory # Tool to query memory from google.genai.types import Content, Part # --- Constants --- APP_NAME = "memory_example_app" USER_ID = "mem_user" MODEL = "gemini-flash-latest" # Use a valid model # --- Agent Definitions --- # Agent 1: Simple agent to capture information info_capture_agent = LlmAgent( model=MODEL, name="InfoCaptureAgent", instruction="Acknowledge the user's statement.", ) # Agent 2: Agent that can use memory memory_recall_agent = LlmAgent( model=MODEL, name="MemoryRecallAgent", instruction="Answer the user's question. Use the 'load_memory' tool " "if the answer might be in past conversations.", tools=[load_memory] # Give the agent the tool ) # --- Services --- # Services must be shared across runners to share state and memory session_service = InMemorySessionService() memory_service = InMemoryMemoryService() # Use in-memory for demo async def run_scenario(): # --- Scenario --- # Turn 1: Capture some information in a session print("--- Turn 1: Capturing Information ---") runner1 = Runner( # Start with the info capture agent agent=info_capture_agent, app_name=APP_NAME, session_service=session_service, memory_service=memory_service # Provide the memory service to the Runner ) session1_id = "session_info" await runner1.session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=session1_id) user_input1 = Content(parts=[Part(text="My favorite project is Project Alpha.")], role="user") # Run the agent final_response_text = "(No final response)" async for event in runner1.run_async(user_id=USER_ID, session_id=session1_id, new_message=user_input1): if event.is_final_response() and event.content and event.content.parts: final_response_text = event.content.parts[0].text print(f"Agent 1 Response: {final_response_text}") # Get the completed session completed_session1 = await runner1.session_service.get_session(app_name=APP_NAME, user_id=USER_ID, session_id=session1_id) # Add this session's content to the Memory Service print("\n--- Adding Session 1 to Memory ---") await memory_service.add_session_to_memory(completed_session1) print("Session added to memory.") # Turn 2: Recall the information in a new session print("\n--- Turn 2: Recalling Information ---") runner2 = Runner( # Use the second agent, which has the memory tool agent=memory_recall_agent, app_name=APP_NAME, session_service=session_service, # Reuse the same service memory_service=memory_service # Reuse the same service ) session2_id = "session_recall" await runner2.session_service.create_session(app_name=APP_NAME, user_id=USER_ID, session_id=session2_id) user_input2 = Content(parts=[Part(text="What is my favorite project?")], role="user") # Run the second agent final_response_text_2 = "(No final response)" async for event in runner2.run_async(user_id=USER_ID, session_id=session2_id, new_message=user_input2): if event.is_final_response() and event.content and event.content.parts: final_response_text_2 = event.content.parts[0].text print(f"Agent 2 Response: {final_response_text_2}") # To run this example, you can use the following snippet: # asyncio.run(run_scenario()) # await run_scenario() ``` ``` import { InMemoryMemoryService, InMemorySessionService, LOAD_MEMORY, LlmAgent, Runner } from '@google/adk'; import { createUserContent } from '@google/genai'; // --- Constants --- const APP_NAME = "memory_example_app"; const USER_ID = "mem_user"; const MODEL = "gemini-2.5-flash"; // --- Agent Definitions --- // Agent 1: Simple agent to capture information const infoCaptureAgent = new LlmAgent({ model: MODEL, name: "InfoCaptureAgent", instruction: "Acknowledge the user's statement concisely.", }); // Agent 2: Agent that can use memory const memoryRecallAgent = new LlmAgent({ model: MODEL, name: "MemoryRecallAgent", instruction: "Answer the user's question. Use the 'load_memory' tool if the answer might be in past conversations.", tools: [LOAD_MEMORY] }); // Export for 'adk run' compatibility (to avoid 'No BaseAgent found' error) export const root_agent = memoryRecallAgent; // --- Services --- const sessionService = new InMemorySessionService(); const memoryService = new InMemoryMemoryService(); async function runScenario() { // --- Turn 1: Capture some information in a session --- console.log("--- Turn 1: Capturing Information ---"); const runner1 = new Runner({ agent: infoCaptureAgent, appName: APP_NAME, sessionService, memoryService }); const session1Id = "session_info"; await sessionService.createSession({ appName: APP_NAME, userId: USER_ID, sessionId: session1Id }); const userInput1 = createUserContent("My favorite project is Project Alpha."); let finalResponseText = "(No final response)"; for await (const event of runner1.runAsync({ userId: USER_ID, sessionId: session1Id, newMessage: userInput1 })) { // Capture any text response from the agent if (event.author === infoCaptureAgent.name && event.content?.parts) { const text = event.content.parts.map(p => p.text || "").join("").trim(); if (text) finalResponseText = text; } } console.log(`Agent 1 Response: ${finalResponseText}`); // Get the completed session and add to Memory const completedSession1 = await sessionService.getSession({ appName: APP_NAME, userId: USER_ID, sessionId: session1Id }); console.log("\n--- Adding Session 1 to Memory ---"); if (completedSession1) { await memoryService.addSessionToMemory(completedSession1); console.log("Session added to memory."); } // --- Turn 2: Recall the information in a new session --- console.log("\n--- Turn 2: Recalling Information ---"); const runner2 = new Runner({ agent: memoryRecallAgent, appName: APP_NAME, sessionService, memoryService }); const session2Id = "session_recall"; await sessionService.createSession({ appName: APP_NAME, userId: USER_ID, sessionId: session2Id }); const userInput2 = createUserContent("What is my favorite project?"); let finalResponseText2 = "(No final response)"; for await (const event of runner2.runAsync({ userId: USER_ID, sessionId: session2Id, newMessage: userInput2 })) { // Capture any text response from the agent if (event.author === memoryRecallAgent.name && event.content?.parts) { const text = event.content.parts.map(p => p.text || "").join("").trim(); if (text) finalResponseText2 = text; } } console.log(`Agent 2 Response: ${finalResponseText2}`); // Exit immediately to prevent the ADK CLI from starting an interactive loop process.exit(0); } // Execute the scenario runScenario().catch(err => { console.error(err); process.exit(1); }); ``` ``` import ( "context" "fmt" "log" "strings" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/agent/llmagent" "google.golang.org/adk/v2/memory" "google.golang.org/adk/v2/model/gemini" "google.golang.org/adk/v2/runner" "google.golang.org/adk/v2/session" "google.golang.org/adk/v2/tool" "google.golang.org/adk/v2/tool/functiontool" "google.golang.org/genai" ) const ( appName = "go_memory_example_app" userID = "go_mem_user" modelID = "gemini-2.5-flash" ) // Args defines the input structure for the memory search tool. type Args struct { Query string `json:"query" jsonschema:"The query to search for in the memory."` } // Result defines the output structure for the memory search tool. type Result struct { Results []string `json:"results"` } // memorySearchToolFunc is the implementation of the memory search tool. // This function demonstrates accessing memory via agent.Context. func memorySearchToolFunc(tctx agent.Context, args Args) (Result, error) { fmt.Printf("Tool: Searching memory for query: '%s'\n", args.Query) // The SearchMemory function is available on the context. searchResults, err := tctx.SearchMemory(context.Background(), args.Query) if err != nil { log.Printf("Error searching memory: %v", err) return Result{}, fmt.Errorf("failed memory search") } var results []string for _, res := range searchResults.Memories { if res.Content != nil { results = append(results, textParts(res.Content)...) } } return Result{Results: results}, nil } // Define a tool that can search memory. var memorySearchTool = must(functiontool.New( functiontool.Config{ Name: "search_past_conversations", Description: "Searches past conversations for relevant information.", }, memorySearchToolFunc, )) // This example demonstrates how to use the MemoryService in the Go ADK. // It covers two main scenarios: // 1. Adding a completed session to memory and recalling it in a new session. // 2. Searching memory from within a custom tool using the agent.Context. func main() { ctx := context.Background() // --- Services --- // Services must be shared across runners to share state and memory. sessionService := session.InMemoryService() memoryService := memory.InMemoryService() // Use in-memory for this demo. // --- Scenario 1: Capture information in one session --- fmt.Println("--- Turn 1: Capturing Information ---") infoCaptureAgent := must(llmagent.New(llmagent.Config{ Name: "InfoCaptureAgent", Model: must(gemini.NewModel(ctx, modelID, nil)), Instruction: "Acknowledge the user's statement.", })) runner1 := must(runner.New(runner.Config{ AppName: appName, Agent: infoCaptureAgent, SessionService: sessionService, MemoryService: memoryService, // Provide the memory service to the Runner })) session1ID := "session_info" must(sessionService.Create(ctx, &session.CreateRequest{AppName: appName, UserID: userID, SessionID: session1ID})) userInput1 := genai.NewContentFromText("My favorite project is Project Alpha.", "user") var finalResponseText string for event, err := range runner1.Run(ctx, userID, session1ID, userInput1, agent.RunConfig{}) { if err != nil { log.Printf("Agent 1 Error: %v", err) continue } if event.LLMResponse.Content != nil && !event.LLMResponse.Partial { finalResponseText = strings.Join(textParts(event.LLMResponse.Content), "") } } fmt.Printf("Agent 1 Response: %s\n", finalResponseText) // Add the completed session to the Memory Service fmt.Println("\n--- Adding Session 1 to Memory ---") resp, err := sessionService.Get(ctx, &session.GetRequest{AppName: appName, UserID: userID, SessionID: session1ID}) if err != nil { log.Fatalf("Failed to get completed session: %v", err) } if err := memoryService.AddSessionToMemory(ctx, resp.Session); err != nil { log.Fatalf("Failed to add session to memory: %v", err) } fmt.Println("Session added to memory.") // --- Scenario 2: Recall the information in a new session using a tool --- fmt.Println("\n--- Turn 2: Recalling Information ---") memoryRecallAgent := must(llmagent.New(llmagent.Config{ Name: "MemoryRecallAgent", Model: must(gemini.NewModel(ctx, modelID, nil)), Instruction: "Answer the user's question. Use the 'search_past_conversations' tool if the answer might be in past conversations.", Tools: []tool.Tool{memorySearchTool}, // Give the agent the tool })) runner2 := must(runner.New(runner.Config{ Agent: memoryRecallAgent, AppName: appName, SessionService: sessionService, MemoryService: memoryService, })) session2ID := "session_recall" must(sessionService.Create(ctx, &session.CreateRequest{AppName: appName, UserID: userID, SessionID: session2ID})) userInput2 := genai.NewContentFromText("What is my favorite project?", "user") var finalResponseText2 string for event, err := range runner2.Run(ctx, userID, session2ID, userInput2, agent.RunConfig{}) { if err != nil { log.Printf("Agent 2 Error: %v", err) continue } if event.LLMResponse.Content != nil && !event.LLMResponse.Partial { finalResponseText2 = strings.Join(textParts(event.LLMResponse.Content), "") } } fmt.Printf("Agent 2 Response: %s\n", finalResponseText2) } ``` ``` import com.google.adk.agents.LlmAgent; import com.google.adk.agents.RunConfig; import com.google.adk.events.Event; import com.google.adk.runner.InMemoryRunner; import com.google.adk.sessions.Session; import com.google.adk.tools.LoadMemoryTool; import com.google.genai.types.Content; import com.google.genai.types.Part; import java.util.Optional; public class MemoryExample { public static void main(String[] args) { String appName = "memory_example_app"; String userId = "mem_user"; String model = "gemini-flash-latest"; // An agent that can recall past information using the load_memory tool. LlmAgent agent = LlmAgent.builder() .model(model) .name("MemoryAgent") .instruction( "Answer the user's question. Use the 'load_memory' tool " + "if the answer might be in past conversations.") .tools(new LoadMemoryTool()) .build(); // InMemoryRunner bundles in-memory session and memory services and shares // them across every session it creates. InMemoryRunner runner = new InMemoryRunner(agent, appName); // --- Turn 1: capture information in one session --- Session captureSession = runner.sessionService().createSession(appName, userId).blockingGet(); Content statement = Content.fromParts(Part.fromText("My favorite project is Project Alpha.")); runner .runAsync(userId, captureSession.id(), statement, RunConfig.builder().build()) .blockingSubscribe(); // Persist the finished session to memory. Session completedSession = runner .sessionService() .getSession(appName, userId, captureSession.id(), Optional.empty()) .blockingGet(); runner.memoryService().addSessionToMemory(completedSession).blockingAwait(); // --- Turn 2: recall the information in a new session --- Session recallSession = runner.sessionService().createSession(appName, userId).blockingGet(); Content question = Content.fromParts(Part.fromText("What is my favorite project?")); runner .runAsync(userId, recallSession.id(), question, RunConfig.builder().build()) .blockingForEach( (Event event) -> { if (event.finalResponse()) { event .content() .flatMap(Content::parts) .ifPresent( parts -> parts.forEach(part -> part.text().ifPresent(System.out::println))); } }); } } ``` ``` /** * This example demonstrates the basic flow using the `InMemoryMemoryService` in Kotlin. * It shows how to capture information in one session, add it to memory, and recall it in another. */ fun main() = runBlocking { // --- Constants --- val appName = "memory_example_app" val userId = "mem_user" val model = Gemini(name = "gemini-flash-latest") // --- Agent Definitions --- // Agent 1: Simple agent to capture information val infoCaptureAgent = LlmAgent( name = "InfoCaptureAgent", model = model, instruction = Instruction("Acknowledge the user's statement."), ) // Agent 2: Agent that can use memory val memoryRecallAgent = LlmAgent( name = "MemoryRecallAgent", model = model, instruction = Instruction( "Answer the user's question. Use the 'load_memory' tool " + "if the answer might be in past conversations.", ), // Give the agent the tool tools = listOf(LoadMemoryTool()), ) // --- Services --- // Services must be shared across runners to share state and memory val sessionService = InMemorySessionService() val memoryService = InMemoryMemoryService() // --- Turn 1: Capturing Information --- println("--- Turn 1: Capturing Information ---") val runner1 = InMemoryRunner( agent = infoCaptureAgent, appName = appName, sessionService = sessionService, memoryService = memoryService, ) val sessionId1 = "session_info" val userInput1 = Content.fromText(Role.USER, "My favorite project is Project Alpha.") // Run the agent runner1 .runAsync( userId = userId, sessionId = sessionId1, newMessage = userInput1, ).collect { event -> event.content?.parts?.forEach { part -> if (!part.text.isNullOrBlank()) { println("Agent Response: ${part.text}") } } } // Get the completed session using SessionKey val session1 = sessionService.getSession(SessionKey(appName, userId, sessionId1)) // Add this session's content to the Memory Service println("\n--- Adding Session 1 to Memory ---") if (session1 != null) { memoryService.addSessionToMemory(session1) println("Session added to memory.") } // --- Turn 2: Recalling Information --- println("\n--- Turn 2: Recalling Information ---") val runner2 = InMemoryRunner( agent = memoryRecallAgent, appName = appName, // Reuse the same service sessionService = sessionService, // Reuse the same service memoryService = memoryService, ) val sessionId2 = "session_recall" val userInput2 = Content.fromText(Role.USER, "What is my favorite project?") // Run the second agent runner2 .runAsync( userId = userId, sessionId = sessionId2, newMessage = userInput2, ).collect { event -> event.content?.parts?.forEach { part -> if (!part.text.isNullOrBlank()) { println("Agent Response: ${part.text}") } } } } ``` ### 在工具内搜索内存[¶](<https://adk.dev/sessions/memory/#search-memory-within-a-tool>) 也可以通过使用工具上下文从自定义工具内搜索内存. PythonTypeScriptGoJavaKotlin ``` from google.adk.tools import ToolContext async def search_past_conversations( query: str, tool_context: ToolContext ) -> dict: response = await tool_context.search_memory(query) return { "results": [ part.text for entry in response.memories for part in (entry.content.parts or []) if part.text ] } ``` ``` // Within a tool implementation async runAsync({ args, toolContext }: RunAsyncToolRequest) { const query = args['query'] as string; const response = await toolContext.searchMemory(query); // process response return { memories: response.memories.map(m => m.content.parts?.map(p => p.text).join(' ')).join('\n') }; } ``` ``` // memorySearchToolFunc is the implementation of the memory search tool. // This function demonstrates accessing memory via agent.Context. func memorySearchToolFunc(tctx agent.Context, args Args) (Result, error) { fmt.Printf("Tool: Searching memory for query: '%s'\n", args.Query) // The SearchMemory function is available on the context. searchResults, err := tctx.SearchMemory(context.Background(), args.Query) if err != nil { log.Printf("Error searching memory: %v", err) return Result{}, fmt.Errorf("failed memory search") } var results []string for _, res := range searchResults.Memories { if res.Content != nil { results = append(results, textParts(res.Content)...) } } return Result{Results: results}, nil } // Define a tool that can search memory. var memorySearchTool = must(functiontool.New( functiontool.Config{ Name: "search_past_conversations", Description: "Searches past conversations for relevant information.", }, memorySearchToolFunc, )) ``` ``` // Within a tool implementation public Single<ToolOutput> execute(ToolContext context) { String query = ...; // get query from arguments return context.searchMemory(query) .map(response -> { // process response return new ToolOutput(response.memories().toString()); }); } ``` ``` suspend fun searchWithinTool( context: ToolContext, args: Map<String, Any>, ): String { val query = args["query"] as String val response = context.invocationContext.memoryService?.searchMemory( appName = context.invocationContext.session.key.appName, userId = context.invocationContext.session.key.userId, query = query, ) // process response return response?.memories?.joinToString("\n") { it.content.parts.joinToString(" ") { p -> p.text ?: "" } } ?: "" } ``` ## 记忆库[¶](<https://adk.dev/sessions/memory/#memory-bank>) 那个... `VertexAiMemoryBankService` 将您的代理连接到 [记忆库](<https://cloud.google.com/vertex-ai/generative-ai/docs/agent-engine/memory-bank/overview>),一个完全管理好的Google Cloud服务,为对话代理提供精密,持续的内存能力. ### 如何运作[¶](<https://adk.dev/sessions/memory/#how-it-works>) 该服务处理两个关键操作: - **生成记忆 :** 谈话结束后,可以将会话活动送至记忆库,记忆库将信息作为"记忆"进行智能处理和存储. - **获取回忆 :** 您的代理代码可以针对记忆库发布搜索查询,以获取过去对话中的相关记忆. ### 直接内存摄入 `add_memory`[¶](<https://adk.dev/sessions/memory/#direct-memory-ingestion-with-add_memory>) 除了从会场历史中产生记忆之外, `VertexAiMemoryBankService` 也支持直接内存通过 `add_memory` 这种方法可以准确控制存储在记忆库中的事实。 如何运作取决于 `enable_consolidation` 选项 : - **直接创建( 默认 ) :** 默认, `add_memory` 呼唤基础 `memories.create` API. 每一个 `MemoryEntry` 您提供的是作为单独独立的内存项添加的。 ``` from google.adk.memory import VertexAiMemoryBankService from google.adk.memory.memory_entry import MemoryEntry from google.genai.types import Content, Part memory_service = VertexAiMemoryBankService(...) await memory_service.add_memory( app_name="my-app", user_id="user-123", memories=[ MemoryEntry(content=Content(parts=[Part(text="The user's favorite color is blue.")])) ] ) ``` - **合并创建 :** 如果你准备好了 `enable_consolidation` 改为: `True` 输入 `custom_metadata`,服务使用 `memories.generate` API. 此设置使得记忆库能够将新的内存项目与现有的相关记忆进行智能化整合,防止冗余,并建立一个更加一致的知识库. ``` await memory_service.add_memory( app_name="my-app", user_id="user-123", memories=[ MemoryEntry(content=Content(parts=[Part(text="The user's favorite color is light blue.")])) ], custom_metadata={"enable_consolidation": True} ) ``` ### 先决条件[¶](<https://adk.dev/sessions/memory/#prerequisites>) 在使用此特性之前, 您必须具备 : 1. **谷歌云计划:** 启用代理平台 API 。 2. **代理运行时间 :** 您需要在代理平台上创建代理运行时间 。 您不需要将您的代理运行时间部署到代理运行时间来使用内存库 。 此设置将为您提供 **代理运行时间 ID** 用于配置。 3. **认证 :** 确保您的本地环境被认证为访问 Google Cloud 服务。 最简单的方式是运行 : ``` gcloud auth application-default login ``` 4. **环境变量 :** 此服务需要您的 Google 云项目 ID 和位置 。 设置为环境变量 : ``` export GOOGLE_CLOUD_PROJECT="your-gcp-project-id" export GOOGLE_CLOUD_LOCATION="your-gcp-location" ``` 关于连接到Google Cloud的更多信息,请见ADK代理商 [连接到 Google 云和代理平台](<https://adk.dev/get-started/google-cloud/>). ### 配置[¶](<https://adk.dev/sessions/memory/#configuration>) 要把你的经纪人连接到记忆库,你就使用 `--memory_service_uri` 启动 ADK 服务器时的旗帜 (`adk web` 或 时 间 `adk api_server`。统一资源识别符(URI)必须采用格式。 `agentengine://<agent_engine_id>`. 狂欢吧 ``` adk web path/to/your/agents_dir --memory_service_uri="agentengine://1234567890" ``` 或者,您可以通过手动即时操作来配置您的代理以使用记忆库 `VertexAiMemoryBankService` 并传递给 `Runner`. PythonKotlin ``` from google import adk from google.adk.memory import VertexAiMemoryBankService memory_service = VertexAiMemoryBankService( project="PROJECT_ID", location="LOCATION", agent_engine_id="AGENT_ENGINE_ID" ) runner = adk.Runner( ... memory_service=memory_service ) ``` ``` /** Memory Bank keeps LLM-extracted memories in a Vertex AI Agent Engine. */ fun memoryBankRunner(agent: LlmAgent): InMemoryRunner { val memoryService = VertexAiMemoryBankService( project = "PROJECT_ID", location = "LOCATION", agentEngineId = "AGENT_ENGINE_ID", ) return InMemoryRunner( agent = agent, appName = "memory_bank_app", memoryService = memoryService, ) } ``` ## RAG 内存[¶](<https://adk.dev/sessions/memory/#rag-memory>) 那个... `VertexAiRagMemoryService` 将对话框存储在 [知识引擎](<https://cloud.google.com/vertex-ai/generative-ai/docs/rag-engine/rag-overview>) 并按矢量相似性检索它们。当您已经拥有 RAG 基础设施或想要原始的文本检索,而不是记忆库生成的 LLM 提取的记忆时使用它。需要代理平台 SDK 。 PythonKotlin ``` from google.adk.memory import VertexAiRagMemoryService memory_service = VertexAiRagMemoryService( rag_corpus="projects/PROJECT_ID/locations/LOCATION/ragCorpora/CORPUS_ID", similarity_top_k=5, vector_distance_threshold=0.6, ) ``` ``` /** * RAG memory stores whole transcripts in a Knowledge Engine corpus and retrieves them by vector * similarity. */ fun ragMemoryRunner(agent: LlmAgent): InMemoryRunner { val memoryService = VertexAiRagMemoryService( project = "PROJECT_ID", location = "LOCATION", // A bare corpus id, NOT a full resource name. Kotlin expands it to // projects/{project}/locations/{location}/ragCorpora/{id} and rejects an // already-expanded name -- unlike the Python tab above, which takes the full name. ragCorpus = "CORPUS_ID", similarityTopK = 5, vectorDistanceThreshold = 0.6, ) return InMemoryRunner( agent = agent, appName = "rag_memory_app", memoryService = memoryService, ) } ``` ## 在代理服务器中使用内存[¶](<https://adk.dev/sessions/memory/#use-memory-in-your-agent>) 当一个内存服务配置时,您的代理可以使用一个工具或召回来检索记忆. ADK包括两个预建工具,用于检索记忆: - **预装内存**:在每次转弯开始时自动检索内存,类似于回调. - **装入内存**:当你的经纪人决定会有所帮助时,收回记忆. **示例:** PythonTypeScriptGoJavaKotlin ``` from google.adk.agents import Agent from google.adk.tools import preload_memory agent = Agent( model=MODEL_ID, name='weather_sentiment_agent', instruction="...", tools=[preload_memory] ) ``` ``` import { LlmAgent, PRELOAD_MEMORY } from '@google/adk'; const agent = new LlmAgent({ model: MODEL_ID, name: 'weather_sentiment_agent', instruction: "...", tools: [PRELOAD_MEMORY] }); ``` ``` import ( "google.golang.org/adk/v2/agent/llmagent" "google.golang.org/adk/v2/tool" "google.golang.org/adk/v2/tool/preloadmemorytool" ) agent, _ := llmagent.New(llmagent.Config{ Model: model, Name: "weather_sentiment_agent", Instruction: "...", Tools: []tool.Tool{preloadmemorytool.New()}, }) ``` ``` import com.google.adk.agents.LlmAgent; import com.google.adk.tools.LoadMemoryTool; LlmAgent agent = new LlmAgent.Builder() .model(MODEL_ID) .name("weather_sentiment_agent") .instruction("...") .tools(new LoadMemoryTool()) .build(); ``` ``` fun preloadMemoryAgent(model: Gemini) { val agent = LlmAgent( model = model, name = "weather_sentiment_agent", instruction = Instruction("..."), tools = listOf(PreloadMemoryTool()), ) } ``` 为了从你的会话中提取记忆,你需要打电话 `add_session_to_memory`。例如,您可以通过回调自动实现此步骤 : PythonTypeScriptGoKotlin ``` from google.adk.agents import Agent from google.adk.tools import preload_memory async def auto_save_session_to_memory_callback(callback_context): await callback_context.add_session_to_memory() agent = Agent( model=MODEL, name="Generic_QA_Agent", instruction="Answer the user's questions", tools=[preload_memory], after_agent_callback=auto_save_session_to_memory_callback, ) ``` ``` import { LlmAgent, PRELOAD_MEMORY, SingleAgentCallback } from '@google/adk'; const autoSaveSessionToMemoryCallback: SingleAgentCallback = async (callbackContext) => { if (callbackContext.invocationContext.memoryService) { await callbackContext.invocationContext.memoryService.addSessionToMemory( callbackContext.invocationContext.session ); } }; const agent = new LlmAgent({ model: MODEL, name: "Generic_QA_Agent", instruction: "Answer the user's questions", tools: [PRELOAD_MEMORY], afterAgentCallback: autoSaveSessionToMemoryCallback, }); ``` 在 ADK Go 中,代理调用无法访问内存服务。从插件中保存会话 `AfterRunCallback` ,然后与内存服务一起对运行器上的插件进行注册: ``` import ( "log" "google.golang.org/adk/v2/agent" "google.golang.org/adk/v2/agent/llmagent" "google.golang.org/adk/v2/plugin" "google.golang.org/adk/v2/runner" "google.golang.org/adk/v2/tool" "google.golang.org/adk/v2/tool/loadmemorytool" ) autoSavePlugin, _ := plugin.New(plugin.Config{ Name: "auto_save_session_to_memory", AfterRunCallback: func(ctx agent.InvocationContext) { if m := ctx.Memory(); m != nil { if err := m.AddSessionToMemory(ctx, ctx.Session()); err != nil { log.Printf("failed to save session to memory: %v", err) } } }, }) rootAgent, _ := llmagent.New(llmagent.Config{ Model: model, Name: "Generic_QA_Agent", Instruction: "Answer the user's questions", Tools: []tool.Tool{loadmemorytool.New()}, }) r, _ := runner.New(runner.Config{ AppName: "my_app", Agent: rootAgent, SessionService: sessionService, MemoryService: memoryService, PluginConfig: runner.PluginConfig{ Plugins: []*plugin.Plugin{autoSavePlugin}, }, }) ``` ``` suspend fun autoSaveSessionToMemoryCallback( context: CallbackContext, ): CallbackChoice<Unit, Content> { context.addSessionToMemory() return CallbackChoice.Continue(Unit) } fun agentWithCallback(model: Gemini) { val agent = LlmAgent( model = model, name = "Generic_QA_Agent", instruction = Instruction("Answer the user's questions"), tools = listOf(PreloadMemoryTool()), afterAgentCallbacks = listOf(AfterAgentCallback(::autoSaveSessionToMemoryCallback)), ) } ``` ### 从召回中写入特定事件或事实[¶](<https://adk.dev/sessions/memory/#write-specific-events-or-facts-from-a-callback>) 在ADKKotlin v0.7.0中支持过 那个... `CallbackContext.addSessionToMemory` 方法是内存的默认行为,并保存您代理的全部会话。当您需要更精确的控制时, `CallbackContext` 还提供了另外两种方法: `addEventsToMemory`,用于选定事件的子集,以及 `addMemory`两者都接受任选 `customMetadata`,并同时从当前引用中填写应用程序、用户和会话。 ``` /** * Saves a chosen set of events rather than the whole session, tagged so they can * be filtered later. The events come from the caller: CallbackContext does not * expose the session. */ suspend fun saveEventsToMemory( context: CallbackContext, events: List<Event>, ) { // appName, userId and sessionId are taken from the invocation. Throws // IllegalStateException if the runner has no memory service configured. context.addEventsToMemory(events, customMetadata = mapOf("source" to "turn_callback")) } /** Writes an explicit fact, instead of letting the service derive one from events. */ suspend fun rememberPreferenceCallback(context: CallbackContext): CallbackChoice<Unit, Content> { val preference = MemoryEntry(content = Content.fromText(Role.USER, "Prefers window seats.")) context.addMemory(listOf(preference)) return CallbackChoice.Continue(Unit) } ``` 全部三个投出 `IllegalStateException` 如果运行者没有配置内存服务,那么它们会在运行时而不是编译时失败. ## 扩展内存能力[¶](<https://adk.dev/sessions/memory/#extend-memory-capabilities>) 内存服务从 `BaseMemoryService` 支持在代理内存中添加会话和活动,包括自定义元数据。使用 `add_session_to_memory` 财务报告和财务报告 `add_events_to_memory` 内存服务方法,例如: `InMemoryMemoryService` 修改内存数据,如下代码示例所示: ``` import asyncio from google.adk.memory import InMemoryMemoryService # Assume my_memory_service is an instance of InMemoryMemoryService # and my_latest_events is a list of new adk.Event objects from the latest turn. my_latest_events = [...] async def update_incremental_memory(my_memory_service, my_latest_events): # Example 1: Basic incremental update await my_memory_service.add_events_to_memory( app_name="my-app", user_id="my-user", events=my_latest_events, session_id="my-optional-session-id" ) # Example 2: Incremental update with Custom Metadata await my_memory_service.add_events_to_memory( app_name="my-app", user_id="my-user", events=my_latest_events, session_id="my-optional-session-id", custom_metadata={ "my_custom_key": "my_custom_value" } ) async def update_session_memory(my_memory_service, my_completed_session): # Example 3: Applying custom metadata to a full session await my_memory_service.add_session_to_memory( session=my_completed_session, custom_metadata={ "category": "user_preference" } ) ``` ## 高级概念[¶](<https://adk.dev/sessions/memory/#advanced-concepts>) ### 记忆在实践中如何发挥作用[¶](<https://adk.dev/sessions/memory/#how-memory-works-in-practice>) 内存工作流程包括以下步骤: 1. **会话交互 :** 用户通过一个 `Session`,由 a 管理 `SessionService`。在此互动过程中,将记录事件,并更新会话状态。 2. **摄入内存 :** 当会话结束或抓取重要信息时,您的应用程序会调用 `memory_service.add_session_to_memory(session)`。此动作可以提取关键数据并持续到您的长期知识库, 如代理运行时记忆库。 3. **后问曰:** 在不同的,或者在同一场次,你可能会问一个需要过去上下文的问题,例如,“我们上周讨论了项目X是什么?” 4. **代理使用内存工具 :** 配备内存检索工具的代理工具, 如内置工具 `load_memory` 工具,确认对过去上下文的需要。它使用工具,提供搜索查询(例如“上周讨论项目X”)。 5. **搜索执行 :** 工具内部调用 `memory_service.search_memory(app_name=..., user_id=..., query=...)`. 6. **返回结果 :** 那个... `MemoryService` 搜索其商店,使用关键词匹配或语义搜索,并返回匹配的片段为 `SearchMemoryResponse` 包含一个列表 `MemoryEntry` 对象,每个控件 `content`,并且所有可选 : `id`, `author`, `timestamp`,以及 `custom_metadata`. 7. **代理使用结果 :** 工具返回这些结果给代理商, 通常作为上下文或函数响应的一部分。 代理商然后可以使用此检索到的信息来向用户表达最后的答案 。 ### 一个特工能否获得一个以上的内存服务?[¶](<https://adk.dev/sessions/memory/#can-an-agent-have-access-to-more-than-one-memory-service>) - **通过标准配置:没有.** B. 框架`adk web`, `adk api_server`)被设计为每次通过 . `--memory_service_uri` 单人服务被连接到跑者身上 并暴露通过 `tool_context.search_memory()` 财务报告和财务报告 `callback_context.search_memory()`. - **在你的特工密码里 是的** 你可以即兴演奏一下 `BaseMemoryService` 并且从一个自定义工具中查阅,该工具已经有一个 `ToolContext` 用于框架配置服务。 例如,您的代理可以使用框架配置 `InMemoryMemoryService` 用于对话历史,并手动即时化 第二次服务,a `VertexAiMemoryBankService`, a `VertexAiRagMemoryService` 或任何其它文件的证明书 `BaseMemoryService` 执行,用于单独的知识库。 #### 示例:使用两个内存服务[¶](<https://adk.dev/sessions/memory/#example-use-two-memory-services>) PythonKotlin ``` from google.adk.agents import Agent from google.adk.memory import InMemoryMemoryService from google.adk.tools import ToolContext # Second memory service for docs lookup; could be any BaseMemoryService. docs_memory = InMemoryMemoryService() async def search_all_memory(query: str, tool_context: ToolContext) -> dict: """Search both the conversational memory and the docs corpus.""" conversational = await tool_context.search_memory(query) docs = await docs_memory.search_memory( app_name="docs", user_id="shared", query=query ) return { "from_conversations": [ part.text for entry in conversational.memories for part in (entry.content.parts or []) if part.text ], "from_docs": [ part.text for entry in docs.memories for part in (entry.content.parts or []) if part.text ], } agent = Agent( model="gemini-flash-latest", name="multi_memory_agent", instruction=( "Answer questions using both your conversation history and the " "docs knowledge base. Use the search_all_memory tool." ), tools=[search_all_memory], ) ``` ``` /** * Example of using two memory services in Kotlin. */ suspend fun searchAllMemory( toolContext: ToolContext, query: String, docsMemory: InMemoryMemoryService, ): Map<String, List<String>> { // Search the conversational memory (configured in the runner) val conversational = toolContext.invocationContext.memoryService?.searchMemory( appName = toolContext.invocationContext.session.key.appName, userId = toolContext.invocationContext.session.key.userId, query = query, ) // Search a separate docs knowledge base val docs = docsMemory.searchMemory( appName = "docs", userId = "shared", query = query, ) return mapOf( "from_conversations" to ( conversational?.memories?.map { it.content.parts.joinToString(" ") { p -> p.text ?: "" } } ?: emptyList() ), "from_docs" to docs.memories.map { it.content.parts.joinToString(" ") { p -> p.text ?: "" } }, ) } fun multiMemoryAgent(model: Gemini) { // docs_memory could be any MemoryService implementation val docsMemory = InMemoryMemoryService() val agent = LlmAgent( model = model, name = "multi_memory_agent", instruction = Instruction( "Answer questions using both your conversation history and the " + "docs knowledge base. Use the search_all_memory tool.", ), // In a real app, you'd wrap searchAllMemory in a @Tool annotated class // and pass docsMemory to its constructor. ) } ```

查看原始来源