跳到主要内容
深度代理带有一个本地文件系统来卸载内存。此文件系统存储在状态中,因此对于单个线程是瞬时的——当对话结束时文件会丢失。 您可以通过提供 LangGraph Store 并设置 use_longterm_memory=True 来扩展深度代理的长期记忆。这使得持久存储能够在线程和对话之间保留。

设置

from deepagents import create_deep_agent
from langgraph.store.memory import InMemoryStore

store = InMemoryStore()  # Or any other Store object
agent = create_deep_agent(
    store=store,
    use_longterm_memory=True
)

工作原理

启用长期记忆后,深度代理维护两个独立的文件系统

1. 短期(瞬时)文件系统

  • 存储在代理的状态中
  • 仅在单个线程内持久化
  • 线程结束时文件丢失
  • 通过标准路径访问:/notes.txt

2. 长期(持久)文件系统

  • 存储在 LangGraph Store 中
  • 跨所有线程和对话持久化
  • 文件无限期保留
  • 通过特殊前缀访问:/memories/notes.txt

“/memories/” 路径约定

长期记忆的关键是 /memories/ 路径前缀
  • /memories/ 开头的文件存储在 Store 中(持久)
  • 没有此前缀的文件保留在瞬时状态中
  • 所有文件系统工具(lsread_filewrite_fileedit_file)都适用于两者
# Transient file (lost after thread ends)
agent.invoke({
    "messages": [{"role": "user", "content": "Write draft to /draft.txt"}]
})

# Persistent file (survives across threads)
agent.invoke({
    "messages": [{"role": "user", "content": "Save final report to /memories/report.txt"}]
})

跨线程持久性

/memories/ 中的文件可以从任何线程访问
import uuid

# Thread 1: Write to long-term memory
config1 = {"configurable": {"thread_id": str(uuid.uuid4())}}
agent.invoke({
    "messages": [{"role": "user", "content": "Save my preferences to /memories/preferences.txt"}]
}, config=config1)

# Thread 2: Read from long-term memory (different conversation!)
config2 = {"configurable": {"thread_id": str(uuid.uuid4())}}
agent.invoke({
    "messages": [{"role": "user", "content": "What are my preferences?"}]
}, config=config2)
# Agent can read /memories/preferences.txt from the first thread

用例

用户偏好设置

存储跨会话保留的用户偏好设置
agent = create_deep_agent(
    store=store,
    use_longterm_memory=True,
    system_prompt="""When users tell you their preferences, save them to
    /memories/user_preferences.txt so you remember them in future conversations."""
)

自我完善指令

代理可以根据反馈更新自己的指令
agent = create_deep_agent(
    store=store,
    use_longterm_memory=True,
    system_prompt="""You have a file at /memories/instructions.txt with additional
    instructions and preferences.

    Read this file at the start of conversations to understand user preferences.

    When users provide feedback like "please always do X" or "I prefer Y",
    update /memories/instructions.txt using the edit_file tool."""
)
随着时间的推移,指令文件会积累用户偏好设置,帮助代理改进。

知识库

通过多次对话积累知识
# Conversation 1: Learn about a project
agent.invoke({
    "messages": [{"role": "user", "content": "We're building a web app with React. Save project notes."}]
})

# Conversation 2: Use that knowledge
agent.invoke({
    "messages": [{"role": "user", "content": "What framework are we using?"}]
})
# Agent reads /memories/project_notes.txt from previous conversation

研究项目

在会话之间维护研究状态
research_agent = create_deep_agent(
    store=store,
    use_longterm_memory=True,
    system_prompt="""You are a research assistant.

    Save your research progress to /memories/research/:
    - /memories/research/sources.txt - List of sources found
    - /memories/research/notes.txt - Key findings and notes
    - /memories/research/report.md - Final report draft

    This allows research to continue across multiple sessions."""
)

存储实现

任何 LangGraph BaseStore 实现都适用

InMemoryStore(开发)

适用于测试和开发,但数据在重启时会丢失
from langgraph.store.memory import InMemoryStore

store = InMemoryStore()
agent = create_deep_agent(store=store, use_longterm_memory=True)

PostgresStore(生产)

对于生产环境,请使用持久存储
from langgraph.store.postgres import PostgresStore
import os

store = PostgresStore(connection_string=os.environ["DATABASE_URL"])
agent = create_deep_agent(store=store, use_longterm_memory=True)

最佳实践

使用描述性路径

使用清晰、分层的路径组织长期文件
# ✅ Good: Organized and descriptive
/memories/user_preferences/language.txt
/memories/projects/project_alpha/status.txt
/memories/research/quantum_computing/sources.txt

# ❌ Bad: Generic and unorganized
/memories/temp.txt
/memories/data.txt
/memories/file1.txt

记录持久化内容

在系统提示中,阐明何时使用长期存储与短期存储
system_prompt="""You have access to two types of storage:

SHORT-TERM (paths without /memories/):
- Current conversation notes
- Temporary scratch work
- Draft documents

LONG-TERM (paths starting with /memories/):
- User preferences and settings
- Completed reports and documents
- Knowledge that should persist across conversations
- Project state and progress

Always use /memories/ for information that should survive beyond this conversation."""

按助手 ID 隔离存储

对于多租户应用程序,提供 assistant_id 以隔离存储
config = {
    "configurable": {
        "thread_id": "thread-123",
    },
    "metadata": {
        "assistant_id": "user-456"  # Namespace isolation
    }
}

agent.invoke({"messages": [...]}, config=config)
每个助手在 Store 中都有自己的命名空间,防止交叉污染。

在生产中使用持久存储

# ❌ Development only - data lost on restart
store = InMemoryStore()

# ✅ Production - data persists
from langgraph.store.postgres import PostgresStore
store = PostgresStore(connection_string=os.environ["DATABASE_URL"])

列出文件

ls 工具显示来自两个文件系统的文件
agent.invoke({
    "messages": [{"role": "user", "content": "List all files"}]
})

# Example output:
# Transient files:
# - /draft.txt
# - /temp_notes.txt
#
# Long-term files:
# - /memories/user_preferences.txt
# - /memories/project_status.txt
来自 Store 的文件在列表中以 /memories/ 为前缀。

限制

需要存储

启用长期记忆时必须提供 Store
# ❌ This will error
agent = create_deep_agent(use_longterm_memory=True)  # Missing store!

# ✅ Correct
agent = create_deep_agent(
    use_longterm_memory=True,
    store=InMemoryStore()
)

代理必须使用正确的路径

代理必须学会使用 /memories/ 前缀进行持久化。系统提示会教导这一点,但代理必须遵循指令。

无自动清理

长期文件无限期保留。没有内置的 TTL 或自动清理。如果需要,您需要实施清理策略。
以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.