The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(gateway): opt-in `served_model` footer field shows the model that really answered
teknium1bafb778edcbd
diff --git a/agent/agent_runtime_helpers.py b/agent/agent_runtime_helpers.pyindex d92f0cb7955..7ecd400daba 100644--- a/agent/agent_runtime_helpers.py+++ b/agent/agent_runtime_helpers.py@@ -1858,6 +1858,9 @@ def create_openai_client(agent, client_kwargs: dict, *, reason: str, shared: boo# ``process_bootstrap.OpenAI`` is a lazy SDK proxy; resolved at call time so tests can patch it.from agent import process_bootstrapclient = process_bootstrap.OpenAI(**client_kwargs)+ # Routing proxies name the deployment they served in a response header (#54864).+ from agent.served_model import install_served_model_capture+ install_served_model_capture(agent, client)_ra().logger.info("OpenAI client created (%s, shared=%s) %s", reason, shared, agent._client_log_context())return clientdiff --git a/agent/served_model.py b/agent/served_model.pynew file mode 100644index 00000000000..4f68150729f--- /dev/null+++ b/agent/served_model.py@@ -0,0 +1,68 @@+"""Per-response *served model* capture for routing proxies (#54864).++A LiteLLM-style proxy answers with the configured alias in the body's ``model`` field and puts+the deployment it really routed to in a response header (``x-litellm-model-id``, else the+upstream ``x-litellm-model-api-base``). The OpenAI SDK's parsed objects drop headers, so the+capture rides an ``httpx`` response hook on the client Hermes builds for the agent; it stores+the header onto ``agent.last_served_model`` (``None`` when the response carried none, so a+value never outlives the request that produced it). Consumers: ``agent/turn_finalizer.py``+(result ``served_model`` / ``requested_model``) and the opt-in gateway footer field+``served_model`` (``gateway/runtime_footer.py``). Fail-open everywhere.+"""++from __future__ import annotations++import logging+from typing import Any, Optional++logger = logging.getLogger(__name__)++SERVED_MODEL_HEADERS: tuple[str, ...] = ("x-litellm-model-id", "x-litellm-model-api-base")+_HOOK_MARK = "_hermes_served_model_hook"+++def served_model_from_headers(headers: Any) -> Optional[str]:+ """First non-empty served-model header, or ``None``."""+ if headers is None or not hasattr(headers, "get"):+ return None+ for name in SERVED_MODEL_HEADERS:+ value = headers.get(name)+ if value not in (None, ""):+ return str(value).strip()+ return None+++def install_served_model_capture(agent: Any, client: Any) -> None:+ """Register the response hook on *client*'s ``httpx`` transport (idempotent per client)."""+ http_client = getattr(client, "_client", None)+ hooks = getattr(http_client, "event_hooks", None)+ if not isinstance(hooks, dict):+ return+ if any(getattr(h, _HOOK_MARK, False) for h in hooks.get("response", ())):+ return++ def _on_response(response: Any) -> None:+ try:+ if 200 <= int(getattr(response, "status_code", 0)) < 300:+ agent.last_served_model = served_model_from_headers(getattr(response, "headers", None))+ except Exception:+ logger.debug("served-model header capture skipped", exc_info=True)++ setattr(_on_response, _HOOK_MARK, True)+ try:+ # httpx copies on assignment; rebuild the mapping instead of mutating the live list.+ http_client.event_hooks = {**hooks, "response": [*hooks.get("response", ()), _on_response]}+ except Exception:+ logger.debug("served-model hook install skipped", exc_info=True)+++def result_model_fields(agent: Any) -> dict[str, Optional[str]]:+ """``requested_model`` / ``served_model`` for the turn result: the proxy header when the+ last response carried one, else Hermes' own fallback route (primary → active model)."""+ served = getattr(agent, "last_served_model", None)+ requested = agent.model+ if not served and getattr(agent, "_fallback_activated", False):+ primary = str((getattr(agent, "_primary_runtime", None) or {}).get("model") or "").strip()+ if primary and primary != agent.model:+ requested, served = primary, agent.model+ return {"requested_model": requested, "served_model": served or None}diff --git a/agent/turn_finalizer.py b/agent/turn_finalizer.pyindex a1a46cfc488..92663289b8e 100644--- a/agent/turn_finalizer.py+++ b/agent/turn_finalizer.py@@ -18,6 +18,7 @@ from agent.context_compressor import _DB_PERSISTED_MARKERfrom agent.message_content import flatten_message_textfrom agent.message_metadata import append_message, stamp_message_timestampfrom agent.message_sanitization import _sanitize_surrogates+from agent.served_model import result_model_fields# Verification-continuation nudges (verify-on-stop / pre_verify) must be stripped from# returned/live history to avoid role-alternation breaks; the assistant response is@@ -572,6 +573,8 @@ def finalize_turn("pre_transform_response": _pre_transform_response,"response_previewed": getattr(agent, "_response_was_previewed", False),"model": agent.model,+ # requested_model / served_model: proxy-reported deployment or Hermes' own fallback route.+ **result_model_fields(agent),"provider": agent.provider,"base_url": agent.base_url,**{key: getattr(agent, f"session_{key}") for key in _SESSION_TOKEN_KEYS},diff --git a/gateway/run_turn.py b/gateway/run_turn.pyindex 569e1d637cb..3d1f213eb84 100644--- a/gateway/run_turn.py+++ b/gateway/run_turn.py@@ -1627,6 +1627,8 @@ class GatewayTurnMixin:context_tokens=agent_result.get("last_prompt_tokens", 0) or 0,context_length=agent_result.get("context_length") or None,cwd=_terminal_scope_cwd(""), turn_seconds=_turn_seconds,+ requested_model=agent_result.get("requested_model"),+ served_model=agent_result.get("served_model"),)except Exception as _footer_err:logger.debug("runtime_footer build failed: %s", _footer_err)diff --git a/gateway/runtime_footer.py b/gateway/runtime_footer.pyindex 090bdf0cc9f..54c923c8209 100644--- a/gateway/runtime_footer.py+++ b/gateway/runtime_footer.py@@ -3,7 +3,9 @@ minimal. Config: ``display.runtime_footer: {enabled: bool, fields: [model, conte(order shown; drop any to hide), per-platform override ``display.platforms.<p>.runtime_footer``,toggled by ``/footer on|off``. Fields: ``model`` (vendor prefix dropped), ``context_pct`` (last-calloccupancy), ``latency`` (turn wall-clock, opt-in — NOT in the default set so an unset ``fields``-renders exactly as before), ``cwd`` (home-relative). ``gateway/run.py`` appends the footer to the+renders exactly as before), ``served_model`` (opt-in, ``alias → served``: the deployment a routing+proxy reported via ``x-litellm-model-id`` / ``x-litellm-model-api-base``, or Hermes' own fallback+route; skipped when the served model is the requested one), ``cwd`` (home-relative). ``gateway/run.py`` appends the footer to thefinal response only (never to tool-progress or streaming partials); when streaming alreadydelivered the text, it goes out as a trailing message via ``send_trailing_footer()``."""@@ -74,6 +76,7 @@ def _format_latency(seconds: float) -> str:def format_runtime_footer(*, model: Optional[str], context_tokens: int,context_length: Optional[int], cwd: Optional[str] = None,turn_seconds: Optional[float] = None,+ requested_model: Optional[str] = None, served_model: Optional[str] = None,fields: Iterable[str] = _DEFAULT_FIELDS) -> str:"""Render the footer line, or "" if no fields have data. Fields whose data is missing (andunknown field names) are skipped silently — a partial footer beats ``?%`` or empty slots."""@@ -82,8 +85,16 @@ def format_runtime_footer(*, model: Optional[str], context_tokens: int,return f"{max(0, min(100, round((context_tokens / context_length) * 100)))}%"return ""+ def served() -> str:+ requested = requested_model or model+ alias = _model_short(requested)+ if served_model and served_model not in (alias, requested):+ return f"{alias} → {served_model}"+ return ""+renderers = {"model": lambda: _model_short(model),+ "served_model": served,"context_pct": context_pct,# Skipped when the caller did not measure (None) or the value is negative."latency": lambda: _format_latency(turn_seconds) if turn_seconds is not None and turn_seconds >= 0 else "",@@ -94,7 +105,8 @@ def format_runtime_footer(*, model: Optional[str], context_tokens: int,def build_footer_line(*, user_config: dict[str, Any] | None, platform_key: str | None,model: Optional[str], context_tokens: int, context_length: Optional[int],- cwd: Optional[str] = None, turn_seconds: Optional[float] = None) -> str:+ cwd: Optional[str] = None, turn_seconds: Optional[float] = None,+ requested_model: Optional[str] = None, served_model: Optional[str] = None) -> str:"""Entry point for gateway/run.py: footer text, or "" when disabled / no data. Callers append itto the final response themselves, preserving a single blank line of separation.``turn_seconds`` is the caller-measured (``time.monotonic()``) run duration; ``None`` skips the@@ -104,4 +116,5 @@ def build_footer_line(*, user_config: dict[str, Any] | None, platform_key: str |return ""return format_runtime_footer(model=model, context_tokens=context_tokens,context_length=context_length, cwd=cwd, turn_seconds=turn_seconds,+ requested_model=requested_model, served_model=served_model,fields=cfg.get("fields") or _DEFAULT_FIELDS)diff --git a/hermes_cli/config_defaults.py b/hermes_cli/config_defaults.pyindex 7de1d0017dd..9338fb22a3e 100644--- a/hermes_cli/config_defaults.py+++ b/hermes_cli/config_defaults.py@@ -921,7 +921,9 @@ DEFAULT_CONFIG = {# Per-platform: display.platforms.<platform>.runtime_footer."runtime_footer": {"enabled": False,- "fields": ["model", "context_pct", "cwd"], # order shown; drop any to hide+ # order shown; drop any to hide. Opt-in extras: latency, served_model (alias → the+ # deployment a routing proxy reported / Hermes' fallback route).+ "fields": ["model", "context_pct", "cwd"],},# CLI/TUI status bar fields. Non-empty = only listed fields show (built-in order kept,# config controls visibility not ordering); empty = default set. Available: model,diff --git a/tests/agent/test_served_model.py b/tests/agent/test_served_model.pynew file mode 100644index 00000000000..16b8cf92eb6--- /dev/null+++ b/tests/agent/test_served_model.py@@ -0,0 +1,45 @@+"""agent.served_model — per-response served-model capture behind routing proxies (#54864)."""++from __future__ import annotations++import httpx+import openai++from agent.served_model import install_served_model_capture, result_model_fields+++class _Agent:+ model = "hermes-router"+ _fallback_activated = False+ _primary_runtime: dict = {}+++def test_httpx_hook_captures_litellm_header_and_clears_when_absent():+ served = {"value": "gpt-4o-2024-11-20"}++ def handler(request: httpx.Request) -> httpx.Response:+ headers = {"x-litellm-model-id": served["value"]} if served["value"] else {}+ return httpx.Response(200, json={+ "id": "c", "object": "chat.completion", "created": 0, "model": "hermes-router",+ "choices": [{"index": 0, "message": {"role": "assistant", "content": "ok"}, "finish_reason": "stop"}],+ }, headers=headers)++ client = openai.OpenAI(api_key="x", base_url="http://proxy.test/v1",+ http_client=httpx.Client(transport=httpx.MockTransport(handler)), max_retries=0)+ agent = _Agent()+ install_served_model_capture(agent, client)+ install_served_model_capture(agent, client) # idempotent: one hook per client+ assert len(client._client.event_hooks["response"]) == 1++ client.chat.completions.create(model="hermes-router", messages=[{"role": "user", "content": "hi"}])+ assert result_model_fields(agent) == {"requested_model": "hermes-router", "served_model": "gpt-4o-2024-11-20"}++ served["value"] = "" # next response has no routing header: the stale value must not survive+ client.chat.completions.create(model="hermes-router", messages=[{"role": "user", "content": "hi"}])+ assert result_model_fields(agent) == {"requested_model": "hermes-router", "served_model": None}++ # Hermes' own fallback route surfaces the same way when no proxy header is present.+ agent._fallback_activated = True+ agent._primary_runtime = {"model": "gpt-5.6-sol"}+ agent.model = "qwen/qwen3.8-max"+ assert result_model_fields(agent) == {"requested_model": "gpt-5.6-sol", "served_model": "qwen/qwen3.8-max"}diff --git a/tests/gateway/test_runtime_footer.py b/tests/gateway/test_runtime_footer.pyindex 1ca63a90c61..1dae4d68ed9 100644--- a/tests/gateway/test_runtime_footer.py+++ b/tests/gateway/test_runtime_footer.py@@ -317,3 +317,25 @@ def test_default_build_footer_line_ignores_turn_seconds(monkeypatch):with_timing = build_footer_line(**common, turn_seconds=125.0)assert baseline == "gpt-5.4 · 5% · /var/data"assert with_timing == baseline+++def test_format_footer_served_model_is_opt_in_and_skips_same_model():+ """#54864: `served_model` renders `alias → served` only when listed AND the served model+ differs from the requested one; the default field set never shows it."""+ # Default fields: served model is invisible.+ assert "→" not in format_runtime_footer(+ model="hermes-router", context_tokens=0, context_length=None, cwd="/x",+ served_model="gpt-4o-2024-11-20")+ line = format_runtime_footer(+ model="hermes-router", context_tokens=0, context_length=None, cwd="/x",+ served_model="gpt-4o-2024-11-20", fields=["served_model"])+ assert line == "hermes-router → gpt-4o-2024-11-20"+ # Hermes fallback route: requested primary → active model.+ line = format_runtime_footer(+ model="qwen/qwen3.8-max", context_tokens=0, context_length=None, cwd="/x",+ requested_model="gpt-5.6-sol", served_model="qwen/qwen3.8-max", fields=["served_model"])+ assert line == "gpt-5.6-sol → qwen/qwen3.8-max"+ # Served == requested (no header, no fallback): field skipped, nothing empty rendered.+ assert format_runtime_footer(+ model="gpt-5.4", context_tokens=0, context_length=None, cwd="/x",+ served_model=None, fields=["served_model"]) == ""diff --git a/website/docs/user-guide/configuration.md b/website/docs/user-guide/configuration.mdindex 5519255cf9f..3f767d928a7 100644--- a/website/docs/user-guide/configuration.md+++ b/website/docs/user-guide/configuration.md@@ -2260,9 +2260,10 @@ Supported fields:| `model` | Bare model id, vendor prefix dropped | `gpt-5.4` || `context_pct` | Last-call context occupancy as a percent | `5%` || `latency` | Wall-clock duration of the turn | `22s`, `1m05s` |+| `served_model` | The model that actually answered, when it differs from the one you configured: the deployment a routing proxy reported in its `x-litellm-model-id` (or `x-litellm-model-api-base`) response header, or the fallback model Hermes switched to for the turn | `hermes-router → gpt-4o-2024-11-20` || `cwd` | Home-relative working directory | `~` |-The default field set is `["model", "context_pct", "cwd"]`. `latency` is opt-in — add it to `fields` to use it. Fields whose data is unavailable are skipped silently rather than rendering an empty slot.+The default field set is `["model", "context_pct", "cwd"]`. `latency` and `served_model` are opt-in — add them to `fields` to use them. `served_model` renders nothing when the served model is the configured one (or when the proxy sends no such header), so behind a routing proxy or an active fallback it is the field that makes the switch visible. Fields whose data is unavailable are skipped silently rather than rendering an empty slot.The `/footer` slash command toggles this at runtime in any session.