GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — feat(opencode): add LLM provider fallback chain by j3k0 · Pull Request #26292 · anomalyco/opencode

Conversation

@j3k0

@j3k0 j3k0 commented May 8, 2026 •
edited
Loading

Uh oh!

There was an error while loading. Please reload this page.

Copy link
Copy Markdown

Issue for this PR

Closes #7602

Type of change

  • Bug fix
  • New feature
  • Refactor / code improvement
  • Documentation

What does this PR do?

Adds a configurable fallback chain so that when a provider returns a transient error (rate limit, overload, 5xx), OpenCode automatically retries on the next model in the chain instead of failing the session.

{
  "model": "anthropic/claude-sonnet-4-20250514",
  "fallbacks": ["openai/gpt-4.1", "deepseek/deepseek-v4"],
  "cooldown_seconds": 300
}

fallbacks can be set at the top level or per-agent. cooldown_seconds defaults to 300 — after a retryable failure, that provider/model is skipped for the cooldown duration so you don't wait on retries to an overloaded provider.

Why built-in instead of a proxy: cheaper providers are unreliable, and routing through LiteLLM degrades tool-call quality. When a provider gets overloaded, falling through immediately is faster than retrying the same one.

Design

Data flow

User sends message
       │
       ▼
  LLM.run(input)
       │
       ▼
  pickStart(primary, fallbacks, cooldown)
       │
       ├─ primary available → call primary
       │
       └─ primary on cooldown → find first available fallback
                                 │
                                 └─ all on cooldown → pick soonest expiry
       │
       ▼
  streamText() → Effect Stream
       │
       ├── success → Stream ends normally. Clear cooldown on the winning provider.
       │
       └── retryable error → CooldownManager.put(failed, duration)
                              │
                              ▼
              chainFallback → try next in chain
                              │
                              ├── success → prepend notice event, continue stream
                              │
                              └── error → chain next fallback (or fail)

Cooldown durations

Trigger Duration Source
Rate limit / 5xx / overload cooldown_seconds (default 300) Config
Quota limit (weekly/monthly) 6 hours Hardcoded
Provider sends retry-after header Parsed value Provider response

On success, the winning provider's cooldown is cleared so it's immediately available next request.

Key decisions

  1. Cooldown over session state — We track what's failed, not what's succeeded. No "sticky" fallback — once a provider recovers, traffic routes back naturally.

  2. Stream-level error detection — Providers can return HTTP 200 with an error in the stream body. We wrap fullStream to throw on { type: "error" } chunks, triggering fallback just like a connection error.

  3. Quota limits trigger fallback (6h cooldown) — A quota-limited provider is unavailable, not the session. Fallback keeps the session alive. The 6h cooldown prevents hammering a capped provider.

  4. No dedup in the chain — The same model can appear twice. After falling through once, the primary may be worth retrying with fresh context. Cooldown handles this naturally — if primary is still on cooldown, it's skipped; if it's cleared, trying it again is valid.

  5. Model attribution updates on fallback — When a fallback succeeds, usedFallback propagates back so events, logs, and billing reflect the actual provider that handled the request.

Config contract

// Top-level (applies to all agents)
{
  "model": "anthropic/claude-sonnet-4-20250514",
  "fallbacks": ["openai/gpt-4.1", "deepseek/deepseek-v4"],
  "cooldown_seconds": 300
}

// Per-agent (overrides top-level)
{
  "agents": {
    "code": {
      "model": "anthropic/claude-sonnet-4-20250514",
      "fallbacks": ["openai/gpt-4.1"]
    }
  }
}

New fields: fallbacks (array of provider/model strings), cooldown_seconds (positive int, default 300).

Not in scope

  • Per-provider cooldown configuration (use cooldown_seconds globally for now)
  • TTFT timeout thresholds (per-provider config, separate feature)
  • Admin API to inspect/clear cooldown state (runtime only, no persistence)
  • Persisted cooldown across restarts (cooldowns reset on process restart)

How did you verify your code works?

  • Unit tests for CooldownManager (put/get/clear/expiry) and config validation (fallbacks array and cooldown_seconds)
  • Integration test: stream error with fallbacks triggers fallback, stream error without fallbacks halts with error
  • Running this in production for 1 week across daily work without issues
  • bun typecheck passes for all 12 packages in the monorepo

Screenshots / recordings

N/A — no UI changes visible in screenshots (toast is a runtime notification)

Checklist

  • I have tested my changes locally
  • I have not included unrelated changes in this PR

Comparison with related PRs

Reviewed #24369, #26192, #24013, #18443, and the closed #13189:

  • vs feat(processor): add model fallback chain when retries are exhausted #24369: We have cooldown (they have none), stream error detection, and user notification. They have a resolveFallbackChain utility — minor convenience we can add later.
  • vs fix(session): add fallback retry handling and harden pre-push bun path #26192: They identified the model attribution gap (events/logs/billing showing original provider instead of fallback) — now fixed in our PR. Their dedup would prevent trying the same model twice in a chain, but this can be intentional (try primary, fall through, then retry primary with fresh context). Our cooldown solves this differently.
  • vs fix(opencode): stop retrying non-transient rate limits #24013: We take the opposite approach — quota-limited providers should trigger fallback (the next provider may not be quota-limited), but we put them on a 6h cooldown instead of the default 5min. This way the session doesn't fail just because one provider hit its monthly cap.
  • vs fix(retry): retry transient 429 responses even when provider marks non-retryable #18443: They handle 429+isRetryable=false from provider proxies. Our code already handles this via 5xx override, but the explicit 429 path would be a good future improvement.
  • vs feat: add model fallback support with TTFT-based timeout #13189 (closed, stale): They had TTFT timeout and session state tracking. Our cooldown naturally routes away from failed providers toward working ones (simpler), and TTFT is better handled per-provider in config.

Key differences in our approach:

  • Cooldown is superior to session state: remembers what's failed, not what's succeeded — no "sticky" fallback
  • Stream error detection via first-chunk peek catches 200-with-error responses
  • retry-after header parsing respects provider-suggested backoff
  • Quota limits trigger fallback with 6h cooldown: the provider is unavailable, not the session
  • No dedup by design: deliberate — allows retrying primary after falling through

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

abcdef0101, loss-and-quick, CamJW101, Serpentian, ChanGarcia10, scriptcoded, mikeatlas, jere2101, tonism, suhz, and 8 more reacted with thumbs up emoji mikeatlas and benhoIIand reacted with hooray emoji
All reactions
  • 👍 18 reactions
  • 🎉 2 reactions
@github-actions github-actions Bot added the needs:compliance This means the issue will auto-close after 2 hours. label May 8, 2026
@github-actions

github-actions Bot commented May 8, 2026

Copy link
Copy Markdown
Contributor

The following comment was made by an LLM, it may be inaccurate:

Based on the search results, I found several related PRs that address similar functionality:

Potential Related PRs

  1. PR fix(session): add fallback retry handling and harden pre-push bun path #26192 - fix(session): add fallback retry handling and harden pre-push bun path

    • Related because it adds fallback retry handling in the session layer, which is closely related to the fallback chain feature
  2. PR feat(processor): add model fallback chain when retries are exhausted #24369 - feat(processor): add model fallback chain when retries are exhausted

    • Similar feature but for the processor - implements a fallback chain mechanism when retries are exhausted
  3. PR fix(opencode): stop retrying non-transient rate limits #24013 - fix(opencode): stop retrying non-transient rate limits

    • Related to distinguishing transient errors (rate limits, 5xx) that should trigger fallbacks
  4. PR fix(retry): retry transient 429 responses even when provider marks non-retryable #18443 - fix(retry): retry transient 429 responses even when provider marks non-retryable

    • Related to handling transient 429 rate limit errors which is a key trigger for the fallback chain

These PRs address related concerns around provider fallback chains, transient error handling, and retry logic, though they appear to be separate implementations in different components. PR #26292 appears to be the consolidated, comprehensive implementation of this functionality.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot removed the needs:compliance This means the issue will auto-close after 2 hours. label May 8, 2026
@github-actions

github-actions Bot commented May 8, 2026

Copy link
Copy Markdown
Contributor

Thanks for updating your PR! It now meets our contributing guidelines. 👍

mdlmarkham reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@j3k0
j3k0 force-pushed the feat/llm-fallback branch 6 times, most recently from 9526a6b to bd85c37 Compare May 10, 2026 13:15
@j3k0 j3k0 mentioned this pull request May 10, 2026
[FEATURE]: Native Model Fallback / Failover Support #7602
Closed
@j3k0
j3k0 force-pushed the feat/llm-fallback branch 6 times, most recently from 0d07b43 to e54c5c1 Compare May 16, 2026 08:38
@loss-and-quick loss-and-quick mentioned this pull request May 16, 2026
feat(session): add configurable fallback model chain #27939
Closed
3 of 6 tasks
@j3k0

j3k0 commented May 17, 2026

Copy link
Copy Markdown
Author

Update: Added a structured Design section to this PR that covers the full data flow, cooldown duration table, key architectural decisions, config contract, and explicit scope boundaries. Goal: make it easy to validate the approach at a glance.

For anyone following #7602 — this is the most complete implementation of native fallback to date:

Feature This PR #24369 #26192 Plugin (opencode-runtime-fallback)
Cooldown with auto-recovery 5min default, 6h for quota None None 60s fixed
Stream error detection (200+error body) Yes No No No
retry-after header parsing Yes No No No
Model attribution on fallback Yes No Partial No
Quota limits trigger fallback Yes (6h cooldown) No No Yes
Notification on fallback switch Yes No No Yes
Per-agent fallback chains Yes No No Yes
Zero infra (no proxy/LiteLLM) Yes Yes Yes Yes

Running in production for 1+ week, all tests passing. Would love a review from the core team — happy to iterate on the design if there are concerns about the approach.

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

This was referenced May 17, 2026
Retry w/ different model #310
Closed
feat(processor): add model fallback chain when retries are exhausted #24369
Closed
[Feature Request] Configurable Retry Mechanism via opencode.json #3011
Closed
fix(session): add fallback retry handling and harden pre-push bun path #26192
Closed
Implement exponential back-off when hitting rate limits #1712
Closed
@j3k0
j3k0 force-pushed the feat/llm-fallback branch 3 times, most recently from 34e3b42 to a7d8ea5 Compare May 21, 2026 17:59
@j3k0
j3k0 requested a review from adamdotdevin as a code owner May 21, 2026 17:59
@j3k0
j3k0 force-pushed the feat/llm-fallback branch 2 times, most recently from 7dda3d0 to cc4902c Compare May 29, 2026 05:10
@j3k0
j3k0 force-pushed the feat/llm-fallback branch from cc4902c to 9705510 Compare May 29, 2026 08:12
@github-actions github-actions Bot mentioned this pull request May 29, 2026
feat(opencode): add LiteLLM plugin integration #29937
Closed
3 of 6 tasks
@CamJW101

CamJW101 commented Jun 4, 2026

Copy link
Copy Markdown

This is a hard +1 from me and my entire team. There are rate limits everywhere you look now. What happens when Opencode Go hits limits? You just wait it out or go manually edit the file. At least having some sort of fallback in the event of rate limits, downtime, or errors so that the work continues in unexpected circumstances is essential in production.

ChanGarcia10, teijo-alex, mdlmarkham, and Gusser93 reacted with thumbs up emoji
All reactions
  • 👍 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot mentioned this pull request Jun 5, 2026
feat(tui): add backup models array #30852
Closed
3 tasks done
@ChanGarcia10

ChanGarcia10 commented Jun 8, 2026

Copy link
Copy Markdown

This is much needed.

mdlmarkham, Akagi201, tliuyx, and Gusser93 reacted with thumbs up emoji
All reactions
  • 👍 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@j3k0
feat(session): add model fallback chain with cooldown and error class…
5339bd2
…ification
@j3k0
j3k0 force-pushed the feat/llm-fallback branch from 9705510 to 5339bd2 Compare June 8, 2026 17:39
@IMPACTAredChile

IMPACTAredChile commented Jun 13, 2026

Copy link
Copy Markdown

🙏

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@j3k0

j3k0 commented Jun 15, 2026

Copy link
Copy Markdown
Author

After a month of rebasing my PR with almost guaranteed conflicts, I gave up and switched to oh-my-pi (https://omp.sh) - it supports canonical model names with "provider order". It does the job and maybe better than opencode.

I'll keep that PR open just in case the team ever look at it. I understand they have a thousands PR now, so it's probably lost.

suhz and zcutlip reacted with heart emoji
All reactions
  • ❤️ 2 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@mdlmarkham

mdlmarkham commented Jun 19, 2026

Copy link
Copy Markdown

I'd really like to have this one...

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@suhz

suhz commented Jun 21, 2026

Copy link
Copy Markdown

+1 we need this

LuisPeregrina, manosKas, and LuminairPrime reacted with thumbs up emoji
All reactions
  • 👍 3 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@HuanLinOTO

HuanLinOTO commented Jul 1, 2026

Copy link
Copy Markdown

We need this feature!

LuisPeregrina, kyay006, manosKas, taina0407, and LuminairPrime reacted with thumbs up emoji
All reactions
  • 👍 5 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@github-actions github-actions Bot mentioned this pull request Jul 3, 2026
feat(core): implement models fallback #35188
Closed
3 of 6 tasks
@ceoro9

ceoro9 commented Jul 21, 2026

Copy link
Copy Markdown

this is outside the scope of this project. For this use case, use a dedicated proxy: https://github.com/router-for-me/CLIProxyAPI

Gusser93, debanjandhar12, CamJW101, and LuminairPrime reacted with thumbs down emoji
All reactions
  • 👎 4 reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@taina0407

taina0407 commented Jul 26, 2026

Copy link
Copy Markdown

this is outside the scope of this project. For this use case, use a dedicated proxy: https://github.com/router-for-me/CLIProxyAPI

What is the definition of project scope here? What you suggest is to use another project/tool to just fulfilling a missing feature of this project?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@bukit-kronik

bukit-kronik commented Aug 3, 2026

Copy link
Copy Markdown

much needed..

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@coderabbitai coderabbitai Bot mentioned this pull request Aug 3, 2026
fix(config): Updated opencode slim config ninjasitm/nitm-opencode-starter#3
Merged
@github-actions github-actions Bot mentioned this pull request Aug 13, 2026
feat(processor): add model fallback chain when retries are exhausted #42424
Closed
5 tasks done
@github-actions github-actions Bot mentioned this pull request Sep 15, 2026
feat(provider): configurable model fallback on transient errors and timeouts #49125
Closed
3 of 6 tasks
@xblurx

xblurx commented Sep 17, 2026

Copy link
Copy Markdown

whats stopping from merging this?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@acaliebe acaliebe mentioned this pull request Sep 18, 2026
Plugins: chat.params hook cannot override the model (only sampling params) — model-switch plugins are forced to abort+resend, which breaks one-shot opencode run callers #49712
Closed
hunterchristian added a commit to chipp-ai/opencode that referenced this pull request Sep 23, 2026
@hunterchristian @claude
feat(core): add automatic model fallback on exhausted retries
878fe22
Agents can now configure a fallback model chain (agents.<name>.fallback
in config, or the older top-level agent: format). When the selected
model fails after RequestExecutor's transport retry budget is spent
(429/5xx/529), or with a quota/transport/model-not-found failure, the
V2 session runner switches to the next untried fallback and retries
the turn -- rather than erroring the whole turn out to the user.

Ported from real, working upstream implementations rather than written
from scratch (per the standing "reuse upstream PR work" directive for
this fork): anomalyco#35188 already targeted this repo's V2
session runner (unlike anomalyco#49125/anomalyco#26292/anomalyco#27939/anomalyco#42424, which patch the
legacy V1 processor.ts our own AGENTS.md says new orchestration code
must not bridge through) and is the primary source for the config
schema shape and general approach. The retry-exhaustion classifier's
names/shape come from anomalyco#49125; its logic reuses RequestExecutor's
existing LLMError.retryable flag as the single source of truth for
"is this retryable" instead of re-deriving a second status-code list.
Model-switch attribution is recorded via the session's existing
SessionEvent.ModelSwitched event rather than mutating an in-flight
input object in place -- a lesson taken directly from anomalyco#27939's
writeup of a real bug in its own V1-era approach.

New packages/core/src/session/runner/fallback.ts (~40 lines: a
classifier + a candidate resolver) and a new ContinueAfterFallback
turn-transition in packages/core/src/session/runner/llm.ts, following
the exact pattern already used for post-compaction turn continuation.
Config plumbing threads the new field through packages/schema/src/
agent.ts, packages/core/src/config/agent.ts (+ plugin and v1 config
variants). Regenerated the client and legacy JS SDKs.

Known, honestly-scoped gaps: the switch is sticky for the rest of the
session (no cooldown/return-to-primary); no mid-stream failover once
assistant output has started; only errors marked retryable trigger a
switch, so some in-stream provider errors won't while an equivalent
HTTP status will; fallback is per-agent only, not per-model or
global; a fallback model uses its default variant; no TUI/docs yet.

New packages/core/test/session-runner-fallback.test.ts (9 tests)
exercises real RequestExecutor retry counts against a scripted fake
HTTP client -- exact call sequences, session projection correctness
(model-switched message inserted, no leaked failed assistant message,
correct final session model), chain-walking past an unresolvable
model, non-retryable failures correctly not switching, and chain
exhaustion still surfacing the real terminal error. Full packages/core
suite: 1164 pass (only the pre-existing, unrelated pty flake). bun
typecheck clean across all 30 packages.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@CamJW101

CamJW101 commented Sep 29, 2026

Copy link
Copy Markdown

this is outside the scope of this project. For this use case, use a dedicated proxy: https://github.com/router-for-me/CLIProxyAPI

The entire project is about being able to use whatever provider you want, correct? How on earth is being able to assign provider fallbacks not in scope? I'd love any sort of explanation.

LuminairPrime reacted with thumbs up emoji
All reactions
  • 👍 1 reaction

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr

thdxr commented Oct 10, 2026

Copy link
Copy Markdown
Member

This branch has been upgraded to V2. We're no longer taking PRs for V1. If you think this is still relevant, please port it over and open it for V2.

— from 𝕺𝖕𝖊𝖓𝕮𝖔𝖉𝖊

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@thdxr thdxr closed this Oct 10, 2026
@LuminairPrime LuminairPrime mentioned this pull request Oct 13, 2026
[FEATURE]: Model fallback/failover #55008
Closed
1 task done
@LuminairPrime

LuminairPrime commented Oct 13, 2026

Copy link
Copy Markdown

this is outside the scope of this project

How is handling the failure of a model in OpenCode not in OpenCode's scope?

All reactions

Sorry, something went wrong.

Uh oh!

There was an error while loading. Please reload this page.

@vicgupta vicgupta mentioned this pull request Oct 25, 2026
Survive provider outages: opt-in fallback model chain (--fallback-model, fallback_models) that switches models after retries on 429/5xx/network errors are exhausted vicgupta/tinyagent#117
Closed
18 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Reviewers

@adamdotdevin adamdotdevin Awaiting requested review from adamdotdevin

Uh oh!

There was an error while loading. Please reload this page.

Assignees

No one assigned

Labels

None yet

Projects

None yet

Milestone

No milestone

Development

Successfully merging this pull request may close these issues.

[FEATURE]: Native Model Fallback / Failover Support

Uh oh!

There was an error while loading. Please reload this page.

13 participants

@j3k0 @CamJW101 @ChanGarcia10 @IMPACTAredChile @mdlmarkham @suhz @HuanLinOTO @ceoro9 @taina0407 @bukit-kronik @xblurx @thdxr @LuminairPrime
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.
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.