为 Agent 添加 Agent Memory,以便其可以跨对话召回持久上下文。
本指南使用 Agents SDK 将 memory recall 公开为模型可调用的工具。如果你使用其他 Agent 框架,也可以采用相同模式:使用 ingest() 或 remember() 存储 memory,通过 Agent 的某个工具公开 recall(),并在 system prompt 中告知模型何时搜索 memory。
- 注册 Cloudflare 账户 ↗。
- 安装
Node.js↗。
您还需要获得 Agent Memory 的使用权限。
当模型需要相关内存来回答或行动时,使用 recall()。当您拥有对话消息,并希望 Agent Memory 自动提取持久内存时,使用 ingest()。当您的 Agent 已经知道要存储的确切内存时,使用 remember()。
不要在每次模型轮次后都调用 ingest()。相反,应在用户处于空闲状态、对话被压缩时,或在其他自然的检查点进行批量摄取。
创建一个 Worker 项目:
npm create cloudflare@latest -- memory-agentyarn create cloudflare memory-agentpnpm create cloudflare@latest memory-agent设置时,选择以下选项:
- 对于 What would you like to start with?(希望从什么开始?),选择
Hello World example。 - 对于 Which template would you like to use?(希望使用哪个模板?),选择
Worker only。 - 对于 Which language do you want to use?(希望使用哪种语言?),选择
TypeScript。 - 对于 Do you want to use git for version control?(是否使用 Git 进行版本控制?),选择
Yes。 - 对于 Do you want to add an AGENTS.md file to help AI coding tools understand Cloudflare APIs?(是否添加 AGENTS.md 文件以帮助 AI 编程工具理解 Cloudflare API?),选择
Yes。 - 对于 Do you want to deploy your application?(是否部署应用?),选择
No(部署前还需要进行一些修改)。
进入项目目录:
cd memory-agent安装本指南中使用的依赖:
npm i agents ai @ai-sdk/provider zodyarn add agents ai @ai-sdk/provider zodpnpm add agents ai @ai-sdk/provider zodbun add agents ai @ai-sdk/provider zod命名空间 (Namespace) 限制了您的应用程序的内存配置文件的范围。使用 Wrangler 创建一个:
npx wrangler agent-memory namespace create my-agentyarn wrangler agent-memory namespace create my-agentpnpm wrangler agent-memory namespace create my-agent您将在 Worker 绑定中使用该命名空间名称 my-agent。
在 Wrangler 配置中添加 agent_memory 绑定(binding),并注册 Agent 的 Durable Object。
{
"$schema": "./node_modules/wrangler/config-schema.json",
"name": "memory-agent",
"main": "src/server.ts",
"upload_source_maps": true,
// Set this to today's date
"compatibility_date": "2026-11-14",
"compatibility_flags": [
"nodejs_compat"
],
"ai": {
"binding": "AI"
},
"agent_memory": [
{
"binding": "MEMORY",
"namespace": "my-agent"
}
],
"durable_objects": {
"bindings": [
{
"name": "ChatAgent",
"class_name": "ChatAgent"
}
]
},
"migrations": [
{
"tag": "v1",
"new_sqlite_classes": [
"ChatAgent"
]
}
]
}name = "memory-agent"
main = "src/server.ts"
upload_source_maps = true
# Set this to today's date
compatibility_date = "2026-11-14"
compatibility_flags = ["nodejs_compat"]
[ai]
binding = "AI"
[[agent_memory]]
binding = "MEMORY"
namespace = "my-agent"
[[durable_objects.bindings]]
name = "ChatAgent"
class_name = "ChatAgent"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["ChatAgent"]为您绑定的服务生成本地 TypeScript 类型:
npx wrangler typesyarn wrangler typespnpm wrangler types不能仅因为您的应用程序拥有内存绑定,模型就能使用内存。您需要通过一个工具公开召回功能,并指导模型何时调用它。
本指南使用 Agents SDK 的 Lifecycle 在 Durable Object 上构建 Agent。Sessions 功能用于存储对话。agents/sessions 仍处于实验阶段,其 API 可能会在不同版本之间发生变化。
创建 src/server.ts。该文件定义 system prompt,以及一个调用 recall() 的 search_memory 工具:
import { DurableObject } from "cloudflare:workers";
import { tool } from "ai";
import { z } from "zod";
import { Lifecycle } from "agents/lifecycle";
import { routeAgentRequest } from "agents/routing";
import { Sessions } from "agents/sessions";
const SYSTEM_PROMPT = `You are a helpful assistant.
Long-term memory is available through the search_memory tool.
MEMORY POLICY
- Search memory with search_memory when the user asks what you know or remember about them.
- Search memory when the request depends on prior sessions, preferences, project state, conventions, decisions, or long-running tasks.
- Phrase memory searches as concise topics, not questions.
- Do not search memory to repeat something the user just said in the current conversation.
- When search_memory returns results, always incorporate them into your response. The results are real memories from previous conversations.
- Treat recalled memories as helpful context, not guaranteed truth. If a memory is important for an irreversible action, confirm with the user.`;
const MEMORY_PROFILE_NAME = "demo-user";
export class ChatAgent extends DurableObject {
sessions = new Sessions();
lifecycle = Lifecycle.install(this).use(this.sessions);
session = this.sessions.session();
memoryTools() {
return {
search_memory: tool({
description:
"Search durable memory: facts, events, instructions, and tasks from prior conversations.",
inputSchema: z.object({
query: z.string().describe("A concise topic to search for"),
}),
execute: async ({ query }) => {
const profile = await this.env.MEMORY.getProfile(MEMORY_PROFILE_NAME);
const { answer } = await profile.recall(query, {
responseLength: "short",
});
return answer || "No relevant memories found.";
},
}),
};
}
}
export default {
async fetch(request, env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};import { DurableObject } from "cloudflare:workers";
import { tool } from "ai";
import { z } from "zod";
import { Lifecycle } from "agents/lifecycle";
import { routeAgentRequest } from "agents/routing";
import { Sessions } from "agents/sessions";
const SYSTEM_PROMPT = `You are a helpful assistant.
Long-term memory is available through the search_memory tool.
MEMORY POLICY
- Search memory with search_memory when the user asks what you know or remember about them.
- Search memory when the request depends on prior sessions, preferences, project state, conventions, decisions, or long-running tasks.
- Phrase memory searches as concise topics, not questions.
- Do not search memory to repeat something the user just said in the current conversation.
- When search_memory returns results, always incorporate them into your response. The results are real memories from previous conversations.
- Treat recalled memories as helpful context, not guaranteed truth. If a memory is important for an irreversible action, confirm with the user.`;
const MEMORY_PROFILE_NAME = "demo-user";
export class ChatAgent extends DurableObject<Env> {
readonly sessions = new Sessions();
readonly lifecycle = Lifecycle.install(this).use(this.sessions);
readonly session = this.sessions.session();
memoryTools() {
return {
search_memory: tool({
description:
"Search durable memory: facts, events, instructions, and tasks from prior conversations.",
inputSchema: z.object({
query: z.string().describe("A concise topic to search for"),
}),
execute: async ({ query }) => {
const profile = await this.env.MEMORY.getProfile(MEMORY_PROFILE_NAME);
const { answer } = await profile.recall(query, {
responseLength: "short",
});
return answer || "No relevant memories found.";
},
}),
};
}
}
export default {
async fetch(request: Request, env: Env) {
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;System prompt 与工具同样重要。它会告知模型何时调用 search_memory、何时不应调用,以及如何处理召回的 memory。每一轮使用的 prompt 都相同,因此模型提供商可以将其保留在 prompt cache 中。
接下来,为 Agent 添加持久保存 memory 的方式。在 chat Agent 中,通常先将对话存储到 session,然后在用户进入空闲状态后调用 ingest()。Scheduler 功能会在稍后运行 ingest,即使 Durable Object 在此期间被逐出也不受影响。
替换 src/server.ts 顶部的 import:
import { DurableObject } from "cloudflare:workers";
import { convertToModelMessages, generateText, stepCountIs, tool } from "ai";
import { z } from "zod";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/ai-sdk";
import { routeAgentRequest } from "agents/routing";
import { Scheduler } from "agents/schedules";
import { Sessions } from "agents/sessions";import { DurableObject } from "cloudflare:workers";
import {
convertToModelMessages,
generateText,
stepCountIs,
tool,
type UIMessage,
} from "ai";
import { z } from "zod";
import { Lifecycle } from "agents/lifecycle";
import { createAI } from "agents/models/ai-sdk";
import { routeAgentRequest } from "agents/routing";
import { Scheduler } from "agents/schedules";
import { Sessions } from "agents/sessions";在文件顶部靠近 import 的位置添加 ingest 延迟:
const MEMORY_INGEST_DELAY_SECONDS = 10;const MEMORY_INGEST_DELAY_SECONDS = 10;然后按以下结构更新 ChatAgent。注释标出了保留第 4 步中 memoryTools() 的位置。
export class ChatAgent extends DurableObject {
sessions = new Sessions();
scheduler = new Scheduler({
callbacks: {
ingestMemory: () => this.runIngest(),
},
});
lifecycle = Lifecycle.install(this).use(this.sessions).use(this.scheduler);
session = this.sessions.session();
// Keep `memoryTools()` from step 4 here.
async chat(message) {
// RPC calls do not start the Lifecycle on their own.
await this.lifecycle.start();
await this.session.appendMessage({
id: `user-${crypto.randomUUID()}`,
role: "user",
parts: [{ type: "text", text: message }],
});
await this.scheduleIngest();
const ai = createAI({ binding: this.env.AI });
const result = await generateText({
model: ai("@cf/zai-org/glm-5.3-flash"),
system: SYSTEM_PROMPT,
messages: await convertToModelMessages(await this.session.getHistory()),
tools: this.memoryTools(),
stopWhen: stepCountIs(5),
});
await this.session.appendMessage({
id: `assistant-${crypto.randomUUID()}`,
role: "assistant",
parts: [{ type: "text", text: result.text }],
});
return result.text;
}
async scheduleIngest() {
// Replace any pending ingest, so it runs once the user goes idle.
for (const schedule of await this.scheduler.list()) {
if (schedule.callback === "ingestMemory") {
await this.scheduler.cancel(schedule.id);
}
}
await this.scheduler.set(MEMORY_INGEST_DELAY_SECONDS, "ingestMemory");
}
async runIngest() {
const cursor = (await this.ctx.storage.get("ingestCursor")) ?? 0;
const history = await this.session.getHistory();
const messages = history
.slice(cursor)
.filter(
(message) => message.role === "user" || message.role === "assistant",
)
.map((message) => ({
role: message.role,
content: message.parts
.map((part) =>
part.type === "text" && typeof part.text === "string"
? part.text
: "",
)
.filter(Boolean)
.join("\n\n"),
}))
.filter((message) => message.content);
if (messages.length > 0) {
const profile = await this.env.MEMORY.getProfile(MEMORY_PROFILE_NAME);
await profile.ingest(messages, { sessionId: this.lifecycle.name });
}
await this.ctx.storage.put("ingestCursor", history.length);
return { ingested: messages.length };
}
}export class ChatAgent extends DurableObject<Env> {
readonly sessions = new Sessions();
readonly scheduler = new Scheduler({
callbacks: {
ingestMemory: () => this.runIngest(),
},
});
readonly lifecycle = Lifecycle.install(this)
.use(this.sessions)
.use(this.scheduler);
readonly session = this.sessions.session();
// Keep `memoryTools()` from step 4 here.
async chat(message: string): Promise<string> {
// RPC calls do not start the Lifecycle on their own.
await this.lifecycle.start();
await this.session.appendMessage({
id: `user-${crypto.randomUUID()}`,
role: "user",
parts: [{ type: "text", text: message }],
});
await this.scheduleIngest();
const ai = createAI({ binding: this.env.AI });
const result = await generateText({
model: ai("@cf/zai-org/glm-5.3-flash"),
system: SYSTEM_PROMPT,
messages: await convertToModelMessages(
(await this.session.getHistory()) as UIMessage[],
),
tools: this.memoryTools(),
stopWhen: stepCountIs(5),
});
await this.session.appendMessage({
id: `assistant-${crypto.randomUUID()}`,
role: "assistant",
parts: [{ type: "text", text: result.text }],
});
return result.text;
}
private async scheduleIngest() {
// Replace any pending ingest, so it runs once the user goes idle.
for (const schedule of await this.scheduler.list()) {
if (schedule.callback === "ingestMemory") {
await this.scheduler.cancel(schedule.id);
}
}
await this.scheduler.set(MEMORY_INGEST_DELAY_SECONDS, "ingestMemory");
}
private async runIngest(): Promise<{ ingested: number }> {
const cursor = (await this.ctx.storage.get<number>("ingestCursor")) ?? 0;
const history = await this.session.getHistory();
const messages = history
.slice(cursor)
.filter(
(message) => message.role === "user" || message.role === "assistant",
)
.map((message) => ({
role: message.role as "user" | "assistant",
content: message.parts
.map((part) =>
part.type === "text" && typeof part.text === "string"
? part.text
: "",
)
.filter(Boolean)
.join("\n\n"),
}))
.filter((message) => message.content);
if (messages.length > 0) {
const profile = await this.env.MEMORY.getProfile(MEMORY_PROFILE_NAME);
await profile.ingest(messages, { sessionId: this.lifecycle.name });
}
await this.ctx.storage.put("ingestCursor", history.length);
return { ingested: messages.length };
}
}将默认 export 替换为一个小型测试 endpoint。每个 conversationId 都映射到一个单独的 Durable Object,并拥有自己的 session 历史记录。Worker 通过 RPC 调用 chat():
export default {
async fetch(request, env) {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/chat") {
const { message, conversationId = "default" } = await request.json();
if (!message) {
return Response.json({ error: "Missing message" }, { status: 400 });
}
const agent = env.ChatAgent.getByName(conversationId);
const response = await agent.chat(message);
return Response.json({ response });
}
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
};export default {
async fetch(request: Request, env: Env) {
const url = new URL(request.url);
if (request.method === "POST" && url.pathname === "/chat") {
const { message, conversationId = "default" } =
(await request.json()) as {
message?: string;
conversationId?: string;
};
if (!message) {
return Response.json({ error: "Missing message" }, { status: 400 });
}
const agent = env.ChatAgent.getByName(conversationId);
const response = await agent.chat(message);
return Response.json({ response });
}
return (
(await routeAgentRequest(request, env)) ??
new Response("Not found", { status: 404 })
);
},
} satisfies ExportedHandler<Env>;摄取路径是 scheduleIngest() 和 runIngest()。每个用户消息都会取消上一个挂起的摄取并安排一个新的摄取,因此 Agent Memory 会在用户进入空闲状态后处理对话,而不是在每个 Agent 轮次后都进行处理。
runIngest() 会在 Durable Object 的存储中保留 cursor,因此每个批次只包含尚未 ingest 的消息。sessionId 会在共享的 memory profile 中按对话对 memory 进行分组。
本演示在多个对话中跨用了一个 Agent Memory 配置文件 demo-user。在生产环境中,请选择与您的应用范围(如用户、团队、租户或组织)相匹配的配置文件名称。
你也可以在 session 压缩时运行 ingest 逻辑。关键限制是应在自然检查点分批 ingest,而不是在 Agent 每一轮结束后执行。在生产环境中,请选择与应用用户体验相匹配的 ingest 延迟。
对大多数应用而言,自动摄取已足够。如果您希望模型立即存储特定内存,请添加一个服务器端工具,其执行函数会调用 remember()。
当 Agent 已经知道要存储的准确内存时,可以使用此方法。例如,在用户说“记住我更喜欢简洁的答案”后,模型可能会调用 rememberMemory 工具。
如果模型能够调用内存写入工具,请添加系统提示词指令,定义什么值得被记住以及何时请求确认。对于许多 Agent 而言,自动对话摄取比直接给模型一个写入内存的工具更简单、更安全。
启动本地开发服务:
npx wrangler devyarn wrangler devpnpm wrangler dev向第一个对话发送请求,让其记住一个持久的偏好:
curl -X POST "http://localhost:8787/chat" \
-H "Content-Type: application/json" \
-d '{"conversationId":"first-chat","message":"I prefer TypeScript examples and concise answers."}'在发送下一个请求之前,请等待至少 30 秒。代码安排在用户闲置 10 秒后运行摄取,随后 Agent Memory 需要额外的时间来提取、分类并索引这些内存,之后这些内容才可供召回。
在另一个对话中提出一个依赖持久 memory 的问题。此请求使用不同的 session 历史记录,但使用相同的 Agent Memory profile。
curl -X POST "http://localhost:8787/chat" \
-H "Content-Type: application/json" \
-d '{"conversationId":"second-chat","message":"What do you know or remember about me and my preferences?"}'模型应调用 search_memory,接收 Agent Memory 召回的 memory,并在响应中使用该上下文。第二个对话与第一个对话不共享 session 历史记录,因此它对用户偏好的任何了解都来自 Agent Memory。