Skip to main content
深度智能体自带本地文件系统以卸载内存。此文件系统存储在状态中,因此对单个线程来说是短暂的——当对话结束时文件会丢失。 您可以通过提供 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/ 开头的路径的文件存储在存储中(持久)
  • 没有此前缀的文件保持为瞬态状态
  • 所有文件系统工具(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
存储中的文件在列表中带有 /memories/ 前缀。

局限性

店铺是必需的

您必须在启用长期记忆时提供存储。
# ❌ 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或自动清理功能。如有需要,您需要实现清理策略。