The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
refactor(models): dedupe ollama probe failure/ollama-config lookups, pricing fetch/entry helpers; logger parity in models_local
Teknium5c9580c69658
diff --git a/hermes_cli/models_local.py b/hermes_cli/models_local.pyindex 609edd38315..1ec9b48ad71 100644--- a/hermes_cli/models_local.py+++ b/hermes_cli/models_local.py@@ -12,6 +12,7 @@ from __future__ import annotationsimport http.clientimport json+import loggingimport osimport timeimport urllib.error@@ -21,6 +22,9 @@ from pathlib import Pathfrom typing import Any, NamedTuple, Optionalfrom hermes_cli.urllib_security import url_origin+# Log-record parity with the origin module.+logger = logging.getLogger("hermes_cli.models")+def _root_for_ollama_native_api(base_url: str) -> str:"""Convert an OpenAI-style Ollama base URL to the native API root."""@@ -46,6 +50,14 @@ def _normalize_openai_base_url(base_url: Optional[str]) -> str:return value+def _configured_ollama_base_url() -> str:+ """``providers.ollama.base_url`` (legacy keys ``api`` / ``url``), or ``""``."""+ from hermes_cli.models import _get_provider_config_dict++ cfg = _get_provider_config_dict("ollama")+ return str(cfg.get("base_url") or cfg.get("api") or cfg.get("url") or "").strip()++def _get_ollama_base_url() -> str:"""Resolve the local Ollama-compatible endpoint URL.@@ -54,16 +66,10 @@ def _get_ollama_base_url() -> str:active ``model.base_url`` only when the active provider is ollama/custom, then to Ollama's localdefault."""- from hermes_cli.models import _get_model_config_dict, _get_provider_config_dict, should_use_ollama_native_catalog- provider_cfg = _get_provider_config_dict("ollama")- configured = (- provider_cfg.get("base_url", "")- or provider_cfg.get("api", "")- or provider_cfg.get("url", "")- or ""- )+ from hermes_cli.models import _get_model_config_dict, should_use_ollama_native_catalog+ configured = _configured_ollama_base_url()if configured:- return str(configured).strip()+ return configuredmodel_cfg = _get_model_config_dict()model_provider = str(model_cfg.get("provider", "") or "").strip().lower()@@ -71,10 +77,9 @@ def _get_ollama_base_url() -> str:if model_provider == "ollama" and model_base:return model_baseif model_provider == "custom" and model_base:- # Only reuse the active bare custom endpoint when it is actually- # Ollama-compatible. Otherwise a user working against an unrelated- # OpenAI-compatible endpoint would make the Ollama picker probe that- # endpoint's /api/tags and hide their local Ollama catalog.+ # Only reuse the active bare custom endpoint when it is actually Ollama-compatible;+ # otherwise the Ollama picker would probe an unrelated endpoint's /api/tags and hide the+ # local Ollama catalog.try:if should_use_ollama_native_catalog("custom", model_base):return model_base@@ -126,9 +131,7 @@ def _get_ollama_request_headers() -> dict[str, str]:api_key = str(entry.get("api_key") or "").strip()if not api_key:- key_env = str(- entry.get("key_env") or entry.get("api_key_env") or ""- ).strip()+ key_env = str(entry.get("key_env") or entry.get("api_key_env") or "").strip()api_key = os.getenv(key_env, "").strip() if key_env else ""if api_key and not any(key.lower() == "authorization" for key in result):result["Authorization"] = f"Bearer {api_key}"@@ -141,17 +144,10 @@ def _get_ollama_native_headers(api_key: Optional[str] = None,) -> dict[str, str]:"""Resolve Ollama credentials and headers for one endpoint origin."""- from hermes_cli.models import _get_ollama_request_headers, _get_provider_config_dict- entry = _get_provider_config_dict("ollama")- configured_base = str(- entry.get("base_url") or entry.get("api") or entry.get("url") or ""- ).strip()+ from hermes_cli.models import _get_ollama_request_headers+ configured_base = _configured_ollama_base_url()explicit_key = str(api_key or "").strip()- configured_matches = bool(- configured_base- and base_url- and _same_ollama_native_root(base_url, configured_base)- )+ configured_matches = bool(configured_base and base_url and _same_ollama_native_root(base_url, configured_base))if not configured_matches and not explicit_key:return {}headers = _get_ollama_request_headers() if configured_matches else {}@@ -165,18 +161,12 @@ def _get_ollama_native_headers(return headers-_OLLAMA_LOCAL_MODELS_CACHE_TTL: int = 300 # seconds (5 minutes)--+# Native /api/tags probe caches, keyed by root (+ header fingerprint): successful catalogs,+# failure timestamps (short negative TTL), and whether the root answered the native probe.+_OLLAMA_LOCAL_MODELS_CACHE_TTL: int = 300 # seconds_OLLAMA_LOCAL_MODELS_CACHE: dict[str, tuple[tuple[str, ...], float]] = {}--_OLLAMA_LOCAL_PROBE_FAILURE_CACHE: dict[str, float] = {}--_OLLAMA_LOCAL_PROBE_REACHABLE: dict[str, bool] = {}--_OLLAMA_LOCAL_PROBE_FAILURE_TTL: int = 30@@ -216,6 +206,25 @@ def _ollama_probe_cache_key(root: str, headers: Optional[dict[str, str]]) -> strreturn cache_key+def _parse_ollama_tags(payload: Any) -> Optional[list[str]]:+ """Model ids from an ``/api/tags`` payload; None when the shape is not Ollama's."""+ raw_models = payload.get("models") if isinstance(payload, dict) else None+ if not isinstance(raw_models, list):+ return None+ models: list[str] = []+ seen: set[str] = set()+ for item in raw_models:+ if not isinstance(item, dict):+ return None+ model_id = str(item.get("model") or item.get("name") or "").strip()+ if model_id and model_id not in seen:+ seen.add(model_id)+ models.append(model_id)+ if raw_models and not models:+ return None+ return models++def probe_ollama_local_models(base_url: Optional[str] = None,timeout: float = 2.0,@@ -245,72 +254,27 @@ def probe_ollama_local_models(return None_OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)+ def _unreachable() -> None:+ _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False)+ _remember_ollama_cache(_OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic())+try:- url = root.rstrip("/") + "/api/tags"- request_headers = {"User-Agent": _HERMES_USER_AGENT}- request_headers.update(headers or {})- req = urllib.request.Request(url, headers=request_headers)+ request_headers = {"User-Agent": _HERMES_USER_AGENT, **(headers or {})}+ req = urllib.request.Request(root.rstrip("/") + "/api/tags", headers=request_headers)with _urlopen_model_catalog_request(req, timeout=timeout) as resp:payload = json.loads(resp.read().decode())- except (- ValueError,- OSError,- TimeoutError,- http.client.HTTPException,- urllib.error.URLError,- json.JSONDecodeError,- UnicodeDecodeError,- ):- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False- )- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()- )+ except (ValueError, OSError, TimeoutError, http.client.HTTPException, urllib.error.URLError,+ json.JSONDecodeError, UnicodeDecodeError):+ _unreachable()return None- raw_models = payload.get("models") if isinstance(payload, dict) else None- if not isinstance(raw_models, list):- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False- )- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()- )- return None-- models: list[str] = []- seen: set[str] = set()- for item in raw_models:- if isinstance(item, dict):- model_id = str(item.get("model") or item.get("name") or "").strip()- else:- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False- )- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()- )- return None- if not model_id or model_id in seen:- continue- seen.add(model_id)- models.append(model_id)- if raw_models and not models:- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, False- )- _remember_ollama_cache(- _OLLAMA_LOCAL_PROBE_FAILURE_CACHE, failure_key, time.monotonic()- )+ models = _parse_ollama_tags(payload)+ if models is None:+ _unreachable()return None_remember_ollama_cache(_OLLAMA_LOCAL_PROBE_REACHABLE, cache_key, True)_OLLAMA_LOCAL_PROBE_FAILURE_CACHE.pop(failure_key, None)- _remember_ollama_cache(- _OLLAMA_LOCAL_MODELS_CACHE,- cache_key,- (tuple(models), time.monotonic()),- )+ _remember_ollama_cache(_OLLAMA_LOCAL_MODELS_CACHE, cache_key, (tuple(models), time.monotonic()))return models@@ -354,7 +318,7 @@ def should_use_ollama_native_catalog(or an ambiguous custom URL on Ollama's default port actually serves ``/api/tags``; othercustom endpoints keep the ``/models`` probe."""- from hermes_cli.models import _get_provider_config_dict, probe_ollama_local_models+ from hermes_cli.models import probe_ollama_local_modelsrequested = str(provider or "").strip().lower()root = _root_for_ollama_native_api(base_url or "")if root:@@ -365,40 +329,18 @@ def should_use_ollama_native_catalog(except ValueError:pass- known_non_local_providers = {- "openrouter",- "nous",- "anthropic",- "openai",- "openai-codex",- "gemini",- "ollama-cloud",- }- if requested in known_non_local_providers:+ if requested in {"openrouter", "nous", "anthropic", "openai", "openai-codex", "gemini", "ollama-cloud"}:return False+ configured_base = _configured_ollama_base_url()if requested == "ollama":if not root:return False- configured = _get_provider_config_dict("ollama")- configured_base = str(- configured.get("base_url")- or configured.get("api")- or configured.get("url")- or ""- ).strip()if configured_base and not _same_ollama_native_root(root, configured_base):return probe_ollama_local_models(root, timeout=0.5, headers=headers) is not Nonereturn True- provider_cfg = _get_provider_config_dict("ollama")- configured_ollama_base_url = str(- provider_cfg.get("base_url", "")- or provider_cfg.get("api", "")- or provider_cfg.get("url", "")- or ""- ).strip()- if configured_ollama_base_url and _same_ollama_native_root(root, configured_ollama_base_url):+ if configured_base and _same_ollama_native_root(root, configured_base):return Trueif not root:@@ -500,25 +442,15 @@ def _lmstudio_fetch_raw_models(provider="lmstudio",code="auth_rejected",) from exc- import logging- logging.getLogger(__name__).debug(- "LM Studio probe at %s failed with HTTP %s", server_root, exc.code,- )+ logger.debug("LM Studio probe at %s failed with HTTP %s", server_root, exc.code)return Noneexcept Exception as exc:- import logging- logging.getLogger(__name__).debug(- "LM Studio probe at %s failed: %s", server_root, exc,- )+ logger.debug("LM Studio probe at %s failed: %s", server_root, exc)return Noneraw_models = payload.get("models") if isinstance(payload, dict) else Noneif not isinstance(raw_models, list):- import logging- logging.getLogger(__name__).debug(- "LM Studio probe at %s returned malformed payload (no `models` list)",- server_root,- )+ logger.debug("LM Studio probe at %s returned malformed payload (no `models` list)", server_root)return Nonereturn raw_modelsdiff --git a/hermes_cli/models_pricing.py b/hermes_cli/models_pricing.pyindex e2e0bfff078..f6c2d4cc451 100644--- a/hermes_cli/models_pricing.py+++ b/hermes_cli/models_pricing.py@@ -219,6 +219,31 @@ def compute_sale_discount(return None+def _get_json(url: str, headers: dict[str, str], timeout: float, opener=None) -> Optional[dict]:+ """GET *url* as JSON via the origin's catalog opener (or *opener*); None on any failure."""+ from hermes_cli.models import _urlopen_model_catalog_request++ try:+ req = urllib.request.Request(url, headers=headers)+ with (opener or _urlopen_model_catalog_request)(req, timeout=timeout) as resp:+ return json.loads(resp.read().decode())+ except Exception:+ return None+++def _pricing_entry(pricing: dict, prompt_key: str = "prompt", completion_key: str = "completion") -> dict[str, Any]:+ """Picker-shape ``{prompt, completion[, input_cache_read, input_cache_write]}`` from a catalog+ ``pricing`` block whose cache fields already use the hermes names."""+ entry: dict[str, Any] = {+ "prompt": str(pricing.get(prompt_key, "")),+ "completion": str(pricing.get(completion_key, "")),+ }+ for key in ("input_cache_read", "input_cache_write"):+ if pricing.get(key):+ entry[key] = str(pricing[key])+ return entry++def fetch_models_with_pricing(api_key: str | None = None,base_url: str = "https://openrouter.ai/api",@@ -238,7 +263,7 @@ def fetch_models_with_pricing(discount under ``pricing.original``, those pre-discount rates are copied through as a nested``original`` dict so pickers can show sale chrome."""- from hermes_cli.models import _HERMES_USER_AGENT, _urlopen_model_catalog_request+ from hermes_cli.models import _HERMES_USER_AGENTurl_root = (base_url or "").rstrip("/")cache_key = url_root + _pricing_auth_fingerprint(api_key)if not force_refresh:@@ -247,23 +272,16 @@ def fetch_models_with_pricing(return cachedurl = url_root + "/v1/models"- headers: dict[str, str] = {- "Accept": "application/json",- "User-Agent": _HERMES_USER_AGENT,- }+ headers = {"Accept": "application/json", "User-Agent": _HERMES_USER_AGENT}if api_key:headers["Authorization"] = f"Bearer {api_key}"-- 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:+ payload = _get_json(url, headers, timeout)+ 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, 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._seed_reasoning_caps(url, payload.get("data"))result: dict[str, dict[str, Any]] = {}@@ -271,30 +289,17 @@ def fetch_models_with_pricing(mid = item.get("id")pricing = item.get("pricing")if mid and isinstance(pricing, dict):- entry: dict[str, Any] = {- "prompt": str(pricing.get("prompt", "")),- "completion": str(pricing.get("completion", "")),- }- if pricing.get("input_cache_read"):- entry["input_cache_read"] = str(pricing["input_cache_read"])- if pricing.get("input_cache_write"):- entry["input_cache_write"] = str(pricing["input_cache_write"])- # Sale chrome is Nous Portal-only. Never copy pricing.original for- # OpenRouter / other OpenAI-compatible catalogs.- if include_sale_original:- original = pricing.get("original")- if isinstance(original, dict):- orig_entry: dict[str, str] = {}- for key in (- "prompt",- "completion",- "input_cache_read",- "input_cache_write",- ):- if original.get(key) not in (None, ""):- orig_entry[key] = str(original[key])- if orig_entry.get("prompt") or orig_entry.get("completion"):- entry["original"] = orig_entry+ entry = _pricing_entry(pricing)+ # Sale chrome is Nous Portal-only; never copy pricing.original for other catalogs.+ original = pricing.get("original") if include_sale_original else None+ if isinstance(original, dict):+ orig_entry = {+ key: str(original[key])+ for key in ("prompt", "completion", "input_cache_read", "input_cache_write")+ if original.get(key) not in (None, "")+ }+ if orig_entry.get("prompt") or orig_entry.get("completion"):+ entry["original"] = orig_entryresult[mid] = entryreturn _cache_catalog(cache_key, result, cache_ttl_seconds)@@ -318,14 +323,8 @@ def fetch_ai_gateway_pricing(if cached is not None:return cached- try:- req = urllib.request.Request(- f"{cache_key}/models",- headers={"Accept": "application/json"},- )- with urllib.request.urlopen(req, timeout=timeout) as resp:- payload = json.loads(resp.read().decode())- except Exception:+ payload = _get_json(f"{cache_key}/models", {"Accept": "application/json"}, timeout, opener=urllib.request.urlopen)+ if payload is None:return _cache_catalog(cache_key, {})result: dict[str, dict[str, str]] = {}@@ -334,18 +333,8 @@ def fetch_ai_gateway_pricing(continuemid = item.get("id")pricing = item.get("pricing")- if not (mid and isinstance(pricing, dict)):- continue- entry: dict[str, str] = {- "prompt": str(pricing.get("input", "")),- "completion": str(pricing.get("output", "")),- }- if pricing.get("input_cache_read"):- entry["input_cache_read"] = str(pricing["input_cache_read"])- if pricing.get("input_cache_write"):- entry["input_cache_write"] = str(pricing["input_cache_write"])- result[mid] = entry-+ if mid and isinstance(pricing, dict):+ result[mid] = _pricing_entry(pricing, "input", "output")return _cache_catalog(cache_key, result)@@ -366,7 +355,6 @@ def _resolve_nous_pricing_credentials() -> tuple[str, str]:Without (1), a staging profile's sale ``pricing.original`` never reaches the pickers — theanonymous fallback would hit prod, which has no ``original`` field."""- env_base = Nonetry:from hermes_cli.auth import _nous_inference_env_override@@ -562,7 +550,7 @@ def _fetch_novita_pricing(per-token strings the shared pricing formatter expects. Results are cached in``_pricing_cache`` keyed on the resolved base URL so menu renders don't re-hit the network."""- from hermes_cli.models import _HERMES_USER_AGENT, _urlopen_model_catalog_request+ from hermes_cli.models import _HERMES_USER_AGENTapi_key = os.getenv("NOVITA_API_KEY", "").strip()if not api_key:return {}@@ -574,18 +562,9 @@ def _fetch_novita_pricing(if cached is not None:return cached- url = cache_key + "/models"- headers = {- "Authorization": f"Bearer {api_key}",- "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:+ headers = {"Authorization": f"Bearer {api_key}", "Accept": "application/json", "User-Agent": _HERMES_USER_AGENT}+ payload = _get_json(cache_key + "/models", headers, timeout)+ if payload is None:return _cache_catalog(cache_key, {})result: dict[str, dict[str, str]] = {}@@ -619,28 +598,18 @@ def _fetch_deepinfra_pricing((OpenRouter shape). Cached via the catalog helper so repeated picker renders are free."""from hermes_cli.models import _fetch_deepinfra_models_by_tag- items = _fetch_deepinfra_models_by_tag(- "chat", timeout=timeout, force_refresh=force_refresh- )- if not items:- return {}-+ items = _fetch_deepinfra_models_by_tag("chat", timeout=timeout, force_refresh=force_refresh)result: dict[str, dict[str, str]] = {}- for item in items:+ for item in items or []:metadata = item.get("metadata") or {}pricing = metadata.get("pricing") if isinstance(metadata, dict) else Noneif not isinstance(pricing, dict):continue- entry: dict[str, str] = {}- inp = pricing.get("input_tokens")- out = pricing.get("output_tokens")- cache_read = pricing.get("cache_read_tokens")- if inp is not None:- entry["prompt"] = str(float(inp) / 1_000_000)- if out is not None:- entry["completion"] = str(float(out) / 1_000_000)- if cache_read is not None:- entry["input_cache_read"] = str(float(cache_read) / 1_000_000)+ entry = {+ ours: str(float(pricing[theirs]) / 1_000_000)+ for theirs, ours in (("input_tokens", "prompt"), ("output_tokens", "completion"), ("cache_read_tokens", "input_cache_read"))+ if pricing.get(theirs) is not None+ }if entry:result[item["id"]] = entryreturn resultdiff --git a/hermes_cli/models_validate.py b/hermes_cli/models_validate.pyindex dc80f1323d5..6393d03aaa8 100644--- a/hermes_cli/models_validate.py+++ b/hermes_cli/models_validate.py@@ -193,9 +193,9 @@ def _ollama_probe_headers(req: _Request) -> dict[str, str]:``api_key`` becomes the Authorization header unless the caller already sent one."""from hermes_cli import models as _m+ from hermes_cli.models_local import _configured_ollama_base_url- cfg = _m._get_provider_config_dict("ollama")- configured_base = str(cfg.get("base_url") or cfg.get("api") or cfg.get("url") or "").strip()+ configured_base = _configured_ollama_base_url()configured_allowed = not (configured_base and not _m._same_ollama_native_root(req.base_url or "", configured_base))