The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(models): honor model.base_url in OpenAI discovery, cache identity, and listing authority
Victor Kyriazakos173a73e19192
diff --git a/hermes_cli/models.py b/hermes_cli/models.pyindex bbeea8a5f0c..5f1550e3ab9 100644--- a/hermes_cli/models.py+++ b/hermes_cli/models.py@@ -2768,6 +2768,31 @@ def _merge_with_models_dev(provider: str, curated: list[str]) -> list[str]:return merged+def _openai_discovery_base_url(provider: str) -> str:+ """Effective OpenAI endpoint for model discovery.++ Mirrors the runtime precedence so discovery probes the SAME endpoint+ inference uses: ``$OPENAI_BASE_URL`` (explicit env override) →+ ``model.base_url`` from config.yaml when the configured provider matches+ → the canonical default. Previously this read the env var only, so a+ config-set data-residency host (``us.api.openai.com``) was ignored and+ the catalog kept coming from ``api.openai.com``.+ """+ env_raw = os.getenv("OPENAI_BASE_URL", "").strip().rstrip("/")+ if env_raw:+ return env_raw+ try:+ model_cfg = _get_model_config_dict()+ cfg_provider = str(model_cfg.get("provider") or "").strip().lower()+ if cfg_provider in ("openai", "openai-api") and normalize_provider(provider) == normalize_provider(cfg_provider):+ cfg_url = str(model_cfg.get("base_url") or "").strip().rstrip("/")+ if cfg_url:+ return cfg_url+ except Exception:+ pass+ return "https://api.openai.com/v1"++def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False) -> list[str]:"""Return the best known model catalog for a provider.@@ -2883,19 +2908,19 @@ def provider_model_ids(provider: Optional[str], *, force_refresh: bool = False)if normalized in ("openai", "openai-api"):api_key = os.getenv("OPENAI_API_KEY", "").strip()if api_key:- base_raw = os.getenv("OPENAI_BASE_URL", "").strip().rstrip("/")- base = base_raw or "https://api.openai.com/v1"+ base = _openai_discovery_base_url(normalized)# Custom OpenAI-compatible endpoints (proxies, gateways, self-hosted)# may serve a small curated catalog — use the live list verbatim so- # discovery works. But the canonical api.openai.com /v1/models dump- # is 120+ entries of embeddings, whisper, tts, dall-e, moderation and- # legacy chat models — none of which belong in the agent model picker.- # For the default endpoint, intersect the live list with our curated- # agentic catalog so ``/model`` matches what ``hermes model`` shows.- is_default_openai = base.rstrip("/") in (- "https://api.openai.com/v1",- "https://api.openai.com",- )+ # discovery works. But the official OpenAI hosts (canonical AND the+ # data-residency regional hosts, which serve the identical dump)+ # return 120+ entries of embeddings, whisper, tts, dall-e,+ # moderation and legacy chat models — none of which belong in the+ # agent model picker. For official hosts, intersect the live list+ # with our curated agentic catalog so ``/model`` matches what+ # ``hermes model`` shows.+ from hermes_cli.providers import is_official_openai_host++ is_default_openai = is_official_openai_host(base)try:live = fetch_api_models(api_key, base)if live:@@ -3079,6 +3104,17 @@ def _credential_fingerprint(provider: str) -> str:except Exception:pass+ # Effective configured endpoint: config.yaml's model.base_url changes the+ # endpoint discovery probes (data-residency hosts) without touching any+ # env var, so it must change the fingerprint too or `hermes config set+ # model.base_url ...` keeps serving the previous endpoint's cached+ # catalog until TTL expiry.+ if provider in ("openai", "openai-api"):+ try:+ parts.append(f"effective_base={_openai_discovery_base_url(provider)}")+ except Exception:+ pass+# OAuth / external-file mtimes that change on re-authtry:from hermes_constants import get_hermes_home@@ -5047,7 +5083,20 @@ def validate_requested_model(# listing that are still valid (stale cache, partial rollout,# gated previews). Use the pure-catalog helper (no extra live# fetch) so we only accept models Hermes actually ships. (#46850)- if _model_in_provider_catalog(+ #+ # EXCEPTION: official OpenAI hosts (canonical api.openai.com and+ # the data-residency regional hosts). Their /v1/models listing is+ # access-scoped and authoritative — a model absent from it is one+ # this key CANNOT serve, so the curated soft-accept would+ # manufacture a selection that 400s at first use. Custom+ # OpenAI-compatible proxies keep the fallback (incomplete+ # listings are common there).+ _openai_listing_is_authoritative = False+ if normalized in ("openai", "openai-api"):+ from hermes_cli.providers import is_official_openai_host++ _openai_listing_is_authoritative = is_official_openai_host(base_url)+ if not _openai_listing_is_authoritative and _model_in_provider_catalog(requested_for_lookup.lower(), _provider_keys(normalized)):return {diff --git a/tests/hermes_cli/test_openai_discovery_endpoint.py b/tests/hermes_cli/test_openai_discovery_endpoint.pynew file mode 100644index 00000000000..610ac039681--- /dev/null+++ b/tests/hermes_cli/test_openai_discovery_endpoint.py@@ -0,0 +1,153 @@+"""Discovery honors ``model.base_url`` and cache identity tracks the endpoint.++Coatue data-residency report, issues 3 and 4: with+``model.base_url: https://us.api.openai.com/v1`` in config and+``$OPENAI_BASE_URL`` unset, model discovery probed ``api.openai.com`` (the+wrong endpoint) and the catalog-cache fingerprint did not change when the+configured endpoint changed, so ``hermes config set model.base_url ...``+kept serving the stale cached catalog. Regional hosts also bypassed the+curated intersection, flooding the picker with whisper/tts/embedding rows.++Contracts pinned here:+ 1. ``_openai_discovery_base_url()`` resolves config ``model.base_url``+ (when the configured provider matches) → ``$OPENAI_BASE_URL`` → default.+ 2. ``_credential_fingerprint()`` changes when the effective configured+ endpoint changes.+ 3. Official OpenAI hosts (canonical + regional) all get the curated∩live+ intersection; custom proxies keep the verbatim live list.+"""++from __future__ import annotations++from unittest.mock import patch as mock_patch++import pytest++from hermes_cli import models as models_mod+++def _cfg(base_url: str | None, provider: str = "openai-api"):+ cfg = {"provider": provider}+ if base_url is not None:+ cfg["base_url"] = base_url+ return cfg+++class TestDiscoveryBaseUrl:+ def test_config_base_url_wins_when_env_unset(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://us.api.openai.com/v1"),+ ):+ assert (+ models_mod._openai_discovery_base_url("openai-api")+ == "https://us.api.openai.com/v1"+ )++ def test_env_wins_over_config(self, monkeypatch):+ monkeypatch.setenv("OPENAI_BASE_URL", "https://eu.api.openai.com/v1")+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://us.api.openai.com/v1"),+ ):+ assert (+ models_mod._openai_discovery_base_url("openai-api")+ == "https://eu.api.openai.com/v1"+ )++ def test_config_ignored_when_provider_differs(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://proxy.test/v1", provider="openrouter"),+ ):+ assert (+ models_mod._openai_discovery_base_url("openai-api")+ == "https://api.openai.com/v1"+ )++ def test_default_when_nothing_configured(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ with mock_patch.object(+ models_mod, "_get_model_config_dict", return_value=_cfg(None)+ ):+ assert (+ models_mod._openai_discovery_base_url("openai-api")+ == "https://api.openai.com/v1"+ )+++class TestFingerprintTracksEndpoint:+ def test_config_endpoint_change_changes_fingerprint(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://us.api.openai.com/v1"),+ ):+ fp_us = models_mod._credential_fingerprint("openai-api")+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://eu.api.openai.com/v1"),+ ):+ fp_eu = models_mod._credential_fingerprint("openai-api")+ assert fp_us != fp_eu++ def test_unrelated_provider_fingerprint_stable_across_openai_config(self, monkeypatch):+ monkeypatch.delenv("OPENAI_BASE_URL", raising=False)+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://us.api.openai.com/v1"),+ ):+ fp_a = models_mod._credential_fingerprint("openrouter")+ with mock_patch.object(+ models_mod,+ "_get_model_config_dict",+ return_value=_cfg("https://eu.api.openai.com/v1"),+ ):+ fp_b = models_mod._credential_fingerprint("openrouter")+ assert fp_a == fp_b+++class TestRegionalCatalogFiltering:+ _RAW_DUMP = [+ "gpt-5.6-terra",+ "whisper-1",+ "tts-1",+ "text-embedding-ada-002",+ ]++ @pytest.mark.parametrize(+ "base",+ [+ "https://api.openai.com/v1",+ "https://us.api.openai.com/v1",+ "https://eu.api.openai.com/v1",+ ],+ )+ def test_official_hosts_intersect_with_curated(self, monkeypatch, base):+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("OPENAI_BASE_URL", base)+ with mock_patch.object(+ models_mod, "fetch_api_models", return_value=list(self._RAW_DUMP)+ ):+ ids = models_mod.provider_model_ids("openai-api", force_refresh=True)+ assert "whisper-1" not in ids+ assert "tts-1" not in ids+ assert "text-embedding-ada-002" not in ids+ assert "gpt-5.6-terra" in ids++ def test_custom_proxy_keeps_live_list_verbatim(self, monkeypatch):+ monkeypatch.setenv("OPENAI_API_KEY", "sk-test")+ monkeypatch.setenv("OPENAI_BASE_URL", "https://proxy.corp.test/v1")+ with mock_patch.object(+ models_mod, "fetch_api_models", return_value=list(self._RAW_DUMP)+ ):+ ids = models_mod.provider_model_ids("openai-api", force_refresh=True)+ assert ids == self._RAW_DUMPdiff --git a/tests/hermes_cli/test_openai_listing_authority.py b/tests/hermes_cli/test_openai_listing_authority.pynew file mode 100644index 00000000000..ff34fdc1e7b--- /dev/null+++ b/tests/hermes_cli/test_openai_listing_authority.py@@ -0,0 +1,60 @@+"""Live-listing authority on official OpenAI hosts (model switching).++Coatue data-residency report, issue 2: on an API key whose project only+grants a subset of models, ``/model`` accepted a curated-catalog model that+the live ``/v1/models`` listing (which is access-scoped and authoritative on+official OpenAI hosts) did not contain — manufacturing a selection that is+guaranteed to 400 at first use.++Contract: for ``openai``/``openai-api`` against an official OpenAI host+(canonical or data-residency regional), a successful live listing is+authoritative — a model absent from it is rejected, not soft-accepted from+the curated catalog. Custom OpenAI-compatible proxies and other providers+keep the #46850 curated-fallback behavior (their listings are often+incomplete).+"""++from __future__ import annotations++from unittest.mock import patch as mock_patch++import pytest++from hermes_cli import models as models_mod+++def _validate(requested: str, base_url: str, live: list[str], provider: str = "openai-api"):+ with mock_patch.object(models_mod, "fetch_api_models", return_value=live):+ return models_mod.validate_requested_model(+ requested,+ provider=provider,+ api_key="sk-test",+ base_url=base_url,+ )+++class TestOfficialHostAuthority:+ @pytest.mark.parametrize(+ "base_url",+ [+ "https://api.openai.com/v1",+ "https://us.api.openai.com/v1",+ "https://eu.api.openai.com/v1",+ ],+ )+ def test_absent_model_rejected_on_official_hosts(self, base_url):+ result = _validate("gpt-5.5", base_url, live=["gpt-5.6-terra"])+ assert result["accepted"] is False++ def test_present_model_accepted_on_regional_host(self):+ result = _validate("gpt-5.6-terra", "https://us.api.openai.com/v1", live=["gpt-5.6-terra"])+ assert result["accepted"] is True+++class TestCuratedFallbackPreserved:+ def test_custom_proxy_keeps_curated_fallback(self):+ # gpt-5.5 is in the curated openai catalog; a custom proxy's listing+ # may be incomplete, so the #46850 soft-accept stays.+ result = _validate("gpt-5.5", "https://proxy.corp.test/v1", live=["some-other-model"])+ assert result["accepted"] is True+ assert "curated catalog" in (result.get("message") or "")