Repository navigation
fix(aikit): leave room for OpenRouter's input overcount when clamping max tokens - #137
Merged
Merged
Conversation
… max tokens
OpenRouter checks input + max_tokens against the context window before
routing, using its own tokenizer, which can count several percent more
input than our estimate. With only 4096 tokens spare, models whose output
limit spans the window were rejected with a 400 ("This endpoint's maximum
context length is ...") at around 10% of the window.
The output ceiling now leaves 15% of the estimated input unused (at least
4096). When that would leave less than 32768 tokens of output, only the
fixed 4096 margin is kept and output is capped at 32768.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
OpenRouter rejected a request at ~10% of a 1M window:
The model's catalog output limit spans the whole window, so
clampMaxTokensToContextsizedmax_tokensaswindow − estimated input − 4096. aikit estimated the input at 100,762 tokens. OpenRouter counts with its own tokenizer before routing and got 105,153, about 4.4k more than the 4096-token margin, so the request went 295 tokens over the window.Fix
The margin now scales with the input, matching Pi's fix for the same OpenRouter behaviour:
For the failing request, the ceiling becomes 932,699, and 105,153 + 932,699 fits in the window. Small windows behave as before.
Workaround until this ships: cap the model in
settings.jsoncwith"stealth/crouton-alpha": { "maxTokens": 8192 }.Tests
packages/aikit/test/maxtokens.test.tsadds Pi's clamp cases, including the failing request above.vp checkandvp run typecheckpass.🤖 Generated with Claude Code