Skip to content

工具输出过大时应截断,避免下一轮请求触发 413 #249

Description

@CorrectRoadH

问题

我在用 bub 跑一个 eval。这个 eval 的任务是:在一个 Next.js App Router 项目里创建 Server Action,用来创建新 post;post 列表使用 cache tag 缓存;创建后需要让下一次页面加载一定拿到 fresh data,不能看到 stale cached data。

任务过程中,agent 为了确认 next/cache 里相关 API 的名字和用法,执行了下面这类命令:

grep -R "updateTag\|revalidateTag" -n node_modules/next | head -50
grep -R "cacheTag\|unstable_cacheTag" -n node_modules/next | head -50

这个命令看起来有 head -50,但 node_modules/next 里的 compiled/runtime bundle 和 source map 有很长的单行内容,所以工具调用结果仍然非常大。随后下一轮请求失败,返回:

<html>
<head><title>413 Request Entity Too Large</title></head>
<body>
<center><h1>413 Request Entity Too Large</h1></center>
<hr><center>openresty</center>
</body>
</html>

结果是 bub 没有继续完成 eval,而是因为上下文/请求体过大直接失败了。

期望行为

工具输出进入 tape、上下文或下一轮模型请求之前,应该有硬上限保护。一次输出过大的 shell 命令应该被截断并标记,而不是让整个 agent 回合因为 provider / reverse proxy 的 413 失败。

建议方案

可以参考 Claude Code 的做法:当工具输出超过上限时,不把完整内容直接回灌给模型,而是把完整输出写到外部文件,并在工具结果末尾告诉 LLM 完整结果保存在哪里。

例如工具结果可以变成:

<前 N 行或前 N bytes 的输出>

[output truncated: original 18.4 MB exceeded 128 KB limit]
[full output saved to: /tmp/bub-tool-output/run-abc123-call-xyz.stdout]
[hint: use `tail -n 200 /tmp/bub-tool-output/run-abc123-call-xyz.stdout` to inspect the end]

这样有几个好处:

  • 下一轮模型上下文保持有界,不会因为单次工具输出触发 413
  • 完整输出没有丢,agent 需要时可以自己用 tail / sed / rg 继续查看。
  • 对 eval 和 tracing 更友好:失败原因会变成可控的截断提示,而不是 provider request body 爆掉。
  • 相比只做简单截断,spill-to-file 保留了调试能力。

可以考虑默认策略:

  1. 为每次 tool result 设置最大 inline 上限,例如按 bytes 或 UTF-8 字符数限制。
  2. 超出上限时,把完整 stdout/stderr 写入临时文件或 run artifact。
  3. 返回给模型的 tool result 包含:开头摘要、截断原因、原始大小、保存路径、建议的 tail 命令。
  4. tape / trace 里也记录截断后的内容和外部文件路径,避免 trace 本身继续膨胀。
  5. 加一个回归测试:工具返回多 MB 单行输出时,下一轮模型请求仍不会超限,并且模型能看到完整输出路径。

一个更简单的 fallback 是只做硬截断,并在末尾说明为什么截断;但更推荐上面的 spill-to-file,因为它既保护上下文,也保留完整调试信息。

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