Loading...
  • 构建
  • 管理
  • 模型与定价
  • 客户端 SDK
  • API 参考
Search...
⌘K
Log in
记忆工具
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...

Solutions

  • AI agents
  • Code modernization
  • Coding
  • Customer support
  • Education
  • Financial services
  • Government
  • Life sciences

Partners

  • Amazon Bedrock
  • Google Cloud's Vertex AI

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Company

  • Anthropic
  • Careers
  • Economic Futures
  • Research
  • News
  • Responsible Scaling Policy
  • Security and compliance
  • Transparency

Learn

  • Blog
  • Courses
  • Use cases
  • Connectors
  • Customer stories
  • Engineering at Anthropic
  • Events
  • Powered by Claude
  • Service partners
  • Startups program

Help and security

  • Availability
  • Status
  • Support
  • Discord

Terms and policies

  • Privacy policy
  • Responsible disclosure policy
  • Terms of service: Commercial
  • Terms of service: Consumer
  • Usage policy
构建/工具

记忆工具

Claude 可以通过记忆文件目录在对话间存储和检索信息。了解如何使用记忆工具来构建持久化知识。

Was this page helpful?

  • view
  • create
  • str_replace
  • insert
  • delete
  • rename

记忆工具使 Claude 能够通过记忆文件目录在对话间存储和检索信息。Claude 可以创建、读取、更新和删除在会话间持久化的文件,允许它随时间积累知识,而无需将所有内容保存在上下文窗口中。

这是即时上下文检索的关键原语:与其预先加载所有相关信息,代理将学到的内容存储在记忆中,并按需检索。这使活跃上下文专注于当前相关的内容,对于加载所有内容会导致上下文窗口溢出的长期运行工作流至关重要。有关更广泛的模式,请参阅有效的上下文工程。

记忆工具在客户端运行:你通过自己的基础设施控制数据的存储位置和方式。

通过反馈表分享你对此功能的反馈。

This feature is eligible for Zero Data Retention (ZDR). When your organization has a ZDR arrangement, data sent through this feature is not stored after the API response is returned.

用例

  • 在多个代理执行间维护项目上下文
  • 从过去的交互、决策和反馈中学习
  • 随时间构建知识库
  • 启用跨对话学习,其中 Claude 在重复工作流中改进

工作原理

启用后,Claude 在开始任务前会自动检查其记忆目录。Claude 可以在 /memories 目录中创建、读取、更新和删除文件,以存储工作时学到的内容,然后在未来对话中引用这些记忆,以更有效地处理类似任务或从中断处继续。

由于这是一个客户端工具,Claude 进行工具调用来执行记忆操作,你的应用程序在本地执行这些操作。这使你能够完全控制记忆的存储位置和方式。出于安全考虑,你应该将所有记忆操作限制在 /memories 目录中。

示例:记忆工具调用如何工作

当你要求 Claude 帮助完成任务时,Claude 会自动首先检查其记忆目录。以下是典型交互的样子:

1. 用户请求:

"帮我回复这个客户服务工单。"

2. Claude 检查记忆目录:

"我会帮你回复客户服务工单。让我检查我的记忆中是否有任何之前的上下文。"

Claude 调用记忆工具:

{
  "type": "tool_use",
  "id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "name": "memory",
  "input": {
    "command": "view",
    "path": "/memories"
  }
}

3. 你的应用程序返回目录内容:

{
  "type": "tool_result",
  "tool_use_id": "toolu_01C4D5E6F7G8H9I0J1K2L3M4",
  "content": "Here're the files and directories up to 2 levels deep in /memories, excluding hidden items and node_modules:\n4.0K\t/memories\n1.5K\t/memories/customer_service_guidelines.xml\n2.0K\t/memories/refund_policies.xml"
}

4. Claude 读取相关文件:

{
  "type": "tool_use",
  "id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "name": "memory",
  "input": {
    "command": "view",
    "path": "/memories/customer_service_guidelines.xml"
  }
}

5. 你的应用程序返回文件内容:

{
  "type": "tool_result",
  "tool_use_id": "toolu_01D5E6F7G8H9I0J1K2L3M4N5",
  "content": "Here's the content of /memories/customer_service_guidelines.xml with line numbers:\n     1\t<guidelines>\n     2\t<addressing_customers>\n     3\t- Always address customers by their first name\n     4\t- Use empathetic language\n..."
}

6. Claude 使用记忆来帮助:

"根据你的客户服务指南,我可以帮你起草回复。请分享工单详情..."

有关模型支持,请参阅工具参考。

入门

要使用记忆工具:

  1. 将记忆工具添加到你的请求中
  2. 为记忆操作实现客户端处理程序

要在你的应用程序中处理记忆工具操作,你需要为每个记忆命令实现处理程序。SDK 提供了处理工具接口的记忆工具助手。你可以继承 BetaAbstractMemoryTool(Python)或使用 betaMemoryTool(TypeScript)来实现你自己的记忆后端(基于文件、数据库、云存储、加密文件等)。

有关工作示例,请参阅:

  • Python:examples/memory/basic.py
  • TypeScript:examples/tools-helpers-memory.ts

基本用法

工具命令

你的客户端实现需要处理这些记忆工具命令。虽然这些规范描述了 Claude 最熟悉的推荐行为,但你可以根据用例修改实现并根据需要返回字符串。

view

显示目录内容或文件内容,支持可选的行范围:

{
  "command": "view",
  "path": "/memories",
  "view_range": [1, 10] // 可选:查看特定行
}

返回值

对于目录: 返回显示文件和目录及其大小的列表:

Here're the files and directories up to 2 levels deep in {path}, excluding hidden items and node_modules:
{size}    {path}
{size}    {path}/{filename1}
{size}    {path}/{filename2}
  • 列出最多 2 级深度的文件
  • 显示人类可读的大小(例如 5.5K、1.2M)
  • 排除隐藏项(以 . 开头的文件)和 node_modules
  • 在大小和路径之间使用制表符

对于文件: 返回带有标题和行号的文件内容:

Here's the content of {path} with line numbers:
{line_numbers}{tab}{content}

行号格式:

  • 宽度:6 个字符,右对齐,用空格填充
  • 分隔符:行号和内容之间的制表符
  • 索引:1 索引(第一行是第 1 行)
  • 行限制:超过 999,999 行的文件应返回错误:"File {path} exceeds maximum line limit of 999,999 lines."

示例输出:

Here's the content of /memories/notes.txt with line numbers:
     1	Hello World
     2	This is line two
    10	Line ten
   100	Line one hundred

错误处理

  • 文件/目录不存在:"The path {path} does not exist. Please provide a valid path."

create

创建新文件:

{
  "command": "create",
  "path": "/memories/notes.txt",
  "file_text": "Meeting notes:\n- Discussed project timeline\n- Next steps defined\n"
}

返回值

  • 成功:"File created successfully at: {path}"

错误处理

  • 文件已存在:"Error: File {path} already exists"

str_replace

替换文件中的文本:

{
  "command": "str_replace",
  "path": "/memories/preferences.txt",
  "old_str": "Favorite color: blue",
  "new_str": "Favorite color: green"
}

返回值

  • 成功:"The memory file has been edited." 后跟编辑文件的代码片段和行号

错误处理

  • 文件不存在:"Error: The path {path} does not exist. Please provide a valid path."
  • 文本未找到:"No replacement was performed, old_str `\{old_str}` did not appear verbatim in {path}."
  • 重复文本:当 old_str 出现多次时,返回:"No replacement was performed. Multiple occurrences of old_str `\{old_str}` in lines: {line_numbers}. Please ensure it is unique"

目录处理

如果路径是目录,返回"文件不存在"错误。

insert

在特定行插入文本:

{
  "command": "insert",
  "path": "/memories/todo.txt",
  "insert_line": 2,
  "insert_text": "- Review memory tool documentation\n"
}

返回值

  • 成功:"The file {path} has been edited."

错误处理

  • 文件不存在:"Error: The path {path} does not exist"
  • 无效的行号:"Error: Invalid `insert_line` parameter: {insert_line}. It should be within the range of lines of the file: [0, {n_lines}]"

目录处理

如果路径是目录,返回"文件不存在"错误。

delete

删除文件或目录:

{
  "command": "delete",
  "path": "/memories/old_file.txt"
}

返回值

  • 成功:"Successfully deleted {path}"

错误处理

  • 文件/目录不存在:"Error: The path {path} does not exist"

目录处理

递归删除目录及其所有内容。

rename

重命名或移动文件/目录:

{
  "command": "rename",
  "old_path": "/memories/draft.txt",
  "new_path": "/memories/final.txt"
}

返回值

  • 成功:"Successfully renamed {old_path} to {new_path}"

错误处理

  • 源不存在:"Error: The path {old_path} does not exist"
  • 目标已存在:返回错误(不覆盖):"Error: The destination {new_path} already exists"

目录处理

重命名目录。

提示指导

启用记忆工具时,此指令会自动包含在系统提示中:

IMPORTANT: ALWAYS VIEW YOUR MEMORY DIRECTORY BEFORE DOING ANYTHING ELSE.
MEMORY PROTOCOL:
1. Use the `view` command of your `memory` tool to check for earlier progress.
2. ... (work on the task) ...
     - As you make progress, record status / progress / thoughts etc in your memory.
ASSUME INTERRUPTION: Your context window might be reset at any moment, so you risk losing any progress that is not recorded in your memory directory.

如果你观察到 Claude 创建混乱的记忆文件,你可以包含此指令:

注意:编辑记忆文件夹时,始终尝试保持其内容最新、连贯和有组织。你可以重命名或删除不再相关的文件。除非必要,否则不要创建新文件。

你也可以指导 Claude 写入记忆的内容。例如:"仅在你的记忆系统中写下与 <topic> 相关的信息。"

安全考虑

实现记忆存储时的重要安全问题:

敏感信息

Claude 通常会拒绝在记忆文件中写下敏感信息。但是,你可能想实现更严格的验证,以剥离潜在的敏感信息。

文件存储大小

考虑跟踪记忆文件大小并防止文件增长过大。考虑添加记忆读取命令可以返回的最大字符数,并让 Claude 分页浏览内容。

记忆过期

考虑定期清除在较长时间内未被访问的记忆文件。

路径遍历保护

恶意路径输入可能会尝试访问 /memories 目录外的文件。你的实现必须验证所有路径以防止目录遍历攻击。

考虑这些保障措施:

  • 验证所有路径都以 /memories 开头
  • 将路径解析为其规范形式,并验证它们保持在记忆目录内
  • 拒绝包含 ../、..\\ 或其他遍历模式的路径
  • 监视 URL 编码的遍历序列(%2e%2e%2f)
  • 使用你的语言的内置路径安全实用程序(例如 Python 的 pathlib.Path.resolve() 和 relative_to())

错误处理

记忆工具使用与文本编辑器工具类似的错误处理模式。有关详细的错误消息和行为,请参阅上面的各个工具命令部分。常见错误包括文件未找到、权限错误、无效路径和重复文本匹配。

上下文编辑集成

记忆工具与上下文编辑配对以管理长期运行的对话。有关详情,请参阅上下文编辑。

与压缩一起使用

记忆工具也可以与压缩配对,它提供较旧对话上下文的服务器端摘要。虽然上下文编辑在客户端清除特定工具结果,但压缩在接近上下文窗口限制时自动在服务器端摘要整个对话。

对于长期运行的代理工作流,考虑同时使用两者:压缩使活跃上下文可管理,无需客户端簿记,记忆在压缩边界间持久化重要信息,以便在摘要中不会丢失任何关键内容。

多会话软件开发模式

对于跨越多个代理会话的长期运行软件项目,记忆文件需要有意引导,而不仅仅是在工作进行时临时写入。下面的模式将记忆转变为结构化恢复机制,因此每个新会话可以准确地从上一个会话停止的地方继续。

工作原理

  1. 初始化会话: 第一个会话在任何实质性工作开始前设置记忆工件。这包括进度日志(跟踪已完成和接下来要做的事),功能清单(定义工作范围),以及对项目需要的任何启动或初始化脚本的引用。

  2. 后续会话: 每个新会话通过读取这些记忆工件来打开。这在几秒内恢复项目的完整状态,无需重新探索代码库或追溯早期决策。

  3. 会话结束更新: 在会话结束前,它使用已完成和剩余的内容更新进度日志。这确保下一个会话有准确的起点。

关键原则

一次处理一个功能。仅在端到端验证确认其有效后才标记功能完成,而不是在代码编写后。这使进度日志值得信赖,并防止范围蔓延在会话间复合。

有关此模式实际应用的详细案例研究,包括初始化脚本、进度文件结构和基于 git 的恢复,请参阅长期运行代理的有效工具。

后续步骤

查看所有工具

Anthropic 提供的工具及其属性的目录。

上下文编辑

与记忆一起管理对话长度。

client = anthropic.Anthropic()

message = client.messages.create(
    model="claude-opus-4-7",
    max_tokens=2048,
    messages=[
        {
            "role": "user",
            "content": "I'm working on a Python web scraper that keeps crashing with a timeout error. Here's the problematic function:\n\n```python\ndef fetch_page(url, retries=3):\n    for i in range(retries):\n        try:\n            response = requests.get(url, timeout=5)\n            return response.text\n        except requests.exceptions.Timeout:\n            if i == retries - 1:\n                raise\n            time.sleep(1)\n```\n\nPlease help me debug this.",
        }
    ],
    tools=[{"type": "memory_20250818", "name": "memory"}],
)

print(message)