记忆:长期存储的知识…… MemoryService¶
虽然…… Session )记录历史数据(的变更过程)。events)以及临时数据(state在单次对话中,代理可能需要从之前的交互中检索信息。这就是“记忆”(memory)概念发挥作用的地方。 长期知识(Long-Term Knowledge) 以及
MemoryService “开始发挥作用”(即某个因素或机制开始对某个过程或结果产生影响)。你可以这样理解:
Session/State: 这指的是你在某次特定聊天过程中的短期记忆(即你当时能够记住的信息)。- 长期知识(Long-Term Knowledge)
MemoryService)这是一个可搜索的档案库或知识库,代理可以从中查阅信息;这些信息可能来源于许多过去的聊天记录或其他来源。
The MemoryService 角色¶
The BaseMemoryService (或 Service 在 Go 语言中,该接口用于管理这个可搜索的、长期存储的知识库。它支持以下操作:
- “摄取信息”(Ingesting Information):指将数据或信息从外部来源(如文件、数据库、网络等)读取并存储到系统中的过程。这个过程通常包括数据的清洗、转换和验证等步骤,以确保数据的质量和准确性。
add_session_to_memory:接收一个已完成的任务/项目/结果等。Session该方法会将相关的信息添加到长期知识存储系统中。这种做法非常适合自动捕捉对话的精髓(即对话的核心内容)。add_events_to_memory:在不需要重新读取整个会话数据的情况下,追加一些事件信息(例如最新发生的事件)。当您希望在长时间运行的会话过程中中途将数据写入内存时,这种方法非常有用。add_memory:添加了显式的说明/内容。MemoryEntry这些对象直接被存储到内存中。这种方法提供了细粒度的控制能力,非常适合从其他来源注入特定的数据或信息。
- 搜索信息(Searching Information)
search_memory): 让我们让一个代理(通常是通过某种方式)来执行相应的操作。Tool根据搜索查询,查询知识库并检索相关的片段或上下文信息。
add_events_to_memory 和 add_memory 这些功能是可选的,并非所有服务都支持;因此在依赖它们之前,请务必确认您所选择的服务确实支持这些功能。
选择合适的内存服务¶
Python ADK 包含三个组件(或模块)。 MemoryService 请参考下表,以确定哪种解决方案最适合您的代理(agent)。
| 功能 | InMemoryMemoryService | VertexAiMemoryBankService | VertexAiRagMemoryService |
|---|---|---|---|
| 持久性(Persistence) | 没有数据丢失;系统重启后,所有数据都会被保留。 | 是的,由 Agent Platform 管理。 | 是的,这些数据被存储在 Knowledge Engine 中。 |
| 主要使用场景(Primary Use Case) | 原型设计、本地开发以及简单的测试。 | 从用户对话中构建有意义、且会不断发展的记忆(即:通过用户交流的内容,创造出具有价值且会随时间变化的“记忆”或信息)。 | 可以对整个对话语料库进行向量搜索(即利用向量算法进行检索),也可以将该搜索结果与其他使用 RAG(Retrieval with Aggregation)技术索引的内容一起进行展示。 |
| 内存数据提取(Memory Data Extraction) | 存储完整的对话内容 | 提取内容 有意义的信息 从对话中获取信息,并利用大型语言模型(LLM)的功能将这些信息与用户现有的记忆相结合。 | 存储完整的对话内容,并对其进行索引处理。 知识引擎(Knowledge Engine). |
| 搜索功能 | 基本的关键词匹配功能。 | 高级语义搜索功能。 | 在知识引擎(Knowledge Engine)上使用向量相似性算法进行搜索。 |
| 设置复杂性(Setup Complexity) | 无。这是默认设置。 | “Low”:需要特定的条件或资源才能实现。 Agent Runtime 该实例位于代理平台上(Instance on the Agent Platform)。 | **Medium. 需要(某些条件或资源)……** 知识引擎(Knowledge Engine). |
| 依赖项(Dependencies) | 无。 | Google Cloud 项目,Agent Platform API | Google Cloud 项目、Knowledge Engine 以及 Agent Platform SDK(可选安装)。 |
| 何时使用它 | 当你需要在多个会话的聊天记录中搜索相关信息以进行原型设计时。 | 当你希望你的代理能够记住过去的互动内容,并从中学习时。 | 当你已经拥有 RAG(Retrieval, Adaptation, and Generation)基础设施,或者希望获取大量的原始对话记录时,就可以使用这些工具来处理这些数据。 |
你随时都可以进行导入操作。 VertexAiRagMemoryService from google.adk.memory但是,构建这个系统会引发(一些问题或挑战)。 ImportError 除非已经安装了 Agent Platform SDK;否则…… pip install google-adk[gcp]内存银行(Memory Bank)以及基于 RAG(Random Access Group)技术的存储机制已在相关文档中进行了详细说明。 “Memory Bank”(内存银行) 和 RAG Memory 如下所示。
InMemoryMemoryService¶
The InMemoryMemoryService 该组件将会话信息存储在应用程序的内存中,并支持基本的关键词匹配功能(用于搜索)。它无需任何额外的配置,非常适合用于原型开发或简单的测试场景——在这些场景中,数据持久化并不是必需的。
示例:添加内存条并查询相关内存信息。
这个示例展示了使用该工具时的基本操作流程。 InMemoryMemoryService 为了简化代码结构。
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}")
}
}
}
}
在某个工具内搜索相关内存信息。¶
您还可以通过使用工具的上下文,在自定义工具内部搜索内存信息。
// 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,
))
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 ?: "" }
} ?: ""
}
“Memory Bank”(内存银行)¶
The VertexAiMemoryBankService 将您的代理连接到…… 内存银行这是一种完全由 Google Cloud 提供管理的服务,它为对话式应用程序(conversational agents)提供了先进且持久的内存管理功能。
它是如何工作的?¶
该服务主要处理两项关键操作:
- “生成记忆”(Generating Memories) 在对话结束时,你可以将会话中的所有事件发送到“记忆库”(Memory Bank)中。该系统会智能地处理这些信息,并将其存储为“记忆”(memories)。
- “回忆的追寻”: 您的代理代码可以向“记忆库”发送搜索请求,从而检索出过去对话中相关的信息(即“记忆”内容)。
直接从内存中读取数据(即不经过任何中间处理步骤) add_memory¶
除了根据会话历史记录生成回忆之外, VertexAiMemoryBankService
还支持通过直接内存读取(direct memory ingestion)的方式进行数据导入。 add_memory 这个方法让你能够精确地控制存储在“内存银行”(Memory Bank)中的数据。
其工作原理取决于…… enable_consolidation option:
-
**直接创建(默认方式):** 默认情况下,
add_memory“calls the underlying” 的意思是:该功能或程序会调用底层的(即更基础、更核心的)功能或程序来完成任务。memories.createAPI:每个(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.")])) ] ) -
“创建与整合”(Creation with Consolidation): 如果您设置了……
enable_consolidation给……;发送到……True在……里面;在……期间custom_metadata该服务使用了……memories.generate这个 API 设置允许“记忆库”(Memory Bank)智能地将新的记忆内容与现有的相关记忆内容进行整合,从而避免数据冗余,并构建一个更加连贯的知识体系。
先决条件¶
在使用此功能之前,您必须满足以下条件:
- 一个 Google Cloud 项目: 在启用了 Agent Platform API 的情况下……
- 代理运行时(Agent Runtime): 你需要在 Agent Platform 上创建一个 Agent Runtime。 使用 Memory Bank 时,无需将你的代理程序部署到该 Agent Runtime 中。 这样的设置将为你提供所需的功能。 代理运行时 ID(Agent Runtime ID) 这是配置过程中必需的元素。
-
身份验证: 请确保您的本地环境已通过身份验证,以便能够访问 Google Cloud 服务。最简单的方法是运行以下命令:
-
环境变量: 该服务需要您的 Google Cloud 项目 ID 和所在地区(Location)。请将这些信息设置为环境变量:
有关如何从 ADK 代理连接到 Google Cloud 的更多信息,请参阅…… 连接到 Google Cloud 和 Agent Platform.
配置¶
要将您的代理连接到 Memory Bank,您需要使用…… --memory_service_uri
在启动 ADK 服务器时设置相应的标志。)adk web 或者 adk api_server统一资源标识符(URI)必须采用以下格式:
agentengine://<agent_engine_id>.
或者,您也可以通过手动实例化相关类来配置您的代理程序,使其使用“Memory Bank”功能。 VertexAiMemoryBankService 然后将其传递给…… Runner.
/** 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内存(Random Access Group Memory,随机存取组内存)¶
The VertexAiRagMemoryService 将对话内容存储在……中。 知识引擎(Knowledge Engine)
该工具通过向量相似性来检索所需信息。当您已经拥有 RAG(Retrieval-Augmented Grammar)基础设施,或者希望直接获取原始文本转录内容(而非由 LLM 从“Memory Bank”中提取的记忆内容)时,可以使用该工具。使用该工具需要 Agent Platform SDK。
/**
* 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,
)
}
在你的代理程序中使用内存。¶
当内存服务被配置好后,您的代理可以使用相应的工具或回调函数来检索数据。ADK 提供了两个用于检索数据的预构建工具:
- 预加载内存:在每个回合开始时,系统会自动释放内存(类似于回调函数的功能)。
- 加载内存:当您的代理认为有必要时,会检索相关内存数据。
示例:
要从您的会话中提取记忆(即数据),您需要调用相应的函数或方法。 add_session_to_memory例如,您可以使用回调函数来自动化这个步骤:
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 中,代理回调(agent callbacks)无法访问内存服务。因此,需要从插件(Plugin)中保存会话数据(session data)。 AfterRunCallback 相反,应该将这个插件与内存服务一起注册到运行器(runner)上。
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)),
)
}
从回调函数中写入具体的事件或事实。¶
The CallbackContext.addSessionToMemory 该方法(method)是默认的行为方式,用于存储代理(agent)的所有会话数据(session data)。当你需要更精细的控制时……
CallbackContext 还提供了另外两种方法: addEventsToMemory对于所选的一组事件(即某个特定的事件子集),以及…… addMemory“对于事实,你需要自己去构建(即通过自己的努力来获取或理解这些事实)。”
两者都支持可选参数(即用户可以选择是否使用某些功能或输入某些信息)。 customMetadata这两个参数都会从当前的调用中获取应用程序(app)、用户(user)以及会话(session)的相关信息,并将这些信息填充到相应的字段中。
/**
* 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 如果运行程序(runner)没有配置任何内存管理服务(memory service),那么它们会在运行时失败,而不是在编译时失败。
扩展内存容量¶
内存服务得到了扩展(即功能得到了增强或范围得到了扩大)。 BaseMemoryService 支持将会话(sessions)和事件(events)添加到代理(agent)的内存中,包括自定义元数据(custom metadata)。请使用……
add_session_to_memory 和 add_events_to_memory 内存服务的相关方法
例如(methods of memory services, such as...) 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"
}
)
高级概念¶
内存在实际使用中的工作原理¶
内存处理的工作流程包括以下步骤:
- 会话交互(Session Interaction): 用户通过某种方式与代理进行交互。
Session由……管理SessionService在此交互过程中,系统会记录相关事件,并可能更新会话状态(session state)。 - 数据被加载到内存中: 当会话结束时,或者当会话捕获到重要信息时,您的应用程序会执行相应的操作(即调用相应的函数或方法)。
memory_service.add_session_to_memory(session)此操作会提取关键数据,并将其存储到您的长期知识存储系统中(例如代理的运行时内存库)。 - 后续查询(Later Query): 在不同的会话中,或者在同一个会话中,你可能会提出一个需要参考过去讨论内容的问题,例如:“上周我们关于项目 X 讨论了什么?”
- 代理程序使用内存检测工具: 一名配备了记忆检索工具的特工(例如内置的记忆检索功能)。
load_memory该工具需要了解用户之前的使用背景或相关信息。因此,用户需要再次使用该工具,并提供一个搜索查询(例如:“上周关于项目 X 的讨论”)。 - 搜索执行: 该工具在内部会进行相应的调用(即执行某些操作)。
memory_service.search_memory(app_name=..., user_id=..., query=...). - 返回的结果: The
MemoryService它会使用关键词在自身的数据库中搜索(无论是通过匹配搜索还是语义搜索),然后返回与关键词匹配的内容片段作为搜索结果。SearchMemoryResponse包含一个列表……MemoryEntry这些对象每个都包含(某些内容)。content所有这些内容都是可选的:id,author,timestamp,以及custom_metadata. - 代理使用这些结果: 该工具将这些结果返回给代理(agent),通常作为上下文信息或函数响应的一部分。代理随后可以利用这些获取到的信息来生成最终的用户回复。
一个代理(agent)是否可以同时访问多个内存服务(memory service)?¶
- 通过标准配置:否。 该框架(
adk web,adk api_server该产品设计为一次只能配置一个内存服务(即通过相应的配置接口或命令来配置一个内存服务)。--memory_service_uriflag。这个单独的服务被直接连接到 runner(运行系统)中,并通过该系统对外提供接口(即被公开使用)。tool_context.search_memory()和callback_context.search_memory(). - 在你的代理程序代码中:可以。 你可以创建第二个实例(即第二个对象)。
BaseMemoryService并且可以通过一个自定义工具来查询该信息;这个自定义工具本身就已经具备了相关功能(即可以直接用于查询数据)。ToolContext用于由框架配置的服务。
例如,您的代理可以使用该框架预先配置好的设置(即框架中已定义的参数或规则)。 InMemoryMemoryService
为了获取对话记录(conversation history),需要手动实例化第二个服务(a second service)。
VertexAiMemoryBankService, a VertexAiRagMemoryService 在文档语料库(docs corpus)中,或者
在任何其他数据源中。 BaseMemoryService 关于实现细节的内容,请参考另一个知识库。
示例:使用两个内存服务¶
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.
)
}