Loading...
    • 开发者指南
    • API 参考
    • MCP
    • 资源
    • 更新日志
    Search...
    ⌘K
    入门
    Claude 简介快速开始
    模型与定价
    模型概览选择模型Claude 4.6 新特性迁移指南模型弃用定价
    使用 Claude 构建
    功能概览使用 Messages API处理停止原因提示词最佳实践
    上下文管理
    上下文窗口压缩上下文编辑
    能力
    提示缓存扩展思考自适应思考推理力度流式消息批量处理引用多语言支持Token 计数嵌入视觉PDF 支持Files API搜索结果结构化输出
    工具
    概览如何实现工具使用细粒度工具流式传输Bash 工具代码执行工具程序化工具调用计算机使用工具文本编辑器工具网页抓取工具网页搜索工具记忆工具工具搜索工具
    Agent Skills
    概览快速开始最佳实践企业级 Skills通过 API 使用 Skills
    Agent SDK
    概览快速开始TypeScript SDKTypeScript V2(预览版)Python SDK迁移指南
    API 中的 MCP
    MCP 连接器远程 MCP 服务器
    第三方平台上的 Claude
    Amazon BedrockMicrosoft FoundryVertex AI
    提示工程
    概览提示词生成器使用提示词模板提示词优化器清晰直接使用示例(多样本提示)让 Claude 思考(思维链)使用 XML 标签赋予 Claude 角色(系统提示词)链式复杂提示长上下文技巧扩展思考技巧
    测试与评估
    定义成功标准开发测试用例使用评估工具降低延迟
    加强安全护栏
    减少幻觉提高输出一致性防范越狱攻击流式拒绝减少提示词泄露保持 Claude 角色设定
    管理与监控
    Admin API 概览数据驻留工作空间用量与成本 APIClaude Code Analytics API零数据留存
    Console
    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
    • Catalog
    • 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
    • Catalog
    • 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 能够通过记忆文件目录在对话之间存储和检索信息。

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

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

    记忆工具目前处于 beta 阶段。要启用它,请在 API 请求中使用 beta 头 context-management-2025-06-27。

    请通过我们的反馈表单分享您对此功能的反馈。

    使用场景

    • 在多次智能体执行之间维护项目上下文
    • 从过去的交互、决策和反馈中学习
    • 随时间构建知识库
    • 实现跨对话学习,使 Claude 在重复工作流中不断改进

    工作原理

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

    由于这是一个客户端工具,Claude 会发出工具调用来执行记忆操作,而您的应用程序在本地执行这些操作。这使您可以完全控制记忆的存储位置和方式。为了安全起见,您应该将所有记忆操作限制在 /memories 目录中。

    示例:记忆工具调用的工作方式

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

    1. 用户请求:

    "Help me respond to this customer service ticket."

    2. Claude 检查记忆目录:

    "I'll help you respond to the customer service ticket. Let me check my memory for any previous context."

    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 使用记忆来提供帮助:

    "Based on your customer service guidelines, I can help you craft a response. Please share the ticket details..."

    支持的模型

    记忆工具可在以下模型上使用:

    • Claude Opus 4.6 (claude-opus-4-6)
    • Claude Opus 4.5 (claude-opus-4-5-20251101)
    • Claude Opus 4.1 (claude-opus-4-1-20250805)
    • Claude Opus 4 (claude-opus-4-20250514)
    • Claude Sonnet 4.5 (claude-sonnet-4-5-20250929)
    • Claude Sonnet 4 (claude-sonnet-4-20250514)
    • Claude Haiku 4.5 (claude-haiku-4-5-20251001)

    快速开始

    要使用记忆工具:

    1. 在 API 请求中包含 beta 头 context-management-2025-06-27
    2. 将记忆工具添加到您的请求中
    3. 实现客户端的记忆操作处理程序

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

    有关工作示例,请参阅:

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

    基本用法

    curl https://api.anthropic.com/v1/messages \
        --header "x-api-key: $ANTHROPIC_API_KEY" \
        --header "anthropic-version: 2023-06-01" \
        --header "content-type: application/json" \
        --header "anthropic-beta: context-management-2025-06-27" \
        --data '{
            "model": "claude-opus-4-6",
            "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"
            }]
        }'

    工具命令

    您的客户端实现需要处理这些记忆工具命令。虽然这些规范描述了 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 写入记忆的内容,例如,"Only write down information relevant to <topic> in your memory system."

    安全注意事项

    以下是实现记忆存储时的重要安全注意事项:

    敏感信息

    Claude 通常会拒绝在记忆文件中写入敏感信息。但是,您可能需要实现更严格的验证来过滤潜在的敏感信息。

    文件存储大小

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

    记忆过期

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

    路径遍历保护

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

    考虑以下安全措施:

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

    错误处理

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

    与上下文编辑配合使用

    记忆工具可以与上下文编辑结合使用,当对话上下文增长超过配置的阈值时,上下文编辑会自动清除旧的工具结果。这种组合使得长时间运行的智能体工作流成为可能,否则这些工作流将超出上下文限制。

    它们如何协同工作

    当启用上下文编辑且您的对话接近清除阈值时,Claude 会自动收到警告通知。这会提示 Claude 在工具结果从上下文窗口中清除之前,将任何重要信息保存到记忆文件中。

    工具结果被清除后,Claude 可以在需要时从记忆文件中检索存储的信息,有效地将记忆作为其工作上下文的扩展。这使 Claude 能够:

    • 在不丢失关键信息的情况下继续复杂的多步骤工作流
    • 即使在工具结果被移除后也能引用过去的工作和决策
    • 在超出典型上下文限制的对话中保持连贯的上下文
    • 随时间构建知识库,同时保持活动上下文窗口可管理

    示例工作流

    考虑一个包含许多文件操作的代码重构项目:

    1. Claude 对文件进行大量编辑,生成许多工具结果
    2. 随着上下文增长并接近您的阈值,Claude 收到警告
    3. Claude 将到目前为止所做的更改总结到记忆文件中(例如 /memories/refactoring_progress.xml)
    4. 上下文编辑自动清除较旧的工具结果
    5. Claude 继续工作,在需要回忆已完成的更改时引用记忆文件
    6. 工作流可以无限期继续,Claude 同时管理活动上下文和持久记忆

    配置

    要同时使用这两个功能:

    response = client.beta.messages.create(
        model="claude-opus-4-6",
        max_tokens=4096,
        messages=[...],
        tools=[
            {
                "type": "memory_20250818",
                "name": "memory"
            },
            # Your other tools
        ],
        betas=["context-management-2025-06-27"],
        context_management={
            "edits": [
                {
                    "type": "clear_tool_uses_20250919",
                    "trigger": {
                        "type": "input_tokens",
                        "value": 100000
                    },
                    "keep": {
                        "type": "tool_uses",
                        "value": 3
                    }
                }
            ]
        }
    )

    您还可以排除记忆工具调用不被清除,以确保 Claude 始终可以访问最近的记忆操作:

    context_management={
        "edits": [
            {
                "type": "clear_tool_uses_20250919",
                "exclude_tools": ["memory"]
            }
        ]
    }

    与压缩配合使用

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

    对于长时间运行的智能体工作流,考虑同时使用两者:压缩无需客户端记录即可保持活动上下文可管理,而记忆在压缩边界之间持久保存重要信息,确保摘要中不会丢失关键内容。

    Was this page helpful?

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