The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(agent): pin the reset_at reach through try_activate_fallback and add opt-in fallback.min_switch_reset_seconds
teknium1f568b860d7da
diff --git a/agent/chat_completion_helpers.py b/agent/chat_completion_helpers.pyindex 327e734b99e..315641d14cf 100644--- a/agent/chat_completion_helpers.py+++ b/agent/chat_completion_helpers.py@@ -2001,7 +2001,9 @@ def try_activate_fallback(agent, reason: "FailoverReason | None" = None, reset_a"""Switch to the next fallback model/provider in the chain; False when exhausted. Swaps client,model slug and provider in place so the retry loop continues on the new backend; clientconstruction goes through resolve_provider_client (no duplicated provider→key mappings)."""- from agent.fallback_cooldown import _arm_rate_limit_cooldown+ from agent.fallback_cooldown import _arm_rate_limit_cooldown, switch_deferred_by_reset+ if switch_deferred_by_reset(agent, reason, reset_at):+ return Falsecooldown_seconds = _arm_rate_limit_cooldown(agent, reason, reset_at=reset_at)while True:if agent._fallback_index >= len(agent._fallback_chain):diff --git a/agent/fallback_cooldown.py b/agent/fallback_cooldown.pyindex 785353dbcda..769a5fbf5cb 100644--- a/agent/fallback_cooldown.py+++ b/agent/fallback_cooldown.py@@ -11,6 +11,37 @@ logger = logging.getLogger(__name__)_RATE_LIMIT_FAILOVER_REASONS = frozenset({FailoverReason.rate_limit, FailoverReason.billing, FailoverReason.upstream_rate_limit})+def _provider_reset_delay(reset_at) -> float | None:+ """Seconds until the provider-declared reset, or None when missing/invalid/expired."""+ from agent.credential_pool import _parse_absolute_timestamp+ parsed = _parse_absolute_timestamp(reset_at)+ delay = parsed - time.time() if parsed is not None else None+ if delay is not None and math.isfinite(delay) and delay > 0:+ return delay+ return None+++def switch_deferred_by_reset(agent, reason: "FailoverReason | None", reset_at) -> bool:+ """Opt-in ``fallback.min_switch_reset_seconds`` (default 0 = off, #117484): when the primary's+ rate limit reopens sooner than N seconds, switching model mid-task costs more than waiting, so+ the fallback walk is skipped and the retry loop's own backoff rides out the window. Only for+ rate-limit failovers leaving the primary with a valid future ``reset_at``."""+ if reason not in _RATE_LIMIT_FAILOVER_REASONS or getattr(agent, "_fallback_activated", False):+ return False+ try:+ from hermes_cli.config import load_config+ threshold = float((load_config() or {}).get("fallback", {}).get("min_switch_reset_seconds") or 0)+ except Exception:+ return False+ if threshold <= 0:+ return False+ delay = _provider_reset_delay(reset_at)+ if delay is None or delay >= threshold:+ return False+ logging.info("Rate limit resets in %.0f s (< fallback.min_switch_reset_seconds=%.0f): staying on the primary", delay, threshold)+ return True++def _arm_rate_limit_cooldown(agent, reason: "FailoverReason | None", reset_at=None,) -> int | None:@@ -30,10 +61,8 @@ def _arm_rate_limit_cooldown(return Nonebackoff_count = getattr(agent, "_rate_limit_backoff_count", 0)agent._rate_limit_backoff_count = backoff_count + 1- from agent.credential_pool import _parse_absolute_timestamp- parsed_reset_at = _parse_absolute_timestamp(reset_at)- provider_delay = parsed_reset_at - time.time() if parsed_reset_at is not None else None- if provider_delay is not None and math.isfinite(provider_delay) and provider_delay > 0:+ provider_delay = _provider_reset_delay(reset_at)+ if provider_delay is not None:backoff_seconds = math.ceil(provider_delay)source = "provider reset"else:diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex c6adde7d7e2..9b9a2e6acdc 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -22,6 +22,10 @@ DEFAULT_CONFIG = {"model": "","providers": {},"fallback_providers": [],+ # min_switch_reset_seconds: opt-in (0 = off). When a rate-limited primary declares a reset+ # sooner than this many seconds, stay on it (the retry backoff rides out the window) instead+ # of switching the turn to a fallback model.+ "fallback": {"min_switch_reset_seconds": 0},"credential_pool_strategies": {},"toolsets": ["hermes-cli"],# journal_mode: SQLite journal mode for every Hermes DB. "wal" default; use "delete" ondiff --git a/tests/agent/test_provider_reset_cooldown.py b/tests/agent/test_provider_reset_cooldown.pyindex 927d3f5c08b..c46bf46ce0d 100644--- a/tests/agent/test_provider_reset_cooldown.py+++ b/tests/agent/test_provider_reset_cooldown.py@@ -6,8 +6,29 @@ from unittest.mock import MagicMock, patchimport pytestfrom agent.error_classifier import FailoverReason-from agent.fallback_cooldown import _arm_rate_limit_cooldownfrom agent.turn_recovery import route_classified_error+from run_agent import AIAgent+++def _agent_with_one_fallback():+ with (+ patch("model_tools.get_tool_definitions", return_value=[]),+ patch("model_tools.check_toolset_requirements", return_value={}),+ patch("agent.process_bootstrap.OpenAI"),+ ):+ agent = AIAgent(+ api_key="test-key", provider="openrouter", base_url="https://openrouter.ai/api/v1",+ model="primary/model", quiet_mode=True, skip_context_files=True, skip_memory=True,+ fallback_model=[{"provider": "openai-codex", "model": "gpt-5.5"}],+ )+ agent.client = None+ return agent+++def _fallback_client():+ client = SimpleNamespace(base_url="https://chatgpt.com/backend-api/codex", api_key="fb-key")+ client.chat = SimpleNamespace(completions=SimpleNamespace(create=lambda *a, **k: None))+ return client@pytest.mark.parametrize(@@ -20,27 +41,38 @@ from agent.turn_recovery import route_classified_error(1_699_999_999, 60),],)-def test_rate_limit_cooldown_prefers_only_valid_future_provider_resets(- reset_at, expected_seconds,-):- agent = SimpleNamespace(- provider="openrouter",- _primary_runtime={"provider": "openrouter"},- _fallback_activated=False,- _rate_limit_backoff_count=0,- )+def test_fallback_switch_benches_primary_until_valid_future_provider_reset(reset_at, expected_seconds):+ """Drives the production entry (agent._try_activate_fallback -> try_activate_fallback):+ the reset_at kwarg must reach the cooldown arming, not just the helper."""+ agent = _agent_with_one_fallback()with (+ patch("agent.auxiliary_client.resolve_provider_client", return_value=(_fallback_client(), "gpt-5.5")),patch("agent.fallback_cooldown.time.time", return_value=1_700_000_000),patch("agent.fallback_cooldown.time.monotonic", return_value=500),):- armed = _arm_rate_limit_cooldown(- agent, FailoverReason.rate_limit, reset_at=reset_at,- )+ assert agent._try_activate_fallback(reason=FailoverReason.rate_limit, reset_at=reset_at) is True- assert armed == expected_seconds+ assert agent.model == "gpt-5.5"assert agent._rate_limited_until == 500 + expected_seconds[email protected](("threshold", "switched"), [(0, True), (120, False)])+def test_min_switch_reset_seconds_keeps_primary_when_reset_is_imminent(threshold, switched):+ """Opt-in fallback.min_switch_reset_seconds (#117484): a reset 30 s out is below a 120 s+ threshold, so the turn stays on the primary and no cooldown is armed; 0 (default) switches."""+ agent = _agent_with_one_fallback()+ with (+ patch("agent.auxiliary_client.resolve_provider_client", return_value=(_fallback_client(), "gpt-5.5")),+ patch("hermes_cli.config.load_config", return_value={"fallback": {"min_switch_reset_seconds": threshold}}),+ patch("agent.fallback_cooldown.time.time", return_value=1_700_000_000),+ ):+ activated = agent._try_activate_fallback(reason=FailoverReason.rate_limit, reset_at=1_700_000_030)++ assert activated is switched+ assert (agent.model == "gpt-5.5") is switched+ assert (getattr(agent, "_rate_limited_until", None) is not None) is switched++def test_eager_rate_limit_fallback_forwards_extracted_reset_time():reset_at = 1_900_000_000agent = MagicMock()diff --git a/website/docs/user-guide/features/fallback-providers.md b/website/docs/user-guide/features/fallback-providers.mdindex 7dabb0b02e0..6c47a6f2d0b 100644--- a/website/docs/user-guide/features/fallback-providers.md+++ b/website/docs/user-guide/features/fallback-providers.md@@ -39,6 +39,17 @@ fallback_providers:Each entry requires both `provider` and `model`. Entries missing either field are ignored.+When a rate-limit response names its reset time, the primary is benched until exactly then (a provider that says nothing gets the exponential 60 s → 4 h backoff). Optionally, skip the switch when the primary reopens soon:++```yaml+fallback:+ min_switch_reset_seconds: 120 # 0 (default) = always switch+```++| Key | Default | Effect |+|-----|---------|--------|+| `fallback.min_switch_reset_seconds` | `0` (off) | A rate-limited primary whose declared reset is sooner than this many seconds is not swapped for a fallback; the retry backoff waits out the window instead. |+Gemini fallback entries accept `gemini`, `google`, `google-gemini`, and`google-ai-studio`. On Google's native API endpoint, all use the native Geminiclient, including its `generationConfig.thinkingConfig` translation. A custom