Skip to content

fix(streaming): fix estimateTokenCount overestimation causing max_tokens: 1 (#83)#84

Merged
ltmoerdani merged 1 commit into
mainfrom
fix/issue-83-estimate-token-count-overflow
Jul 24, 2026
Merged

fix(streaming): fix estimateTokenCount overestimation causing max_tokens: 1 (#83)#84
ltmoerdani merged 1 commit into
mainfrom
fix/issue-83-estimate-token-count-overflow

Conversation

@ltmoerdani

Copy link
Copy Markdown
Owner

Description

The word-count-based heuristic (words * 1.15) in estimateTokenCount() dramatically overestimates token counts for JSON-serialized chat messages (3-5× actual), because every structural JSON character ({, }, ", :, ,) is counted as a separate word.

For conversations approaching the context window (~754K tokens on a 1M window), this inflated safeOutputBudget to 1, sending max_tokens: 1 to the API — models generated exactly 1 token then stopped with finishReason: length.

Fix

  1. estimateTokenCount() heuristic — replaced words * 1.15 with charEstimate-based: 1 token ≈ 4 characters (OpenAI standard) + 10% code buffer + CJK characters. See docs/issues/37-20260724-estimate-token-count-overflow.md.

  2. MIN_OUTPUT_BUDGET = 4096 — safety net in modelLimits() to prevent safeOutputBudget collapse under any estimation scenario.

Verification

All 4 test scenarios pass:

Scenario OLD max_tokens NEW max_tokens
Issue #83 (754K, 1M ctx) 1 4,096
Medium (130K, 262K ctx) 37,145 65,536
Small (1K, 100K ctx) 32,000 32,000 ✅
Code-heavy (200K, 1M ctx) 128,000 128,000 ✅

npm run compile: ✅ no errors
Extension v0.4.3 installed locally: ✅

Related

Closes #83

…ens: 1 (#83)

The word-count-based heuristic (words * 1.15) in estimateTokenCount()
dramatically overestimates token counts for JSON-serialized chat
messages (3-5x actual), because every structural JSON character
({, }, ", :, ,) is counted as a separate word.

For conversations approaching the context window (~754K tokens on 1M
window), this inflated safeOutputBudget to 1, sending max_tokens: 1
to the API — models generated exactly 1 token then stopped.

Fix:
- Replace words * 1.15 with charEstimate-based heuristic using
  OpenAI standard 1 token ~ 4 characters + 10% code buffer + CJK
- Add MIN_OUTPUT_BUDGET = 4096 safety net to prevent collapse

Closes #83
@ltmoerdani ltmoerdani mentioned this pull request Jul 24, 2026
@ltmoerdani
ltmoerdani merged commit fb34314 into main Jul 24, 2026
2 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG]

1 participant