跳到内容

LangMem

LangMem 帮助智能体从其随时间推移的交互中学习和适应。

它提供了从对话中提取重要信息、通过提示词优化来改进智能体行为以及维护长期记忆的工具。

它既提供了可与任何存储系统一起使用的函数式原语,也提供了与 LangGraph 存储层的原生集成。

这能让您的智能体不断改进,个性化其响应,并在不同会话间保持一致的行为。

主要特性

  • 🧩 核心记忆 API,可与任何存储系统配合使用
  • 🧠 记忆管理工具,智能体可以在活跃对话的“热路径”中使用这些工具来记录和搜索信息
  • ⚙️ 后台记忆管理器,可自动提取、整合和更新智能体知识
  • 与 LangGraph 的长期记忆存储原生集成,在所有 LangGraph 平台部署中默认可用

安装

pip install -U langmem

使用您喜欢的LLM提供商的API密钥配置您的环境

export ANTHROPIC_API_KEY="sk-..."  # Or another supported LLM provider

创建一个智能体

只需几行代码,即可创建一个能主动管理其自身长期记忆的智能体。

# Import core components (1)
from langgraph.prebuilt import create_react_agent
from langgraph.store.memory import InMemoryStore
from langmem import create_manage_memory_tool, create_search_memory_tool

# Set up storage (2)
store = InMemoryStore(
    index={
        "dims": 1536,
        "embed": "openai:text-embedding-3-small",
    }
) 

# Create an agent with memory capabilities (3)
agent = create_react_agent(
    "anthropic:claude-3-5-sonnet-latest",
    tools=[
        # Memory tools use LangGraph's BaseStore for persistence (4)
        create_manage_memory_tool(namespace=("memories",)),
        create_search_memory_tool(namespace=("memories",)),
    ],
    store=store,
)
  1. 记忆工具适用于任何 LangGraph 应用。这里我们使用 create_react_agent 来运行一个带工具的 LLM,但您也可以将这些工具添加到您现有的智能体中,或在没有智能体的情况下构建自定义记忆系统

  2. InMemoryStore 将记忆保存在进程内存中——重启后会丢失。对于生产环境,请使用 AsyncPostgresStore 或类似的数据库支持的存储,以在服务器重启后持久化记忆。

  3. 记忆工具(create_manage_memory_toolcreate_search_memory_tool)让您控制存储哪些内容。智能体从对话中提取关键信息,保持记忆的一致性,并知道何时搜索过去的交互。请参阅记忆工具了解配置选项。

然后使用该智能体

# Store a new memory (1)
agent.invoke(
    {"messages": [{"role": "user", "content": "Remember that I prefer dark mode."}]}
)

# Retrieve the stored memory (2)
response = agent.invoke(
    {"messages": [{"role": "user", "content": "What are my lighting preferences?"}]}
)
print(response["messages"][-1].content)
# Output: "You've told me that you prefer dark mode."
  1. 智能体可以决定存储什么以及何时存储记忆。无需特殊命令——只需正常聊天,智能体就会使用 create_manage_memory_tool 来存储相关细节。

  2. 智能体在不同聊天之间保持上下文。当您询问之前的交互时,LLM 可以调用 create_search_memory_tool 来搜索内容相似的记忆。请参阅记忆工具以自定义记忆的存储和检索,并参阅热路径快速入门以获取更完整的示例,了解如何在智能体无需显式搜索的情况下包含记忆。

现在,智能体可以从对话中存储重要信息,在需要时搜索其记忆,并在不同对话之间持久化知识。

下一步

更多示例和详细文档