Skip to content

[Feature]: Tool 结果超限时应持久化到本地文件而非直接注入上下文 #4

@huanghuoguoguo

Description

@huanghuoguoguo

背景

当前 Tool(包括 MCP 工具)返回的大内容会通过 Tool Manager 执行后直接序列化并注入到上下文中。当返回内容过大时(如爬取网页、查询大数据、读取长文件等),会:

  1. 直接撑爆上下文窗口
  2. 导致后续 LLM 调用失败或成本激增
  3. 即使有截断机制,也会丢失重要信息

建议

当 Tool 返回内容超过预设阈值时,采用持久化 + 引用策略:

机制设计

  1. 检测超限:Tool 返回结果后,检查内容长度是否超过阈值(如 max-tool-result-chars)

  2. 持久化到本地

    • 将超限内容写入临时文件,如 tmp/tool-results/{tool_call_id}.txt
    • 文件路径作为 Tool 返回结果的替代
  3. 返回文件引用

{
  "type": "file_reference",
  "path": "tmp/tool-results/abc123.txt",
  "size": 50000,
  "truncated": false,
  "hint": "内容已持久化,使用 read 工具读取需要的部分"
}
  1. Agent 按需读取
    • Agent 收到文件引用后,根据任务需要决定是否读取
    • 可使用 read 工具分段读取,或先用 exec 命令(如 head、grep)预处理
    • 避免"一次性全量注入上下文"的问题

优势

  • 不会撑爆上下文:大内容持久化后只保留引用,上下文保持精简
  • 信息不丢失:截断机制会丢失信息,持久化则保留完整内容供按需访问
  • Agent 自主决策:Agent 根据任务需要决定读取多少内容,而非被迫接收全量
  • 分段读取:支持 read 工具的 offset/limit 参数,只读需要的部分

配置项建议

local-agent:
  tool-result-persistence:
    enabled: true
    threshold-chars: 8000        # 超过此长度触发持久化
    storage-dir: ./tmp/tool-results
    cleanup-after-session: true  # 会话结束后清理临时文件

与现有机制的关系

  • 与 max-tool-result-chars 截断机制配合:可先截断再持久化,或直接持久化
  • 与 context-window 感知配合:Agent 在预算紧张时可选择不读取大文件

参考

类似机制在其他框架中的应用:

  • Claude Code 的 read 工具支持分段读取大文件
  • OpenAI Assistants API 的 files 功能支持文件引用而非直接注入内容

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions