使用方法
要为智能体添加长期记忆,请创建一个存储实例并将其传递给create_agent:
- InMemoryStore
- PostgreSQL
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [],
store,
});
npm install @langchain/langgraph-checkpoint-postgres
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [],
store,
});
import { createAgent } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [],
store,
});
runtime.store 参数对存储进行读取和写入操作。示例请参见在工具中读取长期记忆和从工具写入长期记忆。
若要深入了解记忆类型(语义记忆、情景记忆、程序记忆)以及写入记忆的策略,请参阅记忆概念指南。
记忆存储
LangGraph 将长期记忆作为 JSON 文档存储在存储中。 每条记忆都通过自定义的namespace(类似文件夹)和唯一的 key(类似文件名)进行组织。命名空间通常包含用户或组织 ID 或其他标签,以便于组织信息。
这种结构支持记忆的层级化组织。同时,也支持通过内容过滤器进行跨命名空间搜索。
- InMemoryStore
- PostgreSQL
import { InMemoryStore } from "@langchain/langgraph";
const embed = (texts: string[]): number[][] => {
// Replace with an actual embedding function or LangChain embeddings object
return texts.map(() => [1.0, 2.0]);
};
// InMemoryStore saves data to an in-memory dictionary. Use a DB-backed store in production use.
const store = new InMemoryStore({ index: { embed, dims: 2 } });
const userId = "my-user";
const applicationContext = "chitchat";
const namespace = [userId, applicationContext];
await store.put(namespace, "a-memory", {
rules: [
"User likes short, direct language",
"User only speaks English & TypeScript",
],
"my-key": "my-value",
});
// get the "memory" by ID
const item = await store.get(namespace, "a-memory");
// search for "memories" within this namespace, filtering on content equivalence, sorted by vector similarity
const items = await store.search(namespace, {
filter: { "my-key": "my-value" },
query: "language preferences",
});
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const embed = (texts: string[]): number[][] => {
return texts.map(() => [1.0, 2.0]);
};
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI, {
index: { embed, dims: 2 },
});
await store.setup();
const userId = "my-user";
const applicationContext = "chitchat";
const namespace = [userId, applicationContext];
await store.put(namespace, "a-memory", {
rules: [
"User likes short, direct language",
"User only speaks English & TypeScript",
],
"my-key": "my-value",
});
const item = await store.get(namespace, "a-memory");
const items = await store.search(namespace, {
filter: { "my-key": "my-value" },
query: "language preferences",
});
在工具中读取长期记忆
- InMemoryStore
- PostgreSQL
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore将数据保存到内存字典中。在生产环境中请使用基于数据库的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// 使用put方法向存储写入示例数据
await store.put(
["users"], // 用于分组相关数据的命名空间(users命名空间用于用户数据)
"user_123", // 命名空间内的键(用户ID作为键)
{
name: "John Smith",
language: "English",
}, // 为给定用户存储的数据
);
const getUserInfo = tool(
// 查询用户信息。
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
// 访问存储 - 与提供给`createAgent`的是同一个存储
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 从存储中检索数据 - 返回带有value和metadata的StoreValue对象
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "Look up user info by userId from the store.",
schema: z.object({}),
},
);
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [getUserInfo],
contextSchema,
// 将存储传递给智能体 - 使智能体在运行工具时能够访问存储
store,
});
// 运行智能体
const result = await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
console.log(result.messages.at(-1)?.content);
/**
* 输出:
* 用户信息:
* - **姓名:** John Smith
* - **语言:** English
*/
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
import * as z from "zod";
import { createAgent, tool, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
await store.put(["users"], "user_123", {
name: "John Smith",
language: "English",
});
const getUserInfo = tool(
async (_, runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("userId is required");
const userInfo = await runtime.store.get(["users"], userId);
return userInfo?.value ? JSON.stringify(userInfo.value) : "Unknown user";
},
{
name: "getUserInfo",
description: "根据用户ID从存储中查找用户信息。",
schema: z.object({}),
},
);
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [getUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "look up user information" }] },
{ context: { userId: "user_123" } },
);
从工具写入长期记忆
- InMemoryStore
- PostgreSQL
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";
// InMemoryStore 将数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();
const contextSchema = z.object({
userId: z.string(),
});
// Schema 定义了供 LLM 使用的用户信息结构
const UserInfo = z.object({
name: z.string(),
});
// 允许代理更新用户信息的工具(适用于聊天应用)
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) {
throw new Error("userId is required");
}
// 将数据存储到存储中(命名空间、键、数据)
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{
name: "save_user_info",
description: "保存用户信息",
schema: UserInfo,
},
);
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [saveUserInfo],
contextSchema,
store,
});
// 运行代理
await agent.invoke(
{ messages: [{ role: "user", content: "My name is John Smith" }] },
// 通过上下文传递 userId 以标识正在更新谁的信息
{ context: { userId: "user_123" } },
);
// 你可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // 输出: { name: "John Smith" }
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "google-genai:gemini-3.6-flash",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "openai:gpt-5.5",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "anthropic:claude-sonnet-4-6",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "openrouter:openrouter:z-ai/glm-5.2",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "fireworks:accounts/fireworks/models/glm-5p2",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "baseten:zai-org/GLM-5.2",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
import * as z from "zod";
import { tool, createAgent, type ToolRuntime } from "langchain";
import { PostgresStore } from "@langchain/langgraph-checkpoint-postgres/store";
const DB_URI =
process.env.POSTGRES_URI ??
"postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable";
const store = PostgresStore.fromConnString(DB_URI);
await store.setup();
const contextSchema = z.object({ userId: z.string() });
const UserInfo = z.object({ name: z.string() });
const saveUserInfo = tool(
async (
userInfo: z.infer<typeof UserInfo>,
runtime: ToolRuntime<unknown, z.infer<typeof contextSchema>>,
) => {
const userId = runtime.context.userId;
if (!userId) throw new Error("需要提供 userId");
await runtime.store.put(["users"], userId, userInfo);
return "用户信息保存成功。";
},
{ name: "save_user_info", description: "保存用户信息", schema: UserInfo },
);
const agent = createAgent({
model: "ollama:north-mini-code-1.0",
tools: [saveUserInfo],
contextSchema,
store,
});
await agent.invoke(
{ messages: [{ role: "user", content: "我叫约翰·史密斯" }] },
{ context: { userId: "user_123" } },
);
const result = await store.get(["users"], "user_123");
console.log(result?.value);
Connect these docs to Claude, VSCode, and more via MCP for real-time answers.

