Repository navigation
feat: check pinned models against their context window (#136) - #163
Merged
Merged
Conversation
New opt-in factory option, contextWindowPinCheck. A pinned catalog model whose window can't hold the request's input (inputTokenCount, else the estimate) is never called: with allowFallback: false the request throws the new ContextWindowExceededError (a NoRouteError with the model, window and token count), otherwise the pinned provider is skipped as CONTEXT_WINDOW and the request falls back as usual. Models outside the catalog and unpinned requests aren't checked. The option is part of the response cache key when on. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A caller's fallback rule brings a pin-check-skipped provider back only
with a different fallbackModel, so the pinned model is never called.
- When no other provider is left in the plan (one provider configured,
or reasoning.strict or an image request removed the rest), the request
throws ContextWindowExceededError instead of an untyped dead end. The
error gains `reason` ('allowFallback-false' | 'no-other-provider').
- inputTokensSource gains 'mixed' for a caller count plus the package's
estimate (tool-loop turns, classify's system prompt), tracked in a
WeakSet so response cache keys are unaffected.
- Tests for the tool loop, classify, fallback rules, strict reasoning,
images, model-ID correction and caching; README and CHANGELOG updated.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…136) - The fallback-rule guard compares the rule's fallbackModel after model-ID correction, so an outdated ID can't bring the pin back. - When the pin is skipped and every other provider is unavailable, the response and streaming paths and getRoutingInfo throw ContextWindowExceededError (reason 'no-other-provider'). - Built-in fallback rules leave a skipped pin's plan untouched. - The streaming path's request copy keeps the partly-estimated mark. - README notes that a rule's different model is sent unchecked; docs and the sweep checkpoint updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reviews found that a pin skip could still hand the oversized input to a
smaller, unpinned model: when no other planned model fit, or when the
provider that fit was unavailable. Now, when contextWindowPinCheck skips
the pin, every other provider whose planned model can't hold the input
is skipped too, with or without contextWindowRouting, and the request
throws ContextWindowExceededError ('no-other-provider') when no
provider that fits can be called.
Docs cover the tool-loop fallback, fallback-rule exceptions, analyzeImage,
the corrected model ID, and the 503/429 trade-off. Tests cover no
fitting fallback, an unavailable fitting provider (quota, circuit,
ledger), chain order and the tool-loop fallback.
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.
Part of #136 (long-context slice: checking pinned models against their context window).
What
New opt-in factory option,
contextWindowPinCheck(off by default). It checks a pinned catalog model (request.model) against its context window before any call, using the caller'sinputTokenCountwhen set, else the estimate.ContextWindowExceededError, and no call is made. That happens withallowFallback: false, and when no other provider with a planned model that holds the input can be called: one provider configured;reasoning.strictor an image request removed the rest; the others' planned models are too small too; or every provider that fits is unavailable (quota-exhausted, circuit open, ledger-limited). The error carriesmodelProvider,model,contextWindow,inputTokens,inputTokensSource('caller','mixed'or'estimate') andreason('allowFallback-false'or'no-other-provider'). Its message never includes the prompt.CONTEXT_WINDOWinfallback.failedAttempts, and so is every other provider whose planned model can't hold the input, with or withoutcontextWindowRouting. The request goes only to providers that fit; if that provider then fails (for example 503 or 429), its error is thrown rather than falling through to a smaller model. A caller'sfallbackRulesentry brings the provider back only when it names a differentfallbackModel(compared after model-ID correction), so the pinned model is never called. That different model is sent unchecked.'mixed'counts: yourinputTokenCountplus the package's estimate of what it added (tool-loop turns, or the system promptclassifysupplies). The mark is kept outside the request, in a WeakSet, so response cache keys aren't affected.generateResponseWithTools(with fallback allowed, a turn that outgrows the pin moves to another provider partway through the loop),classify,analyzeImage, and the clientgetRoutingInfo. The option is part of the response cache key when on, so default keys don't change.This covers the campaign-continuity need in #136 that "a request whose input estimate … passes the window fails before the call, with a typed error", for pinned models.
Design choices
contextWindowRoutingnever skips a pinned model ("its provider decides"), so changing that option wouldn't be additive.ContextWindowExceededErrorextendsNoRouteErrorand keeps codeNO_ROUTE. Code that already handles theallowFallback: falserouting failures keeps working, and the new class adds structured details.maxTokens: the same rule ascontextWindowRouting, because providers differ on whether the requested output must also fit. Output limits are the remaining Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136 slice.inputTokenCount, the check uses the characters ÷ 4 estimate, so a pin near the edge of its window could be rejected although it would fit. The README says to passinputTokenCountwhen that matters.Review fixes (after the first adversarial review)
fallbackModel.ALL_PROVIDERS_FAILED. It now throwsContextWindowExceededErrorwithreason: 'no-other-provider', which covers the Workers-AI-only case in Requirements from campaign-continuity: what a Workers-AI-only, governed app needs from llm-providers #136.inputTokensSourcesaid'caller'for tool-loop andclassifycounts that are partly estimated. These are now'mixed', and the mark carries over when an outdated model ID is corrected.classify, fallback rules with and without a different model,reasoning.strict, image requests, model-ID correction, and caching for marked requests.getRoutingInfotext, and the pin-check section (dead ends, fallback rules,'mixed', tool loops stopping after earlier tools have run). The debug log wording and the sweep checkpoint are also fixed.LLMProviders.fromEnv()still can't set this option,contextWindowRoutingorcontextWindowModelSwitch. That's left for the existingfromEnvcleanup.Review fixes (after the second adversarial review)
ALL_PROVIDERS_FAILED(or a plainNoRouteErrorfromgetRoutingInfo). The response and streaming paths andgetRoutingInfonow throwContextWindowExceededErrorwithreason: 'no-other-provider'.ContextWindowExceededErrorextendsNoRouteError(and soConfigurationError), for compatibility with existingNoRouteErrorhandling.Review fixes (after the third review and two narrow re-checks)
ContextWindowExceededError('no-other-provider'). The last narrow re-check confirmed this on all three paths, with routing on and off and with exhausted, circuit-open and ledger-limited fitting providers, and found no remaining route except a caller's ownfallbackRules(documented). Its verdict was LGTM.analyzeImageandclassifyare covered; thecontextWindowRoutingfallback-rule exception; the error'smodelis the corrected ID;quotaHookdenials stayQuotaDeniedError.Files
src/errors.ts,src/index.ts:ContextWindowExceededError, exported.src/utils/input-token-count.ts(internal): the partly-estimated mark.src/factory.ts: the option, a planner block after the context-window skips and before theallowFallback: falsetrim, the fallback-rule guard, the tool-loop andclassifymarks, and a cache-key entry.src/__tests__/context-window-pin-check.test.ts(new, 38 tests). Disabling the rejection, either no-other-provider throw, the skip, the fallback-rule guard (including ID correction and built-in rules), the partly-estimated marks, the cache-key entry or the exact-window boundary each makes tests fail, as does dropping the fitting-model check or the extra skips. Tests cover no fitting fallback, an unavailable fitting provider (quota, circuit, ledger), chain order and the tool-loop fallback.allowFallbacksection), CHANGELOG[Unreleased], and the sweep checkpoint.Validation
npm run typecheck,npm test(1,112 passing across 37 files),npm run build,bash scripts/package-smoke.sh,npm run test:worker-import,git diff --check: all passed. No live or billable requests were made.🤖 Generated with Claude Code