Repository navigation
feat: fall back to other models on overload, outage or refusal - #126
Conversation
gopaljigaur
left a comment
There was a problem hiding this comment.
Findings:
- Tool message images are gated on
modelonly, 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). - A refused completion's usage is counted, but the budget is not checked before the next model is called.
- Conflicts with #120 in
run.pyand docs; a resolution is suggested inline. - 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
fallbacksstill holds. - Missing tests for cancellation during a fallback attempt and for per-model
response_formatgating.
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.
ad84dc9 to
0dec46f
Compare
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.
0dec46f to
b96e200
Compare
gopaljigaur
left a comment
There was a problem hiding this comment.
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-modelresponse_format. - Overflow integration:
max_tokensis computed against the configured model's window fromrequests[0], then applied to every request. AContextWindowExceededErrorhas status 400, so_falls_backre-raises it to the remedies in_complete, and the retry starts again withmodel. test_an_overflow_lowers_max_tokens_for_every_modelpins the order[tiny, FALLBACK, tiny, FALLBACK]and the same loweredmax_tokenson 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.
_summarizesizes its prompt to the summarizing model's own window, so falling back would mean a window and a trim per model. The docs nameCompaction.modelas the way through an outage. --is-ancestorwithorigin/mainholds. 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.
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:litellm.ContentPolicyViolationError);finish_reason == "content_filter", feat(core)!: report finish reasons and stop on cut or filtered output #98)._completion_kwargswith 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.ModelFallbackevent carriesmodel,fallback_model, and theerrorit raised; for a refusal,usageholds the refused completion's usage, which is counted in the run because the provider bills it.StepFinished.modelnames 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 achatspan: a failed one ends with an error, a refused one ends throughon_llm_end, and the answering one'sgen_ai.response.modelnames the model.model, which the docs say.max_total_tokensormax_costends the run withstop_reason="budget"before the next model is called.fallback_modelstogether withrouteris rejected. A Router has its ownfallbacksandcontent_policy_fallbacks.cyclops/core/fallback.py. Inrun.py, feat: retry a completion that overflows the context window #120's_completestays the overflow loop and calls_complete_with_fallbacksinside it: a loweredmax_tokensgoes on every model's request, and the context window followsmodel. The compaction summary does not fall back; the docs say so.completion.pytypes the stream's run as a small_Outputprotocol, 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:UnsupportedParamsErrorthat tool-mode detection relies on;Exceptionwith only the last message, which loses the type and status code;x-litellm-attempted-fallbackshidden header.context_window_fallbacksandcontent_policy_fallbacksare 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'sFallbackModeland a hosted model router'smodelsprovider 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 lowernum_retriesto 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.modelstays the configured model;StepFinished.modelgives the model per step.Tests
tests/test_fallback.pycovers:StepFinished.modelattribution;response_format);uv run pytest(570 passed),uv run pre-commit run --all-filesanduv run mypy cyclopsall 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