hermes-smart-router 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- hermes_smart_router-0.2.0/LICENSE +21 -0
- hermes_smart_router-0.2.0/PKG-INFO +8 -0
- hermes_smart_router-0.2.0/README.md +162 -0
- hermes_smart_router-0.2.0/hermes_smart_router.egg-info/PKG-INFO +8 -0
- hermes_smart_router-0.2.0/hermes_smart_router.egg-info/SOURCES.txt +18 -0
- hermes_smart_router-0.2.0/hermes_smart_router.egg-info/dependency_links.txt +1 -0
- hermes_smart_router-0.2.0/hermes_smart_router.egg-info/requires.txt +1 -0
- hermes_smart_router-0.2.0/hermes_smart_router.egg-info/top_level.txt +6 -0
- hermes_smart_router-0.2.0/pyproject.toml +11 -0
- hermes_smart_router-0.2.0/setup.cfg +4 -0
- hermes_smart_router-0.2.0/smart_router/__init__.py +10 -0
- hermes_smart_router-0.2.0/smart_router/__main__.py +386 -0
- hermes_smart_router-0.2.0/smart_router/ollama.py +299 -0
- hermes_smart_router-0.2.0/smart_router/router.py +409 -0
- hermes_smart_router-0.2.0/smart_router/tier.py +301 -0
- hermes_smart_router-0.2.0/tests/__init__.py +0 -0
- hermes_smart_router-0.2.0/tests/test_cli.py +342 -0
- hermes_smart_router-0.2.0/tests/test_ollama.py +513 -0
- hermes_smart_router-0.2.0/tests/test_router.py +1016 -0
- hermes_smart_router-0.2.0/tests/test_tier.py +146 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 raydatalab
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
# Hermes Smart Router
|
|
2
|
+
|
|
3
|
+
<p align="center">
|
|
4
|
+
<img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
|
|
5
|
+
<img src="https://img.shields.io/badge/python-3.10+-blue.svg" alt="Python">
|
|
6
|
+
<img src="https://img.shields.io/badge/Hermes-v0.17+-purple.svg" alt="Hermes">
|
|
7
|
+
</p>
|
|
8
|
+
|
|
9
|
+
Intelligent model tier routing for Hermes Agent — helps the agent pick the right model for each query.
|
|
10
|
+
|
|
11
|
+
> **Note:** Hermes does not support in-session model switching via skills. The router classifies queries and recommends a tier; the user must run the suggested `/model` command manually.
|
|
12
|
+
|
|
13
|
+
## The Problem
|
|
14
|
+
|
|
15
|
+
A user may have access to multiple model tiers: a local model (fast, free, offline), a low-cost cloud model, and a more capable frontier model. Without routing, every query goes to the same target, incurring unnecessary cost on simple tasks and under-serving complex ones.
|
|
16
|
+
|
|
17
|
+
## The Solution
|
|
18
|
+
|
|
19
|
+
A Hermes skill that classifies queries on demand and recommends the appropriate model tier. Classification runs entirely on the local machine:
|
|
20
|
+
|
|
21
|
+
```
|
|
22
|
+
"Translate hello to German" → local (Ollama, free)
|
|
23
|
+
"Explain how DNS works" → flash (low-cost API)
|
|
24
|
+
"Design a multi-region database" → pro (highest capability)
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
Routing uses [semantic-router](https://github.com/aurelio-labs/semantic-router) with local Ollama embeddings — zero API calls, zero cost. After the one-time embedding model pull, classification runs entirely offline.
|
|
28
|
+
|
|
29
|
+
## Tiers
|
|
30
|
+
|
|
31
|
+
| Tier | Purpose | Provider examples |
|
|
32
|
+
|------|---------|-------------------|
|
|
33
|
+
| **local** | Free, offline, private — simple lookups, translations, formatting | Ollama (llama3.2, qwen3, mistral), any local model |
|
|
34
|
+
| **flash** | Fast, low-cost — everyday coding, explanations, general Q&A | DeepSeek Flash, Gemini Flash, GPT-4o-mini, Claude Haiku |
|
|
35
|
+
| **pro** | Highest capability — complex architecture, debugging, multi-step reasoning | DeepSeek Pro, Gemini Pro, GPT-4o, Claude Sonnet |
|
|
36
|
+
|
|
37
|
+
One API token, different models for different complexity. There is no requirement for multiple providers — a single provider such as OpenRouter or DeepSeek provides both flash and pro tiers.
|
|
38
|
+
|
|
39
|
+
## Features
|
|
40
|
+
|
|
41
|
+
- 3-tier routing: local / flash / pro, auto-selected per query
|
|
42
|
+
- 100% local classification via Ollama embeddings — no cloud dependencies
|
|
43
|
+
- Ollama lifecycle: auto-start when needed, auto-kill when idle
|
|
44
|
+
- No GPU required — runs on CPU
|
|
45
|
+
- Queries never leave the local machine during routing decisions
|
|
46
|
+
|
|
47
|
+
## Installation
|
|
48
|
+
|
|
49
|
+
**Prerequisites:** Hermes Agent v0.17+, Python 3.10+, Ollama installed.
|
|
50
|
+
|
|
51
|
+
### Via Hermes (recommended)
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
hermes skills install hermes-smart-router
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
If the short form is unavailable, use the repo path:
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
hermes skills install raydatalab/hermes-smart-router
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Then run the one-time setup script to install Python dependencies into Hermes' environment and pull the embedding model (~30 seconds, once per machine):
|
|
64
|
+
|
|
65
|
+
```bash
|
|
66
|
+
git clone https://github.com/raydatalab/hermes-smart-router.git
|
|
67
|
+
cd hermes-smart-router && bash scripts/install.sh
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
The script auto-detects Hermes' Python venv and installs there — the skill can import `smart_router` immediately after.
|
|
71
|
+
|
|
72
|
+
### Manual
|
|
73
|
+
|
|
74
|
+
```bash
|
|
75
|
+
git clone https://github.com/raydatalab/hermes-smart-router.git
|
|
76
|
+
cd hermes-smart-router && bash scripts/install.sh
|
|
77
|
+
hermes skills install SKILL.md
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
On first use, Smart Router detects available Ollama models from `ollama list` and adapts. If no cloud providers are configured, the skill operates in local-only mode — no errors, no missing-config warnings.
|
|
81
|
+
|
|
82
|
+
## Configuration
|
|
83
|
+
|
|
84
|
+
Configure via `hermes config set` for each tier, or add a `smart_router:` block in config.yaml with the following structure:
|
|
85
|
+
|
|
86
|
+
```yaml
|
|
87
|
+
smart_router:
|
|
88
|
+
enabled: true
|
|
89
|
+
default_tier: flash
|
|
90
|
+
encoder_model: nomic-embed-text
|
|
91
|
+
tiers:
|
|
92
|
+
local:
|
|
93
|
+
provider: custom
|
|
94
|
+
model: llama3.2:3b
|
|
95
|
+
base_url: http://localhost:11434/v1
|
|
96
|
+
flash:
|
|
97
|
+
provider: openrouter
|
|
98
|
+
model: google/gemini-flash-1.5
|
|
99
|
+
pro:
|
|
100
|
+
provider: openrouter
|
|
101
|
+
model: anthropic/claude-sonnet-4
|
|
102
|
+
ollama:
|
|
103
|
+
auto_start: true
|
|
104
|
+
idle_timeout: 300
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Providers are configured via `hermes model` — no manual `.env` editing is required.
|
|
108
|
+
|
|
109
|
+
## Provider Support
|
|
110
|
+
|
|
111
|
+
| Tier | Ollama | OpenRouter | DeepSeek | Anthropic | OpenAI | Custom endpoint |
|
|
112
|
+
|------|--------|------------|----------|-----------|--------|-----------------|
|
|
113
|
+
| local | auto-detect | — | — | — | — | configurable |
|
|
114
|
+
| flash | — | ✓ | ✓ | ✓ | ✓ | ✓ |
|
|
115
|
+
| pro | — | ✓ | ✓ | ✓ | ✓ | ✓ |
|
|
116
|
+
|
|
117
|
+
The local tier auto-detects whichever Ollama model is available. Flash and pro tiers work with any provider Hermes supports — the `provider` and `model` fields in the tier config determine the target.
|
|
118
|
+
|
|
119
|
+
## Usage
|
|
120
|
+
|
|
121
|
+
Once loaded, the skill provides a classification tool the agent invokes when the current model feels wrong for the query — either too weak or too expensive. The router fires `needs_switch` in both directions, and the agent recommends a `/model` command the user can execute:
|
|
122
|
+
|
|
123
|
+
```
|
|
124
|
+
Agent (flash): receives "Design a fault-tolerant payment system"
|
|
125
|
+
→ classifies → needs_switch=true → recommends pro upgrade
|
|
126
|
+
💡 Switch to pro: /model deepseek deepseek-v4-pro
|
|
127
|
+
Agent: [detailed architecture answer]
|
|
128
|
+
|
|
129
|
+
Agent (pro): receives "Translate hello to German"
|
|
130
|
+
→ classifies → needs_switch=true → recommends flash downgrade
|
|
131
|
+
💡 Downgrade to flash: /model deepseek deepseek-v4-flash
|
|
132
|
+
Agent: Hallo
|
|
133
|
+
```
|
|
134
|
+
|
|
135
|
+
### Python API
|
|
136
|
+
|
|
137
|
+
```python
|
|
138
|
+
from smart_router.router import get_router
|
|
139
|
+
|
|
140
|
+
router = get_router()
|
|
141
|
+
decision = router.resolve("Explain how DNS works", current_tier="flash")
|
|
142
|
+
# → {"tier": "flash", "model": {...}, "ollama_ready": null, "needs_switch": false}
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### CLI
|
|
146
|
+
|
|
147
|
+
```bash
|
|
148
|
+
python -m smart_router route "What is the capital of France?"
|
|
149
|
+
python -m smart_router chat # interactive mode with stats
|
|
150
|
+
python -m smart_router tiers # list configured tiers
|
|
151
|
+
python -m smart_router ollama status # check Ollama
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
If installed via the script into Hermes' venv, use that Python directly:
|
|
155
|
+
|
|
156
|
+
```bash
|
|
157
|
+
~/.hermes/hermes-agent/venv/bin/python3 -m smart_router route "What is the capital of France?"
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
## License
|
|
161
|
+
|
|
162
|
+
MIT
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
hermes_smart_router.egg-info/PKG-INFO
|
|
5
|
+
hermes_smart_router.egg-info/SOURCES.txt
|
|
6
|
+
hermes_smart_router.egg-info/dependency_links.txt
|
|
7
|
+
hermes_smart_router.egg-info/requires.txt
|
|
8
|
+
hermes_smart_router.egg-info/top_level.txt
|
|
9
|
+
smart_router/__init__.py
|
|
10
|
+
smart_router/__main__.py
|
|
11
|
+
smart_router/ollama.py
|
|
12
|
+
smart_router/router.py
|
|
13
|
+
smart_router/tier.py
|
|
14
|
+
tests/__init__.py
|
|
15
|
+
tests/test_cli.py
|
|
16
|
+
tests/test_ollama.py
|
|
17
|
+
tests/test_router.py
|
|
18
|
+
tests/test_tier.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
semantic-router[ollama]>=0.1.15
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
[project]
|
|
2
|
+
name = "hermes-smart-router"
|
|
3
|
+
version = "0.2.0"
|
|
4
|
+
description = "Intelligent model tier routing for Hermes Agent"
|
|
5
|
+
requires-python = ">=3.10"
|
|
6
|
+
dependencies = [
|
|
7
|
+
"semantic-router[ollama]>=0.1.15",
|
|
8
|
+
]
|
|
9
|
+
|
|
10
|
+
[tool.setuptools.packages.find]
|
|
11
|
+
where = ["."]
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Hermes Smart Router — Intelligent model tier routing for Hermes Agent.
|
|
3
|
+
|
|
4
|
+
Classifies queries on demand and recommends the optimal model tier:
|
|
5
|
+
- local (Ollama, free)
|
|
6
|
+
- flash (low-cost API)
|
|
7
|
+
- pro (frontier API, highest quality)
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
__version__ = "0.2.0"
|
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CLI entry point for Smart Router.
|
|
3
|
+
|
|
4
|
+
Usage:
|
|
5
|
+
python -m smart_router route [--json] [--verbose] <query>
|
|
6
|
+
python -m smart_router ollama start|stop|status [--json]
|
|
7
|
+
python -m smart_router chat [--verbose]
|
|
8
|
+
python -m smart_router tiers # list configured tiers
|
|
9
|
+
python -m smart_router status [--json] # show version, tiers, Ollama status
|
|
10
|
+
|
|
11
|
+
Examples:
|
|
12
|
+
python -m smart_router route "What is the capital of France?"
|
|
13
|
+
python -m smart_router route --json "Design a microservice architecture"
|
|
14
|
+
python -m smart_router ollama status
|
|
15
|
+
python -m smart_router status
|
|
16
|
+
python -m smart_router chat
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
import json
|
|
20
|
+
import sys
|
|
21
|
+
import logging
|
|
22
|
+
from typing import Optional
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
SEPARATOR = "─" * 50
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _setup_logging(verbose: bool) -> None:
|
|
30
|
+
"""Configure logging level based on verbosity flag."""
|
|
31
|
+
level = logging.DEBUG if verbose else logging.WARNING
|
|
32
|
+
logging.basicConfig(level=level, format="%(levelname)s: %(message)s")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _parse_flags(args: list[str]) -> tuple[bool, bool, list[str]]:
|
|
36
|
+
"""Extract --json and --verbose from args, returning (json_mode, verbose, remaining)."""
|
|
37
|
+
json_mode = False
|
|
38
|
+
verbose = False
|
|
39
|
+
remaining: list[str] = []
|
|
40
|
+
for arg in args:
|
|
41
|
+
if arg == "--json":
|
|
42
|
+
json_mode = True
|
|
43
|
+
elif arg == "--verbose":
|
|
44
|
+
verbose = True
|
|
45
|
+
else:
|
|
46
|
+
remaining.append(arg)
|
|
47
|
+
return json_mode, verbose, remaining
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
# ---------------------------------------------------------------------------
|
|
51
|
+
# Route command
|
|
52
|
+
# ---------------------------------------------------------------------------
|
|
53
|
+
|
|
54
|
+
def cmd_route(args: list[str]) -> None:
|
|
55
|
+
"""Classify a query and print the routing decision."""
|
|
56
|
+
json_mode, verbose, remaining = _parse_flags(args)
|
|
57
|
+
_setup_logging(verbose)
|
|
58
|
+
|
|
59
|
+
query = " ".join(remaining) if remaining else "Hello, how are you?"
|
|
60
|
+
|
|
61
|
+
from .router import ModelRouter
|
|
62
|
+
|
|
63
|
+
router = ModelRouter()
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
info = router.route_info(query)
|
|
67
|
+
except Exception as e:
|
|
68
|
+
if json_mode:
|
|
69
|
+
print(json.dumps({"error": str(e)}, ensure_ascii=False))
|
|
70
|
+
else:
|
|
71
|
+
print(f"Error: {e}")
|
|
72
|
+
sys.exit(1)
|
|
73
|
+
|
|
74
|
+
if json_mode:
|
|
75
|
+
print(json.dumps(info, indent=2, ensure_ascii=False))
|
|
76
|
+
else:
|
|
77
|
+
model = info["model"]
|
|
78
|
+
provider_model = f"{model['provider']}/{model['model']}"
|
|
79
|
+
base_url = model.get("base_url", "")
|
|
80
|
+
url_info = f"\n Base URL: {base_url}" if base_url else ""
|
|
81
|
+
|
|
82
|
+
print(f"Query: {info['query']}")
|
|
83
|
+
print(f"Tier: {info['tier']}")
|
|
84
|
+
print(f"Model: {provider_model}{url_info}")
|
|
85
|
+
print(f"Summary: {info['description']}")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
# ---------------------------------------------------------------------------
|
|
89
|
+
# Ollama commands
|
|
90
|
+
# ---------------------------------------------------------------------------
|
|
91
|
+
|
|
92
|
+
def cmd_ollama(args: list[str]) -> None:
|
|
93
|
+
"""Manage Ollama lifecycle: start, stop, status."""
|
|
94
|
+
json_mode, verbose, remaining = _parse_flags(args)
|
|
95
|
+
_setup_logging(verbose)
|
|
96
|
+
|
|
97
|
+
from .ollama import OllamaManager
|
|
98
|
+
|
|
99
|
+
mgr = OllamaManager()
|
|
100
|
+
|
|
101
|
+
if not remaining or remaining[0] == "status":
|
|
102
|
+
status = mgr.status()
|
|
103
|
+
if json_mode:
|
|
104
|
+
print(json.dumps(status, indent=2))
|
|
105
|
+
else:
|
|
106
|
+
print("Ollama Status")
|
|
107
|
+
print(SEPARATOR)
|
|
108
|
+
print(f" Running: {'✓ yes' if status['running'] else '✗ no'}")
|
|
109
|
+
print(f" Binary: {'✓ found' if status['binary_exists'] else '✗ not found'}")
|
|
110
|
+
print(f" Model: {status['model'] or '(none)'}")
|
|
111
|
+
print(f" Model loaded: {'✓ yes' if status['model_loaded'] else '✗ no'}")
|
|
112
|
+
print(f" Model pulled: {'✓ yes' if status['model_pulled'] else '✗ no'}")
|
|
113
|
+
print(f" Idle: {status['idle_seconds']}s (timeout: {status['idle_timeout']}s)")
|
|
114
|
+
print(f" Managed PID: {status['our_pid'] or 'none'}")
|
|
115
|
+
print(f" WSL: {'✓ yes' if status['wsl'] else '✗ no'}")
|
|
116
|
+
return
|
|
117
|
+
|
|
118
|
+
action = remaining[0]
|
|
119
|
+
if action == "start":
|
|
120
|
+
ok = mgr.ensure_running()
|
|
121
|
+
if json_mode:
|
|
122
|
+
print(json.dumps({"action": "start", "success": ok}))
|
|
123
|
+
else:
|
|
124
|
+
print(f"Ollama start: {'✓ ready' if ok else '✗ failed'}")
|
|
125
|
+
if not ok:
|
|
126
|
+
print(" Is ollama installed? Try: curl -fsSL https://ollama.com/install.sh | sh")
|
|
127
|
+
|
|
128
|
+
elif action == "stop":
|
|
129
|
+
ok = mgr.ensure_killed(force=True)
|
|
130
|
+
if json_mode:
|
|
131
|
+
print(json.dumps({"action": "stop", "success": ok}))
|
|
132
|
+
else:
|
|
133
|
+
print(f"Ollama stop: {'✓ killed' if ok else '✗ not killed (may be systemd-managed)'}")
|
|
134
|
+
|
|
135
|
+
else:
|
|
136
|
+
print(f"Unknown action: {action}. Use: start, stop, status", file=sys.stderr)
|
|
137
|
+
sys.exit(1)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
# ---------------------------------------------------------------------------
|
|
141
|
+
# Tiers command
|
|
142
|
+
# ---------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
def cmd_tiers(args: list[str]) -> None:
|
|
145
|
+
"""List configured tiers with model info."""
|
|
146
|
+
json_mode, verbose, remaining = _parse_flags(args)
|
|
147
|
+
_setup_logging(verbose)
|
|
148
|
+
|
|
149
|
+
from .tier import get_tiers, DEFAULT_TIER
|
|
150
|
+
|
|
151
|
+
tiers = get_tiers()
|
|
152
|
+
|
|
153
|
+
if json_mode:
|
|
154
|
+
print(json.dumps({"tiers": tiers, "default": DEFAULT_TIER}, indent=2, ensure_ascii=False))
|
|
155
|
+
return
|
|
156
|
+
|
|
157
|
+
print("Smart Router — Configured Tiers")
|
|
158
|
+
print(SEPARATOR)
|
|
159
|
+
for name, config in tiers.items():
|
|
160
|
+
marker = " ★ DEFAULT" if name == DEFAULT_TIER else ""
|
|
161
|
+
m = config["models"]
|
|
162
|
+
provider_model = f"{m['provider']}/{m['model']}"
|
|
163
|
+
print(f" [{name}]{marker}")
|
|
164
|
+
print(f" Model: {provider_model}")
|
|
165
|
+
if "base_url" in m:
|
|
166
|
+
print(f" Base URL: {m['base_url']}")
|
|
167
|
+
print(f" Utterances: {len(config['utterances'])} examples")
|
|
168
|
+
print(f" Description: {config.get('description', '')}")
|
|
169
|
+
print()
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
# ---------------------------------------------------------------------------
|
|
173
|
+
# Status command
|
|
174
|
+
# ---------------------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
def cmd_status(args: list[str]) -> None:
|
|
177
|
+
"""Show smart-router version, configured tiers, and Ollama status."""
|
|
178
|
+
json_mode, verbose, remaining = _parse_flags(args)
|
|
179
|
+
_setup_logging(verbose)
|
|
180
|
+
|
|
181
|
+
from . import __version__
|
|
182
|
+
from .tier import get_tiers, DEFAULT_TIER
|
|
183
|
+
from .ollama import OllamaManager
|
|
184
|
+
|
|
185
|
+
tiers = get_tiers()
|
|
186
|
+
ollama = OllamaManager()
|
|
187
|
+
ostatus = ollama.status()
|
|
188
|
+
|
|
189
|
+
status_data = {
|
|
190
|
+
"version": __version__,
|
|
191
|
+
"default_tier": DEFAULT_TIER,
|
|
192
|
+
"encoder_model": "nomic-embed-text",
|
|
193
|
+
"tiers": {},
|
|
194
|
+
"ollama": ostatus,
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
for name, config in tiers.items():
|
|
198
|
+
status_data["tiers"][name] = {
|
|
199
|
+
"model": dict(config["models"]),
|
|
200
|
+
"utterance_count": len(config["utterances"]),
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
if json_mode:
|
|
204
|
+
print(json.dumps(status_data, indent=2, ensure_ascii=False))
|
|
205
|
+
return
|
|
206
|
+
|
|
207
|
+
print("Smart Router Status")
|
|
208
|
+
print(SEPARATOR)
|
|
209
|
+
print(f" Version: {__version__}")
|
|
210
|
+
print(f" Default tier: {DEFAULT_TIER}")
|
|
211
|
+
print(f" Encoder: nomic-embed-text (Ollama)")
|
|
212
|
+
print()
|
|
213
|
+
print(" Configured Tiers:")
|
|
214
|
+
for name, config in tiers.items():
|
|
215
|
+
marker = " ★ default" if name == DEFAULT_TIER else ""
|
|
216
|
+
m = config["models"]
|
|
217
|
+
base_url = m.get("base_url", "")
|
|
218
|
+
url_info = f" @ {base_url}" if base_url else ""
|
|
219
|
+
print(f" [{name}]{marker}")
|
|
220
|
+
print(f" Model: {m['provider']}/{m['model']}{url_info}")
|
|
221
|
+
print()
|
|
222
|
+
print(" Ollama:")
|
|
223
|
+
print(f" Running: {'✓ yes' if ostatus['running'] else '✗ no'}")
|
|
224
|
+
print(f" Binary: {'✓ found' if ostatus['binary_exists'] else '✗ not found'}")
|
|
225
|
+
print(f" Chat model: {ostatus['model'] or '(none)'}")
|
|
226
|
+
print(f" Model loaded: {'✓ yes' if ostatus['model_loaded'] else '✗ no'}")
|
|
227
|
+
print(f" Model pulled: {'✓ yes' if ostatus['model_pulled'] else '✗ no'}")
|
|
228
|
+
if ostatus.get("idle_seconds") is not None:
|
|
229
|
+
print(f" Idle: {ostatus['idle_seconds']}s (timeout: {ostatus['idle_timeout']}s)")
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
# ---------------------------------------------------------------------------
|
|
233
|
+
# Chat (interactive) command
|
|
234
|
+
# ---------------------------------------------------------------------------
|
|
235
|
+
|
|
236
|
+
def cmd_chat(args: list[str]) -> None:
|
|
237
|
+
"""Interactive routing test with session statistics."""
|
|
238
|
+
json_mode, verbose, remaining = _parse_flags(args)
|
|
239
|
+
_setup_logging(verbose)
|
|
240
|
+
|
|
241
|
+
from .router import ModelRouter
|
|
242
|
+
|
|
243
|
+
router = ModelRouter()
|
|
244
|
+
|
|
245
|
+
# Session routing statistics
|
|
246
|
+
stats: dict[str, int] = {"local": 0, "flash": 0, "pro": 0}
|
|
247
|
+
|
|
248
|
+
print("╔══════════════════════════════════════════════════╗")
|
|
249
|
+
print("║ Smart Router — Interactive Test ║")
|
|
250
|
+
print("╠══════════════════════════════════════════════════╣")
|
|
251
|
+
print("║ Type a query to see tier + model routing. ║")
|
|
252
|
+
print("║ Commands: :stats :reset :help quit ║")
|
|
253
|
+
print("╚══════════════════════════════════════════════════╝")
|
|
254
|
+
print()
|
|
255
|
+
|
|
256
|
+
while True:
|
|
257
|
+
try:
|
|
258
|
+
query = input("query ▸ ").strip()
|
|
259
|
+
except (EOFError, KeyboardInterrupt):
|
|
260
|
+
print()
|
|
261
|
+
break
|
|
262
|
+
|
|
263
|
+
if not query:
|
|
264
|
+
continue
|
|
265
|
+
|
|
266
|
+
# Handle special commands
|
|
267
|
+
if query.lower() in ("quit", "exit", "q"):
|
|
268
|
+
print("Goodbye!")
|
|
269
|
+
break
|
|
270
|
+
|
|
271
|
+
if query.startswith(":"):
|
|
272
|
+
_handle_chat_command(query, stats, router)
|
|
273
|
+
continue
|
|
274
|
+
|
|
275
|
+
# Route the query
|
|
276
|
+
info = router.route_info(query)
|
|
277
|
+
tier = info["tier"]
|
|
278
|
+
stats[tier] += 1
|
|
279
|
+
model = info["model"]
|
|
280
|
+
provider_model = f"{model['provider']}/{model['model']}"
|
|
281
|
+
|
|
282
|
+
# Display routing decision
|
|
283
|
+
tier_symbols = {"local": "🖥 ", "flash": "⚡", "pro": "🧠"}
|
|
284
|
+
symbol = tier_symbols.get(tier, "→")
|
|
285
|
+
|
|
286
|
+
print(f" {symbol} Tier: {tier}")
|
|
287
|
+
print(f" Model: {provider_model}")
|
|
288
|
+
if "base_url" in model:
|
|
289
|
+
print(f" URL: {model['base_url']}")
|
|
290
|
+
print(f" {info['description']}")
|
|
291
|
+
print()
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def _handle_chat_command(cmd: str, stats: dict[str, int], router) -> None:
|
|
295
|
+
"""Process in-chat meta-commands (prefixed with ':')."""
|
|
296
|
+
cmd = cmd.lower()
|
|
297
|
+
|
|
298
|
+
if cmd == ":stats":
|
|
299
|
+
total = sum(stats.values())
|
|
300
|
+
print(f" Session Stats ({total} queries)")
|
|
301
|
+
print(f" {'─' * 28}")
|
|
302
|
+
if total == 0:
|
|
303
|
+
print(" No queries yet.")
|
|
304
|
+
else:
|
|
305
|
+
for tier, count in stats.items():
|
|
306
|
+
pct = (count / total * 100) if total > 0 else 0
|
|
307
|
+
bar = "█" * int(pct / 5) + "░" * (20 - int(pct / 5))
|
|
308
|
+
print(f" {tier:8s} {bar} {count:3d} ({pct:3.0f}%)")
|
|
309
|
+
|
|
310
|
+
elif cmd == ":reset":
|
|
311
|
+
for key in stats:
|
|
312
|
+
stats[key] = 0
|
|
313
|
+
print(" Stats reset.")
|
|
314
|
+
|
|
315
|
+
elif cmd == ":help":
|
|
316
|
+
print(" Commands:")
|
|
317
|
+
print(" :stats Show session routing statistics")
|
|
318
|
+
print(" :reset Reset session statistics")
|
|
319
|
+
print(" :help Show this help")
|
|
320
|
+
print(" :tiers List configured tiers")
|
|
321
|
+
print(" quit Exit interactive mode")
|
|
322
|
+
|
|
323
|
+
elif cmd == ":tiers":
|
|
324
|
+
from .tier import get_tiers, DEFAULT_TIER
|
|
325
|
+
tiers = get_tiers()
|
|
326
|
+
for name, config in tiers.items():
|
|
327
|
+
marker = " (default)" if name == DEFAULT_TIER else ""
|
|
328
|
+
m = config["models"]
|
|
329
|
+
print(f" [{name}]{marker}: {m['provider']}/{m['model']}")
|
|
330
|
+
|
|
331
|
+
else:
|
|
332
|
+
print(f" Unknown command: {cmd}. Type :help for available commands.")
|
|
333
|
+
|
|
334
|
+
print()
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
# ---------------------------------------------------------------------------
|
|
338
|
+
# Main entry point
|
|
339
|
+
# ---------------------------------------------------------------------------
|
|
340
|
+
|
|
341
|
+
def main() -> None:
|
|
342
|
+
"""Parse subcommand and dispatch."""
|
|
343
|
+
|
|
344
|
+
usage_text = (
|
|
345
|
+
"Smart Router CLI — intelligent model tier routing\n"
|
|
346
|
+
"\n"
|
|
347
|
+
"Usage:\n"
|
|
348
|
+
" python -m smart_router route [--json] [--verbose] <query>\n"
|
|
349
|
+
" python -m smart_router ollama start|stop|status [--json]\n"
|
|
350
|
+
" python -m smart_router chat [--verbose]\n"
|
|
351
|
+
" python -m smart_router tiers [--json]\n"
|
|
352
|
+
" python -m smart_router status [--json]\n"
|
|
353
|
+
"\n"
|
|
354
|
+
"Examples:\n"
|
|
355
|
+
' python -m smart_router route "What is the capital of France?"\n'
|
|
356
|
+
' python -m smart_router route --json "Design a system"\n'
|
|
357
|
+
" python -m smart_router ollama status\n"
|
|
358
|
+
)
|
|
359
|
+
|
|
360
|
+
if len(sys.argv) < 2:
|
|
361
|
+
print(usage_text)
|
|
362
|
+
sys.exit(0)
|
|
363
|
+
|
|
364
|
+
command = sys.argv[1]
|
|
365
|
+
args = sys.argv[2:]
|
|
366
|
+
|
|
367
|
+
if command == "route":
|
|
368
|
+
cmd_route(args)
|
|
369
|
+
elif command == "ollama":
|
|
370
|
+
cmd_ollama(args)
|
|
371
|
+
elif command == "chat":
|
|
372
|
+
cmd_chat(args)
|
|
373
|
+
elif command == "tiers":
|
|
374
|
+
cmd_tiers(args)
|
|
375
|
+
elif command == "status":
|
|
376
|
+
cmd_status(args)
|
|
377
|
+
elif command in ("--help", "-h", "help"):
|
|
378
|
+
print(usage_text)
|
|
379
|
+
else:
|
|
380
|
+
print(f"Unknown command: {command}", file=sys.stderr)
|
|
381
|
+
print("Available: route, ollama, chat, tiers, status", file=sys.stderr)
|
|
382
|
+
sys.exit(1)
|
|
383
|
+
|
|
384
|
+
|
|
385
|
+
if __name__ == "__main__":
|
|
386
|
+
main()
|