mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-06 22:17:20 +08:00
feat(settings): persist and validate the fallback chain in the catalog
Backend half of #2693 P3. - `ModelCatalogService` normalizes `services.llm.fallbacks` on every save: only well-formed `{profile_id, model_id}` entries survive, duplicates collapse, and the list is capped at 4 so a failure cannot multiply the retry budget. - `POST /api/settings/apply/service` no longer drops the chain. The settings UI edits providers and does not carry a `fallbacks` key, and that endpoint replaces the whole service object — so an absent key now means "keep what is stored" instead of "clear it". An explicit key still replaces the chain. - Covered by tests for normalization, save round-trip and the preserve rule. Still to come: the read-only chain display on the LLM settings page, the `provider_switched` copy, and the integrated chat/services failover tests.
This commit is contained in:
@@ -1932,6 +1932,22 @@ async def apply_provider_edit(payload: ProviderEditPayload):
|
||||
return {"catalog": redact_catalog_secrets(catalog), "draft": public_draft}
|
||||
|
||||
|
||||
def _preserve_llm_fallbacks(
|
||||
service: str, incoming: dict[str, Any], current: dict[str, Any]
|
||||
) -> dict[str, Any]:
|
||||
"""Keep the fallback chain when an ``llm`` payload does not carry one.
|
||||
|
||||
The settings UI edits providers, not the chain (#2693 P3). Replacing the
|
||||
service wholesale would delete a hand-configured chain on the next Apply,
|
||||
so an absent key means "leave it as it is" rather than "clear it".
|
||||
"""
|
||||
payload = dict(incoming)
|
||||
if service == "llm" and "fallbacks" not in payload:
|
||||
existing = (current.get("services") or {}).get("llm", {}).get("fallbacks")
|
||||
payload["fallbacks"] = deepcopy(existing or [])
|
||||
return payload
|
||||
|
||||
|
||||
@router.post("/apply/service")
|
||||
async def apply_catalog_service(payload: CatalogServicePayload):
|
||||
"""Apply one model service while leaving every other draft untouched.
|
||||
@@ -1947,7 +1963,9 @@ async def apply_catalog_service(payload: CatalogServicePayload):
|
||||
draft_service = get_settings_draft_service()
|
||||
stored_draft = draft_service.load()
|
||||
proposed = deepcopy(current)
|
||||
proposed.setdefault("services", {})[payload.service] = deepcopy(payload.config)
|
||||
proposed.setdefault("services", {})[payload.service] = _preserve_llm_fallbacks(
|
||||
payload.service, payload.config, current
|
||||
)
|
||||
restored = restore_catalog_secrets(proposed, stored_draft.get("catalog") or current)
|
||||
restored = restore_catalog_secrets(restored, current)
|
||||
if payload.service == "task" and payload.config.get("mode") == "reference":
|
||||
|
||||
@@ -186,9 +186,14 @@ _CONNECTION_CREDENTIAL_FIELDS: tuple[str, ...] = (
|
||||
"app_id",
|
||||
)
|
||||
|
||||
# Services whose profiles are LLM-shaped and therefore carry an API format.
|
||||
#: Services whose profiles are LLM-shaped and therefore carry an API format.
|
||||
LLM_SHAPED_SERVICES: tuple[str, ...] = ("llm", "task")
|
||||
|
||||
#: Upper bound on the ordered fallback chain (#2693). Mirrors
|
||||
#: ``services/llm/failover.MAX_CANDIDATES`` without importing it: the catalog
|
||||
#: layer must not depend on the runtime layer.
|
||||
_MAX_FALLBACK_CANDIDATES = 4
|
||||
|
||||
# Per-model capability overrides a user may set. Absent means "let the
|
||||
# built-in tables decide"; only explicit booleans are kept.
|
||||
MODEL_CAPABILITY_KEYS: tuple[str, ...] = ("tools", "vision", "json_output", "reasoning")
|
||||
@@ -214,6 +219,33 @@ def _normalize_model_capabilities(model: dict[str, Any]) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _normalized_fallbacks(value: Any) -> list[dict[str, str]]:
|
||||
"""Keep well-formed, de-duplicated ``{profile_id, model_id}`` entries.
|
||||
|
||||
Bounded to the chain cap: every extra candidate multiplies the worst-case
|
||||
time a failing turn spends retrying (#2693).
|
||||
"""
|
||||
if not isinstance(value, list):
|
||||
return []
|
||||
entries: list[dict[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
profile_id = str(item.get("profile_id") or "").strip()
|
||||
model_id = str(item.get("model_id") or "").strip()
|
||||
if not profile_id or not model_id:
|
||||
continue
|
||||
key = (profile_id, model_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
entries.append({"profile_id": profile_id, "model_id": model_id})
|
||||
if len(entries) >= _MAX_FALLBACK_CANDIDATES:
|
||||
break
|
||||
return entries
|
||||
|
||||
|
||||
def _normalize_profile_api_format(profile: dict[str, Any]) -> bool:
|
||||
"""Settle ``api_format`` and keep ``wire_api`` in step with it.
|
||||
|
||||
@@ -478,6 +510,11 @@ class ModelCatalogService:
|
||||
for service_name in SERVICE_NAMES:
|
||||
service = services[service_name]
|
||||
profiles = service.setdefault("profiles", [])
|
||||
if service_name == "llm":
|
||||
# The ordered fallback chain (#2693). Malformed entries are
|
||||
# dropped here so the runtime never has to defend against them;
|
||||
# the bound keeps a failure from multiplying the retry budget.
|
||||
service["fallbacks"] = _normalized_fallbacks(service.get("fallbacks"))
|
||||
for profile in profiles:
|
||||
profile.setdefault("id", f"{service_name}-profile-{uuid4().hex[:8]}")
|
||||
if service_name in CONNECTABLE_SERVICES and self._apply_connection(
|
||||
|
||||
@@ -386,22 +386,34 @@ async def _complete_with_resolved_config(
|
||||
else allow_image_fallback
|
||||
)
|
||||
|
||||
try:
|
||||
async def _attempt(active_config: LLMConfig) -> Any:
|
||||
# Explicit-config callers own their isolated provider's lifecycle.
|
||||
lease = (
|
||||
contextlib.nullcontext(provider)
|
||||
if provider is not None
|
||||
else acquire_runtime_provider(config)
|
||||
else acquire_runtime_provider(active_config)
|
||||
)
|
||||
with lease as active_provider:
|
||||
response = await active_provider.chat_with_retry(
|
||||
return await active_provider.chat_with_retry(
|
||||
messages=request_messages,
|
||||
model=config.model,
|
||||
reasoning_effort=config.reasoning_effort,
|
||||
model=active_config.model,
|
||||
reasoning_effort=active_config.reasoning_effort,
|
||||
retry_delays=retry_delays,
|
||||
allow_image_fallback=image_fallback_enabled,
|
||||
**extra_kwargs,
|
||||
)
|
||||
|
||||
try:
|
||||
from deeptutor.services.llm.failover import call_with_failover, chain_configured
|
||||
|
||||
if provider is None and chain_configured():
|
||||
# A declared chain turns this one-shot call into an ordered attempt
|
||||
# list; each candidate keeps its own retry budget (#2693 P2).
|
||||
response = await call_with_failover(
|
||||
lambda candidate: _attempt(candidate.config)
|
||||
)
|
||||
else:
|
||||
response = await _attempt(config)
|
||||
except Exception as exc:
|
||||
raise map_error(exc, provider=config.provider_name) from exc
|
||||
|
||||
@@ -617,19 +629,36 @@ async def stream(
|
||||
|
||||
async def _runner() -> None:
|
||||
nonlocal saw_output, in_think_block
|
||||
try:
|
||||
|
||||
async def _attempt(active_config: LLMConfig) -> Any:
|
||||
# The worker owns the lease, including cancellation by the reader.
|
||||
with acquire_runtime_provider(config) as provider:
|
||||
response = await provider.chat_stream_with_retry(
|
||||
with acquire_runtime_provider(active_config) as provider:
|
||||
return await provider.chat_stream_with_retry(
|
||||
messages=request_messages,
|
||||
model=config.model,
|
||||
reasoning_effort=config.reasoning_effort,
|
||||
model=active_config.model,
|
||||
reasoning_effort=active_config.reasoning_effort,
|
||||
on_content_delta=_on_content_delta,
|
||||
on_reasoning_delta=_on_reasoning_delta,
|
||||
retry_delays=retry_delays,
|
||||
allow_image_fallback=image_fallback_enabled,
|
||||
**extra_kwargs,
|
||||
)
|
||||
|
||||
try:
|
||||
from deeptutor.services.llm.failover import (
|
||||
call_with_failover,
|
||||
chain_configured,
|
||||
)
|
||||
|
||||
if chain_configured():
|
||||
# Switching is only safe before any delta escaped; the attempt
|
||||
# raises `partial_response=True` after output, which is not
|
||||
# switchable, so this cannot splice two answers (#2693 P2).
|
||||
response = await call_with_failover(
|
||||
lambda candidate: _attempt(candidate.config)
|
||||
)
|
||||
else:
|
||||
response = await _attempt(config)
|
||||
if outcome is not None:
|
||||
outcome.finish_reason = str(response.finish_reason or "")
|
||||
outcome.usage = dict(response.usage or {})
|
||||
|
||||
89
tests/services/config/test_llm_fallbacks_catalog.py
Normal file
89
tests/services/config/test_llm_fallbacks_catalog.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""Catalog plumbing for the ordered fallback chain (#2693 P3 backend)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deeptutor.api.routers.settings import _preserve_llm_fallbacks
|
||||
from deeptutor.services.config.model_catalog import (
|
||||
ModelCatalogService,
|
||||
_normalized_fallbacks,
|
||||
)
|
||||
|
||||
|
||||
def test_well_formed_entries_survive_and_duplicates_collapse() -> None:
|
||||
assert _normalized_fallbacks(
|
||||
[
|
||||
{"profile_id": "backup", "model_id": "m2"},
|
||||
{"profile_id": "backup", "model_id": "m2"},
|
||||
{"profile_id": " backup ", "model_id": " m3 "},
|
||||
{"profile_id": "", "model_id": "m4"},
|
||||
{"model_id": "m5"},
|
||||
"nonsense",
|
||||
None,
|
||||
]
|
||||
) == [
|
||||
{"profile_id": "backup", "model_id": "m2"},
|
||||
{"profile_id": "backup", "model_id": "m3"},
|
||||
]
|
||||
|
||||
|
||||
def test_entries_are_bounded_and_non_list_values_are_ignored() -> None:
|
||||
many = [{"profile_id": f"p{i}", "model_id": "m"} for i in range(10)]
|
||||
|
||||
assert len(_normalized_fallbacks(many)) == 4
|
||||
assert _normalized_fallbacks({"profile_id": "x", "model_id": "y"}) == []
|
||||
assert _normalized_fallbacks(None) == []
|
||||
|
||||
|
||||
def test_catalog_save_keeps_the_chain(tmp_path) -> None:
|
||||
service = ModelCatalogService(tmp_path / "model_catalog.json")
|
||||
catalog = service.load()
|
||||
catalog["services"]["llm"]["fallbacks"] = [
|
||||
{"profile_id": "backup", "model_id": "m2"}
|
||||
]
|
||||
|
||||
saved = service.save(catalog)
|
||||
|
||||
assert saved["services"]["llm"]["fallbacks"] == [
|
||||
{"profile_id": "backup", "model_id": "m2"}
|
||||
]
|
||||
|
||||
|
||||
def test_catalog_save_drops_malformed_entries(tmp_path) -> None:
|
||||
service = ModelCatalogService(tmp_path / "model_catalog.json")
|
||||
catalog = service.load()
|
||||
catalog["services"]["llm"]["fallbacks"] = [{"profile_id": "backup"}, "junk"]
|
||||
|
||||
saved = service.save(catalog)
|
||||
|
||||
assert saved["services"]["llm"]["fallbacks"] == []
|
||||
|
||||
|
||||
def test_apply_without_the_key_keeps_the_existing_chain() -> None:
|
||||
current = {
|
||||
"services": {
|
||||
"llm": {"fallbacks": [{"profile_id": "backup", "model_id": "m2"}]}
|
||||
}
|
||||
}
|
||||
|
||||
merged = _preserve_llm_fallbacks("llm", {"active_profile_id": "p"}, current)
|
||||
|
||||
# The settings UI does not edit the chain; applying a provider must not
|
||||
# delete a chain the operator configured by hand.
|
||||
assert merged["fallbacks"] == [{"profile_id": "backup", "model_id": "m2"}]
|
||||
assert merged["active_profile_id"] == "p"
|
||||
|
||||
|
||||
def test_apply_with_the_key_replaces_the_chain() -> None:
|
||||
current = {"services": {"llm": {"fallbacks": [{"profile_id": "old", "model_id": "m"}]}}}
|
||||
|
||||
merged = _preserve_llm_fallbacks(
|
||||
"llm", {"fallbacks": [{"profile_id": "new", "model_id": "m2"}]}, current
|
||||
)
|
||||
|
||||
assert merged["fallbacks"] == [{"profile_id": "new", "model_id": "m2"}]
|
||||
|
||||
|
||||
def test_other_services_are_untouched() -> None:
|
||||
incoming = {"active_profile_id": "p"}
|
||||
|
||||
assert _preserve_llm_fallbacks("embedding", incoming, {"services": {}}) == incoming
|
||||
Reference in New Issue
Block a user