工具上下文是一个经常被低估的"水龙头"。每个 Agent 注册一个工具,就要在上下文中放入这个工具的名称、描述、参数说明——这些文本加起来的 token 消耗远超大多数人的直觉。
Anthropic 的实测数据揭示了一个惊人的事实:一个拥有 100 个工具的 Agent,30-40% 的上下文窗口被工具描述占据。也就是说,还没开始对话,Agent 的有效窗口就已经缩水了近一半。
数据来源:Anthropic Effective Context Engineering for AI Agents,2025年9月29日发布。
工具上下文管理的核心策略是按密集度分级:
工具密集度分级管理策略
| 工具数量 | 管理策略 | 上下文影响 |
|---|---|---|
| <10 | 全量静态加载 | 工具描述占 <5% 上下文 |
| 10-30 | 按任务阶段动态加载子集 | 降至 <10% |
| 30-100 | Agent Skills 条件注入 | 按需 <5% |
| 100+ | MCP 动态发现 + 工具路由 | 极低(仅加载当前需要的) |
除了工具描述的静态占用,工具调用的结果也是一个主要的上下文消耗源。一次文件读取可能返回数千个 token,一次 API 调用的结果可能更长。工具结果清除(调用完成后丢弃原始结果,仅保留结论)是成本最低、收益最高的优化策略之一——零成本零延迟,即可节省 20-40% 的 token。
在 OpenClaw 中,工具管理采用的是静态全量加载模式(get_all_tools(base_dir) 一次性加载所有工具)。由于工具数量在 10 个左右,这种策略是合理的。但如果工具数量增长到 30 个以上,就需要考虑动态加载方案。
2.5.1 动手验证:工具结果清除的 Token 节省效果
工具结果清除是"零成本最高收益"的优化策略。我们来用代码量化这个收益——模拟 5 次工具调用,对比"保留完整结果"和"只保留结论"两种策略下的累积 token 消耗。
import json
import pandas as pd
# === 工具结果清除前后对比 ===
# 模拟 5 次工具调用的原始返回结果(真实场景中这些会累积在对话历史中)
tool_calls = [
{
"tool": "read_file",
"input": "backend/db/pool.py",
"raw_result": "文件内容:\n" + "import os\nimport json\nfrom pathlib import Path\n\n"
"class ConfigManager:\n def __init__(self):\n self.config = {}\n"
" def load(self, path):\n with open(path) as f:\n"
" self.config = json.load(f)\n" * 3,
"summary": "ConfigManager 类:加载 JSON 配置文件,包含 load/save 方法。"
},
{
"tool": "search_codebase",
"input": "database connection pool",
"raw_result": json.dumps({"matches": [
{"file": "db/pool.py", "line": 15, "text": "pool = create_async_engine(url, pool_size=20)"},
{"file": "db/pool.py", "line": 28, "text": "pool_recycle=3600, pool_pre_ping=True"},
{"file": "db/session.py", "line": 5, "text": "async_sessionmaker(engine, expire_on_commit=False)"},
{"file": "config.py", "line": 42, "text": "DATABASE_URL = os.getenv('DATABASE_URL')"},
]}, ensure_ascii=False, indent=2),
"summary": "找到 4 处匹配:pool.py 连接池(size=20, recycle=3600),session.py 创建 async session。"
},
{
"tool": "run_tests",
"input": "pytest tests/db/ -v",
"raw_result": "tests/db/test_pool.py::test_connection PASSED\n"
"tests/db/test_pool.py::test_pool_size PASSED\n"
"tests/db/test_pool.py::test_recycle PASSED\n"
"tests/db/test_session.py::test_create PASSED\n"
"tests/db/test_session.py::test_commit PASSED\n"
"tests/db/test_session.py::test_rollback FAILED\n"
"FAILED tests/db/test_session.py::test_rollback - AssertionError\n"
"========================= 5 passed, 1 failed in 3.2s =========================",
"summary": "6 个测试:5 passed, 1 failed (test_rollback AssertionError)。"
},
{
"tool": "read_file",
"input": "config/production.yaml",
"raw_result": "database:\n host: db.prod.internal\n port: 5432\n name: app_production\n"
" pool_size: 50\n max_overflow: 10\nredis:\n host: redis.prod.internal\n"
" port: 6379\n db: 0\n ttl: 3600\nlogging:\n level: WARNING\n sentry_dsn: https://xxx@sentry.io/123",
"summary": "生产配置:DB pool_size=50, max_overflow=10; Redis TTL=3600; 日志 WARNING。"
},
{
"tool": "search_codebase",
"input": "error handling middleware",
"raw_result": json.dumps({"matches": [
{"file": "middleware/error.py", "line": 8, "text": "class ErrorHandlerMiddleware:"},
{"file": "middleware/error.py", "line": 15, "text": "except HTTPException as e:"},
{"file": "middleware/error.py", "line": 22, "text": "except Exception as e: logger.error(...)"},
{"file": "main.py", "line": 12, "text": "app.add_middleware(ErrorHandlerMiddleware)"},
]}, ensure_ascii=False, indent=2),
"summary": "ErrorHandlerMiddleware 捕获 HTTP/通用异常,在 main.py 注册。"
},
]
# 构建对比表格
rows = []
for tc in tool_calls:
raw_t = count_tokens(tc["raw_result"])
sum_t = count_tokens(tc["summary"])
rows.append({
"工具调用": f"{tc['tool']}({tc['input'][:15]})",
"原始 Token": raw_t,
"摘要 Token": sum_t,
"节省": f"{(1-sum_t/raw_t)*100:.0f}%",
})
df = pd.DataFrame(rows)
# 添加合计行
raw_total = df["原始 Token"].sum()
sum_total = df["摘要 Token"].sum()
total_row = pd.DataFrame([{
"工具调用": "合计",
"原始 Token": raw_total,
"摘要 Token": sum_total,
"节省": f"{(1-sum_total/raw_total)*100:.0f}%",
}])
df = pd.concat([df, total_row], ignore_index=True)
print(f"5 次工具调用节省 {raw_total - sum_total} tokens({(1-sum_total/raw_total)*100:.0f}%)\n")
df
5 次工具调用节省 515 tokens(82%)
| 工具调用 | 原始 Token | 摘要 Token | 节省 | |
|---|---|---|---|---|
| 0 | read_file(backend/db/pool) | 153 | 17 | 89% |
| 1 | search_codebase(database connec) | 153 | 32 | 79% |
| 2 | run_tests(pytest tests/db) | 98 | 18 | 82% |
| 3 | read_file(config/producti) | 86 | 25 | 71% |
| 4 | search_codebase(error handling ) | 135 | 18 | 87% |
| 5 | 合计 | 625 | 110 | 82% |
运行结果会显示:5 次工具调用的原始结果累计数千 token,而清除后只保留结论仅需几百 token——节省通常在 80-90% 以上。这个策略的关键优势是零成本零延迟:不需要 LLM 调用,只需要在工具执行完成后用一行代码替换原始结果。
节省 80% token 听起来很诱人,但一个自然的担忧是:把详细结果替换成摘要后,Agent 还能准确回答综合性问题吗? 我们来验证——用同一个需要综合多个工具结果的问题,分别在"原始结果"和"摘要结果"两种上下文下提问:
# === 验证:摘要替代原始结果后,回答质量是否下降? ===
# 综合性问题:需要跨多个工具结果才能回答
question = "根据代码和配置,当前数据库连接池的健康状况如何?有哪些风险点需要关注?"
# 上下文A:拼接全部原始结果
raw_context = "\n\n".join(
f"[{tc['tool']}({tc['input']})] 返回结果:\n{tc['raw_result']}"
for tc in tool_calls
)
# 上下文B:拼接全部摘要
summary_context = "\n".join(
f"[{tc['tool']}({tc['input']})] {tc['summary']}"
for tc in tool_calls
)
# 分别提问
import time
results = {}
for label, context in [("原始结果", raw_context), ("摘要结果", summary_context)]:
prompt = f"以下是工具调用结果:\n{context}\n\n{question}"
tokens_in = count_tokens(prompt)
start = time.time()
response = llm.invoke(prompt)
elapsed = time.time() - start
results[label] = {
"输入 token": tokens_in,
"耗时": round(elapsed, 2),
"回答": response.content,
}
# 对比展示
for label, r in results.items():
print(f"=== {label}({r['输入 token']} tokens, {r['耗时']}s)===")
print(r["回答"][:1000])
print()
saving = results["原始结果"]["输入 token"] - results["摘要结果"]["输入 token"]
print(f"Token 节省: {saving}({saving/results['原始结果']['输入 token']*100:.0f}%),回答质量自行对比上方两段输出")
=== 原始结果(732 tokens, 32.05s)===
根据提供的代码片段、搜索结果、测试报告和生产配置,当前数据库连接池的基本连通性正常,但存在若干值得关注的配置 不一致、事务处理缺陷和工程风险。以下是详细分析。
1. 连接池当前健康状况
| 方面 | 状态 | 说明 |
|---|---|---|
| 基础连接 | ✅ 正常 | test_connection 通过,证明池能成功建立连接。 |
| 池大小检查 | ✅ 通过 | test_pool_size 通过,代码中设置的 pool_size=20 生效。 |
| 连接回收 | ✅ 通过 | test_recycle 通过,pool_recycle=3600 + pool_pre_ping=True 能主动探活并回收陈旧连接。 |
| 会话创建 | ✅ 通过 | test_create 通过,async_sessionmaker 能正常生成会话。 |
| 事务提交 | ✅ 通过 | test_commit 通过,基本提交逻辑正确。 |
| 事务回滚 | ❌ 失败 | test_rollback 失败 (AssertionError),这是关键隐患,直接影响数据一致性。 |
2. 主要风险点及详细分析
🔴 高风险:事务回滚失败 (test_rollback)
- 现象:回滚测试断言失败,说明
session.rollback()后对象状态、数据库状态或异常处理流程与预期不符。 - 可能后果: - 业务异常时事务未能彻底回滚,导致脏数据残留。
- 连接可能没有正确释放到池中(如果回滚异常导致连接泄漏),进而耗尽池。
...
3. 连接回收时间可能长于数据库超时 - 回收时间 `recycle=360 Token 节省: 530(72%),回答质量自行对比上方两段输出
两种方式的局限性:保留完整结果的问题是 token 消耗爆炸——一个读取 1000 行代码文件的工具调用可能返回 5000+ tokens,而 Agent 可能只需要知道"文件包含 ConfigManager 类"这个结论。清除策略的局限性是信息不可逆——如果后续推理需要原始数据的细节,就无法回溯。因此,正确的做法是:将原始结果归档到磁盘,上下文中只保留结论。
选择决策依据:如果你的 Agent 是编程助手、数据分析类(工具调用密集),工具结果清除是首日必启用的策略。如果是对话型 Agent(工具调用少),这个策略的收益有限。判断标准:如果工具上下文占比超过 20%,立即启用清除策略。