Skip to content

The agent that grows with you

refactor(hermes_cli): fold match verdicts into _Match.verdict, ordered validation ladder table, tighter local/pricing bodies and docstrings

Tekniumb30c4f16675b
diff --git a/hermes_cli/models_local.py b/hermes_cli/models_local.py
index 51819a1f046..9de0a34f9fb 100644
--- a/hermes_cli/models_local.py
+++ b/hermes_cli/models_local.py
@@ -91,13 +91,11 @@ def _ollama_host_from_env(env_host: str) -> str:
def _get_ollama_base_url() -> str:
- """Resolve the local Ollama-compatible endpoint URL.
-
- Precedence: explicit ``providers.ollama.base_url`` (wires local endpoints without changing the
- active provider) → active ``model.base_url`` when the active provider is ollama, or custom AND
- the endpoint actually serves ``/api/tags`` (otherwise the picker would probe an unrelated
- endpoint and hide the local catalog) → ``OLLAMA_HOST`` → Ollama's local default.
- """
+ """Resolve the local Ollama-compatible endpoint URL: explicit ``providers.ollama.base_url``
+ (wires local endpoints without changing the active provider) → active ``model.base_url`` when
+ the active provider is ollama, or custom AND the endpoint actually serves ``/api/tags``
+ (otherwise the picker would probe an unrelated endpoint and hide the local catalog) →
+ ``OLLAMA_HOST`` → Ollama's local default."""
from hermes_cli.models import _get_model_config_dict, should_use_ollama_native_catalog
configured = _configured_ollama_base_url()
if configured:
@@ -153,16 +151,10 @@ def _get_ollama_request_headers() -> dict[str, str]:
return result
-def _get_ollama_native_headers(
- base_url: Optional[str],
- *,
- api_key: Optional[str] = None,
-) -> dict[str, str]:
- """Resolve Ollama credentials and headers for one endpoint origin.
-
- Configured headers apply only when *base_url* shares the configured Ollama root; an explicit
- *api_key* replaces any configured Authorization variant rather than inheriting it.
- """
+def _get_ollama_native_headers(base_url: Optional[str], *, api_key: Optional[str] = None) -> dict[str, str]:
+ """Ollama credentials and headers for one endpoint origin. Configured headers apply only when
+ *base_url* shares the configured Ollama root; an explicit *api_key* replaces any configured
+ Authorization variant rather than inheriting it."""
from hermes_cli.models import _get_ollama_request_headers
configured_base = _configured_ollama_base_url()
explicit_key = str(api_key or "").strip()
@@ -230,12 +222,9 @@ def probe_ollama_local_models(
timeout: float = 2.0,
headers: Optional[dict[str, str]] = None,
) -> Optional[list[str]]:
- """Probe local Ollama-compatible models from native ``/api/tags``.
-
- Returns ``None`` when the endpoint cannot be reached or returns malformed data, and a list
- (possibly empty) when ``/api/tags`` was reachable — Ollama's authoritative local catalog
- (``/v1/models`` is not required for local servers).
- """
+ """Probe local Ollama-compatible models from native ``/api/tags`` (Ollama's authoritative local
+ catalog; ``/v1/models`` is not required for local servers). ``None`` when the endpoint cannot be
+ reached or returns malformed data; a list (possibly empty) when it was reachable."""
from hermes_cli.models import _HERMES_USER_AGENT, _get_ollama_base_url, _urlopen_model_catalog_request
root = _root_for_ollama_native_api(base_url or _get_ollama_base_url())
if not root:
@@ -305,14 +294,11 @@ def should_use_ollama_native_catalog(
base_url: Optional[str],
headers: Optional[dict[str, str]] = None,
) -> bool:
- """Return True when model discovery should use local Ollama ``/api/tags``.
-
- Bare ``ollama`` is normalized to ``custom`` elsewhere so runtime paths share the OpenAI-
- compatible client, but local Ollama's authoritative model list is ``/api/tags``. Use it when
- the caller asked for Ollama explicitly, the base URL matches ``providers.ollama.base_url``,
- or an ambiguous custom URL on Ollama's default port actually serves ``/api/tags``; other
- custom endpoints keep the ``/models`` probe.
- """
+ """True when model discovery should use local Ollama ``/api/tags``: the caller asked for Ollama
+ explicitly, the base URL matches ``providers.ollama.base_url``, or an ambiguous custom URL on
+ Ollama's default port actually serves ``/api/tags``. (Bare ``ollama`` is normalized to
+ ``custom`` elsewhere so runtime paths share the OpenAI client, but ``/api/tags`` is the
+ authoritative local list; other custom endpoints keep the ``/models`` probe.)"""
from hermes_cli.models import probe_ollama_local_models
requested = str(provider or "").strip().lower()
root = _root_for_ollama_native_api(base_url or "")
@@ -383,11 +369,8 @@ def _ollama_local_catalog(force_refresh: bool) -> list[str]:
def _lmstudio_server_root(base_url: Optional[str]) -> Optional[str]:
- """LM Studio server root for native ``/api/v1`` endpoints.
-
- Users paste either the OpenAI runtime URL (``.../v1``) or the native prefix (``.../api`` /
- ``.../api/v1``); native probes append ``/api/v1/...`` themselves, so strip all accepted forms.
- """
+ """LM Studio server root: users paste the OpenAI runtime URL (``.../v1``) or the native prefix
+ (``.../api``, ``.../api/v1``); native probes append ``/api/v1/...`` themselves."""
return _strip_suffixes((base_url or "").strip().rstrip("/"), ("/api/v1", "/api", "/v1")) or None
@@ -406,10 +389,8 @@ def _lmstudio_fetch_raw_models(
base_url: Optional[str] = None,
timeout: float = 5.0,
) -> Optional[list[dict]]:
- """Fetch the raw model list from LM Studio's ``/api/v1/models``.
-
- None on network errors / malformed payloads; raises ``AuthError`` on HTTP 401/403.
- """
+ """Raw model list from LM Studio's ``/api/v1/models``; None on network errors / malformed
+ payloads; raises ``AuthError`` on HTTP 401/403."""
from hermes_cli.models import _urlopen_model_catalog_request
server_root = _lmstudio_server_root(base_url)
if not server_root:
@@ -461,12 +442,9 @@ def probe_lmstudio_models(
base_url: Optional[str] = None,
timeout: float = 5.0,
) -> Optional[list[str]]:
- """Probe LM Studio's model listing.
-
- Returns chat-capable model keys — a valid empty list when the server is reachable but has no
- non-embedding models; ``None`` on network errors, malformed responses, or bad base URLs.
- Raises ``AuthError`` on HTTP 401/403 so token issues surface separately from reachability.
- """
+ """Chat-capable LM Studio model keys — a valid empty list when the server is reachable but has
+ no non-embedding models; ``None`` on network errors, malformed responses, or bad base URLs.
+ Raises ``AuthError`` on HTTP 401/403 so token issues surface separately from reachability."""
from hermes_cli.models import _lmstudio_fetch_raw_models
raw_models = _lmstudio_fetch_raw_models(api_key=api_key, base_url=base_url, timeout=timeout)
if raw_models is None:
@@ -532,14 +510,13 @@ def ensure_lmstudio_model_loaded(
"""Ensure ``model`` is loaded and return verified runtime context.
Existing loaded-instance context is authoritative. Cold loads omit ``context_length`` unless the
- caller supplied an explicit override; the returned context must come from LM Studio's echoed or
- refreshed state.
- """
+ caller supplied an explicit override; the returned context comes from LM Studio's echoed or
+ refreshed state."""
from hermes_cli.models import _urlopen_model_catalog_request
def _result(context_length: Optional[int], *, load_attempted: bool = False, rejected: bool = False):
- value = LMStudioLoadResult(context_length, load_attempted, rejected)
- return value if return_load_result else context_length
+ result = LMStudioLoadResult(context_length, load_attempted, rejected)
+ return result if return_load_result else context_length
server_root = _lmstudio_server_root(base_url)
if not server_root:
@@ -548,9 +525,7 @@ def ensure_lmstudio_model_loaded(
explicit_context = _positive_int(target_context_length)
if target_context_length is not None and explicit_context is None:
return _result(None)
-
- raw_models = _lmstudio_raw_models_or_none(api_key, base_url, 10)
- target_entry = _lmstudio_entry_for(raw_models, model) if raw_models is not None else None
+ target_entry = _lmstudio_entry_for(_lmstudio_raw_models_or_none(api_key, base_url, 10) or [], model)
if target_entry is None:
return _result(None)
@@ -569,12 +544,11 @@ def ensure_lmstudio_model_loaded(
load_payload: dict[str, Any] = {"model": model, "echo_load_config": True}
if explicit_context is not None:
load_payload["context_length"] = explicit_context
- load_headers = {**_lmstudio_request_headers(api_key), "Content-Type": "application/json"}
try:
load_request = urllib.request.Request(
server_root + "/api/v1/models/load",
data=json.dumps(load_payload).encode(),
- headers=load_headers,
+ headers={**_lmstudio_request_headers(api_key), "Content-Type": "application/json"},
method="POST",
)
with _urlopen_model_catalog_request(load_request, timeout=timeout) as resp:
@@ -622,12 +596,9 @@ def ollama_model_supports_thinking(
api_key: Optional[str] = None,
timeout: float = 5.0,
) -> Optional[bool]:
- """Tri-state: True if an Ollama (Cloud or local) model advertises ``thinking``.
-
- Probes native ``/api/show`` ``capabilities`` — the authoritative source, since OpenAI-compat
- ``/v1/models`` omits it. False when the probe succeeded without it; None when the probe failed
- so the caller picks the fallback (treated as "don't emit").
- """
+ """Tri-state: True if an Ollama (Cloud or local) model advertises ``thinking`` in native
+ ``/api/show`` ``capabilities`` (authoritative; OpenAI-compat ``/v1/models`` omits it), False
+ when the probe succeeded without it, None when it failed (caller treats as "don't emit")."""
import httpx
server_url = (base_url or "").strip().rstrip("/")
@@ -714,11 +685,7 @@ def fetch_ollama_cloud_models(
api_key = api_key or os.getenv("OLLAMA_API_KEY", "")
base_url = base_url or os.getenv("OLLAMA_BASE_URL", "") or "https://ollama.com/v1"
-
- live_models: list[str] = []
- if api_key:
- live_models = fetch_api_models(api_key, base_url, timeout=8.0) or []
-
+ live_models = (fetch_api_models(api_key, base_url, timeout=8.0) or []) if api_key else []
mdev_models: list[str] = []
try:
from agent.models_dev import list_agentic_models
diff --git a/hermes_cli/models_pricing.py b/hermes_cli/models_pricing.py
index 8b4298ef617..6f095e2a405 100644
--- a/hermes_cli/models_pricing.py
+++ b/hermes_cli/models_pricing.py
@@ -48,12 +48,9 @@ def _cache_catalog(
result: dict[str, dict[str, Any]],
ttl_seconds: Optional[float] = None,
) -> dict[str, dict[str, Any]]:
- """Cache a catalog result, giving an empty one an expiry.
-
- *ttl_seconds* expires a non-empty result too — only for a catalog whose contents depend on
- server-side state the client cannot observe (an org's model policy can change while a long-
- lived process holds the entry).
- """
+ """Cache a catalog result, giving an empty one an expiry. *ttl_seconds* expires a non-empty
+ result too — only for a catalog whose contents depend on server-side state the client cannot
+ observe (an org's model policy can change while a long-lived process holds the entry)."""
from hermes_cli.models import _pricing_cache, _pricing_cache_retry_after
_pricing_cache[cache_key] = result
if not result:
@@ -82,12 +79,9 @@ def _pricing_auth_fingerprint(api_key: str | None) -> str:
def peek_cached_pricing(base_url: str) -> dict[str, dict[str, Any]]:
- """Pricing already cached for *base_url*, or ``{}``. Never fetches.
-
- Accepts a ``/v1``-suffixed URL as well as the pre-``/v1`` root the fetchers key on, and
- prefers an authenticated catalog. Scans (callers hold no credential) newest first, skipping
- expired entries, so a rotated credential does not keep answering from its predecessor's catalog.
- """
+ """Pricing already cached for *base_url* (with or without ``/v1``), or ``{}``; never fetches.
+ Prefers an authenticated catalog, scanning newest first (callers hold no credential) and
+ skipping expired entries so a rotated credential does not answer from its predecessor's."""
from hermes_cli.models import _pricing_cache
root = _strip_v1((base_url or "").rstrip("/"))
authed_prefix = root + _PRICING_AUTH_KEY_PREFIX
@@ -104,12 +98,9 @@ def _strip_v1(url: str) -> str:
def _format_price_per_mtok(per_token_str: str) -> str:
- """Per-token price string → human-friendly $/Mtok string.
-
- Always 2 decimals so right-justified prices align on the decimal point. Sub-cent prices (deep-
- discount cache-hit promos) widen precision until the value shows, keep one extra digit and trim
- trailing zeros instead of collapsing to "$0.00".
- """
+ """Per-token price string → $/Mtok string. Always 2 decimals so right-justified prices align;
+ sub-cent prices (deep-discount cache-hit promos) widen precision until the value shows, keep
+ one extra digit and trim trailing zeros instead of collapsing to "$0.00"."""
try:
val = float(per_token_str)
except (TypeError, ValueError):
@@ -147,19 +138,12 @@ def _sale_pct(current: Any, original: Any) -> int | None:
return int(round((1.0 - (cur / orig)) * 100))
-def compute_sale_discount(
- prompt: str,
- completion: str,
- original: Any,
-) -> tuple[int, str, str] | None:
- """Derive sale chrome from gateway ``pricing.original`` when cheaper (Nous Portal only; callers
- gate on the provider and opted in via ``include_sale_original=True``).
-
- Returns ``(discount_percent, was_prompt_raw, was_completion_raw)`` only when ``original`` is a
- dict and the current prompt (fallback: completion) rate is strictly below the corresponding
- original. Free / $0 models get a flat 100% off, with "was" prices only when the gateway served
- an original (a natively-free stealth model gets bare "-100%" chrome).
- """
+def compute_sale_discount(prompt: str, completion: str, original: Any) -> tuple[int, str, str] | None:
+ """Sale chrome from gateway ``pricing.original`` (Nous Portal only; callers gate on the provider
+ and opted in via ``include_sale_original=True``): ``(discount_percent, was_prompt_raw,
+ was_completion_raw)`` when ``original`` is a dict and the current prompt (fallback: completion)
+ rate is strictly below the original. Free / $0 models get a flat 100% off, with "was" prices
+ only when the gateway served an original (a natively-free stealth model gets bare "-100%")."""
orig_dict = original if isinstance(original, dict) else {}
was_prompt = orig_dict.get("prompt")
was_completion = orig_dict.get("completion")
@@ -224,13 +208,10 @@ def fetch_models_with_pricing(
include_sale_original: bool = False,
cache_ttl_seconds: Optional[float] = None,
) -> dict[str, dict[str, Any]]:
- """Fetch ``/v1/models`` and return ``{model_id: {prompt, completion, ...}}``.
-
- Cached per *base_url* and per credential, so repeated calls are free and one caller's catalog
- never answers another's read. Works with any OpenRouter-compatible endpoint (OpenRouter, Nous
- Portal). *include_sale_original* (Nous Portal only) copies the gateway's pre-discount
- ``pricing.original`` rates through as a nested ``original`` dict for sale chrome.
- """
+ """Fetch ``/v1/models`` (any OpenRouter-compatible endpoint) → ``{model_id: {prompt, completion,
+ ...}}``, cached per *base_url* and per credential so one caller's catalog never answers
+ another's read. *include_sale_original* (Nous Portal only) copies the gateway's pre-discount
+ ``pricing.original`` rates through as a nested ``original`` dict for sale chrome."""
from hermes_cli.models import _HERMES_USER_AGENT
url_root = (base_url or "").rstrip("/")
cache_key = url_root + _pricing_auth_fingerprint(api_key)
@@ -247,9 +228,8 @@ def fetch_models_with_pricing(
if payload is None:
return _cache_catalog(cache_key, {})
- # Same document the reasoning-capability fetch would pull, and every picker/pricing surface
- # goes through here — mirror it so a later hot-path lookup (and the next process) has an
- # answer without its own round-trip.
+ # Same document the reasoning-capability fetch would pull — mirror it so a later hot-path
+ # lookup (and the next process) has an answer without its own round-trip.
_seed_reasoning_caps(url, payload.get("data"))
result: dict[str, dict[str, Any]] = {}
@@ -273,11 +253,7 @@ def fetch_models_with_pricing(
return _cache_catalog(cache_key, result, cache_ttl_seconds)
-def fetch_ai_gateway_pricing(
- timeout: float = 8.0,
- *,
- force_refresh: bool = False,
-) -> dict[str, dict[str, str]]:
+def fetch_ai_gateway_pricing(timeout: float = 8.0, *, force_refresh: bool = False) -> dict[str, dict[str, str]]:
"""Vercel AI Gateway /v1/models pricing, translating its ``input`` / ``output`` field names to
the picker's ``prompt`` / ``completion`` (cache read/write names already match)."""
from hermes_constants import AI_GATEWAY_BASE_URL
@@ -311,21 +287,16 @@ _DEFAULT_NOUS_INFERENCE_BASE = "https://inference-api.nousresearch.com"
def _resolve_nous_pricing_credentials() -> tuple[str, str]:
"""``(api_key, base_url)`` for Nous Portal pricing; base_url is the bare origin (no ``/v1``).
-
- Base URL precedence mirrors runtime credential resolution: ``NOUS_INFERENCE_BASE_URL`` env
- override (staging / preview) → resolved runtime credential ``base_url`` → production default.
- Without the override a staging profile's sale ``pricing.original`` would never reach the
- pickers (prod has no ``original`` field).
- """
+ Precedence mirrors runtime credential resolution: ``NOUS_INFERENCE_BASE_URL`` (staging /
+ preview) → resolved credential ``base_url`` → production default. Without the override a
+ staging profile's sale ``pricing.original`` would never reach the pickers."""
try:
from hermes_cli.auth import _nous_inference_env_override
env_base = _nous_inference_env_override()
except Exception:
env_base = None
-
- api_key = ""
- creds_base = ""
+ api_key = creds_base = ""
try:
from hermes_cli.auth import resolve_nous_runtime_credentials
@@ -335,7 +306,6 @@ def _resolve_nous_pricing_credentials() -> tuple[str, str]:
creds_base = (creds.get("base_url", "") or "").strip()
except Exception:
pass
-
base_url = (env_base or creds_base or _DEFAULT_NOUS_INFERENCE_BASE).rstrip("/")
if base_url.endswith("/v1"):
base_url = base_url[:-3]
@@ -361,14 +331,10 @@ def _fetch_nous_pricing(api_key: str, base_url: str, *, force_refresh: bool) ->
def nous_policy_allowed_ids(*, force_refresh: bool = False) -> Optional[set[str]]:
- """The Nous model ids the caller's org may reach, or ``None`` to not filter.
-
- The gateway omits policy-blocked rows from an authenticated ``GET /v1/models``, so that
- response's keys are the reachable set. ``None`` (leave the caller's list alone) covers the
- three states that cannot narrow it: no policy (or a token too old to say), an anonymous read
- whose catalog is unfiltered, and an empty read (a fetch failure, not an org that may reach
- nothing).
- """
+ """The Nous model ids the caller's org may reach (keys of an authenticated ``GET /v1/models``,
+ which omits policy-blocked rows), or ``None`` to not filter: no policy (or a token too old to
+ say), an anonymous read (unfiltered catalog), or an empty read (a fetch failure, not an org
+ that may reach nothing)."""
from hermes_cli.models import _resolve_nous_pricing_credentials
try:
from hermes_cli.nous_account import nous_policy_present
@@ -395,15 +361,12 @@ def restrict_to_nous_policy(
*,
rescue_empty: bool = False,
) -> list[str]:
- """*model_ids* narrowed to *allowed*, preserving the caller's order.
-
- A ``:free`` sibling is kept when its base model is reachable, mirroring the gateway, which
- admits a row when any of its requestable ids passes. Prefer over-listing: that costs a 403 from
- the authoritative gate, while hiding a row the gate would serve is unrecoverable client-side.
- *rescue_empty*: an allowlist naming only models the curated manifest lacks would leave an
- empty picker — worse than no filter — so return the allowlist itself. Opt-in per list: an
- already-empty list (a paid tier's gated models) means "nothing to gate", not "nothing survived".
- """
+ """*model_ids* narrowed to *allowed*, preserving order. A ``:free`` sibling is kept when its
+ base model is reachable (the gateway admits a row when any requestable id passes); over-listing
+ costs a 403 from the authoritative gate, hiding a servable row is unrecoverable client-side.
+ *rescue_empty*: an allowlist naming only models the curated manifest lacks would leave an empty
+ picker — worse than no filter — so return the allowlist itself. Opt-in per list: an already-
+ empty list (a paid tier's gated models) means "nothing to gate", not "nothing survived"."""
if not allowed:
return list(model_ids)
kept = [mid for mid in model_ids if mid in allowed or mid.split(":", 1)[0] in allowed]
@@ -437,13 +400,9 @@ def get_pricing_for_provider(provider: str, *, force_refresh: bool = False) -> d
return fetcher(force_refresh=force_refresh) if fetcher else {}
-def _fireworks_pricing_from_models_dev(
- *,
- force_refresh: bool = False,
-) -> dict[str, dict[str, str]]:
- """Fireworks picker pricing from the models.dev registry cache — no dedicated network fetch:
- ``fetch_models_dev()`` already keeps a shared in-memory + disk cache (1h TTL), so this is a
- pure dict transform with no per-render network call."""
+def _fireworks_pricing_from_models_dev(*, force_refresh: bool = False) -> dict[str, dict[str, str]]:
+ """Fireworks picker pricing from the models.dev registry cache (``fetch_models_dev()`` keeps a
+ shared in-memory + disk cache, 1h TTL) — a pure dict transform, no per-render network call."""
cache_key = "models.dev/fireworks"
if not force_refresh:
cached = _cached_catalog(cache_key)
@@ -471,14 +430,9 @@ def _fireworks_pricing_from_models_dev(
return _cache_catalog(cache_key, result)
-def _fetch_novita_pricing(
- timeout: float = 8.0,
- *,
- force_refresh: bool = False,
-) -> dict[str, dict[str, str]]:
- """NovitaAI /v1/models pricing. Novita reports per-million-token prices in units of 0.0001 USD;
- converted to the per-token strings the shared formatter expects. Cached on the resolved base
- URL so menu renders don't re-hit the network."""
+def _fetch_novita_pricing(timeout: float = 8.0, *, force_refresh: bool = False) -> dict[str, dict[str, str]]:
+ """NovitaAI /v1/models pricing (per-million prices in units of 0.0001 USD → per-token strings),
+ cached on the resolved base URL so menu renders don't re-hit the network."""
from hermes_cli.models import _HERMES_USER_AGENT
api_key = os.getenv("NOVITA_API_KEY", "").strip()
if not api_key:
@@ -509,14 +463,10 @@ def _fetch_novita_pricing(
return _cache_catalog(cache_key, result)
-def _fetch_deepinfra_pricing(
- timeout: float = 5.0,
- *,
- force_refresh: bool = False,
-) -> dict[str, dict[str, str]]:
- """Picker-shape pricing for DeepInfra chat models: ``input_tokens`` / ``output_tokens`` /
- ``cache_read_tokens`` in $/MTok → per-token ``prompt`` / ``completion`` / ``input_cache_read``.
- Cached via the models-by-tag helper so repeated picker renders are free."""
+def _fetch_deepinfra_pricing(timeout: float = 5.0, *, force_refresh: bool = False) -> dict[str, dict[str, str]]:
+ """DeepInfra chat-model pricing: ``input_tokens`` / ``output_tokens`` / ``cache_read_tokens`` in
+ $/MTok → per-token ``prompt`` / ``completion`` / ``input_cache_read`` (cached by the by-tag
+ helper)."""
from hermes_cli.models import _fetch_deepinfra_models_by_tag
items = _fetch_deepinfra_models_by_tag("chat", timeout=timeout, force_refresh=force_refresh)
result: dict[str, dict[str, str]] = {}
diff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.py
index 6393d03aaa8..2bb8b0dca83 100644
--- a/hermes_cli/models_validate.py
+++ b/hermes_cli/models_validate.py
@@ -1,14 +1,11 @@
"""Validate a requested ``/model`` value against the active provider's catalog.
-Split out of ``hermes_cli.models``; :func:`validate_requested_model` is re-imported there, so
-``hermes_cli.models.validate_requested_model`` keeps resolving. Every catalog fetcher this module
-calls is looked up on ``hermes_cli.models`` at call time (``_m.<name>``), so existing
-``patch("hermes_cli.models.<name>")`` mocks keep intercepting.
-
-Every provider branch returns one of four verdict shapes (see :func:`_verdict`) or ``None`` to
-mean "not decided here — keep walking the ladder". The ladder ORDER is behavior: moa → whitespace
-→ OpenRouter preset parse → LM Studio → Ollama native → custom → codex/xai static → MiniMax →
-Anthropic native → Anthropic Messages → live listing → Bedrock → curated-catalog fallback.
+Split out of ``hermes_cli.models``; :func:`validate_requested_model` is re-imported there. Every
+catalog fetcher this module calls is looked up on ``hermes_cli.models`` at call time (``_m.<name>``)
+so existing ``patch("hermes_cli.models.<name>")`` mocks keep intercepting.
+
+Every provider branch returns a verdict dict (see :func:`_verdict`) or ``None`` for "not decided
+here — keep walking the ladder". The ladder ORDER is behavior (see ``_LADDER``).
"""
from __future__ import annotations
@@ -16,7 +13,7 @@ from __future__ import annotations
import re
from dataclasses import dataclass
from difflib import get_close_matches
-from typing import Any, Optional
+from typing import Any, Callable, Optional
from utils import base_url_host_matches
@@ -25,8 +22,6 @@ from utils import base_url_host_matches
def _verdict(accepted: bool, persist: bool, recognized: bool, message: Optional[str],
corrected_model: Optional[str] = None) -> dict[str, Any]:
- """Build the verdict dict. ``corrected_model`` is only present when set (key order matters
- to nobody, but keep it identical to the historical literals anyway)."""
out: dict[str, Any] = {"accepted": accepted, "persist": persist, "recognized": recognized}
if corrected_model is not None:
out["corrected_model"] = corrected_model
@@ -38,6 +33,10 @@ def _accept() -> dict[str, Any]:
return _verdict(True, True, True, None)
+def _accept_with_note(message: str) -> dict[str, Any]:
+ return _verdict(True, True, True, message)
+
+
def _reject(message: str) -> dict[str, Any]:
return _verdict(False, False, False, message)
@@ -60,6 +59,16 @@ class _Match:
corrected: Optional[str] = None
suggestion_text: str = ""
+ def verdict(self, req: "_Request", *, keep_suffix: bool = False) -> Optional[dict[str, Any]]:
+ """Accept on exact, auto-correct on a near-typo (re-attaching a preserved ``@preset/``
+ suffix when *keep_suffix*), else None so the branch composes its own message."""
+ if self.exact:
+ return _accept()
+ if self.corrected:
+ corrected = req.with_preset_suffix(self.corrected) if keep_suffix else self.corrected
+ return _corrected(req.requested, corrected)
+ return None
+
def _match_in_catalog(
query: str,
@@ -71,37 +80,31 @@ def _match_in_catalog(
suggest_cutoff: float = 0.5,
suggest_label: str = "Similar models",
) -> _Match:
- """The shared ladder: exact membership → typo auto-correct (cutoff .9) → suggestion text.
-
- ``case_insensitive`` matches on lower-cased ids and maps results back to the catalog's
- spelling (MiniMax ships mixed-case ids). ``suggest_query`` overrides the string the
- suggestion search uses (some branches search on the raw request, not the lookup form).
- """
- candidates = list(candidates)
+ """Shared ladder: exact membership → typo auto-correct (cutoff .9) → suggestion text.
+ ``case_insensitive`` matches lower-cased ids and maps results back to the catalog's spelling
+ (MiniMax ships mixed-case ids). ``suggest_query`` overrides the string the suggestion search
+ uses (some branches search on the raw request, not the lookup form)."""
+ pool = list(candidates)
+ display = None
+ if suggest_query is None:
+ suggest_query = query
if case_insensitive:
- display = {c.lower(): c for c in candidates}
+ display = {c.lower(): c for c in pool}
pool = list(display)
- query = query.lower()
- suggest_query = query if suggest_query is None else suggest_query.lower()
- else:
- display = None
- pool = candidates
- suggest_query = query if suggest_query is None else suggest_query
+ query, suggest_query = query.lower(), suggest_query.lower()
def _show(cid: str) -> str:
return display[cid] if display is not None else cid
if query in set(pool):
return _Match(exact=True)
- if auto_correct:
- auto = get_close_matches(query, pool, n=1, cutoff=0.9)
- if auto:
- return _Match(corrected=_show(auto[0]))
+ auto = get_close_matches(query, pool, n=1, cutoff=0.9) if auto_correct else []
+ if auto:
+ return _Match(corrected=_show(auto[0]))
suggestions = get_close_matches(suggest_query, pool, n=3, cutoff=suggest_cutoff)
- text = ""
- if suggestions:
- text = f"\n {suggest_label}: " + ", ".join(f"`{_show(s)}`" for s in suggestions)
- return _Match(suggestion_text=text)
+ if not suggestions:
+ return _Match()
+ return _Match(suggestion_text=f"\n {suggest_label}: " + ", ".join(f"`{_show(s)}`" for s in suggestions))
# ── Request context ──────────────────────────────────────────────────────
@@ -125,19 +128,25 @@ class _Request:
# ── Provider branches (None = not decided here) ─────────────────────────
-def _validate_moa(requested: str) -> dict[str, Any]:
+def _validate_moa(req: _Request) -> dict[str, Any]:
try:
from hermes_cli.config import load_config
from hermes_cli.moa_config import normalize_moa_config
cfg = normalize_moa_config(load_config().get("moa") or {})
- if requested in cfg["presets"]:
+ if req.requested in cfg["presets"]:
return _accept()
- return _reject(f"MoA preset `{requested}` was not found. Run `hermes moa list`.")
+ return _reject(f"MoA preset `{req.requested}` was not found. Run `hermes moa list`.")
except Exception as exc:
return _reject(f"Could not read MoA presets: {exc}")
+def _reject_whitespace(req: _Request) -> Optional[dict[str, Any]]:
+ if any(ch.isspace() for ch in req.requested):
+ return _reject("Model names cannot contain spaces.")
+ return None
+
+
def _parse_openrouter_preset(req: _Request) -> Optional[dict[str, Any]]:
"""OpenRouter presets are account-scoped, so ``@preset/<slug>`` never appears in the public
/v1/models listing. A bare preset is accepted unverified; ``<model>@preset/<slug>`` validates
@@ -185,34 +194,29 @@ def _validate_lmstudio(req: _Request) -> dict[str, Any]:
return _reject(f"Model `{req.requested}` was not found in LM Studio's model listing.")
-def _ollama_probe_headers(req: _Request) -> dict[str, str]:
- """Headers for the Ollama native probe.
+def _drop_authorization(headers: dict[str, str]) -> None:
+ for key in tuple(headers):
+ if key.lower() == "authorization":
+ del headers[key]
- Configured ``providers.ollama.extra_headers`` are only applied when the probed endpoint is
- the configured one (never leak them to a different host). Caller headers win; a caller
- ``api_key`` becomes the Authorization header unless the caller already sent one.
- """
+
+def _ollama_probe_headers(req: _Request) -> dict[str, str]:
+ """Headers for the Ollama native probe. Configured ``providers.ollama.extra_headers`` apply only
+ when the probed endpoint is the configured one (never leak them to a different host). Caller
+ headers win; a caller ``api_key`` becomes the Authorization header unless the caller sent one."""
from hermes_cli import models as _m
from hermes_cli.models_local import _configured_ollama_base_url
configured_base = _configured_ollama_base_url()
- configured_allowed = not (
- configured_base and not _m._same_ollama_native_root(req.base_url or "", configured_base)
- )
+ configured_allowed = not configured_base or _m._same_ollama_native_root(req.base_url or "", configured_base)
+ configured = _m._get_ollama_native_headers(req.base_url, api_key=req.api_key) if configured_allowed else {}
if req.headers is None:
- return _m._get_ollama_native_headers(req.base_url, api_key=req.api_key) if configured_allowed else {}
- out: dict[str, str] = {}
- if configured_allowed:
- out.update(_m._get_ollama_native_headers(req.base_url, api_key=req.api_key))
- for key in tuple(out):
- if key.lower() == "authorization":
- del out[key]
+ return configured
+ out = dict(configured)
+ _drop_authorization(out)
out.update(req.headers)
- caller_has_authorization = any(key.lower() == "authorization" for key in req.headers)
- if req.api_key and not caller_has_authorization:
- for key in tuple(out):
- if key.lower() == "authorization":
- del out[key]
+ if req.api_key and not any(key.lower() == "authorization" for key in req.headers):
+ _drop_authorization(out)
out["Authorization"] = f"Bearer {req.api_key}"
return out
@@ -230,12 +234,9 @@ def _validate_ollama_native(req: _Request) -> Optional[dict[str, Any]]:
return None
models = _m.probe_ollama_local_models(req.base_url, headers=headers)
if models is None:
- # A failed native probe is not authoritative; fall back to the OpenAI-compatible
- # catalog before accepting blindly.
+ # A failed native probe is not authoritative; fall back to the OpenAI-compatible catalog.
models = _m.probe_api_models(
- req.api_key,
- _m._normalize_openai_base_url(req.base_url),
- request_headers=headers,
+ req.api_key, _m._normalize_openai_base_url(req.base_url), request_headers=headers,
).get("models")
if models is None:
return _soft_accept(
@@ -258,18 +259,15 @@ def _validate_custom(req: _Request) -> dict[str, Any]:
from hermes_cli import models as _m
# Probe with the auth shape the api_mode expects.
- if req.api_mode == "anthropic_messages":
- probe = _m.probe_api_models(req.api_key, req.base_url, api_mode=req.api_mode,
- request_headers=req.headers)
- else:
- probe = _m.probe_api_models(req.api_key, req.base_url, request_headers=req.headers)
+ anthropic_style = req.api_mode == "anthropic_messages"
+ probe_kwargs = {"api_mode": req.api_mode} if anthropic_style else {}
+ probe = _m.probe_api_models(req.api_key, req.base_url, request_headers=req.headers, **probe_kwargs)
api_models = probe.get("models")
if api_models is not None:
match = _match_in_catalog(req.lookup, api_models, suggest_query=req.requested)
- if match.exact:
- return _accept()
- if match.corrected:
- return _corrected(req.requested, match.corrected)
+ verdict = match.verdict(req)
+ if verdict is not None:
+ return verdict
message = (
f"Note: `{req.requested}` was not found in this custom endpoint's model listing "
f"({probe.get('probed_url')}). It may still work if the server supports hidden or aliased models."
@@ -286,7 +284,7 @@ def _validate_custom(req: _Request) -> dict[str, Any]:
f"Note: could not reach this custom endpoint's model listing at `{probe.get('probed_url')}`. "
f"Hermes will still save `{req.requested}`, but the endpoint should expose `/models` for verification."
)
- if req.api_mode == "anthropic_messages":
+ if anthropic_style:
message += (
"\n Many Anthropic-compatible proxies do not implement the Models API "
"(GET /v1/models). The model name has been accepted without verification."
@@ -294,7 +292,7 @@ def _validate_custom(req: _Request) -> dict[str, Any]:
if probe.get("suggested_base_url"):
message += f"\n If this server expects `/v1`, try base URL: `{probe.get('suggested_base_url')}`"
# Anthropic-style proxies routinely lack /v1/models, so only they are accepted unverified.
- return _verdict(req.api_mode == "anthropic_messages", True, False, message)
+ return _verdict(anthropic_style, True, False, message)
def _static_catalog(normalized: str) -> list[str]:
@@ -339,10 +337,9 @@ def _validate_static_catalog(req: _Request) -> Optional[dict[str, Any]]:
if not catalog:
return None
match = _match_in_catalog(req.lookup, catalog)
- if match.exact:
- return _accept()
- if match.corrected:
- return _corrected(req.requested, match.corrected)
+ verdict = match.verdict(req)
+ if verdict is not None:
+ return verdict
label = _STATIC_LABELS[req.normalized]
# Plausibility gate: the soft-accept exists for entitlement-gated *hidden* slugs the curated
# listing hasn't caught up with — always the provider's own family (gpt-* / grok-*). An
@@ -373,11 +370,7 @@ def _validate_minimax(req: _Request) -> Optional[dict[str, Any]]:
if not catalog:
return None
match = _match_in_catalog(req.lookup, catalog, case_insensitive=True)
- if match.exact:
- return _accept()
- if match.corrected:
- return _corrected(req.requested, match.corrected)
- return _soft_accept(
+ return match.verdict(req) or _soft_accept(
f"Note: `{req.requested}` was not found in the MiniMax catalog."
f"{match.suggestion_text}"
"\n MiniMax does not expose a /models endpoint, so Hermes cannot verify the model name."
@@ -387,21 +380,17 @@ def _validate_minimax(req: _Request) -> Optional[dict[str, Any]]:
def _validate_anthropic(req: _Request) -> Optional[dict[str, Any]]:
"""Native Anthropic: /v1/models needs x-api-key (or OAuth Bearer) + anthropic-version, so the
- generic Bearer probe 401s — use the native fetcher. Returns None (fall through to the generic
- ladder) when no token is resolvable or the network failed."""
+ generic Bearer probe 401s — use the native fetcher. None (fall through) when no token is
+ resolvable or the network failed."""
from hermes_cli import models as _m
models = _m._fetch_anthropic_models(base_url=req.base_url or None, api_key=req.api_key or None)
if models is None:
return None
match = _match_in_catalog(req.lookup, models, suggest_query=req.requested)
- if match.exact:
- return _accept()
- if match.corrected:
- return _corrected(req.requested, match.corrected)
# Accept anyway — Anthropic gates newer/preview models (snapshot IDs, early access) behind
# accounts even though they aren't listed on /v1/models.
- return _soft_accept(
+ return match.verdict(req) or _soft_accept(
f"Note: `{req.requested}` was not found in Anthropic's /v1/models listing. "
f"It may still work if you have early-access or snapshot IDs."
f"{match.suggestion_text}"
@@ -414,13 +403,8 @@ def _validate_anthropic_messages(req: _Request) -> dict[str, Any]:
from hermes_cli import models as _m
models = _m.fetch_api_models(req.api_key, req.base_url, api_mode=req.api_mode)
- if models is not None:
- match = _match_in_catalog(req.lookup, models)
- if match.exact:
- return _accept()
- if match.corrected:
- return _corrected(req.requested, match.corrected)
- return _soft_accept(
+ verdict = _match_in_catalog(req.lookup, models).verdict(req) if models is not None else None
+ return verdict or _soft_accept(
f"Note: could not verify `{req.requested}` against this endpoint's "
f"model listing. Many Anthropic-compatible proxies do not "
f"implement GET /v1/models. The model name has been accepted "
@@ -471,9 +455,9 @@ def _validate_live_listing(req: _Request) -> Optional[dict[str, Any]]:
return _accept()
# Listed but not found: the account may reach models absent from the public listing
# (e.g. Z.AI Pro/Max plans use glm-5 on coding endpoints) — warn but allow where plausible.
- if match.corrected:
- corrected = req.with_preset_suffix(match.corrected)
- return _corrected(req.requested, corrected)
+ verdict = match.verdict(req, keep_suffix=True)
+ if verdict is not None:
+ return verdict
# Curated-catalog soft-accept: providers omit valid models from live listings (stale cache,
# partial rollout, gated previews). EXCEPTION: official OpenAI hosts (canonical + data-
# residency regional) — their listing is access-scoped and authoritative, so an absent model
@@ -487,16 +471,18 @@ def _validate_live_listing(req: _Request) -> Optional[dict[str, Any]]:
if not listing_authoritative and _m._model_in_provider_catalog(
(variant_base or req.lookup).lower(), _m._provider_keys(req.normalized)
):
- return _verdict(True, True, True,
- f"Note: `{req.requested}` was not found in the live /v1/models listing "
- f"but exists in the curated catalog — accepted.")
+ return _accept_with_note(
+ f"Note: `{req.requested}` was not found in the live /v1/models listing "
+ f"but exists in the curated catalog — accepted."
+ )
# Nous: the Portal's recommended-models feed can list a model before the curated list or the
# docs-hosted manifest catches up; `hermes chat` already accepts those at model-list build
# time, so mirror that source of truth for per-message /model validation.
if req.normalized == "nous" and req.lookup.lower() in _nous_portal_recommended_names():
- return _verdict(True, True, True,
- f"Note: `{req.requested}` was not found in the live /v1/models "
- f"listing but is a current Nous Portal recommendation — accepted.")
+ return _accept_with_note(
+ f"Note: `{req.requested}` was not found in the live /v1/models "
+ f"listing but is a current Nous Portal recommendation — accepted."
+ )
return _reject(
f"Model `{req.requested}` was not found in this provider's model listing."
f"{match.suggestion_text}"
@@ -526,10 +512,9 @@ def _validate_bedrock(req: _Request) -> Optional[dict[str, Any]]:
def _validate_catalog_fallback(req: _Request) -> dict[str, Any]:
- """The /models probe was unreachable: validate against the curated ``provider_model_ids()``
- list so gateway /model switches keep working while a provider's endpoint is down (otherwise
- switch_model() would fail and the gateway never writes the session override). No catalog at
- all → accept with a warning."""
+ """/models unreachable: validate against the curated ``provider_model_ids()`` list so gateway
+ /model switches keep working while a provider's endpoint is down (otherwise switch_model() would
+ fail and the gateway never writes the session override). No catalog → accept with a warning."""
from hermes_cli import models as _m
label = _m._PROVIDER_LABELS.get(req.normalized, req.normalized)
@@ -547,10 +532,7 @@ def _validate_catalog_fallback(req: _Request) -> dict[str, Any]:
variant_base = _m._openrouter_variant_base(req.lookup)
if variant_base is not None and variant_base.lower() in {m.lower() for m in catalog}:
return _accept()
- if match.corrected:
- corrected = req.with_preset_suffix(match.corrected)
- return _corrected(req.requested, corrected)
- return _soft_accept(
+ return match.verdict(req, keep_suffix=True) or _soft_accept(
f"Note: `{req.requested}` was not found in the {label} curated catalog "
f"and the /models endpoint was unreachable.{match.suggestion_text}"
f"\n The model may still work if it exists on the provider."
@@ -559,6 +541,36 @@ def _validate_catalog_fallback(req: _Request) -> dict[str, Any]:
# ── Orchestrator ─────────────────────────────────────────────────────────
+def _is_custom(req: _Request) -> bool:
+ return req.normalized == "custom" or req.normalized.startswith("custom:")
+
+
+def _for(*providers: str) -> Callable[[_Request], bool]:
+ return lambda req: req.normalized in providers
+
+
+# (gate, branch): the branch runs when the gate passes; the first non-None verdict wins. ORDER IS
+# BEHAVIOR: moa → whitespace → OpenRouter preset parse → LM Studio → Ollama native → custom →
+# codex/xai static → MiniMax → Anthropic native → Anthropic Messages → live listing → Bedrock →
+# curated-catalog fallback (always decides).
+_LADDER: tuple[tuple[Callable[[_Request], bool], Callable[[_Request], Optional[dict[str, Any]]]], ...] = (
+ (_for("moa"), _validate_moa),
+ (lambda req: True, _reject_whitespace),
+ (_for("openrouter"), _parse_openrouter_preset),
+ (_for("lmstudio"), _validate_lmstudio),
+ (lambda req: True, _validate_ollama_native),
+ (_is_custom, _validate_custom),
+ (_for("openai-codex", "xai-oauth"), _validate_static_catalog),
+ (_for("minimax", "minimax-cn"), _validate_minimax),
+ (_for("anthropic"), _validate_anthropic),
+ (lambda req: req.api_mode == "anthropic_messages", _validate_anthropic_messages),
+ (lambda req: True, _validate_live_listing),
+ # API unreachable — accept and persist, but warn so typos don't silently break things.
+ (_for("bedrock"), _validate_bedrock),
+ (lambda req: True, _validate_catalog_fallback),
+)
+
+
def validate_requested_model(
model_name: str,
provider: Optional[str],
@@ -568,13 +580,9 @@ def validate_requested_model(
api_mode: Optional[str] = None,
headers: Optional[dict[str, str]] = None,
) -> dict[str, Any]:
- """Validate a ``/model`` value for the active provider.
-
- Returns a dict with: - accepted: whether the CLI should switch to the requested model now -
- persist: whether it is safe to save to config - recognized: whether it matched a known provider
- catalog - message: optional warning / guidance for the user (- corrected_model: when a typo
- was auto-corrected).
- """
+ """Validate a ``/model`` value for the active provider → dict with ``accepted`` (switch now),
+ ``persist`` (safe to save to config), ``recognized`` (matched a known provider catalog),
+ ``message`` (optional warning / guidance) and ``corrected_model`` when a typo was fixed."""
from hermes_cli import models as _m
requested = (model_name or "").strip()
@@ -587,43 +595,10 @@ def validate_requested_model(
if not requested:
return _reject("Model name cannot be empty.")
- if normalized == "moa":
- return _validate_moa(requested)
- if any(ch.isspace() for ch in requested):
- return _reject("Model names cannot contain spaces.")
-
req = _Request(requested, lookup, provider, normalized, api_key, base_url, api_mode, headers)
- if normalized == "openrouter":
- verdict = _parse_openrouter_preset(req)
- if verdict is not None:
- return verdict
- if normalized == "lmstudio":
- return _validate_lmstudio(req)
- verdict = _validate_ollama_native(req)
- if verdict is not None:
- return verdict
- if normalized == "custom" or normalized.startswith("custom:"):
- return _validate_custom(req)
- if normalized in {"openai-codex", "xai-oauth"}:
- verdict = _validate_static_catalog(req)
- if verdict is not None:
- return verdict
- if normalized in {"minimax", "minimax-cn"}:
- verdict = _validate_minimax(req)
- if verdict is not None:
- return verdict
- if normalized == "anthropic":
- verdict = _validate_anthropic(req)
- if verdict is not None:
- return verdict
- if api_mode == "anthropic_messages":
- return _validate_anthropic_messages(req)
- verdict = _validate_live_listing(req)
- if verdict is not None:
- return verdict
- # API unreachable — accept and persist, but warn so typos don't silently break things.
- if normalized == "bedrock":
- verdict = _validate_bedrock(req)
- if verdict is not None:
- return verdict
- return _validate_catalog_fallback(req)
+ for gate, branch in _LADDER:
+ if gate(req):
+ verdict = branch(req)
+ if verdict is not None:
+ return verdict
+ raise AssertionError("unreachable: _validate_catalog_fallback always decides")