[P1/高] estimateTokens 忽略 tool.parameters,token 估算严重偏低 #31

Open
opened 2026-07-21 21:55:57 +08:00 by thzxx · 0 comments
Owner

问题类型

缺陷 / 高 / Agent 引擎

文件位置

electron/harness/prompts/context-builder.ts

问题描述

ContextBuilder.estimateTokens 在估算 system prompt token 时,仅累加 tool.name + tool.description,忽略 tool.parameters:

tools.forEach(tool => {
  total += tool.name.length + tool.description.length;
});

但 tool.parameters(JSON Schema)通常占工具 token 的 70%+:

  • 单个工具 schema 可能 500-2000 tokens
  • 27 个工具总计可能 30K+ tokens

影响

  • 估算 token 严重偏低(可能差 5-10 倍)
  • 上下文压缩阈值判断错误
  • 长会话下 API 请求超长被拒绝

建议修复

tools.forEach(tool => {
  total += tool.name.length + tool.description.length;
  // 估算 parameters schema 的 token
  if (tool.parameters) {
    const schemaStr = JSON.stringify(tool.parameters);
    total += estimateTokens(schemaStr); // 使用同一估算器
  }
});

或调用统一的 estimateMessagesTokens,将 tools 作为 messages 的一部分。

## 问题类型 缺陷 / 高 / Agent 引擎 ## 文件位置 `electron/harness/prompts/context-builder.ts` ## 问题描述 ContextBuilder.estimateTokens 在估算 system prompt token 时,仅累加 tool.name + tool.description,忽略 tool.parameters: ```ts tools.forEach(tool => { total += tool.name.length + tool.description.length; }); ``` 但 tool.parameters(JSON Schema)通常占工具 token 的 70%+: - 单个工具 schema 可能 500-2000 tokens - 27 个工具总计可能 30K+ tokens ## 影响 - 估算 token 严重偏低(可能差 5-10 倍) - 上下文压缩阈值判断错误 - 长会话下 API 请求超长被拒绝 ## 建议修复 ```ts tools.forEach(tool => { total += tool.name.length + tool.description.length; // 估算 parameters schema 的 token if (tool.parameters) { const schemaStr = JSON.stringify(tool.parameters); total += estimateTokens(schemaStr); // 使用同一估算器 } }); ``` 或调用统一的 estimateMessagesTokens,将 tools 作为 messages 的一部分。
thzxx added the ??Agent??? labels 2026-07-21 21:55:57 +08:00
Sign in to join this conversation.
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: MetonaTeam/metona-ai-desktop#31