跳到内容

如何配置动态命名空间

Langmem 提供了一些实用工具,用于管理 LangGraph 的长期记忆存储中的记忆。这些有状态组件在“命名空间”内组织记忆,以便您可以按用户、代理或其他值隔离数据。命名空间可以包含模板变量,这些变量将在运行时从可配置值填充。下面是一个快速示例

API:create_react_agent | create_manage_memory_tool | create_search_memory_tool

from langgraph.store.memory import InMemoryStore
from langgraph.prebuilt import create_react_agent
from langmem import create_manage_memory_tool, create_search_memory_tool

# Create tool with {user_id} template
tool = create_manage_memory_tool(namespace=("memories", "{user_id}"))
# Agent just sees that it has memory. It doesn't know where it's stored.
app = create_react_agent("anthropic:claude-3-5-sonnet-latest", tools=[tool])
# Use with different users
app.invoke(
    {"messages": [{"role": "user", "content": "I like dolphins"}]},
    config={"configurable": {"user_id": "user-123"}}
)  # Stores in ("memories", "user-123")

命名空间模板可用于 LangMem 的任何有状态组件中,例如 create_memory_store_managercreate_manage_memory_tool。下面是一个简单的示例

常见模式

按用户、组织或功能组织记忆

# Organization-level
tool = create_manage_memory_tool(
    namespace=("memories", "{org_id}")
)
app = create_react_agent("anthropic:claude-3-5-sonnet-latest", tools=[tool])
app.invoke(
    {"messages": [{"role": "user", "content": "I'm questioning the new company health plan.."}]},
    config={"configurable": {"org_id": "acme"}}
)

# User within organization
tool = create_manage_memory_tool(
    namespace=("memories", "{org_id}", "{user_id}")
)
# If you wanted to, you could let the agent
# search over all users within an organization
tool = create_search_memory_tool(
    namespace=("memories", "{org_id}")
)
app = create_react_agent("anthropic:claude-3-5-sonnet-latest", tools=[tool])
app.invoke(
    {"messages": [{"role": "user", "content": "What's our policy on dogs at work?"}]},
    config={"configurable": {"org_id": "acme", "user_id": "alice"}}
)

# You could also organize memories by type or category if you prefer 
tool = create_manage_memory_tool(
    namespace=("agent_smith", "memories", "{user_id}", "preferences")
)
app = create_react_agent("anthropic:claude-3-5-sonnet-latest", tools=[tool])
app.invoke(
    {"messages": [{"role": "user", "content": "I like dolphins"}]},
    config={"configurable": {"user_id": "alice"}}
)
模板变量

模板变量(例如 {user_id})必须存在于您的运行时配置的 configurable 字典中。如果它们不

评论