From 608fa9c7af367b17d0e5b774353e4afcf65d794a Mon Sep 17 00:00:00 2001 From: Brooklyn Nicholson Date: Wed, 19 Aug 2026 20:16:49 -0500 Subject: [PATCH] feat(models): read Nous Portal reasoning capabilities from its catalog The Portal serves OpenRouter's catalog schema, so the existing parser and cache-only tri-state contract carry over unchanged. Only the HTTP fetch is generalized across the two catalogs; each keeps its own cache because they list different models. The Portal 403s a catalog read with no User-Agent, so the shared fetch now sends one. --- hermes_cli/models.py | 126 ++++++++++++++--- .../test_nous_reasoning_metadata.py | 132 ++++++++++++++++++ 2 files changed, 235 insertions(+), 23 deletions(-) create mode 100644 tests/hermes_cli/test_nous_reasoning_metadata.py diff --git a/hermes_cli/models.py b/hermes_cli/models.py index f40eb693ba..a6a86c3c92 100644 --- a/hermes_cli/models.py +++ b/hermes_cli/models.py @@ -1600,6 +1600,39 @@ _openrouter_reasoning_caps_cache: dict[str, Optional[dict[str, Any]]] | None = N _openrouter_reasoning_caps_failed_at: float | None = None +def _fetch_reasoning_caps_catalog( + url: str, timeout: float +) -> Optional[dict[str, Optional[dict[str, Any]]]]: + """Fetch one OpenRouter-shaped ``/v1/models`` catalog → per-model caps. + + Shared by every aggregator that serves OpenRouter's catalog schema + (OpenRouter itself, Nous Portal). Returns None when the catalog is + unreachable or carries no usable entries, so callers can remember the + failure and fall back rather than caching an empty result. + + Sends a User-Agent because the Portal 403s anonymous catalog reads. + """ + headers = {"Accept": "application/json", "User-Agent": _HERMES_USER_AGENT} + try: + req = urllib.request.Request(url, headers=headers) + with _urlopen_model_catalog_request(req, timeout=timeout) as resp: + payload = json.loads(resp.read().decode()) + except Exception: + return None + items = payload.get("data") + if not isinstance(items, list): + return None + caps_by_id: dict[str, Optional[dict[str, Any]]] = {} + for item in items: + if not isinstance(item, dict): + continue + mid = str(item.get("id") or "").strip() + if not mid: + continue + caps_by_id[mid] = parse_openrouter_reasoning_capabilities(item) + return caps_by_id or None + + def _fetch_openrouter_reasoning_caps(timeout: float = 6.0) -> Optional[dict[str, Optional[dict[str, Any]]]]: """Fetch + cache per-model reasoning capabilities from the live catalog. @@ -1616,29 +1649,10 @@ def _fetch_openrouter_reasoning_caps(timeout: float = 6.0) -> Optional[dict[str, and (time.monotonic() - _openrouter_reasoning_caps_failed_at) < 60 ): return None - try: - req = urllib.request.Request( - "https://openrouter.ai/api/v1/models", - headers={"Accept": "application/json"}, - ) - with _urlopen_model_catalog_request(req, timeout=timeout) as resp: - payload = json.loads(resp.read().decode()) - except Exception: - _openrouter_reasoning_caps_failed_at = time.monotonic() - return None - items = payload.get("data") - if not isinstance(items, list): - _openrouter_reasoning_caps_failed_at = time.monotonic() - return None - caps_by_id: dict[str, Optional[dict[str, Any]]] = {} - for item in items: - if not isinstance(item, dict): - continue - mid = str(item.get("id") or "").strip() - if not mid: - continue - caps_by_id[mid] = parse_openrouter_reasoning_capabilities(item) - if not caps_by_id: + caps_by_id = _fetch_reasoning_caps_catalog( + "https://openrouter.ai/api/v1/models", timeout + ) + if caps_by_id is None: _openrouter_reasoning_caps_failed_at = time.monotonic() return None _openrouter_reasoning_caps_cache = caps_by_id @@ -1705,6 +1719,72 @@ def warm_openrouter_reasoning_caps_async() -> None: ).start() +# Nous Portal serves OpenRouter's catalog schema, so the same parser and +# tri-state contract apply. Kept in its own cache because the two catalogs +# list different models (and different capabilities for shared ids). +_nous_reasoning_caps_cache: dict[str, Optional[dict[str, Any]]] | None = None +_nous_reasoning_caps_failed_at: float | None = None +_nous_caps_warm_started = False + + +def _fetch_nous_reasoning_caps(timeout: float = 6.0) -> Optional[dict[str, Optional[dict[str, Any]]]]: + """Nous Portal counterpart of :func:`_fetch_openrouter_reasoning_caps`.""" + global _nous_reasoning_caps_cache, _nous_reasoning_caps_failed_at + if _nous_reasoning_caps_cache is not None: + return _nous_reasoning_caps_cache + if ( + _nous_reasoning_caps_failed_at is not None + and (time.monotonic() - _nous_reasoning_caps_failed_at) < 60 + ): + return None + caps_by_id = _fetch_reasoning_caps_catalog( + f"{_DEFAULT_NOUS_INFERENCE_BASE}/v1/models", timeout + ) + if caps_by_id is None: + _nous_reasoning_caps_failed_at = time.monotonic() + return None + _nous_reasoning_caps_cache = caps_by_id + return caps_by_id + + +def nous_model_reasoning_capabilities( + model_id: Optional[str], + *, + timeout: float = 6.0, + allow_fetch: bool = False, +) -> Optional[dict[str, Any]]: + """Return live-catalog reasoning capabilities for a Nous Portal model. + + Same tri-state contract and cache-only default as + :func:`openrouter_model_reasoning_capabilities`; warm the cache with + :func:`warm_nous_reasoning_caps_async` from hot paths. + """ + model = str(model_id or "").strip() + if not model: + return None + caps_by_id = _nous_reasoning_caps_cache + if caps_by_id is None and allow_fetch: + caps_by_id = _fetch_nous_reasoning_caps(timeout=timeout) + if caps_by_id is None: + return None + return caps_by_id.get(model) + + +def warm_nous_reasoning_caps_async() -> None: + """Nous Portal counterpart of :func:`warm_openrouter_reasoning_caps_async`.""" + global _nous_caps_warm_started + if _nous_caps_warm_started or _nous_reasoning_caps_cache is not None: + return + if os.environ.get("PYTEST_CURRENT_TEST"): + return + _nous_caps_warm_started = True + threading.Thread( + target=_fetch_nous_reasoning_caps, + name="nous-reasoning-caps-warm", + daemon=True, + ).start() + + # Canonical low→high ordering used for nearest-level clamping. Kept as an # alias of the single source of truth in ``agent.reasoning_effort``. from agent.reasoning_effort import EFFORT_LADDER as _REASONING_EFFORT_ORDER diff --git a/tests/hermes_cli/test_nous_reasoning_metadata.py b/tests/hermes_cli/test_nous_reasoning_metadata.py new file mode 100644 index 0000000000..b4247efa81 --- /dev/null +++ b/tests/hermes_cli/test_nous_reasoning_metadata.py @@ -0,0 +1,132 @@ +"""Tests for Nous Portal reasoning-capability metadata. + +The Portal serves OpenRouter's catalog schema, so it reuses +``parse_openrouter_reasoning_capabilities`` and the same cache-only tri-state +contract. What is Portal-specific: it 403s a catalog read that arrives +without a User-Agent, and its ``reasoning.mandatory`` flag is what decides +whether a disable can be sent at all. +""" + +import pytest + + +def _mock_response(body: bytes): + class _Resp: + def __enter__(self): + return self + + def __exit__(self, exc_type, exc, tb): + return False + + def read(self): + return body + + return _Resp() + + +_CATALOG = ( + b'{"data": [' + b'{"id": "deepseek/deepseek-v4-pro", "supported_parameters": ["reasoning", "tools"],' + b' "reasoning": {"mandatory": false, "supported_efforts": ["xhigh", "high"]}},' + b'{"id": "arcee-ai/trinity-large-thinking", "supported_parameters": ["reasoning"],' + b' "reasoning": {"mandatory": true}}' + b']}' +) + + +@pytest.fixture +def cold_cache(monkeypatch): + import hermes_cli.models as models_mod + + monkeypatch.setattr(models_mod, "_nous_reasoning_caps_cache", None) + monkeypatch.setattr(models_mod, "_nous_reasoning_caps_failed_at", None) + return models_mod + + +class TestNousModelReasoningCapabilities: + def test_fetch_parses_mandatory_flag(self, cold_cache, monkeypatch): + from hermes_cli.models import nous_model_reasoning_capabilities + + monkeypatch.setattr( + cold_cache, "_urlopen_model_catalog_request", + lambda req, *, timeout: _mock_response(_CATALOG), + ) + optional = nous_model_reasoning_capabilities( + "deepseek/deepseek-v4-pro", allow_fetch=True + ) + assert optional["supports_reasoning"] is True + assert optional["mandatory"] is False + assert optional["supported_efforts"] == ["xhigh", "high"] + + mandatory = nous_model_reasoning_capabilities("arcee-ai/trinity-large-thinking") + assert mandatory["mandatory"] is True + + def test_catalog_read_sends_user_agent(self, cold_cache, monkeypatch): + """The Portal 403s an anonymous catalog read.""" + from hermes_cli.models import nous_model_reasoning_capabilities + + seen = [] + + def _capture(req, *, timeout): + seen.append(req) + return _mock_response(_CATALOG) + + monkeypatch.setattr(cold_cache, "_urlopen_model_catalog_request", _capture) + nous_model_reasoning_capabilities("deepseek/deepseek-v4-pro", allow_fetch=True) + + # urllib title-cases header names. + assert seen[0].get_header("User-agent") + assert "nousresearch.com" in seen[0].full_url + + def test_unlisted_and_empty_models_return_none(self, cold_cache, monkeypatch): + from hermes_cli.models import nous_model_reasoning_capabilities + + monkeypatch.setattr( + cold_cache, "_urlopen_model_catalog_request", + lambda req, *, timeout: _mock_response(_CATALOG), + ) + assert nous_model_reasoning_capabilities("private/route", allow_fetch=True) is None + assert nous_model_reasoning_capabilities("") is None + assert nous_model_reasoning_capabilities(None) is None + + def test_cache_only_by_default_never_fetches(self, cold_cache, monkeypatch): + from hermes_cli.models import nous_model_reasoning_capabilities + + def _boom(req, *, timeout): + raise AssertionError("hot path must not fetch") + + monkeypatch.setattr(cold_cache, "_urlopen_model_catalog_request", _boom) + assert nous_model_reasoning_capabilities("deepseek/deepseek-v4-pro") is None + + def test_unreachable_catalog_rate_limits_refetch(self, cold_cache, monkeypatch): + from hermes_cli.models import nous_model_reasoning_capabilities + + calls = {"n": 0} + + def _boom(req, *, timeout): + calls["n"] += 1 + raise OSError("offline") + + monkeypatch.setattr(cold_cache, "_urlopen_model_catalog_request", _boom) + assert nous_model_reasoning_capabilities("a/b", allow_fetch=True) is None + assert nous_model_reasoning_capabilities("a/b", allow_fetch=True) is None + # Second call inside the failure TTL must not re-fetch. + assert calls["n"] == 1 + + def test_openrouter_cache_is_independent(self, cold_cache, monkeypatch): + """Two catalogs, two caches — a Portal fetch must not answer for OpenRouter.""" + from hermes_cli.models import ( + nous_model_reasoning_capabilities, + openrouter_model_reasoning_capabilities, + ) + + monkeypatch.setattr(cold_cache, "_openrouter_reasoning_caps_cache", None) + monkeypatch.setattr(cold_cache, "_openrouter_reasoning_caps_failed_at", None) + monkeypatch.setattr( + cold_cache, "_urlopen_model_catalog_request", + lambda req, *, timeout: _mock_response(_CATALOG), + ) + assert nous_model_reasoning_capabilities( + "deepseek/deepseek-v4-pro", allow_fetch=True + ) is not None + assert openrouter_model_reasoning_capabilities("deepseek/deepseek-v4-pro") is None