Skip to content

The agent that grows with you

fix(agent): preserve auto-routed provider identity

Gille293e67328c0a
diff --git a/agent/auxiliary_client.py b/agent/auxiliary_client.py
index c6db27104de..523da8e5a1e 100644
--- a/agent/auxiliary_client.py
+++ b/agent/auxiliary_client.py
@@ -4281,7 +4281,7 @@ def _retry_same_provider_sync(
extra_headers: Optional[Dict[str, str]] = None,
) -> Any:
if task == "vision":
- _, retry_client, retry_model = resolve_vision_provider_client(
+ effective_provider, retry_client, retry_model = resolve_vision_provider_client(
provider=resolved_provider,
model=final_model,
base_url=resolved_base_url,
@@ -4297,6 +4297,9 @@ def _retry_same_provider_sync(
api_mode=resolved_api_mode,
main_runtime=main_runtime,
)
+ effective_provider = _effective_provider_for_client(
+ retry_client, resolved_provider,
+ )
if retry_client is None:
raise RuntimeError(
f"Auxiliary {task or 'call'}: provider {resolved_provider} could not be rebuilt after recovery"
@@ -4304,7 +4307,7 @@ def _retry_same_provider_sync(
retry_base = str(getattr(retry_client, "base_url", "") or "")
retry_kwargs = _build_call_kwargs(
- resolved_provider,
+ effective_provider or resolved_provider,
retry_model or final_model,
messages,
temperature=temperature,
@@ -4353,7 +4356,7 @@ async def _retry_same_provider_async(
extra_headers: Optional[Dict[str, str]] = None,
) -> Any:
if task == "vision":
- _, retry_client, retry_model = resolve_vision_provider_client(
+ effective_provider, retry_client, retry_model = resolve_vision_provider_client(
provider=resolved_provider,
model=final_model,
base_url=resolved_base_url,
@@ -4369,6 +4372,9 @@ async def _retry_same_provider_async(
api_key=resolved_api_key,
api_mode=resolved_api_mode,
)
+ effective_provider = _effective_provider_for_client(
+ retry_client, resolved_provider,
+ )
if retry_client is None:
raise RuntimeError(
f"Auxiliary {task or 'call'}: provider {resolved_provider} could not be rebuilt after recovery"
@@ -4376,7 +4382,7 @@ async def _retry_same_provider_async(
retry_base = str(getattr(retry_client, "base_url", "") or "")
retry_kwargs = _build_call_kwargs(
- resolved_provider,
+ effective_provider or resolved_provider,
retry_model or final_model,
messages,
temperature=temperature,
@@ -5388,11 +5394,11 @@ def _resolve_single_provider(
)
return client
-def _resolve_auto(
+def _resolve_auto_route(
main_runtime: Optional[Dict[str, Any]] = None,
task: Optional[str] = None,
-) -> Tuple[Optional[OpenAI], Optional[str]]:
- """Full auto-detection chain.
+) -> Tuple[Optional[OpenAI], Optional[str], str]:
+ """Full auto-detection chain, including the selected provider identity.
Priority:
1. User's main provider + main model, regardless of provider type.
@@ -5529,7 +5535,7 @@ def _resolve_auto(
if client is not None:
logger.info("Auxiliary auto-detect: using main provider %s (%s)",
main_provider, resolved or main_model)
- return client, resolved or main_model
+ return client, resolved or main_model, resolved_provider
# ── Step 2: user-configured fallback policy ─────────────────────────
# In auto mode, respect the task-specific fallback chain first, then the
@@ -5537,14 +5543,14 @@ def _resolve_auto(
# hardcoded provider discovery chain below is only the convenience default
# for users who have not declared a fallback policy.
if task:
- fb_client, fb_model, _fb_label = _try_configured_fallback_chain(
+ fb_client, fb_model, fb_label = _try_configured_fallback_chain(
task, main_provider or "auto", reason="main provider unavailable")
if fb_client is not None:
- return fb_client, fb_model
- fb_client, fb_model, _fb_label = _try_main_fallback_chain(
+ return fb_client, fb_model, _fallback_provider_from_label(fb_label)
+ fb_client, fb_model, fb_label = _try_main_fallback_chain(
task, main_provider or "auto", reason="main provider unavailable")
if fb_client is not None:
- return fb_client, fb_model
+ return fb_client, fb_model, fb_label
# ── Step 3: aggregator / fallback chain ──────────────────────────────
tried = []
@@ -5560,13 +5566,43 @@ def _resolve_auto(
label, model or "default", ", ".join(tried))
else:
logger.info("Auxiliary auto-detect: using %s (%s)", label, model or "default")
- return client, model
+ return client, model, label
tried.append(label)
logger.warning("Auxiliary auto-detect: no provider available (tried: %s). "
"Compression, summarization, and memory flush will not work. "
"Set OPENROUTER_API_KEY or configure a local model in config.yaml.",
", ".join(tried))
- return None, None
+ return None, None, ""
+
+
+def _resolve_auto(
+ main_runtime: Optional[Dict[str, Any]] = None,
+ task: Optional[str] = None,
+) -> Tuple[Optional[OpenAI], Optional[str]]:
+ """Backward-compatible auto resolver for callers that only need client/model."""
+ client, model, _provider = _resolve_auto_route(main_runtime=main_runtime, task=task)
+ return client, model
+
+
+def _tag_effective_provider(client: Any, provider: str) -> None:
+ """Retain auto-routing identity on the client that survives cache reuse."""
+ if client is None or not provider:
+ return
+ try:
+ setattr(client, "_hermes_aux_effective_provider", provider)
+ except (AttributeError, TypeError):
+ logger.debug(
+ "Auxiliary client %s cannot retain effective provider %s",
+ type(client).__name__, provider,
+ )
+
+
+def _effective_provider_for_client(client: Any, fallback: str) -> str:
+ """Return the concrete provider selected for an auto-routed client."""
+ effective_provider = getattr(client, "_hermes_aux_effective_provider", "")
+ if isinstance(effective_provider, str) and effective_provider:
+ return effective_provider
+ return str(fallback or "")
# ── Centralized Provider Router ─────────────────────────────────────────────
@@ -5847,7 +5883,10 @@ def resolve_provider_client(
# ── Auto: try all providers in priority order ────────────────────
if provider == "auto":
- client, resolved = _resolve_auto(main_runtime=main_runtime, task=task)
+ client, resolved, effective_provider = _resolve_auto_route(
+ main_runtime=main_runtime,
+ task=task,
+ )
if client is None:
return None, None
# When auto-detection lands on a non-OpenRouter provider (e.g. a
@@ -5860,8 +5899,12 @@ def resolve_provider_client(
"auxiliary provider (using %r instead)", model, resolved)
model = None
final_model = model or resolved
- return (_to_async_client(client, final_model, is_vision=is_vision) if async_mode
- else (client, final_model))
+ routed_client, routed_model = (
+ _to_async_client(client, final_model, is_vision=is_vision)
+ if async_mode else (client, final_model)
+ )
+ _tag_effective_provider(routed_client, effective_provider)
+ return routed_client, routed_model
# ── OpenRouter ───────────────────────────────────────────
if provider == "openrouter":
@@ -8697,6 +8740,7 @@ def _call_llm_impl(
resolved_api_mode = api_mode
effective_extra_body = _get_task_extra_body(task)
effective_extra_body.update(extra_body or {})
+ effective_provider = resolved_provider
if task == "vision":
effective_provider, client, final_model = resolve_vision_provider_client(
@@ -8733,6 +8777,9 @@ def _call_llm_impl(
api_mode=resolved_api_mode,
main_runtime=main_runtime,
)
+ effective_provider = _effective_provider_for_client(
+ client, resolved_provider,
+ )
if client is None:
# When the user explicitly chose a non-OpenRouter provider but no
# credentials were found, honor the task fallback_chain before
@@ -8747,6 +8794,7 @@ def _call_llm_impl(
if fb_client is not None:
client, final_model = fb_client, fb_model
resolved_provider = fb_label or resolved_provider
+ effective_provider = resolved_provider
else:
raise RuntimeError(
f"Provider '{_explicit}' is set in config.yaml but no API key "
@@ -8761,13 +8809,19 @@ def _call_llm_impl(
if client is None and not resolved_base_url:
logger.info("Auxiliary %s: provider %s unavailable, trying auto-detection chain",
task or "call", resolved_provider)
- client, final_model = _get_cached_client("auto", main_runtime=main_runtime, task=task)
+ client, final_model = _get_cached_client(
+ "auto", main_runtime=main_runtime, task=task,
+ )
+ effective_provider = _effective_provider_for_client(
+ client, "auto",
+ )
if client is None:
raise RuntimeError(
f"No LLM provider configured for task={task} provider={resolved_provider}. "
f"Run: hermes setup")
effective_timeout = _effective_aux_timeout(task, timeout)
+ request_provider = effective_provider or resolved_provider
_set_relay_auxiliary_route(
resolved_provider,
final_model,
@@ -8785,7 +8839,7 @@ def _call_llm_impl(
# endpoint-specific temperature overrides can distinguish
# api.moonshot.ai vs api.kimi.com/coding even on auto-detected routes.
kwargs = _build_call_kwargs(
- resolved_provider, final_model, messages,
+ request_provider, final_model, messages,
temperature=temperature, max_tokens=max_tokens,
tools=tools, timeout=effective_timeout, extra_body=effective_extra_body,
reasoning_config=reasoning_config,
@@ -9463,6 +9517,7 @@ async def _async_call_llm_impl(
task, provider, model, base_url, api_key)
effective_extra_body = _get_task_extra_body(task)
effective_extra_body.update(extra_body or {})
+ effective_provider = resolved_provider
if task == "vision":
effective_provider, client, final_model = resolve_vision_provider_client(
@@ -9500,6 +9555,9 @@ async def _async_call_llm_impl(
api_mode=resolved_api_mode,
main_runtime=main_runtime,
)
+ effective_provider = _effective_provider_for_client(
+ client, resolved_provider,
+ )
if client is None:
_explicit = (resolved_provider or "").strip().lower()
if _explicit and _explicit not in {"auto", "openrouter", "custom"}:
@@ -9511,6 +9569,7 @@ async def _async_call_llm_impl(
fb_client, fb_model or "", is_vision=(task == "vision")
)
resolved_provider = fb_label or resolved_provider
+ effective_provider = resolved_provider
else:
raise RuntimeError(
f"Provider '{_explicit}' is set in config.yaml but no API key "
@@ -9520,13 +9579,22 @@ async def _async_call_llm_impl(
if client is None and not resolved_base_url:
logger.info("Auxiliary %s: provider %s unavailable, trying auto-detection chain",
task or "call", resolved_provider)
- client, final_model = _get_cached_client("auto", async_mode=True, main_runtime=main_runtime, task=task)
+ client, final_model = _get_cached_client(
+ "auto",
+ async_mode=True,
+ main_runtime=main_runtime,
+ task=task,
+ )
+ effective_provider = _effective_provider_for_client(
+ client, "auto",
+ )
if client is None:
raise RuntimeError(
f"No LLM provider configured for task={task} provider={resolved_provider}. "
f"Run: hermes setup")
effective_timeout = _effective_aux_timeout(task, timeout)
+ request_provider = effective_provider or resolved_provider
_set_relay_auxiliary_route(
resolved_provider,
final_model,
@@ -9538,7 +9606,7 @@ async def _async_call_llm_impl(
# api.moonshot.ai vs api.kimi.com/coding even on auto-detected routes.
_client_base = str(getattr(client, "base_url", "") or "")
kwargs = _build_call_kwargs(
- resolved_provider, final_model, messages,
+ request_provider, final_model, messages,
temperature=temperature, max_tokens=max_tokens,
tools=tools, timeout=effective_timeout, extra_body=effective_extra_body,
reasoning_config=reasoning_config,
diff --git a/tests/agent/test_auxiliary_client.py b/tests/agent/test_auxiliary_client.py
index 65ed2f54c7d..0a512e166a6 100644
--- a/tests/agent/test_auxiliary_client.py
+++ b/tests/agent/test_auxiliary_client.py
@@ -4426,3 +4426,65 @@ class TestAsynchronousFallbackCachePlans:
wire_tools = client.chat.completions.create.call_args.kwargs["tools"]
assert "cache_control" in wire_tools[-1]
assert "cache_control" not in tools[-1]
+
+
+class TestAutoRoutedProviderProfileHooks:
+ def test_cached_auto_route_projects_selected_provider_on_every_request(self):
+ """Auto routing must retain the concrete provider for request hooks."""
+ import agent.auxiliary_client as aux
+ from providers.base import ProviderProfile
+
+ hook_calls = []
+
+ class DynamicProfile(ProviderProfile):
+ def build_api_kwargs_extras(self, *, reasoning_config=None, **context):
+ hook_calls.append(context)
+ return {}, {
+ "extra_headers": {
+ "Authorization": f"Bearer token-{len(hook_calls)}",
+ },
+ }
+
+ profile = DynamicProfile(name="agentgateway")
+ client = MagicMock()
+ client.base_url = "https://gateway.example.com/v1"
+ response = MagicMock()
+ response.choices = [MagicMock(message=MagicMock(content="ok"))]
+
+ def lookup_profile(name):
+ return profile if name == "agentgateway" else None
+
+ aux.shutdown_cached_clients()
+ try:
+ with (
+ patch(
+ "agent.auxiliary_client._resolve_task_provider_model",
+ return_value=("auto", "gateway/model", None, None, None),
+ ),
+ patch(
+ "agent.auxiliary_client._resolve_auto_route",
+ return_value=(client, "gateway/model", "agentgateway"),
+ ) as resolve_auto,
+ patch("providers.get_provider_profile", side_effect=lookup_profile),
+ patch(
+ "agent.auxiliary_client._relay_sync_completion",
+ return_value=response,
+ ) as relay,
+ ):
+ for _ in range(2):
+ result = call_llm(
+ task="title_generation",
+ messages=[{"role": "user", "content": "title this"}],
+ )
+ assert result is response
+ finally:
+ aux.shutdown_cached_clients()
+
+ resolve_auto.assert_called_once()
+ assert len(hook_calls) == 2
+ assert relay.call_args_list[0].args[1]["extra_headers"] == {
+ "Authorization": "Bearer token-1",
+ }
+ assert relay.call_args_list[1].args[1]["extra_headers"] == {
+ "Authorization": "Bearer token-2",
+ }