Repository navigation
feat: accept a caller-supplied input token count (#136) - #161
Merged
Merged
Conversation
LLMRequest.inputTokenCount (and CanonicalLLMRequest.inputTokenCount) replaces the characters / 4 estimate for context-window routing, routing info, gateway route plans, recommendations and pre-call cost estimates. It is validated on entry, never sent to a provider, and used only for the first call of a tool loop. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ool-loop calls Provider estimateCost (and so quotaHook.check and the stream fallback cost) now prices LLMRequest.inputTokenCount. Tool-loop calls after the first send the count plus an estimate of the appended messages. Adds invalid-value tests for route plans and cost estimates and documents canonical copying. Co-Authored-By: Claude Opus 5.5 <[email protected]>
… tool-loop overflow Workers AI responses and streams without usage, and streams with no usage at all, now estimate input from LLMRequest.inputTokenCount, so the recorded cost matches the quota check. classify adds an estimate of the system prompt it supplies. The tool loop drops a count that would pass the safe-integer range. Docs name the methods that throw and say one count serves the whole fallback chain. Tests cover all six providers. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Removes the claim that inputTokenCount feeds model recommendations and adds a test that it doesn't. Notes in the CHANGELOG that estimateRequestInputTokens returns the count, says positive safe integer in the canonical JSDoc, and limits the Workers AI cost comment to input. Co-Authored-By: Claude Opus 5.5 <[email protected]>
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.
Summary
Part of #136 (long-context work, with #113). Callers that already know a request's input token count, for example from the target model's tokenizer, can now pass it as
inputTokenCount. It replaces the package's characters ÷ 4 estimate, which is coarse near a 1M window and for non-Latin text.What changes
LLMRequest.inputTokenCount(optional, additive). When it's a positive integer, it is used instead of the estimate for:contextWindowRouting(which providers are skipped asCONTEXT_WINDOW);getRoutingInfo().estimatedInputTokens, andgetGatewayRoutePlan()(itsestimatedInputTokensand the context-length warning);estimateCost(OpenAI, Anthropic, Cloudflare, Cerebras, Groq, NVIDIA, through a sharedBaseProviderhelper). That is theestimatedCostthe factory passes toquotaHook.check, and the fallback cost of a stream that reports no usage.CostTracker.calculateRequestCostuses it too.CanonicalLLMRequest.inputTokenCount, mapped both ways bynormalizeLLMRequest/canonicalToLLMRequest, so route plans don't drop it. It's set only when present, so existing canonical requests keep their shape.inputTokensand prices it, and a stream with no usage at all reports it alongside the pre-call cost. So the input side of the cost the quota hook checks and the cost it records agree. (The output side still differs, as before: the pre-call estimate pricesmaxTokensor 1000 tokens, the recorded estimate the response.)LONG_CONTEXT) and default models still come from message length andmaxTokens. Choosing models from the count belongs with the open Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136 item on switching a provider to a larger model of its own.estimateRequestInputTokens(public) returns the count when it's valid; the CHANGELOG says so.classifyadds an estimate of the system prompt it supplies (which can hold the whole JSON schema) to the caller's count.ConfigurationError:generateResponse,generateResponseStream,generateManagedResponseStream,generateResponseWithTools,classify,getRoutingInfo), before the response cache or any provider is called;generateResponseandstreamResponse(BaseProvider.validateRequest).LLMProviderFactory.getRecommendedModelignores a bad value, like the catalog helpers.Catalog helpers, route plans and cost estimates ignore a bad value and use the estimate, matching how they already treat malformed input (they never throw). Canonical conversion copies the value as-is;
CanonicalLLMRequest.inputTokenCountdocuments this.generateResponseWithToolssends the caller's count on its first call. Later calls send the count plus an estimate of only the messages the loop has appended (assistant turns and tool results), so long non-Latin input isn't re-estimated at characters ÷ 4. If the sum would passNumber.MAX_SAFE_INTEGER, the count is dropped for that call instead of throwing after earlier calls were billed. The caller's request object isn't mutated.contextWindowRoutingit can change which provider serves the request.Tests
New
src/__tests__/input-token-count.test.ts(61 tests):getRoutingInfo,getGatewayRoutePlan,CostTrackerand providerestimateCost; route plans from legacy and canonical requests;estimateCoston all six providers, and the count-basedestimatedCostreachingquotaHook.check;generateResponseandstreamResponse;classify: the injected system prompt added to the count, the caller's own prompt kept, string input untouched, and invalid values rejected before any call.Validation
npm run typecheck,npm test(1038 passing across 35 files),npm run build,bash scripts/package-smoke.sh,npm run test:worker-importandgit diff --checkpass.Review follow-up
After the first adversarial review: the count now reaches provider
estimateCostand so the quota hook (the docs had claimed pre-call cost estimates, but only the unusedCostTrackerhelper read it); later tool-loop calls keep the count; more invalid-value tests; theestimateRequestInputTokensJSDoc no longer says tools aren't counted; canonical copying is documented.After the second review: Workers AI and stream usage estimates use the count, so recorded cost matches the checked cost;
classifycounts the system prompt it injects; the tool loop drops a count that would overflow; the docs name the methods that throw, say "positive safe integer" and explain that one count serves the whole fallback chain; and rejection and body-exclusion tests now cover all six providers.After the third review: the docs no longer claim the count changes model recommendations (a test now asserts it doesn't), the canonical JSDoc says "positive safe integer", the Workers AI cost comment is limited to the input side, and the CHANGELOG notes that
estimateRequestInputTokensreturns the count.Still open on #136
Switching a provider to a larger model of its own, overflow fallback for pinned models, and output limits (including Workers AI's 256-token default).
🤖 Generated with Claude Code