Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
223 changes: 210 additions & 13 deletions agent/auxiliary_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2087,18 +2087,33 @@
"""Detect payment/credit/quota exhaustion errors.

Returns True for HTTP 402 (Payment Required) and for 429/other errors
whose message indicates billing exhaustion rather than rate limiting.
whose message indicates billing exhaustion or daily quota exhaustion
rather than transient rate limiting.

Daily token quota errors (e.g. Bedrock "Too many tokens per day",
Vertex AI "quota exceeded") are functionally equivalent to credit
exhaustion — the provider cannot serve the request until the quota
resets — and should trigger the same provider-fallback logic.
"""
status = getattr(exc, "status_code", None)
if status == 402:
return True
err_lower = str(exc).lower()
# OpenRouter and other providers include "credits" or "afford" in 402 bodies,
# but sometimes wrap them in 429 or other codes.
# Daily quota exhaustion from Bedrock, Vertex AI, and similar providers
# uses different language but is semantically identical to credit exhaustion.
if status in {402, 429, None}:
if any(kw in err_lower for kw in ("credits", "insufficient funds",
"can only afford", "billing",
"payment required")):
if any(kw in err_lower for kw in (
"credits", "insufficient funds",
"can only afford", "billing",
"payment required",
# Daily / monthly quota exhaustion keywords
"quota exceeded", "quota_exceeded",
"too many tokens per day", "daily limit",
"tokens per day", "daily quota",
"resource exhausted", # Vertex AI / gRPC quota errors
)):
return True
return False

Expand Down Expand Up @@ -2579,6 +2594,133 @@
return None, None, ""


def _try_main_agent_model_fallback(
failed_provider: str,
task: str = None,
reason: str = "error",
) -> Tuple[Optional[Any], Optional[str], str]:
"""Last-resort fallback to the user's main agent provider + model.

Used after the configured fallback_chain is exhausted (or empty) for
users with an explicit auxiliary provider. This is the "safety net"
layer: if nothing the user asked for can serve the request, try the
main chat model before giving up.

Skips when the failed provider already IS the main provider (no point
retrying the same backend that just failed).

Returns:
(client, model, provider_label) or (None, None, "") if no fallback.
"""
main_provider = (_read_main_provider() or "").strip()
main_model = (_read_main_model() or "").strip()
if not main_provider or not main_model or main_provider.lower() in {"auto", ""}:
return None, None, ""

skip = (failed_provider or "").lower().strip()
if main_provider.lower() == skip:
# The thing that failed IS the main model — nothing to fall back to.
return None, None, ""
if _is_provider_unhealthy(main_provider):
_log_skip_unhealthy(main_provider, task)
return None, None, ""

try:
client, resolved_model = resolve_provider_client(
provider=main_provider, model=main_model,
)
except Exception:
client, resolved_model = None, None

if client is None:
return None, None, ""

label = f"main-agent({main_provider})"
logger.info(
"Auxiliary %s: %s on %s — falling back to main agent model %s (%s)",
task or "call", reason, failed_provider, label, resolved_model or main_model,
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
)
return client, resolved_model or main_model, label


def _try_configured_fallback_chain(
task: str,
failed_provider: str,
reason: str = "error",
) -> Tuple[Optional[Any], Optional[str], str]:
"""Try user-configured fallback_chain for a specific auxiliary task.

Reads auxiliary.<task>.fallback_chain from config.yaml and tries each
entry in order. Each entry must have at least ``provider``; ``model``,
``base_url``, and ``api_key`` are optional.

Returns:
(client, model, provider_label) or (None, None, "") if no fallback.
"""
if not task:
return None, None, ""

task_config = _get_auxiliary_task_config(task)
chain = task_config.get("fallback_chain")
if not chain or not isinstance(chain, list):
return None, None, ""

skip = failed_provider.lower().strip()
tried = []

for i, entry in enumerate(chain):
if not isinstance(entry, dict):
continue
fb_provider = str(entry.get("provider", "")).strip()
if not fb_provider or fb_provider.lower() == skip:
continue
fb_model = str(entry.get("model", "")).strip() or None
fb_base_url = str(entry.get("base_url", "")).strip() or None
fb_api_key = str(entry.get("api_key", "")).strip() or None

label = f"fallback_chain[{i}]({fb_provider})"

try:
fb_client = _resolve_single_provider(
fb_provider, fb_model, fb_base_url, fb_api_key)
except Exception:
fb_client = None

if fb_client is not None:
logger.info(
"Auxiliary %s: %s on %s — configured fallback to %s (%s)",
task, reason, failed_provider, label, fb_model or "default",
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
)
return fb_client, fb_model, label
tried.append(label)

if tried:
logger.debug(
"Auxiliary %s: configured fallback_chain exhausted (tried: %s)",
task, ", ".join(tried),
)
return None, None, ""


def _resolve_single_provider(
provider: str,
model: Optional[str] = None,
base_url: Optional[str] = None,
api_key: Optional[str] = None,
) -> Optional[Any]:
"""Resolve a single provider entry from fallback_chain to an OpenAI client.

Uses the existing provider resolution infrastructure where possible.
"""
# Reuse resolve_provider_client which handles provider→client mapping
client, resolved_model = resolve_provider_client(
provider=provider,
model=model,
base_url=base_url,
api_key=api_key,
)
return client

def _resolve_auto(main_runtime: Optional[Dict[str, Any]] = None) -> Tuple[Optional[OpenAI], Optional[str]]:
"""Full auto-detection chain.

Expand Down Expand Up @@ -4526,11 +4668,17 @@
or _is_connection_error(first_err)
or _is_rate_limit_error(first_err)
)
# Only try alternative providers when the user didn't explicitly
# configure this task's provider. Explicit provider = hard constraint;
# auto (the default) = best-effort fallback chain. (#7559)
# Respect explicit provider choice for transient errors (auth, request
# validation, etc.) but allow fallback when the provider clearly cannot
# serve the request due to capacity: payment/quota exhaustion and
# connection failures are capacity problems, not request constraints.
# See #26803: daily token quota (429 + "too many tokens per day") must
# fall back just like a 402 credit error.
is_auto = resolved_provider in {"auto", "", None}
if should_fallback and is_auto:
# Capacity errors bypass the explicit-provider gate: the provider
# literally cannot serve this request regardless of user intent.
is_capacity_error = _is_payment_error(first_err) or _is_connection_error(first_err)
if should_fallback and (is_auto or is_capacity_error):
if _is_payment_error(first_err):
reason = "payment error"
# Resolve the actual provider label (resolved_provider may be
Expand All @@ -4546,8 +4694,24 @@
reason = "connection error"
logger.info("Auxiliary %s: %s on %s (%s), trying fallback",
task or "call", reason, resolved_provider, first_err)
fb_client, fb_model, fb_label = _try_payment_fallback(
resolved_provider, task, reason=reason)

# Fallback order (#26882, #26803):
# 1. User-configured fallback_chain (per-task) if set
# 2. Main agent model (last-resort safety net)
# For auto users (no explicit aux provider), use the full
# auto-detection chain instead — its Step 1 IS the main agent
# model, so users on `auto` already get main-model fallback.
fb_client, fb_model, fb_label = (None, None, "")
if is_auto:
fb_client, fb_model, fb_label = _try_payment_fallback(
resolved_provider, task, reason=reason)
else:
fb_client, fb_model, fb_label = _try_configured_fallback_chain(
task, resolved_provider or "auto", reason=reason)
if fb_client is None:
fb_client, fb_model, fb_label = _try_main_agent_model_fallback(
resolved_provider, task, reason=reason)

if fb_client is not None:
fb_kwargs = _build_call_kwargs(
fb_label, fb_model, messages,
Expand All @@ -4557,6 +4721,14 @@
base_url=str(getattr(fb_client, "base_url", "") or ""))
return _validate_llm_response(
fb_client.chat.completions.create(**fb_kwargs), task)
# All fallback layers exhausted — emit a single user-visible
# warning so the operator knows aux task is about to fail.
# (#26882) The error itself is re-raised below.
logger.warning(
"Auxiliary %s: %s on %s and all fallbacks exhausted "
"(fallback_chain + main agent model). Raising original error.",
task or "call", reason, resolved_provider,
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
)
# Connection/timeout errors leave the cached client poisoned (closed
# httpx transport, half-read stream, dead async loop). Drop it from
# the cache regardless of whether we found a fallback above so the
Expand Down Expand Up @@ -4858,8 +5030,12 @@
or _is_connection_error(first_err)
or _is_rate_limit_error(first_err)
)
# Capacity errors (payment/quota/connection) bypass the explicit-provider
# gate — the provider cannot serve the request regardless of user intent.
# See #26803: daily token quota must fall back like a 402 credit error.
is_auto = resolved_provider in {"auto", "", None}
if should_fallback and is_auto:
is_capacity_error = _is_payment_error(first_err) or _is_connection_error(first_err)
if should_fallback and (is_auto or is_capacity_error):
if _is_payment_error(first_err):
reason = "payment error"
_mark_provider_unhealthy(
Expand All @@ -4871,8 +5047,23 @@
reason = "connection error"
logger.info("Auxiliary %s (async): %s on %s (%s), trying fallback",
task or "call", reason, resolved_provider, first_err)
fb_client, fb_model, fb_label = _try_payment_fallback(
resolved_provider, task, reason=reason)

# Fallback order (#26882, #26803):
# 1. User-configured fallback_chain (per-task) if set
# 2. Main agent model (last-resort safety net)
# Auto users get the full auto-detection chain instead — its
# Step 1 IS the main agent model.
fb_client, fb_model, fb_label = (None, None, "")
if is_auto:
fb_client, fb_model, fb_label = _try_payment_fallback(
resolved_provider, task, reason=reason)
else:
fb_client, fb_model, fb_label = _try_configured_fallback_chain(
task, resolved_provider or "auto", reason=reason)
if fb_client is None:
fb_client, fb_model, fb_label = _try_main_agent_model_fallback(
resolved_provider, task, reason=reason)

if fb_client is not None:
fb_kwargs = _build_call_kwargs(
fb_label, fb_model, messages,
Expand All @@ -4888,6 +5079,12 @@
fb_kwargs["model"] = async_fb_model
return _validate_llm_response(
await async_fb.chat.completions.create(**fb_kwargs), task)
# All fallback layers exhausted — warn before re-raising. (#26882)
logger.warning(
"Auxiliary %s (async): %s on %s and all fallbacks exhausted "
"(fallback_chain + main agent model). Raising original error.",
task or "call", reason, resolved_provider,
Comment thread
ethernet8023 marked this conversation as resolved.
Dismissed
)
# Mirror the sync path: drop poisoned clients on connection/timeout
# so the next aux call rebuilds. See issue #23432.
if _is_connection_error(first_err):
Expand Down
1 change: 1 addition & 0 deletions scripts/release.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,7 @@
"santoshhumagain1887@gmail.com": "npmisantosh",
"39641663+luarss@users.noreply.github.com": "luarss",
"16263913+zccyman@users.noreply.github.com": "zccyman",
"zccyman@users.noreply.github.com": "zccyman", # PR #26998 (auxiliary fallback chain)
"ahmetosrak@Ahmet-MacBook-Air.local": "Osraka",
"98612432+Osraka@users.noreply.github.com": "Osraka",
"112634774+ryptotalent@users.noreply.github.com": "ryptotalent",
Expand Down
Loading
Loading