Files
hermes-agent/agent/agent_init_fallback.py
Teknium e7aee67e36 fix(fallback): an init-time fallback keeps its entry's explicit api_mode
walk_init_fallback_chain recomputed every rung's api_mode through
_fallback_api_mode_resolved, so an entry's explicit `api_mode:`
(e.g. an xai-oauth rung pinned to chat_completions) was overridden at
startup while the per-turn path (route_binding.bind_route_entry) keeps
it. Read the entry's hint first, as the per-turn path does, and only
re-detect when the entry declares nothing.

Review finding on #162267 (greptile).
2026-12-01 14:02:07 -08:00

146 lines
7.9 KiB
Python

"""Init-time fallback chain: entry normalization, chain setup, and the fallback's api_mode."""
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any, Dict, List
logger = logging.getLogger("run_agent")
def _fallback_entries(fallback_model) -> list[dict[str, Any]]:
"""Normalize legacy single-dict ``fallback_model`` / list ``fallback_providers``."""
if isinstance(fallback_model, dict):
fallback_model = [fallback_model]
if not isinstance(fallback_model, list):
return []
return [
f for f in fallback_model if isinstance(f, dict) and f.get("provider") and f.get("model")
]
def _init_fallback_chain(agent, fallback_model):
# Stable pool-entry identity: OAuth refreshes can replace the token before a failed
# request is recovered, so the key value alone can't attribute the failure.
from agent.agent_runtime_helpers import sync_credential_pool_entry_id
sync_credential_pool_entry_id(agent)
# Ordered backups tried when the primary is exhausted (legacy single-dict or list).
agent._fallback_chain = _fallback_entries(fallback_model)
agent._fallback_index = 0
agent._fallback_activated = getattr(agent, "_fallback_activated", False)
# Legacy attribute kept for backward compat (tests, external callers)
agent._fallback_model = agent._fallback_chain[0] if agent._fallback_chain else None
chain = agent._fallback_chain
if chain and not agent.quiet_mode:
labels = [f"{f['model']} ({f['provider']})" for f in chain]
if len(chain) == 1:
print(f"🔄 Fallback model: {labels[0]}")
else:
print(f"🔄 Fallback chain ({len(chain)} providers): " + " → ".join(labels))
@dataclass(frozen=True)
class InitFallbackPick:
"""The init-time chain walk's result. ``client`` is the routed client of the rung the agent
now carries (provider, model and api_mode already switched); ``None`` with ``bound`` set means
a MoA rung bound its facade, and with neither set no rung resolved (``refused`` names why)."""
client: Any = None
bound: bool = False
refused: tuple[tuple[str, str], ...] = ()
def walk_init_fallback_chain(agent, fallback_model) -> InitFallbackPick:
"""Put ``agent`` on the first fallback rung whose credentials resolve (the primary had none)."""
from agent.auxiliary_client import resolve_provider_client
refused = []
for fb in _fallback_entries(fallback_model):
fb_provider = str(fb["provider"])
try:
from hermes_cli.fallback_config import resolve_entry_api_key
fb_client, fb_model = resolve_provider_client(
fb["provider"], model=fb["model"], raw_codex=True,
explicit_base_url=fb.get("base_url"), explicit_api_key=resolve_entry_api_key(fb),
)
except Exception as fb_exc:
logger.debug("Init-time fallback entry %s failed: %s", fb_provider, fb_exc, exc_info=True)
# A bare exception (``KeyError()``) stringifies empty; name its type instead.
refused.append((fb_provider, str(fb_exc) or type(fb_exc).__name__))
continue
if fb_client is None:
# The router returns None when no credentials are usable for the entry — a skip
# that leaves no trace otherwise, hiding key-less fallback entries from the log.
logger.debug("Init-time fallback entry %s resolved no usable credentials", fb_provider)
refused.append((fb_provider, "no usable credentials"))
continue
agent._fallback_activated = True
if fb_provider.strip().lower() == "moa":
# The chokepoint handed back the preset's aggregator client, which only proves the
# preset resolves and its aggregator has credentials. A MoA entry means the preset
# itself (same as ``provider: moa`` in config), so bind the facade, not the aggregator.
from agent.moa_loop import bind_moa_runtime
bind_moa_runtime(agent, fb["model"])
return InitFallbackPick(bound=True)
agent.provider = agent.requested_provider = fb["provider"]
agent.model = fb_model or fb["model"]
recompute_init_fallback_api_mode(agent, fb_client, fb)
return InitFallbackPick(client=fb_client)
return InitFallbackPick(refused=tuple(refused))
def bind_init_fallback_runtime(agent) -> None:
"""Route state an init-time fallback owes its rung once the client is built, as the per-turn
switch (``route_binding.bind_route_entry``) does: the credential pool follows the rung, so
401/429 recovery never rotates the unreachable primary's accounts, and prompt caching is
decided for the rung, not the primary ``_init_prompt_cache_config`` saw (a Claude rung behind
a Codex primary otherwise runs uncached). ``_cache_disabled`` still wins. The pool stays bound
only when it holds the rung's key, so it rotates among its own entries; otherwise (an explicit
``api_key`` / ``key_env`` outside it, a per-request token callable) the next turn's restore
would reselect from it and swap the rung's credential for an unrelated static one.
"""
from agent.chat_completion_helpers import _rebind_fallback_credential_pool
from agent.credential_auth_recovery import _entry_for
_rebind_fallback_credential_pool(agent, agent.provider, agent.model)
pool, key = getattr(agent, "_credential_pool", None), getattr(agent, "api_key", None)
static_key = isinstance(key, str) and bool(key)
if pool is not None and not (static_key and _entry_for(pool, None, key) is not None):
pool_provider = getattr(pool, "provider", None) or agent.provider
if static_key:
from agent.turn_failure_copy import auth_add_command
logger.warning(
"Fallback %s/%s: its key is not in the %s credential pool, so that pool is not used for "
"rotation. Run `%s` with this key, or remove the fallback entry's own api_key / key_env "
"to use the pool's keys.",
agent.provider, agent.model, pool_provider, auth_add_command(pool_provider, auth_type="api-key"))
else:
logger.warning(
"Fallback %s/%s does not use a static key (e.g. it mints a per-request token), so the %s "
"credential pool is not used for rotation.", agent.provider, agent.model, pool_provider)
agent._credential_pool = agent._credential_pool_entry_id = None
agent._use_prompt_caching, agent._use_native_cache_layout = agent._anthropic_prompt_cache_policy()
def recompute_init_fallback_api_mode(agent, fb_client, fb: dict) -> None:
"""Give an init-time fallback its own api_mode instead of the unreachable primary's.
A Nous primary configured with ``api_mode: codex_responses`` otherwise leaves a fallback whose
profile serves that model on chat completions (``api_mode_for_model``) on the Responses API,
which silently drops reasoning content (#46527).
The per-turn path (``route_binding.bind_route_entry``) keeps an entry's explicit ``api_mode``
and otherwise recomputes via ``_fallback_api_mode_resolved``; this keeps init in agreement, and
runs before the ``_primary_runtime`` snapshot so ``restore_primary_runtime`` replays the mode.
A detection failure keeps the primary's mode and never blocks the fallback itself.
"""
from agent.chat_completion_helpers import _fallback_api_mode_hint, _fallback_api_mode_resolved
try:
explicit, hinted = _fallback_api_mode_hint(fb, agent.provider, str(fb.get("base_url") or "").strip() or None)
agent.api_mode = hinted if explicit else _fallback_api_mode_resolved(
agent, agent.provider, agent.model, str(getattr(fb_client, "base_url", "") or ""))
except Exception:
logger.debug("Init-time fallback api_mode detection failed for %s", agent.provider, exc_info=True)
return
if hasattr(agent, "_transport_cache"):
agent._transport_cache.clear()