mirror of
https://github.com/HKUDS/DeepTutor.git
synced 2026-12-03 09:50:45 +08:00
feat(chat): name the failing provider and the unused alternatives
Part of #2693, visibility only: the turn still runs the one active model, but a failed turn no longer reads as "the provider connection was interrupted" with no name, no attempt count, and no hint that an alternative is already configured. - `provider_visibility.py` builds the retry and final-failure copy from a pipeline's binding, model and endpoint host, plus the number of configured fallbacks (`services/model_selection/fallbacks.py`: read-only, bounded, tolerant of a hand-edited catalog). - Non-transport provider errors (401/403/429/5xx, model-not-found) are mapped through the existing error taxonomy before they are raised, so the user reads "provider X returned a server-side error" instead of the SDK's raw "Error code: 502" — while the typed error, status code and retry flags that the loop and the forced-finish path branch on are preserved. - The failure trace metadata gains `provider`, `attempts` and `fallbacks_configured`. - zh and en chat prompt copy updated; other capabilities keep the code defaults until their prompt packs are updated. No failover yet: switching, cooldowns and failback land in P1.
This commit is contained in:
@@ -178,9 +178,15 @@ notices:
|
||||
output_truncated: "The model output reached its token limit; asked it to continue."
|
||||
tool_call_truncated: "The model reached its output token limit while writing a tool call. The call was not executed. If this repeats, raise this capability's max tokens or pick a model that reasons less."
|
||||
loop_error_finish: "A step failed ({error}); answering with what has been gathered."
|
||||
provider_retry: "The model provider connection was interrupted; retrying."
|
||||
provider_unavailable: "Unable to reach the model provider. Please retry."
|
||||
provider_stream_interrupted: "The model provider interrupted this response. Please retry."
|
||||
provider_retry: "The model provider connection was interrupted ({provider}); retry {attempt}/{total}."
|
||||
provider_unavailable: "Could not reach the model provider ({provider} / {model}) after {attempts} attempt(s); the turn was stopped."
|
||||
provider_fallbacks_available: "{count} other provider(s) are configured, but this version does not switch to them automatically — change the active model to use one."
|
||||
provider_auth_failed: "The model provider rejected the credentials ({provider}); check the API key and account access."
|
||||
provider_rate_limited: "The model provider is rate-limiting or out of quota ({provider}); retry later or switch models."
|
||||
provider_model_missing: "The model does not exist or this account cannot access it ({provider} / {model})."
|
||||
provider_server_error: "The model provider returned a server-side error ({provider}); retry later."
|
||||
provider_error: "The model provider call failed ({provider}): {error}"
|
||||
provider_stream_interrupted: "The model provider interrupted this response ({provider}). Please retry."
|
||||
context_window_guard: "Trimmed older tool results to keep this turn within the model's context window."
|
||||
tool_schema_fallback: "Provider rejected native tool schemas; retrying without tools."
|
||||
ask_questions_fallback_prompt: "What is the most important goal or constraint I should account for?"
|
||||
|
||||
@@ -134,9 +134,15 @@ notices:
|
||||
output_truncated: "模型输出达到 token 上限,已要求其继续完成回答。"
|
||||
tool_call_truncated: "模型在生成工具调用时达到输出 token 上限,该调用未执行。若反复出现,请提高该能力的最大输出 token,或改用推理更短的模型。"
|
||||
loop_error_finish: "某一步执行失败({error}),将基于已收集的材料作答。"
|
||||
provider_retry: "模型服务连接中断,正在重试。"
|
||||
provider_unavailable: "无法连接模型服务,请重试。"
|
||||
provider_stream_interrupted: "模型服务中断了本次回答,请重试。"
|
||||
provider_retry: "模型服务连接中断({provider}),第 {attempt}/{total} 次重试。"
|
||||
provider_unavailable: "无法连接模型服务({provider} / {model}),已尝试 {attempts} 次,本轮已中断。"
|
||||
provider_fallbacks_available: "目录中另有 {count} 个 provider 已配置;当前版本不会自动切换,需要手动切换模型。"
|
||||
provider_auth_failed: "模型服务认证失败({provider}),请检查 API key 与账号权限。"
|
||||
provider_rate_limited: "模型服务限流或额度已用尽({provider}),请稍后重试或更换模型。"
|
||||
provider_model_missing: "模型不存在或当前账号无权访问({provider} / {model}),请检查模型配置。"
|
||||
provider_server_error: "模型服务端返回错误({provider}),请稍后重试。"
|
||||
provider_error: "模型服务调用失败({provider}):{error}"
|
||||
provider_stream_interrupted: "模型服务中断了本次回答({provider}),请重试。"
|
||||
context_window_guard: "已裁剪较旧的工具结果,以确保本轮在模型上下文窗口内。"
|
||||
tool_schema_fallback: "服务方拒绝了原生工具 schema;将不带工具重试。"
|
||||
ask_questions_fallback_prompt: "我最需要了解的目标或限制条件是什么?"
|
||||
|
||||
@@ -56,6 +56,12 @@ from deeptutor.agents.loop.loop_state import (
|
||||
_reasoning_budget_exhausted,
|
||||
)
|
||||
from deeptutor.agents.loop.prompt_blocks import TOOL_MANIFEST_SNAPSHOT
|
||||
from deeptutor.agents.loop.provider_visibility import (
|
||||
annotate_provider_failure,
|
||||
provider_label,
|
||||
retry_notice,
|
||||
unavailable_message,
|
||||
)
|
||||
from deeptutor.core.context import UnifiedContext
|
||||
from deeptutor.core.trace import build_trace_metadata, merge_trace_metadata, new_call_id
|
||||
from deeptutor.runtime.agentic.messages import (
|
||||
@@ -95,6 +101,7 @@ from deeptutor.services.llm.request_compat import (
|
||||
)
|
||||
from deeptutor.services.llm.usage_frame import usage_breakdown
|
||||
from deeptutor.services.llm.utils import unreachable_endpoint_hint
|
||||
from deeptutor.services.model_selection.fallbacks import fallback_count
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from deeptutor.agents.loop.pipeline import AgenticLoopPipeline
|
||||
@@ -1195,7 +1202,17 @@ class AgentLoop:
|
||||
)
|
||||
)
|
||||
)
|
||||
raise
|
||||
# A 401/429/5xx is not retried here, but it must not reach
|
||||
# the user as the SDK's bare "Error code: 502" (#2693 P0).
|
||||
failed_provider, failed_model = provider_label(self.pipeline)
|
||||
annotated = annotate_provider_failure(
|
||||
exc,
|
||||
self.pipeline._t,
|
||||
provider=failed_provider,
|
||||
model=failed_model,
|
||||
fallbacks=fallback_count(),
|
||||
)
|
||||
raise annotated from exc
|
||||
can_retry = not output_emitted and attempt < len(_PROVIDER_RETRY_DELAYS)
|
||||
if can_retry:
|
||||
logger.warning(
|
||||
@@ -1204,10 +1221,14 @@ class AgentLoop:
|
||||
len(_PROVIDER_RETRY_DELAYS) + 1,
|
||||
exc,
|
||||
)
|
||||
provider, model = provider_label(self.pipeline)
|
||||
await self.stream.progress(
|
||||
self.pipeline._t(
|
||||
"notices.provider_retry",
|
||||
default="The model provider connection was interrupted; retrying.",
|
||||
retry_notice(
|
||||
self.pipeline._t,
|
||||
provider=provider,
|
||||
model=model,
|
||||
attempt=attempt + 1,
|
||||
total=len(_PROVIDER_RETRY_DELAYS) + 1,
|
||||
),
|
||||
source=self.source,
|
||||
stage=stage,
|
||||
@@ -1216,6 +1237,7 @@ class AgentLoop:
|
||||
{
|
||||
"trace_kind": "warning",
|
||||
"error_code": "provider_transport",
|
||||
"provider": provider,
|
||||
"retry_attempt": attempt + 1,
|
||||
},
|
||||
),
|
||||
@@ -1224,6 +1246,10 @@ class AgentLoop:
|
||||
continue
|
||||
|
||||
partial_response = output_emitted
|
||||
provider, model = provider_label(self.pipeline)
|
||||
# Read-only: P0 reports how many alternatives exist, it does not
|
||||
# use them. Cheap and only on the failure path.
|
||||
alternatives = fallback_count()
|
||||
if text_parts or reasoning_parts:
|
||||
messages.append(
|
||||
_assistant_round_message(
|
||||
@@ -1244,23 +1270,29 @@ class AgentLoop:
|
||||
"trace_kind": "call_status",
|
||||
"call_state": "failed",
|
||||
"error_code": "provider_transport",
|
||||
"provider": provider,
|
||||
"attempts": attempt + 1,
|
||||
"fallbacks_configured": alternatives,
|
||||
"retryable": True,
|
||||
"partial_response": partial_response,
|
||||
},
|
||||
),
|
||||
)
|
||||
message = self.pipeline._t(
|
||||
(
|
||||
"notices.provider_stream_interrupted"
|
||||
if partial_response
|
||||
else "notices.provider_unavailable"
|
||||
),
|
||||
default=(
|
||||
"The model provider interrupted this response. Please retry."
|
||||
if partial_response
|
||||
else "Unable to reach the model provider. Please retry."
|
||||
),
|
||||
)
|
||||
if partial_response:
|
||||
message = self.pipeline._t(
|
||||
"notices.provider_stream_interrupted",
|
||||
default="The model provider interrupted this response. Please retry.",
|
||||
provider=provider,
|
||||
model=model,
|
||||
)
|
||||
else:
|
||||
message = unavailable_message(
|
||||
self.pipeline._t,
|
||||
provider=provider,
|
||||
model=model,
|
||||
attempts=attempt + 1,
|
||||
fallbacks=alternatives,
|
||||
)
|
||||
if not partial_response:
|
||||
# "Please retry" is the whole story for a cloud endpoint and
|
||||
# none of it for a self-hosted one, where the connection was
|
||||
|
||||
238
deeptutor/agents/loop/provider_visibility.py
Normal file
238
deeptutor/agents/loop/provider_visibility.py
Normal file
@@ -0,0 +1,238 @@
|
||||
"""Provider-failure copy for the agent loop (issue #2693, P0).
|
||||
|
||||
The loop already told the user "the provider connection was interrupted;
|
||||
retrying" and, on exhaustion, "unable to reach the model provider". Both were
|
||||
anonymous: no provider name, no attempt count, and no mention that the
|
||||
deployment may already have an alternative configured.
|
||||
|
||||
This module builds those two sentences. It takes the pipeline's banner-style
|
||||
``_t`` translator rather than importing i18n state, so it is testable on its
|
||||
own and every capability's prompt pack can override the copy.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Callable
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from deeptutor.services.llm.error_mapping import map_error
|
||||
from deeptutor.services.llm.exceptions import (
|
||||
LLMAPIError,
|
||||
LLMAuthenticationError,
|
||||
LLMError,
|
||||
LLMModelNotFoundError,
|
||||
LLMProviderError,
|
||||
LLMRateLimitError,
|
||||
)
|
||||
|
||||
#: Capabilities without these keys in their prompt pack fall back to these.
|
||||
DEFAULT_RETRY = "The model provider connection was interrupted; retrying."
|
||||
DEFAULT_UNAVAILABLE = "Unable to reach the model provider. Please retry."
|
||||
DEFAULT_FALLBACKS_AVAILABLE = (
|
||||
"{count} other model provider(s) are configured; this version does not "
|
||||
"switch to them automatically."
|
||||
)
|
||||
DEFAULT_AUTH_FAILED = "The model provider rejected the credentials ({provider})."
|
||||
DEFAULT_RATE_LIMITED = "The model provider is rate-limiting or out of quota ({provider})."
|
||||
DEFAULT_MODEL_MISSING = "The model provider has no such model ({provider} / {model})."
|
||||
DEFAULT_SERVER_ERROR = "The model provider returned a server-side error ({provider}); retry later."
|
||||
DEFAULT_PROVIDER_ERROR = "The model provider call failed ({provider}): {error}"
|
||||
|
||||
Translate = Callable[..., str]
|
||||
|
||||
#: Errors whose copy names the provider and suggests the next action. A config
|
||||
#: error already says what to fix, and a parse error is not a provider outage.
|
||||
_ANNOTATABLE = (LLMAPIError, LLMProviderError)
|
||||
|
||||
|
||||
def provider_label(pipeline: Any) -> tuple[str, str]:
|
||||
"""``(provider, model)`` for the turn, best-effort and never raising.
|
||||
|
||||
The provider binding alone ("openai") does not tell an operator *which*
|
||||
endpoint failed, and a deployment can point several profiles at different
|
||||
gateways. The host is appended when there is one.
|
||||
"""
|
||||
provider = str(getattr(pipeline, "binding", "") or "").strip() or "unknown"
|
||||
model = str(getattr(pipeline, "model", "") or "").strip()
|
||||
base_url = str(getattr(pipeline, "base_url", "") or "").strip()
|
||||
if base_url:
|
||||
try:
|
||||
host = urlparse(base_url).netloc
|
||||
except ValueError:
|
||||
host = ""
|
||||
if host and host not in provider:
|
||||
provider = f"{provider} ({host})"
|
||||
return provider, model
|
||||
|
||||
|
||||
def retry_notice(
|
||||
translate: Translate,
|
||||
*,
|
||||
provider: str,
|
||||
model: str,
|
||||
attempt: int,
|
||||
total: int,
|
||||
) -> str:
|
||||
"""Sentence shown between attempts, now naming who is being retried."""
|
||||
return translate(
|
||||
"notices.provider_retry",
|
||||
default=DEFAULT_RETRY,
|
||||
provider=provider,
|
||||
model=model,
|
||||
attempt=attempt,
|
||||
total=total,
|
||||
)
|
||||
|
||||
|
||||
def unavailable_message(
|
||||
translate: Translate,
|
||||
*,
|
||||
provider: str,
|
||||
model: str,
|
||||
attempts: int,
|
||||
fallbacks: int,
|
||||
) -> str:
|
||||
"""Final failure copy, with the attempt count and any configured alternative.
|
||||
|
||||
``fallbacks`` is only a count: P0 does not switch, and the sentence says so
|
||||
rather than implying a failover that does not exist yet.
|
||||
"""
|
||||
message = translate(
|
||||
"notices.provider_unavailable",
|
||||
default=DEFAULT_UNAVAILABLE,
|
||||
provider=provider,
|
||||
model=model,
|
||||
attempts=attempts,
|
||||
)
|
||||
if fallbacks > 0:
|
||||
suffix = translate(
|
||||
"notices.provider_fallbacks_available",
|
||||
default=DEFAULT_FALLBACKS_AVAILABLE,
|
||||
count=fallbacks,
|
||||
)
|
||||
message = f"{message} {suffix}"
|
||||
return message.strip()
|
||||
|
||||
|
||||
def failure_message(
|
||||
translate: Translate,
|
||||
exc: Exception,
|
||||
*,
|
||||
provider: str,
|
||||
model: str,
|
||||
fallbacks: int,
|
||||
) -> str:
|
||||
"""Copy for a provider failure that is *not* retried.
|
||||
|
||||
Before P0 a 401/429/502 surfaced as the SDK's raw text ("Error code: 502"),
|
||||
with no provider, no cause and no hint that an alternative is configured.
|
||||
"""
|
||||
status = getattr(exc, "status_code", None)
|
||||
if isinstance(exc, LLMRateLimitError):
|
||||
message = translate(
|
||||
"notices.provider_rate_limited",
|
||||
default=DEFAULT_RATE_LIMITED,
|
||||
provider=provider,
|
||||
model=model,
|
||||
)
|
||||
elif isinstance(exc, LLMAuthenticationError):
|
||||
message = translate(
|
||||
"notices.provider_auth_failed",
|
||||
default=DEFAULT_AUTH_FAILED,
|
||||
provider=provider,
|
||||
model=model,
|
||||
)
|
||||
elif isinstance(exc, LLMModelNotFoundError):
|
||||
message = translate(
|
||||
"notices.provider_model_missing",
|
||||
default=DEFAULT_MODEL_MISSING,
|
||||
provider=provider,
|
||||
model=model,
|
||||
)
|
||||
elif isinstance(status, int) and status >= 500:
|
||||
message = translate(
|
||||
"notices.provider_server_error",
|
||||
default=DEFAULT_SERVER_ERROR,
|
||||
provider=provider,
|
||||
model=model,
|
||||
)
|
||||
else:
|
||||
message = translate(
|
||||
"notices.provider_error",
|
||||
default=DEFAULT_PROVIDER_ERROR,
|
||||
provider=provider,
|
||||
model=model,
|
||||
error=str(exc),
|
||||
)
|
||||
if fallbacks > 0:
|
||||
suffix = translate(
|
||||
"notices.provider_fallbacks_available",
|
||||
default=DEFAULT_FALLBACKS_AVAILABLE,
|
||||
count=fallbacks,
|
||||
)
|
||||
message = f"{message} {suffix}"
|
||||
return message.strip()
|
||||
|
||||
|
||||
def _looks_like_provider_error(exc: Exception) -> bool:
|
||||
"""Whether *exc* is worth rewriting as a provider failure.
|
||||
|
||||
``map_error`` turns anything into an ``LLMError``, so without this a bug in
|
||||
our own code ("not a provider problem") would be relabelled as a model
|
||||
outage and hide the real stack.
|
||||
"""
|
||||
if isinstance(exc, LLMError):
|
||||
return isinstance(exc, _ANNOTATABLE)
|
||||
if getattr(exc, "status_code", None) is not None:
|
||||
return True
|
||||
module = type(exc).__module__ or ""
|
||||
return module.startswith(("openai", "anthropic", "httpx", "httpcore"))
|
||||
|
||||
|
||||
def annotate_provider_failure(
|
||||
exc: Exception,
|
||||
translate: Translate,
|
||||
*,
|
||||
provider: str,
|
||||
model: str,
|
||||
fallbacks: int,
|
||||
) -> Exception:
|
||||
"""Attach the readable copy to a provider error, keeping its classification.
|
||||
|
||||
``map_error`` returns the caller's own exception when it is already an
|
||||
``LLMError``, so the retry flags and error code downstream callers branch on
|
||||
are preserved; only the human-readable message is replaced.
|
||||
"""
|
||||
if not _looks_like_provider_error(exc):
|
||||
return exc
|
||||
try:
|
||||
typed = map_error(exc, provider=provider)
|
||||
except Exception: # pragma: no cover - mapping must never mask the failure
|
||||
return exc
|
||||
if not isinstance(typed, _ANNOTATABLE):
|
||||
return exc
|
||||
typed.message = failure_message(
|
||||
translate,
|
||||
typed,
|
||||
provider=provider,
|
||||
model=model,
|
||||
fallbacks=fallbacks,
|
||||
)
|
||||
return typed
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DEFAULT_AUTH_FAILED",
|
||||
"DEFAULT_FALLBACKS_AVAILABLE",
|
||||
"DEFAULT_MODEL_MISSING",
|
||||
"DEFAULT_PROVIDER_ERROR",
|
||||
"DEFAULT_RATE_LIMITED",
|
||||
"DEFAULT_RETRY",
|
||||
"DEFAULT_SERVER_ERROR",
|
||||
"DEFAULT_UNAVAILABLE",
|
||||
"annotate_provider_failure",
|
||||
"failure_message",
|
||||
"provider_label",
|
||||
"retry_notice",
|
||||
"unavailable_message",
|
||||
]
|
||||
81
deeptutor/services/model_selection/fallbacks.py
Normal file
81
deeptutor/services/model_selection/fallbacks.py
Normal file
@@ -0,0 +1,81 @@
|
||||
"""Read-only view of the deployment's fallback providers (issue #2693, P0).
|
||||
|
||||
P0 is visibility only: DeepTutor still runs the one active model. This module
|
||||
answers "how many alternatives are already configured?" so a failed turn can
|
||||
say so instead of a bare "please retry".
|
||||
|
||||
The real failover (ordered candidates, cooldown, failback) is a later phase and
|
||||
does not use anything here beyond the same catalog key.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
#: ``services.llm`` key holding the ordered fallback list. Bounded here too:
|
||||
#: a hand-edited file must not be able to make this scan unbounded.
|
||||
FALLBACKS_KEY = "fallbacks"
|
||||
|
||||
#: Mirrors the planned chain cap. Visibility never needs more than this.
|
||||
MAX_FALLBACKS = 4
|
||||
|
||||
|
||||
def _entry(value: Any) -> dict[str, str] | None:
|
||||
"""One well-formed ``{profile_id, model_id}`` entry, or ``None``."""
|
||||
if not isinstance(value, dict):
|
||||
return None
|
||||
profile_id = str(value.get("profile_id") or "").strip()
|
||||
model_id = str(value.get("model_id") or "").strip()
|
||||
if not profile_id or not model_id:
|
||||
return None
|
||||
return {"profile_id": profile_id, "model_id": model_id}
|
||||
|
||||
|
||||
def configured_fallbacks(catalog: dict[str, Any] | None = None) -> list[dict[str, str]]:
|
||||
"""The fallback entries the catalog declares, de-duplicated and bounded.
|
||||
|
||||
Tolerant on purpose: this runs on an error path, so an unreadable catalog or
|
||||
a half-written entry must never turn "the provider is down" into a second
|
||||
exception.
|
||||
"""
|
||||
if catalog is None:
|
||||
try:
|
||||
from deeptutor.services.config import get_model_catalog_service
|
||||
|
||||
catalog = get_model_catalog_service().load()
|
||||
except Exception: # pragma: no cover - settings must not break an error path
|
||||
return []
|
||||
|
||||
services = catalog.get("services") if isinstance(catalog, dict) else None
|
||||
llm = services.get("llm") if isinstance(services, dict) else None
|
||||
declared = llm.get(FALLBACKS_KEY) if isinstance(llm, dict) else None
|
||||
if not isinstance(declared, list):
|
||||
return []
|
||||
|
||||
entries: list[dict[str, str]] = []
|
||||
seen: set[tuple[str, str]] = set()
|
||||
for raw in declared:
|
||||
entry = _entry(raw)
|
||||
if entry is None:
|
||||
continue
|
||||
key = (entry["profile_id"], entry["model_id"])
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
entries.append(entry)
|
||||
if len(entries) >= MAX_FALLBACKS:
|
||||
break
|
||||
return entries
|
||||
|
||||
|
||||
def fallback_count(catalog: dict[str, Any] | None = None) -> int:
|
||||
"""How many fallback candidates are configured (0 when the key is absent)."""
|
||||
return len(configured_fallbacks(catalog))
|
||||
|
||||
|
||||
__all__ = [
|
||||
"FALLBACKS_KEY",
|
||||
"MAX_FALLBACKS",
|
||||
"configured_fallbacks",
|
||||
"fallback_count",
|
||||
]
|
||||
@@ -3059,7 +3059,11 @@ async def test_midloop_transport_failure_retries_current_round(
|
||||
if e.type == StreamEventType.PROGRESS
|
||||
and e.metadata.get("error_code") == "provider_transport"
|
||||
]
|
||||
assert progress == ["The model provider connection was interrupted; retrying."]
|
||||
# The retry is explicit in the trace, now naming what is being retried and
|
||||
# which attempt this is (#2693 P0).
|
||||
assert len(progress) == 1
|
||||
assert "interrupted" in progress[0]
|
||||
assert "retry 1/" in progress[0]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
@@ -3135,6 +3139,8 @@ async def test_first_round_transport_failure_retries_then_becomes_structured_err
|
||||
pipeline = AgenticChatPipeline(language="en")
|
||||
pipeline.registry = _Registry()
|
||||
monkeypatch.setattr(agent_loop_mod, "_PROVIDER_RETRY_DELAYS", (0, 0))
|
||||
# A configured alternative must be reported, not silently promised (#2693 P0).
|
||||
monkeypatch.setattr(agent_loop_mod, "fallback_count", lambda *a, **k: 2)
|
||||
monkeypatch.setattr(pipeline, "_compose_enabled_tools", lambda _context: ["web_search"])
|
||||
monkeypatch.setattr(pipeline, "_build_openai_client", lambda: client)
|
||||
|
||||
@@ -3152,7 +3158,13 @@ async def test_first_round_transport_failure_retries_then_becomes_structured_err
|
||||
assert raised.value.error_code == "provider_transport"
|
||||
assert raised.value.retryable is True
|
||||
assert raised.value.partial_response is False
|
||||
assert str(raised.value) == "Unable to reach the model provider. Please retry."
|
||||
message = str(raised.value)
|
||||
# Names the provider, the attempt count, and that an alternative exists but
|
||||
# was not used — instead of a bare "please retry" (#2693 P0).
|
||||
assert "Could not reach the model provider" in message
|
||||
assert "3 attempt" in message
|
||||
assert "2 other provider(s)" in message
|
||||
assert "does not switch" in message
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
|
||||
173
tests/agents/chat/test_provider_visibility.py
Normal file
173
tests/agents/chat/test_provider_visibility.py
Normal file
@@ -0,0 +1,173 @@
|
||||
"""Provider-failure copy and the prompt templates it formats (#2693 P0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import yaml
|
||||
|
||||
from deeptutor.agents.loop.provider_visibility import (
|
||||
DEFAULT_FALLBACKS_AVAILABLE,
|
||||
DEFAULT_RETRY,
|
||||
DEFAULT_SERVER_ERROR,
|
||||
DEFAULT_UNAVAILABLE,
|
||||
annotate_provider_failure,
|
||||
failure_message,
|
||||
provider_label,
|
||||
retry_notice,
|
||||
unavailable_message,
|
||||
)
|
||||
from deeptutor.services.llm.exceptions import LLMAPIError
|
||||
|
||||
PROMPTS = Path(__file__).resolve().parents[3] / "deeptutor" / "agents" / "chat" / "prompts"
|
||||
|
||||
|
||||
def _translate(pack: dict[str, str]):
|
||||
"""Mimic the pipeline's ``_t``: look up, then ``str.format`` with kwargs."""
|
||||
|
||||
def translate(key: str, default: str = "", **kwargs):
|
||||
value = pack.get(key.rsplit(".", 1)[-1], default)
|
||||
if kwargs:
|
||||
try:
|
||||
return value.format(**kwargs)
|
||||
except (KeyError, IndexError, ValueError):
|
||||
return value
|
||||
return value
|
||||
|
||||
return translate
|
||||
|
||||
|
||||
class _Pipeline:
|
||||
def __init__(self, binding: str = "", model: str = "", base_url: str = "") -> None:
|
||||
self.binding = binding
|
||||
self.model = model
|
||||
self.base_url = base_url
|
||||
|
||||
|
||||
def test_provider_label_is_best_effort() -> None:
|
||||
assert provider_label(_Pipeline("deepseek", "deepseek-chat")) == ("deepseek", "deepseek-chat")
|
||||
assert provider_label(_Pipeline()) == ("unknown", "")
|
||||
|
||||
|
||||
def test_provider_label_names_the_endpoint_host() -> None:
|
||||
# "openai" alone cannot tell an operator which gateway refused the request.
|
||||
assert provider_label(_Pipeline("openai", "gpt-test", "http://127.0.0.1:9/v1")) == (
|
||||
"openai (127.0.0.1:9)",
|
||||
"gpt-test",
|
||||
)
|
||||
assert provider_label(_Pipeline("openai", "gpt-test", "")) == ("openai", "gpt-test")
|
||||
|
||||
|
||||
def test_unavailable_message_without_fallbacks_matches_the_default() -> None:
|
||||
message = unavailable_message(
|
||||
_translate({}),
|
||||
provider="deepseek",
|
||||
model="deepseek-chat",
|
||||
attempts=3,
|
||||
fallbacks=0,
|
||||
)
|
||||
|
||||
assert message == DEFAULT_UNAVAILABLE
|
||||
assert "switch" not in message.lower()
|
||||
|
||||
|
||||
def test_unavailable_message_names_the_alternative_count() -> None:
|
||||
message = unavailable_message(
|
||||
_translate({}),
|
||||
provider="deepseek",
|
||||
model="deepseek-chat",
|
||||
attempts=2,
|
||||
fallbacks=2,
|
||||
)
|
||||
|
||||
assert message.startswith(DEFAULT_UNAVAILABLE)
|
||||
assert DEFAULT_FALLBACKS_AVAILABLE.format(count=2) in message
|
||||
# P0 must not imply the switch already happened.
|
||||
assert "automatically" in message
|
||||
|
||||
|
||||
def test_retry_notice_carries_attempt_numbers() -> None:
|
||||
notice = retry_notice(
|
||||
_translate({}), provider="deepseek", model="deepseek-chat", attempt=1, total=3
|
||||
)
|
||||
|
||||
assert notice == DEFAULT_RETRY
|
||||
|
||||
|
||||
@pytest.mark.parametrize("language", ["zh", "en"])
|
||||
def test_chat_prompt_templates_format_with_the_arguments_the_loop_passes(
|
||||
language: str,
|
||||
) -> None:
|
||||
"""A template/code mismatch would surface as literal ``{provider}`` in the UI."""
|
||||
pack = yaml.safe_load((PROMPTS / language / "agentic_chat.yaml").read_text(encoding="utf-8"))[
|
||||
"notices"
|
||||
]
|
||||
|
||||
retry = retry_notice(
|
||||
_translate(pack), provider="deepseek", model="deepseek-chat", attempt=1, total=3
|
||||
)
|
||||
unavailable = unavailable_message(
|
||||
_translate(pack),
|
||||
provider="deepseek",
|
||||
model="deepseek-chat",
|
||||
attempts=3,
|
||||
fallbacks=2,
|
||||
)
|
||||
|
||||
for text in (retry, unavailable):
|
||||
assert "{" not in text and "}" not in text
|
||||
assert "deepseek" in text
|
||||
assert "3" in retry
|
||||
assert "2" in unavailable
|
||||
|
||||
|
||||
class _StatusError(Exception):
|
||||
"""Stands in for ``openai.InternalServerError``: a status, not a transport."""
|
||||
|
||||
def __init__(self, status_code: int) -> None:
|
||||
super().__init__(f"Error code: {status_code}")
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
def test_server_error_copy_names_the_provider_and_the_alternative() -> None:
|
||||
exc = LLMAPIError("raw", status_code=502, provider="openai")
|
||||
|
||||
message = failure_message(
|
||||
_translate({}),
|
||||
exc,
|
||||
provider="openai (127.0.0.1:9)",
|
||||
model="gpt-test",
|
||||
fallbacks=1,
|
||||
)
|
||||
|
||||
assert message.startswith(DEFAULT_SERVER_ERROR.format(provider="openai (127.0.0.1:9)"))
|
||||
assert DEFAULT_FALLBACKS_AVAILABLE.format(count=1) in message
|
||||
|
||||
|
||||
def test_annotation_preserves_classification_and_replaces_the_raw_text() -> None:
|
||||
raw = _StatusError(502)
|
||||
|
||||
typed = annotate_provider_failure(
|
||||
raw,
|
||||
_translate({}),
|
||||
provider="openai (127.0.0.1:9)",
|
||||
model="gpt-test",
|
||||
fallbacks=1,
|
||||
)
|
||||
|
||||
# A raw SDK error becomes a typed one so downstream retry/error handling keeps
|
||||
# working, and the message is readable instead of "Error code: 502".
|
||||
assert isinstance(typed, LLMAPIError)
|
||||
assert typed.status_code == 502
|
||||
assert "Error code: 502" not in str(typed)
|
||||
assert "server-side error" in str(typed)
|
||||
|
||||
|
||||
def test_annotation_leaves_non_provider_errors_alone() -> None:
|
||||
raw = ValueError("not a provider problem")
|
||||
|
||||
assert (
|
||||
annotate_provider_failure(raw, _translate({}), provider="openai", model="m", fallbacks=0)
|
||||
is raw
|
||||
)
|
||||
74
tests/services/model_selection/test_fallbacks.py
Normal file
74
tests/services/model_selection/test_fallbacks.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""Read-only fallback roster used by the provider-failure copy (#2693 P0)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from deeptutor.services.model_selection.fallbacks import (
|
||||
MAX_FALLBACKS,
|
||||
configured_fallbacks,
|
||||
fallback_count,
|
||||
)
|
||||
|
||||
|
||||
def _catalog(entries) -> dict:
|
||||
return {"services": {"llm": {"fallbacks": entries}}}
|
||||
|
||||
|
||||
def test_missing_key_means_no_fallbacks() -> None:
|
||||
assert configured_fallbacks({}) == []
|
||||
assert configured_fallbacks({"services": {}}) == []
|
||||
assert configured_fallbacks({"services": {"llm": {}}}) == []
|
||||
assert fallback_count({}) == 0
|
||||
|
||||
|
||||
def test_reads_profile_and_model_pairs_in_order() -> None:
|
||||
entries = [
|
||||
{"profile_id": "local-vllm", "model_id": "qwen3-32b"},
|
||||
{"profile_id": "deepseek", "model_id": "deepseek-chat"},
|
||||
]
|
||||
|
||||
assert configured_fallbacks(_catalog(entries)) == entries
|
||||
assert fallback_count(_catalog(entries)) == 2
|
||||
|
||||
|
||||
def test_drops_malformed_and_duplicate_entries() -> None:
|
||||
entries = [
|
||||
{"profile_id": "local-vllm", "model_id": "qwen3-32b"},
|
||||
{"profile_id": "local-vllm", "model_id": "qwen3-32b"},
|
||||
{"profile_id": "", "model_id": "x"},
|
||||
{"profile_id": "x"},
|
||||
"not-a-dict",
|
||||
None,
|
||||
{"profile_id": " deepseek ", "model_id": " deepseek-chat "},
|
||||
]
|
||||
|
||||
assert configured_fallbacks(_catalog(entries)) == [
|
||||
{"profile_id": "local-vllm", "model_id": "qwen3-32b"},
|
||||
{"profile_id": "deepseek", "model_id": "deepseek-chat"},
|
||||
]
|
||||
|
||||
|
||||
def test_bounded_to_the_planned_chain_cap() -> None:
|
||||
entries = [{"profile_id": f"p{i}", "model_id": f"m{i}"} for i in range(MAX_FALLBACKS + 3)]
|
||||
|
||||
assert len(configured_fallbacks(_catalog(entries))) == MAX_FALLBACKS
|
||||
|
||||
|
||||
def test_non_list_value_is_ignored() -> None:
|
||||
# A hand-edited file can hold anything; an error path must not care.
|
||||
assert configured_fallbacks(_catalog({"profile_id": "x"})) == []
|
||||
assert configured_fallbacks(_catalog("nonsense")) == []
|
||||
|
||||
|
||||
def test_unreadable_catalog_degrades_to_zero(monkeypatch) -> None:
|
||||
import deeptutor.services.model_selection.fallbacks as fallbacks
|
||||
|
||||
class _Broken:
|
||||
def load(self):
|
||||
raise RuntimeError("catalog is not initialised")
|
||||
|
||||
monkeypatch.setattr(
|
||||
"deeptutor.services.config.get_model_catalog_service",
|
||||
lambda: _Broken(),
|
||||
)
|
||||
|
||||
assert fallbacks.configured_fallbacks() == []
|
||||
Reference in New Issue
Block a user