[Feature Request]: Provider-level LLM failover — ordered fallback when the active provider exhausts retries
Description
While running a self-hosted 1.7.2 deployment with DeepSeek as the active LLM, we lived through a ~30-minute upstream outage (api.deepseek.com returning 401 network-level from both host and container; other egress fine). Behavior during the outage:
- Provider retries exhausted on the standard backoff (~9 retries, 5s→120s, ~10 minutes), then gave up.
- A second, fully working OpenAI-compatible provider configured in the catalog (local fallback) was never used — there is no provider-level failover.
- Book background compilation stalled mid-chapter; Reading quiz endpoints returned 503; anything generation-shaped was down for the whole outage.
- From the UI this reads as long silences, which is the worst failure mode during a live tutoring session.
Expected Behavior
Some form of provider-level resilience for the active LLM: e.g. an optional ordered fallback chain per deployment (try next configured provider when the active one exhausts retries), or at minimum a surfaced degradation state so operators/learners see "model provider unavailable" rather than silence.
Repro
Hard to schedule a real outage; simulate by pointing the active provider's base_url at a closed port and observing retry-then-stall with a healthy second provider configured.
Related Module
API/Backend (provider_core / capabilities)
Configuration Used
Two LLM profiles: DeepSeek (active) + a local OpenAI-compatible fallback; Books + Reading quiz in active use.
Logs and screenshots
Retry log excerpt: 9 attempts with exponential backoff ending in give-up, no switch to the second provider. Can attach on request.
Additional Information
- DeepTutor Version: 1.7.2 (Docker)
- Operating System: Linux (Docker host)
- Not asking for cross-region magic — a single ordered fallback list would already cover scheduled classes.
I ran into the same gap from the other direction: my primary provider is a Codex subscription, the backup a Claude Code subscription. When the Codex quota runs out, every turn fails with a 429 although a working second profile is configured.
As a local stopgap I patched OpenAICodexProvider to hand a request to ClaudeCodeProvider when the bridge returns 429 before any output. That works in both paths (services/llm factory and the agentic _ProviderOpenAIAdapter), but it's tied to one provider. A general version could look like this:
- Config: an optional ordered list on the
llmservice, e.g.fallbacks: [{profile_id, model_id}], pointing at profiles that already exist in the catalog. Empty by default, so nothing changes for current setups. - Trigger: only errors raised before the first streamed token or tool call:
LLMRateLimitError/ProviderQuotaExceededError, plus transport or auth failures once the normal retries are exhausted. A request is never replayed after partial output. - Placement: a small
FailoverProvider(LLMProvider)built inprovider_factory. The agentic client wraps it in_ProviderOpenAIAdapterwhenever a chain is configured, so raw OpenAI-compatible clients are covered too. - Recovery: every request tries the primary first. Once the quota resets, it's back on the primary without manual switching.
- Visibility: one log line plus a status event ("using fallback model X") so learners don't just see silence.
Does this direction work for you, especially the config location and whether the settings UI should be part of the first PR? If so, I'll open a PR against dev.
问题根因:同一个 provider 重试到耗尽之后就彻底失败,配置里那个能用的备用 provider 永远不会被用到。 期望:首先,最低限度是把"模型不可用"这个降级状态显示出来;进一步是"每个部署一条有序回退链",当 active provider 重试耗尽时试下一个 上面评论涉及的四点提议: 1.fallbacks: [{profile_id, model_id}] 放在 llm 服务下,默认空,可行,但见下面"多用户"风险 2.FailoverProvider(LLMProvider) 建在 provider factory 里,需要把"链"上移到 _resolve_call_config 之上,由 factory 返回包装后的 provider,否则包装器拿不到备选 3.只在"首个 token 前"触发:限流、配额、传输/auth 重试耗尽,可行且安全边界清楚;LLMOperationPaused 必须继续拒绝替换 4.agentic 路径也要覆盖,因为裸 OpenAI 兼容客户端不走 factory, 这条是准的,两处都要包 难点: 1."什么时候允许切"是安全边界,不是性能开关。一旦已经吐了 token、或者已经派发了工具调用,切换意味着重复输出或工具被重复执行(tool_dispatch 那侧没有幂等保证)。必须用 partial_response 严格 gate,并且要在 agent loop 层而不是 provider 层判断"这一轮是否已有副作用"。 2.多用户下"备选 profile 归属谁"。目录里的 profile 可能带的是管理员 key,也可能是用户自带 key(#1927 正在推进 per-user API key)。回退链必须解析成"本次请求 owner 可用的 profile",否则等于让普通用户的请求悄悄用管理员额度,或反之泄露可用性信息。这是我认为最容易被忽略、也最该在 PR 里先定下来的点。 3.task model 与 chat model 是两套解析。后台书稿用的不是 chat 的 active model;如果只改 chat 路径,A 报告里的"书稿卡半章"不会改善。 4.成本与计量:usage_ledger / UsageTracker 按模型记账,回退后必须记实际使用的模型并标出发生过回退,否则成本汇总与"哪个模型答的"都会错。 5.能力差异:备选模型可能不支持图像、不支持 response_format、工具 schema 支持不同(supports_response_format、supports_vision 这类能力表已有)。切换前要按能力重新 sanitize 请求,或者沿用现有的"去图重试"。 6.缓存亲和会失效:prompt_cache_key / session-id(刚在 #2826 / #1991 里修好的那套)在换 provider 后自然失效,这属于可接受的代价,但要在文档里说清楚。 7.和 stream idle timeout 的交互:90 秒无 chunk 就中止(#2813 正在做成可配)。回退链要接在这个超时之后还是之内,需要明确——否则"卡住 90 秒再换"和"退避 10 分钟再换"会叠加。 建议修复顺序: 1.先做可见性:provider 重试期间发一条状态事件、耗尽后给出明确的"模型服务不可用,可切到 X",前端显示出来。这直接消掉"长时间静默"这个最痛的体验,且零风险,不涉及任何切换语义。 2.再做链式回退:catalog 增加 fallbacks、_resolve_call_config 解析出有序链、FailoverProvider 包装、严格 gate 在首个 token 之前、按 owner 解析 profile、计量记录实际模型。测试用打桩 provider 即可,不需要真实故障。 3.最后再加设置界面:和 #2889 那张卡片的做法一致,放在 Models → LLM 页的 profile 编辑里,默认空。
Implemented in #2932: https://github.com/HKUDS/DeepTutor/pull/2932
The turn now builds an ordered chain — the model it actually resolved first, then services.llm.fallbacks from the catalog — and moves to the next candidate when the active one fails before any output. Nothing is replayed after output, a dispatched tool call, or a paused remote operation.
Key behaviours, in case they differ from what you had in mind:
- Cooldown instead of eviction. The failed candidate is cooled (rate limits honour
Retry-After, transport 30s, escalation 60s → 5m → 15m, auth failures disabled until the profile is edited) and the next request starts on the primary again once the cooldown expires. A quota-reset therefore returns you to the primary without a manual switch — the "failback" half of the request. - Fast-fail once a chain exists. Each candidate gets one attempt instead of the default 8×5s→120s schedule, which is where the ten minutes of silence came from.
- Visibility. The failure names the provider and endpoint, the attempt count, and how many alternatives are configured; a switch emits a
provider_failoverevent, and the provider's own retry waits are no longer silent. - Per owner. Cooldowns are keyed per account, so one user's exhausted key cannot cool a shared profile for everyone.
- Configuration is on Settings → Language models (it lists the profiles already set up), and it applies to chat plus the background task model. Image/video/speech/search/embedding models are deliberately out of scope — swapping an embedding model would invalidate existing indexes.
Known limits are listed in the PR: per-process cooldowns with multiple workers, and the context budget still follows the primary's window.
The PR body has the test evidence (1828 backend tests, the two end-to-end failover tests, frontend typecheck/lint/vitest, desktop shell tests).