Skip to content

长期记忆让智能体能够跨不同的对话和会话存储并回忆信息。 与短期记忆不同——后者限定在单个线程范围内——长期记忆可以跨线程持久保存,并可随时回忆。

长期记忆构建在 LangGraph stores 之上,后者将数据保存为按命名空间和键组织的 JSON 文档。

用法 ​

要为智能体添加长期记忆,请创建一个 store 并将其传给 create_agent:

InMemoryStore ​

python
from langchain.agents import create_agent
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

agent: Runnable = create_agent(
    "claude-sonnet-4-6",
    tools=[],
    store=store,
)
ts
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,
});
ts
import { createAgent } from "langchain";
import { InMemoryStore } from "@langchain/langgraph";

// InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
const store = new InMemoryStore();

const agent = createAgent({
  model: "openai:gpt-5.5",
  tools: [],
  store,
});
ts
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,
});
ts
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,
});
ts
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,
});
ts
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,
});
ts
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,
});

PostgreSQL ​

bash
pip install langgraph-checkpoint-postgres
python
from langchain.agents import create_agent
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore  # type: ignore[import-not-found]

DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"

with PostgresStore.from_conn_string(DB_URI) as store:
    store.setup()
    agent: Runnable = create_agent(
        "claude-sonnet-4-6",
        tools=[],
        store=store,
    )
bash
npm install @langchain/langgraph-checkpoint-postgres
ts
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,
});
ts
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,
});
ts
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,
});
ts
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,
});
ts
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,
});
ts
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,
});
ts
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 参数对 store 进行读写。有关示例,请参阅在工具中读取长期记忆和从工具写入长期记忆。

TIP

如需深入了解记忆类型(语义、情景、程序性)以及写入记忆的策略,请参阅记忆概念指南。

记忆存储 ​

LangGraph 将长期记忆作为 JSON 文档存储在 store 中。

每条记忆都组织在自定义的 namespace(类似于文件夹)和唯一的 key(类似于文件名)之下。命名空间通常包含用户或组织 ID 或其他标签,以便更容易地组织信息。

这种结构支持记忆的分层组织。跨命名空间搜索随后可以通过内容过滤器实现。

InMemoryStore ​

python
from collections.abc import Sequence

from langgraph.store.base import IndexConfig
from langgraph.store.memory import InMemoryStore

def embed(texts: Sequence[str]) -> list[list[float]]:
    # 替换为实际的嵌入函数或 LangChain 嵌入对象
    return [[1.0, 2.0] for _ in texts]

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore(index=IndexConfig(embed=embed, dims=2))
user_id = "my-user"
application_context = "chitchat"
namespace = (user_id, application_context)
store.put(
    namespace,
    "a-memory",
    {
        "rules": [
            "User likes short, direct language",
            "User only speaks English & python",
        ],
        "my-key": "my-value",
    },
)
# 按 ID 获取“记忆”
item = store.get(namespace, "a-memory")
# 在此命名空间内搜索“记忆”,按内容等价过滤,并按向量相似度排序
items = store.search(
    namespace, filter={"my-key": "my-value"}, query="language preferences"
)
ts
import { InMemoryStore } from "@langchain/langgraph";

const embed = (texts: string[]): number[][] => {
  // 替换为实际的嵌入函数或 LangChain 嵌入对象
  return texts.map(() => [1.0, 2.0]);
};

// InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
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",
});

// 按 ID 获取“记忆”
const item = await store.get(namespace, "a-memory");

// 在此命名空间内搜索“记忆”,按内容等价过滤,并按向量相似度排序
const items = await store.search(namespace, {
  filter: { "my-key": "my-value" },
  query: "language preferences",
});

PostgreSQL ​

python
from collections.abc import Sequence

from langgraph.store.base import IndexConfig
from langgraph.store.postgres import PostgresStore  # type: ignore[import-not-found]

def embed(texts: Sequence[str]) -> list[list[float]]:
    # 替换为实际的嵌入函数或 LangChain 嵌入对象
    return [[1.0, 2.0] for _ in texts]

DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"

with PostgresStore.from_conn_string(
    DB_URI,
    index=IndexConfig(embed=embed, dims=2),  # type: ignore[arg-type]
) as store:
    store.setup()
    user_id = "my-user"
    application_context = "chitchat"
    namespace = (user_id, application_context)
    store.put(
        namespace,
        "a-memory",
        {
            "rules": [
                "User likes short, direct language",
                "User only speaks English & python",
            ],
            "my-key": "my-value",
        },
    )
    item = store.get(namespace, "a-memory")
    items = store.search(
        namespace, filter={"my-key": "my-value"}, query="language preferences"
    )
ts
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",
});

有关记忆 store 的更多信息,请参阅持久化指南。

在工具中读取长期记忆 ​

InMemoryStore ​

python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="google_genai:gemini-3.6-flash",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="openai:gpt-5.5",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="openrouter:z-ai/glm-5.2",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="fireworks:accounts/fireworks/models/glm-5p2",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="baseten:zai-org/GLM-5.2",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore

@dataclass
class Context:
    user_id: str

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

# 使用 put 方法将示例数据写入存储
store.put(
    (
        "users",
    ),  # 对相关数据进行分组的命名空间(用户数据的 users 命名空间)
    "user_123",  # 命名空间内的键(以用户 ID 作为键)
    {
        "name": "John Smith",
        "language": "English",
    },  # 存储给指定用户的数据
)

@tool
def get_user_info(runtime: ToolRuntime[Context]) -> str:
    """Look up user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    user_id = runtime.context.user_id
    # 从存储中检索数据 - 返回包含 value 和 metadata 的 StoreValue 对象
    user_info = runtime.store.get(("users",), user_id)
    return str(user_info.value) if user_info else "Unknown user"

agent: Runnable = create_agent(
    model="ollama:north-mini-code-1.0",
    tools=[get_user_info],
    # 将存储传给智能体 - 使智能体在运行工具时能访问存储
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "look up user information"}]},
    context=Context(user_id="user_123"),
)
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */
ts
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);

/**
 * Outputs:
 * User Information:
 * - **Name:** John Smith
 * - **Language:** English
 */

PostgreSQL ​

python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore  # type: ignore[import-not-found]

@dataclass
class Context:
    user_id: str

DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"

with PostgresStore.from_conn_string(DB_URI) as store:
    store.setup()
    store.put(("users",), "user_123", {"name": "John Smith", "language": "English"})

    @tool
    def get_user_info(runtime: ToolRuntime[Context]) -> str:
        """Look up user info."""
        assert runtime.store is not None
        user_info = runtime.store.get(("users",), runtime.context.user_id)
        return str(user_info.value) if user_info else "Unknown user"

    agent: Runnable = create_agent(
        "claude-sonnet-4-6",
        tools=[get_user_info],
        store=store,
        context_schema=Context,
    )

    result = agent.invoke(
        {"messages": [{"role": "user", "content": "look up user information"}]},
        context=Context(user_id="user_123"),
    )
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);
ts
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: "Look up user info by userId from the store.",
    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" } },
);
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);
ts
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: "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,
});

await agent.invoke(
  { messages: [{ role: "user", content: "look up user information" }] },
  { context: { userId: "user_123" } },
);

从工具写入长期记忆 ​

InMemoryStore ​

python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="google_genai:gemini-3.6-flash",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="openai:gpt-5.5",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="anthropic:claude-sonnet-4-6",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="openrouter:z-ai/glm-5.2",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="fireworks:accounts/fireworks/models/glm-5p2",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="baseten:zai-org/GLM-5.2",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.memory import InMemoryStore
from typing_extensions import TypedDict

# InMemoryStore 把数据保存在内存字典中。生产环境请使用数据库支持的存储。
store = InMemoryStore()

@dataclass
class Context:
    user_id: str

# TypedDict 定义给 LLM 使用的用户信息结构
class UserInfo(TypedDict):
    name: str

# 允许智能体更新用户信息的工具(对聊天应用很有用)
@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    # 访问存储 - 与传给 `create_agent` 的相同
    assert runtime.store is not None
    store = runtime.store
    user_id = runtime.context.user_id
    # 在存储中保存数据(命名空间、键、数据)
    store.put(("users",), user_id, dict(user_info))
    return "Successfully saved user info."

agent: Runnable = create_agent(
    model="ollama:north-mini-code-1.0",
    tools=[save_user_info],
    store=store,
    context_schema=Context,
)

# 运行智能体
agent.invoke(
    {"messages": [{"role": "user", "content": "My name is John Smith"}]},
    # 通过 context 传入 user_id,用于标识正在更新哪位用户的信息
    context=Context(user_id="user_123"),
)

# 你也可以直接访问存储来获取值
item = store.get(("users",), "user_123")
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }
ts
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 "Successfully saved user info.";
  },
  {
    name: "save_user_info",
    description: "Save user info",
    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" }] },
  // 通过 context 传入 userId,用于标识正在更新哪位用户的信息
  { context: { userId: "user_123" } },
);

// 你也可以直接访问存储来获取值
const result = await store.get(["users"], "user_123");
console.log(result?.value); // Output: { name: "John Smith" }

PostgreSQL ​

python
from dataclasses import dataclass

from langchain.agents import create_agent
from langchain.tools import ToolRuntime, tool
from langchain_core.runnables import Runnable
from langgraph.store.postgres import PostgresStore  # type: ignore[import-not-found]
from typing_extensions import TypedDict

@dataclass
class Context:
    user_id: str

class UserInfo(TypedDict):
    name: str

@tool
def save_user_info(user_info: UserInfo, runtime: ToolRuntime[Context]) -> str:
    """Save user info."""
    assert runtime.store is not None
    runtime.store.put(("users",), runtime.context.user_id, dict(user_info))
    return "Successfully saved user info."

DB_URI = "postgresql://postgres:postgres@localhost:5432/postgres?sslmode=disable"

with PostgresStore.from_conn_string(DB_URI) as store:
    store.setup()
    agent: Runnable = create_agent(
        "claude-sonnet-4-6",
        tools=[save_user_info],
        store=store,
        context_schema=Context,
    )

    agent.invoke(
        {"messages": [{"role": "user", "content": "My name is John Smith"}]},
        context=Context(user_id="user_123"),
    )
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);
ts
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 is required");
    await runtime.store.put(["users"], userId, userInfo);
    return "Successfully saved user info.";
  },
  { name: "save_user_info", description: "Save user info", 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" }] },
  { context: { userId: "user_123" } },
);

const result = await store.get(["users"], "user_123");
console.log(result?.value);