Repository navigation
feat: route around models whose context window can't hold the input - #147
Merged
Merged
Conversation
The factory now skips providers whose planned model's context window is smaller than the request's estimated input (message and system-prompt characters / 4), on the response and streaming paths, and throws NoRouteError before any call when no configured provider's model can hold it. Such requests used to be sent anyway and failed with an error that doesn't fall back. Pinned models and fallback rules that name a fallbackModel are still tried; a rule without a model skips a provider whose planned model can't hold the input. Catalog ranking prefers models that can hold the input and keeps its usual ranking when none can, so the catalog helpers still never throw. Only the input is checked, not maxTokens. No public API is added. Part of #113 and #136. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Skip unfitting providers only when some planned model can hold the estimate; when none can, routing is unchanged. This removes the new pre-call NoRouteError, so an overcounted estimate can't refuse a request that works today, and keeps getGatewayRoutePlan consistent with dispatch. - Count tool-call arguments, tool results and errors, and provider-native text (thinking) in the estimate, so tool loops are covered. - Count non-string content as zero, so the catalog helpers can't throw. - Run the check after the strict-reasoning filter and before allowFallback: false trims the chain. - Drop the redundant fallback-rule clause; document preferredProvider and allowFallback: false behaviour; fix README/CHANGELOG wording. - Tests: tool loop (including generateResponseWithTools), preferredProvider, allowFallback: false without a pin, managed stream, strict reasoning, malformed content, getRecommendedModel / getProviderDefaultModel. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Second review round on #147: - Decide whether a hop fits using only providers that can be tried now (configured, not quota-exhausted, circuit-open or ledger-limited), so a fitting provider that is down no longer drops the smaller ones. - rankModels drops open-breaker models before narrowing to fitting ones, so it can't return [] (and getRecommendedModel can't throw) when healthy compatible models exist. - Restore the fallback-rule guard, applied only while an available hop fits, so rules behave as before when nothing fits. - Count malformed messages, toolCalls, toolResults and providerContent blocks as zero instead of throwing; count every provider-native block kind (text, thinking, redacted thinking, tool-use input). - Use-case inference counts message text only, as before. - Remove the stale rankModels comment; README and CHANGELOG describe the availability rule and the higher estimatedInputTokens for tool loops. - Tests: exhausted and open-breaker fitting provider, open-breaker ranking, three-provider rule when nothing fits, malformed containers, block kinds, inference, image requests. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Third review round on #147, simplifying the design (option A): - Catalog ranking is back to main's code: rankModels, getRoutingInfo, getProviderDefaultModel and getRecommendedModel are unchanged. - The factory computes the estimate once per plan and only removes providers whose planned model can't hold it, when a provider that can be relied on now (not exhausted or ledger-limited, breaker fully closed, whatever enableCircuitBreaker says) has a fitting model. Providers are never reordered or re-planned, so routing is unchanged otherwise. - Fallback rules behave exactly as on main. - The estimate no longer serialises tool-use input (the same data is in toolCalls arguments) and leaves out encrypted redacted thinking; a 200-turn loop plans in about 0.13 ms (main 0.05 ms). - Validated with a 14,000-case planning probe against a main worktree: same planned models everywhere, chains identical or main's chain minus non-fitting providers (only when an available provider fits), small requests identical, allowFallback: false picks the first provider of the full chain. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fourth review round on #147: - Instead of removing providers from the chain at planning, record them in the plan and skip them at dispatch with errorCode CONTEXT_WINDOW, so the skip shows in fallback.failedAttempts and requestedProvider is the real first planned provider. The chain is now always main's chain. - allowFallback: false without a pin: a skipped first provider throws NoRouteError (as for other skips) rather than substituting another. - A provider that a fallback rule targets is tried as before. - New factory option contextWindowRouting (default true); false routes without the check. - Planning has no side effects: breaker state is read without creating a breaker, and the ledger check doesn't log. - Tests: skip record on response and stream, NoRouteError, the switch, degraded and recovering breakers, ledger-limited provider without planning logs, no breaker creation. README and CHANGELOG describe the transient-failure trade-off and the switch. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Fifth review round on #147. Under the default config an overflow error already falls back through the built-in catch-all `error` rule, so the check's real benefit is saving one failed (possibly billed) call, while it costs recovery from a transient failure of the fitting provider. That doesn't justify a default-on behaviour change: - contextWindowRouting is now off by default; with it unset or false, dispatch matches main. - Only the caller's own fallbackRules override a skip; the built-in defaults (including the catch-all) don't. - The option is part of the response cache key when on; default keys are unchanged. - The CONTEXT_WINDOW check runs after the exhausted, breaker and ledger checks on both paths, so existing skip codes keep priority; skips log at debug level. - Docs rewritten around the real benefit and trade-off; CHANGELOG lists the option under Added. - Tests: default-off (unset and false), built-in rules, skip-code order, cache key, no logger calls while planning. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sixth review of #147: - A caller's own fallback rule targeting a provider that was skipped as CONTEXT_WINDOW earlier in the chain now queues it right after the failed provider (at most once), instead of never trying it. - fallbackRules: null keeps the built-in rules and is no longer treated as caller-supplied. - README: separate the pinned-provider and CONTEXT_WINDOW cases in the allowFallback paragraph. - CHANGELOG: narrow the malformed-input claim; non-array messages or a null message still throw in catalog getRoutingInfo, as before. - Tests for the above and for updateConfig toggles. Co-Authored-By: Claude Opus 5.5 <[email protected]>
stackbilt-admin
pushed a commit
to mikemikimike/llm-providers
that referenced
this pull request
Nov 9, 2026
Resolve the CHANGELOG conflict with 1.26.0 and Stackbilt-dev#147, describe the timeout behaviour without naming a release (it ships in the next one), and restore the blank line before ## [1.24.1]. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This was referenced Nov 9, 2026
Merged
stackbilt-admin
added a commit
that referenced
this pull request
Nov 9, 2026
* chore: release 1.27.0 - Opt-in context-window routing and a better input estimate (#147) - Workers AI non-streaming binding timeout (#132) - Checkpoint and README version references updated Co-Authored-By: Claude Opus 5.5 <[email protected]> * docs: 1.27.0 upgrade note for the Workers AI timeout and review fixes Co-Authored-By: Claude Opus 5.5 <[email protected]> --------- Co-authored-by: Kurt Overmier <[email protected]> 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
First slice of the long-context work on #136 (and the "long context checked through fallback" item on #113). It adds opt-in context-window routing,
contextWindowRouting: true, and a better input estimate.Correction to the earlier premise. The #136 audit said an overflow error "doesn't fall back, so the request fails". Under the default config that is wrong. The built-in fallback rules include a catch-all
errorrule, so an overflow already falls back to the next provider. The overflow only ends the request withfallbackRules: []. The real cost of sending an oversized request is one failed call, which may be billed or rate-limited.Saving that call also means a skipped provider can't absorb a transient failure of the provider that fits. That is a fair trade for some callers, but not a reason to change behaviour by default. So the check is off unless you turn it on.
With
contextWindowRouting: truebuildProviderPlancomputes the estimate once. If a provider that can be relied on right now has a planned model whosemaxContextLengthholds the estimate, the providers whose planned model can't hold it are marked to be skipped.errorCode: 'CONTEXT_WINDOW'infallback.failedAttempts, on the response and onStreamCompletion. This check runs after the exhausted, breaker and ledger checks, so those skip codes keep priority.main. A 14,000-casebuildProviderPlanprobe againstmainfound the same chain and models in every case.generateResponse, each turn ofgenerateResponseWithTools,generateManagedResponseStreamandgenerateResponseStream. The clientgetRoutingInforeports the first provider that wouldn't be skipped.fallbackRulestargets is tried as usual, including one skipped earlier in the chain, which is queued right after the provider that failed (at most once). The built-in default rules don't override a skip.allowFallback: falsewithout a pin: a skipped first provider throwsNoRouteErrornamingCONTEXT_WINDOW. No other provider is substituted.Without it (default)
Dispatch is the same as on
main. Tests check that leaving the option unset or setting it tofalseskips nothing and falls back as before. Planning creates no breakers and calls no logger.The estimate (always on)
main).RoutingInfo.estimatedInputTokensand the gateway context-length warning are now higher for tool-loop requests. Use-case inference still counts message text only, and no longer throws on malformed fields.Validation
npm run typecheck,npm test(946 tests),npm run build,npm run test:package,npm run test:worker-importandgit diff --checkall pass.mainworktree: 14,000buildProviderPlancases with identical chain and planned models. The cases covered:preferredProviderandenableCircuitBreakervariants;allowFallback: false, pinned andmaxTokensrequests;falsekeeps the default key;Tests
src/__tests__/context-window-routing.test.tshas 41 tests:false).generateResponseWithTools.enableCircuitBreaker), degraded, recovering and ledger-limited providers; three providers with nothing skipped.preferredProvider;allowFallback: false, which throwsNoRouteError;fallbackRules: null;fallbackRules, throughupdateConfig.API
contextWindowRouting?: booleanonProviderFactoryConfig. It is off by default, documented and tested.estimateRequestInputTokensandfitsContextWindoware internal tomodel-catalog.ts.[Unreleased]section has Added (the option) and Changed (the estimate).Not in this PR (later slices on #136)
maxOutputTokens, and the Workers AI default of 256 output tokens.🤖 Generated with Claude Code