Skip to content

feat: accept a caller-supplied input token count (#136) - #161

Merged
stackbilt-admin merged 4 commits into
mainfrom
feat/136-input-token-count
Nov 10, 2026
Merged

stackbilt-admin merged 4 commits into
mainfrom
feat/136-input-token-count

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

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 as CONTEXT_WINDOW);
    • getRoutingInfo().estimatedInputTokens, and getGatewayRoutePlan() (its estimatedInputTokens and the context-length warning);
    • pre-call cost estimates: each provider's estimateCost (OpenAI, Anthropic, Cloudflare, Cerebras, Groq, NVIDIA, through a shared BaseProvider helper). That is the estimatedCost the factory passes to quotaHook.check, and the fallback cost of a stream that reports no usage. CostTracker.calculateRequestCost uses it too.
  • CanonicalLLMRequest.inputTokenCount, mapped both ways by normalizeLLMRequest / canonicalToLLMRequest, so route plans don't drop it. It's set only when present, so existing canonical requests keep their shape.
  • Not sent to providers. Provider-reported usage is unchanged. Where the package has to estimate usage because the provider reported none, it uses the count: a Workers AI response or stream without usage reports it as inputTokens and 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 prices maxTokens or 1000 tokens, the recorded estimate the response.)
  • Model selection is unchanged: the use case (including LONG_CONTEXT) and default models still come from message length and maxTokens. 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.
  • One count for the whole chain: the same count is used for every provider the request may be routed or fall back to, although tokenizers differ; the docs say to use the largest count you have.
  • classify adds an estimate of the system prompt it supplies (which can hold the whole JSON schema) to the caller's count.
  • Validation: a set value that isn't a positive safe integer throws ConfigurationError:
    • from the factory on entry (generateResponse, generateResponseStream, generateManagedResponseStream, generateResponseWithTools, classify, getRoutingInfo), before the response cache or any provider is called;
    • from a provider called directly, on generateResponse and streamResponse (BaseProvider.validateRequest).
      LLMProviderFactory.getRecommendedModel ignores 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.inputTokenCount documents this.
  • Tool loop: generateResponseWithTools sends 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 pass Number.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.
  • The response cache key already hashes the whole request, so the count is part of the key. That is intended, since with contextWindowRouting it can change which provider serves the request.

Tests

New src/__tests__/input-token-count.test.ts (61 tests):

  • the estimate override; model selection unchanged by the count; invalid values ignored by catalog helpers, getRoutingInfo, getGatewayRoutePlan, CostTracker and provider estimateCost; route plans from legacy and canonical requests;
  • estimateCost on all six providers, and the count-based estimatedCost reaching quotaHook.check;
  • estimated usage: a Workers AI response and stream without usage, and a provider stream with no usage at all;
  • context-window skips driven by the count in both directions;
  • the count absent from the request body of all six providers;
  • rejection of 8 invalid values by the factory before any call or cache read, and by all six providers on generateResponse and streamResponse;
  • the tool loop's count plus appended-message estimate, no count when none was set, and the safe-integer overflow guard;
  • 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-import and git diff --check pass.
  • Docs: README (context windows section), CHANGELOG (Unreleased) and the checkpoint doc.
  • No live or billable requests.

Review follow-up

After the first adversarial review: the count now reaches provider estimateCost and so the quota hook (the docs had claimed pre-call cost estimates, but only the unused CostTracker helper read it); later tool-loop calls keep the count; more invalid-value tests; the estimateRequestInputTokens JSDoc 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; classify counts 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 estimateRequestInputTokens returns 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

kovermier and others added 4 commits November 9, 2026 19:14
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]>
@stackbilt-admin
stackbilt-admin merged commit d782dcc into main Nov 10, 2026
4 checks passed
@stackbilt-admin
stackbilt-admin deleted the feat/136-input-token-count branch November 10, 2026 02:22
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.

2 participants