跳到内容

LangMem

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

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

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

这让你的智能体能够持续改进,个性化它们的响应,并在不同会话中保持一致的行为。

主要特点

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

安装

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 来搜索内容相似的记忆。请参阅 记忆工具 以自定义记忆存储和检索,并参阅 热路径快速入门 以获取一个更完整的示例,说明如何在智能体无需显式搜索的情况下包含记忆。

智能体现在可以存储对话中的重要信息,在相关时搜索其记忆,并在对话之间保留知识。

下一步

更多示例和详细文档