Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -7860,6 +7860,30 @@ def _handle_gquota_command(self, cmd_original: str) -> None:
self._console_print(f" {header:40s} {bar} {pct_str}")
self._console_print()

def _handle_free_models_command(self) -> None:
"""List all free OpenRouter models with tool-calling support.

Surfaces every ``:free`` variant on OpenRouter (not just curated ones)
so users evaluating Hermes Agent can quickly discover zero-cost models.
See ``hermes-agent#17923``.
"""
from hermes_cli.models import fetch_openrouter_free_models
with self._busy_command("Fetching free OpenRouter models..."):
models = fetch_openrouter_free_models()

if not models:
self._console_print(" [yellow]No free OpenRouter models reachable right now.[/]")
return

self._console_print()
self._console_print(f" [bold]Free OpenRouter models[/] ({len(models)} available)")
self._console_print()
for mid, _ in models:
self._console_print(f" {mid}")
self._console_print()
self._console_print(" [dim]Switch with:[/] /model <id> --provider openrouter")
self._console_print()

def _handle_personality_command(self, cmd: str):
"""Handle the /personality command to set predefined personalities."""
parts = cmd.split(maxsplit=1)
Expand Down Expand Up @@ -8457,6 +8481,8 @@ def process_command(self, command: str) -> bool:
self._handle_codex_runtime(cmd_original)
elif canonical == "gquota":
self._handle_gquota_command(cmd_original)
elif canonical == "free-models":
self._handle_free_models_command()

elif canonical == "personality":
# Use original case (handler lowercases the personality name itself)
Expand Down
2 changes: 2 additions & 0 deletions hermes_cli/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,6 +125,8 @@ class CommandDef:
CommandDef("codex-runtime", "Toggle codex app-server runtime for OpenAI/Codex models",
"Configuration", aliases=("codex_runtime",),
args_hint="[auto|codex_app_server]"),
CommandDef("free-models", "List all free OpenRouter models with tool support", "Info",
cli_only=True),
CommandDef("gquota", "Show Google Gemini Code Assist quota usage", "Info",
cli_only=True),

Expand Down
53 changes: 53 additions & 0 deletions hermes_cli/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -1196,6 +1196,59 @@ def fetch_openrouter_models(
return list(curated)


def fetch_openrouter_free_models(timeout: float = 8.0) -> list[tuple[str, str]]:
"""Return all live OpenRouter models with free pricing and tool support.

Unlike :func:`fetch_openrouter_models`, this bypasses the curated picker list
and surfaces every model on OpenRouter where ``pricing.prompt`` and
``pricing.completion`` are both zero AND ``supported_parameters`` advertises
tool-calling. This addresses the gap where free ``:free`` variants appear on
OpenRouter (e.g. ``nvidia/nemotron-3-nano-omni-30b-a3b-reasoning:free``)
but never make it into the curated catalog.

Returns ``[(id, "free"), ...]``. On any network/parse failure, falls back
to the ``:free``-suffixed entries already in :data:`OPENROUTER_MODELS`
so the CLI keeps working offline.

See ``hermes-agent#17923``.
"""
try:
req = urllib.request.Request(
"https://openrouter.ai/api/v1/models",
headers={"Accept": "application/json"},
)
with urllib.request.urlopen(req, timeout=timeout) as resp:
payload = json.loads(resp.read().decode())
except Exception:
return [(mid, "free") for mid, _ in OPENROUTER_MODELS if mid.endswith(":free")]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fallback loses static entries whose catalog description is "free" but whose ID has no :free suffix: this PR's OPENROUTER_MODELS includes openrouter/elephant-alpha and openrouter/owl-alpha. Filter by the catalog's free description through a shared fallback helper, and use it at the other two fallback sites as well.


live_items = payload.get("data", [])
if not isinstance(live_items, list):
return [(mid, "free") for mid, _ in OPENROUTER_MODELS if mid.endswith(":free")]

out: list[tuple[str, str]] = []
seen: set[str] = set()
for item in live_items:
if not isinstance(item, dict):
continue
mid = str(item.get("id") or "").strip()
if not mid or mid in seen:
continue
if not _openrouter_model_is_free(item.get("pricing")):
continue
# Hermes-agent is tool-calling-first; surfacing models that don't
# advertise tools leads to immediate runtime failures when selected.
if not _openrouter_model_supports_tools(item):
continue
seen.add(mid)
out.append((mid, "free"))

if not out:
return [(mid, "free") for mid, _ in OPENROUTER_MODELS if mid.endswith(":free")]

return out


def model_ids(*, force_refresh: bool = False) -> list[str]:
"""Return just the OpenRouter model-id strings."""
return [mid for mid, _ in fetch_openrouter_models(force_refresh=force_refresh)]
Expand Down
125 changes: 125 additions & 0 deletions tests/hermes_cli/test_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -880,3 +880,128 @@ def test_tier_detection_error_defaults_to_paid(self):
patch("hermes_cli.models.check_nous_free_tier", side_effect=RuntimeError("boom")),
):
assert get_nous_recommended_aux_model(vision=False) == "paid-model"


class TestFetchOpenRouterFreeModels:
"""Tests for fetch_openrouter_free_models — see hermes-agent#17923."""

@staticmethod
def _mock_response(payload_bytes: bytes):
class _Resp:
def __enter__(self):
return self
def __exit__(self, exc_type, exc, tb):
return False
def read(self):
return payload_bytes
return _Resp()

def test_returns_only_free_models_with_tool_support(self):
from hermes_cli.models import fetch_openrouter_free_models
payload = (
b'{"data":['
b'{"id":"anthropic/claude-opus-4.6",'
b'"pricing":{"prompt":"0.000015","completion":"0.000075"},'
b'"supported_parameters":["tools"]},'
b'{"id":"nvidia/nemotron-3-nano-30b-a3b:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["tools"]},'
b'{"id":"nvidia/nemotron-nano-9b-v2:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["tools"]}'
b']}'
)
with patch(
"hermes_cli.models.urllib.request.urlopen",
return_value=self._mock_response(payload),
):
models = fetch_openrouter_free_models()

assert models == [
("nvidia/nemotron-3-nano-30b-a3b:free", "free"),
("nvidia/nemotron-nano-9b-v2:free", "free"),
]

def test_filters_out_free_models_without_tool_support(self):
"""Free models that don't advertise tool-calling must not appear:
Hermes Agent is tool-calling-first."""
from hermes_cli.models import fetch_openrouter_free_models
payload = (
b'{"data":['
b'{"id":"vendor/free-no-tools:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["temperature"]},'
b'{"id":"vendor/free-with-tools:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["tools","temperature"]}'
b']}'
)
with patch(
"hermes_cli.models.urllib.request.urlopen",
return_value=self._mock_response(payload),
):
models = fetch_openrouter_free_models()

assert models == [("vendor/free-with-tools:free", "free")]

def test_keeps_free_models_with_missing_supported_parameters(self):
"""Permissive: when supported_parameters is absent, surface the model
(matches the policy in fetch_openrouter_models for offline mirrors)."""
from hermes_cli.models import fetch_openrouter_free_models
payload = (
b'{"data":['
b'{"id":"vendor/free-no-params:free",'
b'"pricing":{"prompt":"0","completion":"0"}}'
b']}'
)
with patch(
"hermes_cli.models.urllib.request.urlopen",
return_value=self._mock_response(payload),
):
models = fetch_openrouter_free_models()

assert models == [("vendor/free-no-params:free", "free")]

def test_falls_back_to_static_free_entries_on_fetch_failure(self):
"""Network failure → return the ``:free`` entries already in
OPENROUTER_MODELS so the user still sees something."""
from hermes_cli.models import fetch_openrouter_free_models
with patch(
"hermes_cli.models.urllib.request.urlopen",
side_effect=OSError("no network"),
):
models = fetch_openrouter_free_models()

expected = [(mid, "free") for mid, _ in OPENROUTER_MODELS if mid.endswith(":free")]
assert models == expected

def test_falls_back_when_api_returns_malformed_payload(self):
from hermes_cli.models import fetch_openrouter_free_models
with patch(
"hermes_cli.models.urllib.request.urlopen",
return_value=self._mock_response(b'{"data": "not a list"}'),
):
models = fetch_openrouter_free_models()

expected = [(mid, "free") for mid, _ in OPENROUTER_MODELS if mid.endswith(":free")]
assert models == expected

def test_dedupes_repeated_ids_in_payload(self):
from hermes_cli.models import fetch_openrouter_free_models
payload = (
b'{"data":['
b'{"id":"vendor/dup:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["tools"]},'
b'{"id":"vendor/dup:free",'
b'"pricing":{"prompt":"0","completion":"0"},'
b'"supported_parameters":["tools"]}'
b']}'
)
with patch(
"hermes_cli.models.urllib.request.urlopen",
return_value=self._mock_response(payload),
):
models = fetch_openrouter_free_models()

assert models == [("vendor/dup:free", "free")]