[P1/高] ContextBuilder estimateTokens 系数与 token-estimator 不一致,导致估算偏差 #47

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

问题类型

缺陷 / 高 / Agent 引擎

文件位置

  • electron/harness/prompts/context-builder.ts (estimateTokens)
  • electron/harness/utils/token-estimator.ts (estimateMessagesTokens)

问题描述

存在两套 token 估算实现:

context-builder.estimateTokens

function estimateTokens(text: string): number {
  return Math.ceil(text.length / 4); // 简单 1/4 估算
}

token-estimator.estimateMessagesTokens(符合 project_memory.md):

// 1.5 token/中文字符, 0.25 token/ASCII, 1 token/其他 Unicode
// + 4 tokens/message 结构开销

两套实现并存导致:

  1. 不同位置估算不一致
  2. 中文场景下严重低估(1/4 vs 1.5)
  3. 压缩阈值判断错误

影响

  • 中文用户上下文压缩过晚
  • API 请求超长被拒

建议修复

  1. 统一使用 token-estimator
import { estimateTextTokens } from '../utils/token-estimator';

function estimateTokens(text: string): number {
  return estimateTextTokens(text);
}
  1. 导出统一 API:token-estimator 暴露 estimateText / estimateMessages 两个粒度
  2. 移除 context-builder 中的私有实现
## 问题类型 缺陷 / 高 / Agent 引擎 ## 文件位置 - `electron/harness/prompts/context-builder.ts` (estimateTokens) - `electron/harness/utils/token-estimator.ts` (estimateMessagesTokens) ## 问题描述 存在两套 token 估算实现: **context-builder.estimateTokens**: ```ts function estimateTokens(text: string): number { return Math.ceil(text.length / 4); // 简单 1/4 估算 } ``` **token-estimator.estimateMessagesTokens**(符合 project_memory.md): ```ts // 1.5 token/中文字符, 0.25 token/ASCII, 1 token/其他 Unicode // + 4 tokens/message 结构开销 ``` 两套实现并存导致: 1. 不同位置估算不一致 2. 中文场景下严重低估(1/4 vs 1.5) 3. 压缩阈值判断错误 ## 影响 - 中文用户上下文压缩过晚 - API 请求超长被拒 ## 建议修复 1. **统一使用 token-estimator**: ```ts import { estimateTextTokens } from '../utils/token-estimator'; function estimateTokens(text: string): number { return estimateTextTokens(text); } ``` 2. **导出统一 API**:token-estimator 暴露 `estimateText` / `estimateMessages` 两个粒度 3. **移除 context-builder 中的私有实现**
thzxx added the Agent????? labels 2026-07-21 21:56:12 +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#47