Skip to content

feat: fall back to other models on overload, outage or refusal - #126

Merged
gopaljigaur merged 4 commits into
mainfrom
feat/model-fallback
Oct 15, 2026
Merged

gopaljigaur merged 4 commits into
mainfrom
feat/model-fallback

Conversation

@gopaljigaur

@gopaljigaur gopaljigaur commented Oct 15, 2026 •

Copy link
Copy Markdown
Owner

What changed

  • AgentConfig.fallback_models: List[str]. When a step's completion fails, the next model in the list gets it. A switch happens when:
  • Each model's request is built by _completion_kwargs with a copy of the config set to that model, so feat!: turn prompt caching on by default with a time to live option #101 caching markers, feat(core): typed reasoning_effort and thinking_budget options #106 reasoning options and structured output are gated per model. Each model gets its own retries.
  • A new ModelFallback event carries model, fallback_model, and the error it raised; for a refusal, usage holds the refused completion's usage, which is counted in the run because the provider bills it.
  • StepFinished.model names the model that answered. That step's usage and cost come from that model's response, which LiteLLM prices by its own model. In telemetry every attempt is a chat span: a failed one ends with an error, a refused one ends through on_llm_end, and the answering one's gen_ai.response.model names the model.
  • Streaming: a model falls back only while none of its text or reasoning has been emitted, the same rule the retries follow. After that, its error or refusal stands.
  • Images a tool returns stay in its tool message only when every model in the chain takes them there, since all models share the history. The tool mode follows model, which the docs say.
  • A refusal whose usage reaches max_total_tokens or max_cost ends the run with stop_reason="budget" before the next model is called.
  • fallback_models together with router is rejected. A Router has its own fallbacks and content_policy_fallbacks.
  • Most of the logic is in the new cyclops/core/fallback.py. In run.py, feat: retry a completion that overflows the context window #120's _complete stays the overflow loop and calls _complete_with_fallbacks inside it: a lowered max_tokens goes on every model's request, and the context window follows model. The compaction summary does not fall back; the docs say so. completion.py types the stream's run as a small _Output protocol, so the fallback can see whether a stream emitted anything.

Decisions

  • LiteLLM's fallback is not used. In 1.105.1, litellm.acompletion(fallbacks=[...]) (litellm_core_utils/fallback_utils.py) has these problems:

    • it moves to the next model on every exception, including auth errors, bad requests and the UnsupportedParamsError that tool-mode detection relies on;
    • once all models fail it raises a plain Exception with only the last message, which loses the type and status code;
    • it never looks at a refusal response;
    • for streams it only covers opening the stream;
    • it reports the switch only through the x-litellm-attempted-fallbacks hidden header.

    context_window_fallbacks and content_policy_fallbacks are read only by the Router. So the switch lives in cyclops, as a loop over per-model requests on top of the existing retry functions.

  • Per call, not sticky. Every step starts with the configured model again. LiteLLM's fallbacks, Pydantic AI's FallbackModel and a hosted model router's models provider option all start each request with the first model. The OpenAI Agents SDK has no built-in fallback. With per-call switching, a run goes back to the primary model once it recovers, and there is no hidden state. The cost is the primary's retries on each step while it is down. The docs say to lower num_retries to switch sooner.

  • Refusal fallback in streams happens only when nothing has been emitted, matching Pydantic AI, whose response-based fallback works only for non-streamed requests.

  • RunResult.model stays the configured model; StepFinished.model gives the model per step.

Tests

tests/test_fallback.py covers:

  • each trigger: overload after retries, spent quota, content policy error, refusal;
  • errors that do not switch;
  • the last model's error and refusal standing;
  • the event;
  • refused usage being counted;
  • cost and StepFinished.model attribution;
  • per-step restart;
  • per-model capability gating (reasoning, caching markers and response_format);
  • tool images gated on the whole chain;
  • a refusal past the budget;
  • a cancel during a fallback attempt;
  • an overflow during a fallback;
  • streaming before and after output;
  • no fallback configured;
  • telemetry spans;
  • the router conflict.

uv run pytest (570 passed), uv run pre-commit run --all-files and uv run mypy cyclops all pass.

Docs: docs/guide/agents.md (new "Fallback models" section and config row), docs/guide/streaming.md, docs/guide/tools.md, docs/api-reference.md, and the matching website pages.

Closes #70

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Findings:

  1. Tool message images are gated on model only, so a fallback to a model that takes no images in tool messages gets a 400 and the run fails (verified with a mocked run).
  2. A refused completion's usage is counted, but the budget is not checked before the next model is called.
  3. Conflicts with #120 in run.py and docs; a resolution is suggested inline.
  4. The docs and PR body overstate one LiteLLM limitation (dict fallbacks can override arguments) and credit an option of Vercel's hosted router to the AI SDK. The decision not to use LiteLLM's fallbacks still holds.
  5. Missing tests for cancellation during a fallback attempt and for per-model response_format gating.

Checked and fine: origin/main is an ancestor of the head; pytest (518 passed), pre-commit and mypy pass locally; CI is green; the confidentiality grep and the dash check are clean over title, body, commit, added lines and comments. Per-model reasoning (mutual exclusion and per-parameter gates), caching markers and response_format are built per model; deferred tools rebuild every model's request only when the loaded tools change, and model_copy is shallow, so the per-model copy is cheap. Cost comes from the answering response, refusals call on_llm_end, failed attempts end their chat span with an error, a refusal on the last model ends with stop_reason="content_filter", and a streamed error or refusal after output stands. _Watched and _Output are small and needed: _streamed_completion keeps its emitted flag local, and a refusal after output has to be told apart from one before it.

Conventions: fallback_models matches Pydantic AI's FallbackModel and LiteLLM's fallbacks naming closely enough, and per call is what Pydantic AI and Vercel's hosted router do. Falling back on content_filter by default goes further than both (Pydantic AI needs a response handler for it and Vercel's router reacts to failures only), but #70 asks for it and the docs say it, so I'd keep it.

Comment thread cyclops/core/fallback.py Resolved
Comment thread cyclops/core/fallback.py Resolved
Comment thread cyclops/core/run.py Resolved
Comment thread docs/guide/agents.md Resolved
Comment thread tests/test_fallback.py Resolved
AgentConfig.fallback_models lists models a step's completion goes to in
order when the model is still overloaded or unavailable after its
retries, has spent its quota, is blocked by a content policy or refuses
(finish_reason content_filter). Each request is built with the gates of
the model it goes to, every step starts with the configured model, and
a ModelFallback event marks each switch. StepFinished.model names the
model that answered; a refused completion's usage counts in the run.

LiteLLM's completion fallbacks are not used: they switch on every error,
raise a plain Exception once all fail, send every model the same
arguments and ignore refusals.
Images a tool returns stay in its tool message only when every model in
the chain takes them there, since all models read the same history. A
refusal that reaches the run's token or cost budget ends the run with
"budget" instead of calling the next model. Tests cover both, a cancel
during a fallback attempt and per-model response_format gating; the
docs say the tool mode follows model and correct the comparison with
LiteLLM's fallbacks.
The overflow loop now wraps the fallback chain: a lowered max_tokens
goes on every model's request, the window counts the tools of the
configured model's request, and the step reports the model that
answered. The docs say the window follows model and that the
compaction summary does not fall back.

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

One finding: the budget stop after a refusal leaves the step's steering in run.steering, so a steered message is written to the history twice (inline, with the fix).

Verified at b96e200:

  • The five round 1 fixes are in. Tool message images now need every fallback model (my probe sends the gpt-4o fallback plain text). A refusal past the budget stops with "budget" and does not call the next model. The overflow integration follows the suggested shape. The docs and PR body no longer make the two inaccurate claims. There are new tests for a cancel during a fallback attempt and for per-model response_format.
  • Overflow integration: max_tokens is computed against the configured model's window from requests[0], then applied to every request. A ContextWindowExceededError has status 400, so _falls_back re-raises it to the remedies in _complete, and the retry starts again with model.
  • test_an_overflow_lowers_max_tokens_for_every_model pins the order [tiny, FALLBACK, tiny, FALLBACK] and the same lowered max_tokens on both retried requests, below the window's output limit. It fails if the override goes to the first request only.
  • The summary call not falling back is reasonable. _summarize sizes its prompt to the summarizing model's own window, so falling back would mean a window and a trim per model. The docs name Compaction.model as the way through an outage.
  • --is-ancestor with origin/main holds. pytest (570 passed), pre-commit and mypy pass, and CI is green. The confidentiality grep is clean over the title, body, commits, added lines and comments. The dash check only matches nested markdown list markers in the PR body.

Comment thread cyclops/core/run.py Resolved

@gopaljigaur gopaljigaur left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No findings.

@gopaljigaur
gopaljigaur merged commit 4c248a8 into main Oct 15, 2026
13 checks passed
@gopaljigaur
gopaljigaur deleted the feat/model-fallback branch October 15, 2026 06:18
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.

Model fallback without a Router

1 participant