@simplexai/localmodels-linux-x64 0.1.0-dev.36 → 0.1.0-dev.38
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.
- package/bootstrap.identity +1 -1
- package/bootstrap.sha256 +132 -110
- package/kit.py +1 -0
- package/modules/localmodels/__init__.py +1 -1
- package/modules/localmodels/__main__.py +9 -3
- package/modules/localmodels/bifrost_checks.py +9 -6
- package/modules/localmodels/bifrost_config.py +203 -0
- package/modules/localmodels/bifrost_datasheet.py +12 -2
- package/modules/localmodels/budget.py +13 -2
- package/modules/localmodels/catalog.json +137 -2
- package/modules/localmodels/catalog.py +70 -321
- package/modules/localmodels/catalog_add.py +2 -8
- package/modules/localmodels/catalog_recipes.py +352 -0
- package/modules/localmodels/cli_parser.py +4 -1
- package/modules/localmodels/console.py +5 -4
- package/modules/localmodels/contracts.py +13 -3
- package/modules/localmodels/debug_cli.py +158 -0
- package/modules/localmodels/debug_mode.py +727 -0
- package/modules/localmodels/debug_stub_server.py +192 -0
- package/modules/localmodels/decode_calibration.json +1 -1
- package/modules/localmodels/decode_calibration.py +34 -17
- package/modules/localmodels/gateway.py +21 -155
- package/modules/localmodels/gateway_accept.py +201 -0
- package/modules/localmodels/gateway_bifrost.py +30 -193
- package/modules/localmodels/gateway_cli.py +15 -6
- package/modules/localmodels/gateway_foundations.py +2 -4
- package/modules/localmodels/gateway_probe.py +0 -1
- package/modules/localmodels/gateway_server.py +2 -3
- package/modules/localmodels/gpu_specs.py +12 -0
- package/modules/localmodels/guard.py +2 -7
- package/modules/localmodels/harness.py +16 -129
- package/modules/localmodels/harness_cleanup.py +135 -0
- package/modules/localmodels/harness_gateway.py +16 -14
- package/modules/localmodels/harness_probe.py +12 -4
- package/modules/localmodels/hosts.py +25 -2
- package/modules/localmodels/http_local.py +59 -0
- package/modules/localmodels/install.py +23 -8
- package/modules/localmodels/library_gateway.py +20 -9
- package/modules/localmodels/library_jobs.py +125 -28
- package/modules/localmodels/library_model.py +10 -0
- package/modules/localmodels/library_pricing.py +29 -22
- package/modules/localmodels/library_serve.py +17 -1
- package/modules/localmodels/library_state.py +15 -2
- package/modules/localmodels/library_status.py +30 -0
- package/modules/localmodels/llm_rank.py +185 -39
- package/modules/localmodels/probe.py +108 -174
- package/modules/localmodels/process_identity.py +120 -154
- package/modules/localmodels/process_windows.py +86 -0
- package/modules/localmodels/recommend.py +6 -3
- package/modules/localmodels/recommend_cli.py +14 -6
- package/modules/localmodels/remote_ops.py +65 -0
- package/modules/localmodels/remote_ops_service.py +14 -2
- package/modules/localmodels/runtime_args.py +10 -3
- package/modules/localmodels/runtime_auth.py +5 -9
- package/modules/localmodels/runtime_cli.py +128 -129
- package/modules/localmodels/runtime_discovery.py +84 -0
- package/modules/localmodels/runtime_install.py +101 -0
- package/modules/localmodels/runtime_releases.py +302 -0
- package/modules/localmodels/search_server.py +5 -1
- package/modules/localmodels/service_stop.py +8 -108
- package/modules/localmodels/service_upgrade.py +394 -63
- package/modules/localmodels/services_cli.py +24 -14
- package/modules/localmodels/setup_inspection.py +97 -9
- package/modules/localmodels/setup_text.py +7 -0
- package/modules/localmodels/sizecalc.py +0 -1
- package/modules/localmodels/stack.py +45 -235
- package/modules/localmodels/stack_arena.py +732 -0
- package/modules/localmodels/stack_args.py +21 -12
- package/modules/localmodels/stack_auto.py +384 -3
- package/modules/localmodels/stack_aux_gpu.py +4 -3
- package/modules/localmodels/stack_capacity.py +138 -0
- package/modules/localmodels/stack_cleanup.py +9 -4
- package/modules/localmodels/stack_cli.py +288 -0
- package/modules/localmodels/stack_compose.py +63 -30
- package/modules/localmodels/stack_console.py +9 -6
- package/modules/localmodels/stack_hardware.py +95 -265
- package/modules/localmodels/stack_hardware_text.py +263 -0
- package/modules/localmodels/stack_journal.py +3 -9
- package/modules/localmodels/stack_ledger.py +48 -18
- package/modules/localmodels/stack_lifecycle.py +33 -312
- package/modules/localmodels/stack_llm_ram.py +16 -6
- package/modules/localmodels/stack_mcp.py +729 -0
- package/modules/localmodels/stack_memory.py +0 -2
- package/modules/localmodels/stack_picks.py +62 -15
- package/modules/localmodels/stack_plan.py +19 -1
- package/modules/localmodels/stack_preflight.py +11 -19
- package/modules/localmodels/stack_progress.py +9 -1
- package/modules/localmodels/stack_remove.py +373 -0
- package/modules/localmodels/stack_route.py +101 -17
- package/modules/localmodels/stack_run.py +29 -0
- package/modules/localmodels/stack_suite.py +21 -10
- package/modules/localmodels/stack_summary.py +14 -0
- package/modules/localmodels/stack_try.py +238 -24
- package/modules/localmodels/stack_try_client.py +53 -15
- package/modules/localmodels/stack_try_docs.py +2 -2
- package/modules/localmodels/stack_view.py +24 -171
- package/modules/localmodels/stack_view_access.py +114 -1
- package/modules/localmodels/stack_view_agent.py +3 -13
- package/modules/localmodels/stack_view_hub.py +9 -10
- package/modules/localmodels/stack_view_llm.py +1 -1
- package/modules/localmodels/stack_view_sandbox.py +2 -2
- package/modules/localmodels/stack_view_schema.py +183 -0
- package/modules/localmodels/stack_view_serve.py +7 -1
- package/modules/localmodels/stack_view_service.py +1 -2
- package/modules/localmodels/stack_view_text.py +13 -9
- package/modules/localmodels/stack_warm.py +48 -4
- package/modules/localmodels/stack_warm_store.py +517 -0
- package/modules/localmodels/tools.json +32 -18
- package/modules/localmodels/transport.py +38 -13
- package/modules/localmodels/tui.py +28 -4
- package/modules/localmodels/tui_dialogs.py +136 -0
- package/modules/localmodels/tui_modals.py +279 -0
- package/modules/localmodels/tui_screen.py +113 -154
- package/modules/localmodels/tui_views.py +134 -203
- package/modules/localmodels/web/index.html +510 -101
- package/modules/localmodels/web/sizecalc/app.js +363 -10
- package/modules/localmodels/web/sizecalc/page.html +27 -3
- package/modules/localmodels/web/view/fleet.html +11 -2
- package/modules/localmodels/web/view/fleet.js +191 -17
- package/modules/localmodels/web/view/i18n.js +3 -2
- package/modules/localmodels/web/view/index.html +1 -1
- package/modules/localmodels/web/view/nav.js +22 -3
- package/modules/localmodels/web/view/view.css +63 -18
- package/modules/localmodels/web/view/view.js +169 -32
- package/modules/localmodels/windows_job.py +69 -0
- package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/METADATA +1 -1
- package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/RECORD +128 -106
- package/package.json +1 -1
- package/tool.json +1 -1
- package/modules/localmodels/engines-strata-0.1.49.1.json +0 -31
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/WHEEL +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/entry_points.txt +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/NOTICE +0 -0
- /package/modules/{simplex_localmodels-0.1.0.dev36.dist-info → simplex_localmodels-0.1.0.dev38.dist-info}/licenses/localmodels/HERMES-LICENSE +0 -0
|
@@ -0,0 +1,732 @@
|
|
|
1
|
+
"""``stack arena``: blind local A/B LLM comparison with a content-free Elo leaderboard.
|
|
2
|
+
|
|
3
|
+
Compares two loopback OpenAI-compatible ``/chat/completions`` targets (either explicit
|
|
4
|
+
``--endpoint-a``/``--endpoint-b`` flags or the installed stack's primary and fastest LLMs).
|
|
5
|
+
Slot order is randomized per match with ``secrets.randbelow(2)`` and model identities stay
|
|
6
|
+
hidden until after voting.
|
|
7
|
+
|
|
8
|
+
Only model IDs, numeric Elo ratings, aggregate outcome counts and timestamps are persisted
|
|
9
|
+
to ``$LOCALMODELS_STATE/arena.json`` with ``0600`` permissions. Prompts, completions,
|
|
10
|
+
reasoning text, API keys, endpoints and HTTP error details are never written to disk.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import argparse
|
|
16
|
+
import http.client
|
|
17
|
+
import ipaddress
|
|
18
|
+
import json
|
|
19
|
+
import math
|
|
20
|
+
import re
|
|
21
|
+
import secrets
|
|
22
|
+
import sys
|
|
23
|
+
import time
|
|
24
|
+
import urllib.error
|
|
25
|
+
import urllib.parse
|
|
26
|
+
import urllib.request
|
|
27
|
+
from collections.abc import Sequence
|
|
28
|
+
from dataclasses import dataclass, field
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
from typing import Literal, TypedDict
|
|
31
|
+
|
|
32
|
+
from localmodels import cli_help, console, hosts, http_local, stack_up, stack_verify
|
|
33
|
+
from localmodels.plan_envelope import utc_now
|
|
34
|
+
from localmodels.records import Plan
|
|
35
|
+
from localmodels.stack_plan import StackError, command
|
|
36
|
+
|
|
37
|
+
ARENA_SCHEMA: Literal["localmodels.stack-arena/v1"] = "localmodels.stack-arena/v1"
|
|
38
|
+
LEADERBOARD_SCHEMA: Literal["localmodels.stack-arena-leaderboard/v1"] = (
|
|
39
|
+
"localmodels.stack-arena-leaderboard/v1"
|
|
40
|
+
)
|
|
41
|
+
MATCH_SCHEMA: Literal["localmodels.stack-arena-match/v1"] = "localmodels.stack-arena-match/v1"
|
|
42
|
+
INITIAL_RATING = 1500.0
|
|
43
|
+
K_FACTOR = 32.0
|
|
44
|
+
DEFAULT_MAX_TOKENS = 512
|
|
45
|
+
MAX_TOKENS_CAP = 32768
|
|
46
|
+
MAX_PROMPT_CHARS = 8192
|
|
47
|
+
MAX_RESPONSE_BYTES = 4 << 20
|
|
48
|
+
REQUEST_TIMEOUT_S = 120.0
|
|
49
|
+
VOTES = ("a", "b", "tie", "both-bad", "skip")
|
|
50
|
+
_THINK_BLOCK = re.compile(r"<think>.*?</think>", re.DOTALL)
|
|
51
|
+
_THINK_TAIL = re.compile(r"<think>.*\Z", re.DOTALL)
|
|
52
|
+
_CHAT_CONTRACTS = (None, "", "chat", "openai-chat")
|
|
53
|
+
_HTTP_LABELS = {
|
|
54
|
+
400: "request rejected (HTTP 400)",
|
|
55
|
+
401: "authentication rejected (HTTP 401)",
|
|
56
|
+
403: "access refused (HTTP 403)",
|
|
57
|
+
404: "endpoint not found (HTTP 404)",
|
|
58
|
+
413: "prompt too long (HTTP 413)",
|
|
59
|
+
429: "rate limited (HTTP 429)",
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class ModelStats(TypedDict):
|
|
64
|
+
model_id: str
|
|
65
|
+
rating: float
|
|
66
|
+
wins: int
|
|
67
|
+
losses: int
|
|
68
|
+
ties: int
|
|
69
|
+
both_bad: int
|
|
70
|
+
matches: int
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
class LeaderboardRow(ModelStats):
|
|
74
|
+
rank: int
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
class VoteSummary(TypedDict):
|
|
78
|
+
decisive: int
|
|
79
|
+
ties: int
|
|
80
|
+
both_bad: int
|
|
81
|
+
total: int
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class ArenaStore(TypedDict):
|
|
85
|
+
schema: Literal["localmodels.stack-arena/v1"]
|
|
86
|
+
updated_at: str | None
|
|
87
|
+
k_factor: float
|
|
88
|
+
initial_rating: float
|
|
89
|
+
votes: VoteSummary
|
|
90
|
+
models: dict[str, ModelStats]
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True)
|
|
94
|
+
class ArenaTarget:
|
|
95
|
+
model_id: str
|
|
96
|
+
wire_model: str
|
|
97
|
+
chat_url: str
|
|
98
|
+
api_key: str | None = field(default=None, repr=False)
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
@dataclass(frozen=True)
|
|
102
|
+
class SideResult:
|
|
103
|
+
model_id: str
|
|
104
|
+
content: str
|
|
105
|
+
latency_ms: float
|
|
106
|
+
error: str | None
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
def arena_path() -> Path:
|
|
110
|
+
return hosts.state_dir() / "arena.json"
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
def _nonneg_int(value: object) -> int:
|
|
114
|
+
if isinstance(value, int) and not isinstance(value, bool) and value >= 0:
|
|
115
|
+
return value
|
|
116
|
+
raise StackError("Saved arena state is invalid; fix or remove arena.json.")
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
def _finite_float(value: object) -> float:
|
|
120
|
+
if isinstance(value, int | float) and not isinstance(value, bool):
|
|
121
|
+
number = float(value)
|
|
122
|
+
if math.isfinite(number):
|
|
123
|
+
return number
|
|
124
|
+
raise StackError("Saved arena state is invalid; fix or remove arena.json.")
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
def _parse_model_stats(model_id: str, raw: object) -> ModelStats:
|
|
128
|
+
if not isinstance(raw, dict) or raw.get("model_id") != model_id:
|
|
129
|
+
raise StackError("Saved arena state has invalid model counts.")
|
|
130
|
+
return {
|
|
131
|
+
"model_id": model_id,
|
|
132
|
+
"rating": _finite_float(raw.get("rating")),
|
|
133
|
+
"wins": _nonneg_int(raw.get("wins")),
|
|
134
|
+
"losses": _nonneg_int(raw.get("losses")),
|
|
135
|
+
"ties": _nonneg_int(raw.get("ties")),
|
|
136
|
+
"both_bad": _nonneg_int(raw.get("both_bad")),
|
|
137
|
+
"matches": _nonneg_int(raw.get("matches")),
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _parse_votes(raw: object) -> VoteSummary:
|
|
142
|
+
if not isinstance(raw, dict):
|
|
143
|
+
raise StackError("Saved arena state has invalid vote summary.")
|
|
144
|
+
return {
|
|
145
|
+
"decisive": _nonneg_int(raw.get("decisive")),
|
|
146
|
+
"ties": _nonneg_int(raw.get("ties")),
|
|
147
|
+
"both_bad": _nonneg_int(raw.get("both_bad")),
|
|
148
|
+
"total": _nonneg_int(raw.get("total")),
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def load_store() -> ArenaStore:
|
|
153
|
+
"""Read and validate the content-free Elo store from disk."""
|
|
154
|
+
path = arena_path()
|
|
155
|
+
if not path.is_file():
|
|
156
|
+
return {
|
|
157
|
+
"schema": ARENA_SCHEMA,
|
|
158
|
+
"updated_at": None,
|
|
159
|
+
"k_factor": K_FACTOR,
|
|
160
|
+
"initial_rating": INITIAL_RATING,
|
|
161
|
+
"votes": {"decisive": 0, "ties": 0, "both_bad": 0, "total": 0},
|
|
162
|
+
"models": {},
|
|
163
|
+
}
|
|
164
|
+
try:
|
|
165
|
+
raw: object = json.loads(path.read_text(encoding="utf-8"))
|
|
166
|
+
except (OSError, ValueError, UnicodeDecodeError, RecursionError, OverflowError):
|
|
167
|
+
raise StackError("Saved arena state cannot be read; fix or remove arena.json.") from None
|
|
168
|
+
if not isinstance(raw, dict) or raw.get("schema") != ARENA_SCHEMA:
|
|
169
|
+
raise StackError("Saved arena state has an unsupported schema.")
|
|
170
|
+
updated_at, k_factor = raw.get("updated_at"), _finite_float(raw.get("k_factor"))
|
|
171
|
+
initial_rating, raw_models = _finite_float(raw.get("initial_rating")), raw.get("models")
|
|
172
|
+
if (
|
|
173
|
+
(updated_at is not None and not isinstance(updated_at, str))
|
|
174
|
+
or k_factor <= 0
|
|
175
|
+
or not isinstance(raw_models, dict)
|
|
176
|
+
):
|
|
177
|
+
raise StackError("Saved arena state is invalid; fix or remove arena.json.")
|
|
178
|
+
models: dict[str, ModelStats] = {}
|
|
179
|
+
for key, val in raw_models.items():
|
|
180
|
+
if not isinstance(key, str):
|
|
181
|
+
raise StackError("Saved arena state has invalid model counts.")
|
|
182
|
+
models[key] = _parse_model_stats(key, val)
|
|
183
|
+
return {
|
|
184
|
+
"schema": ARENA_SCHEMA,
|
|
185
|
+
"updated_at": updated_at,
|
|
186
|
+
"k_factor": k_factor,
|
|
187
|
+
"initial_rating": initial_rating,
|
|
188
|
+
"votes": _parse_votes(raw.get("votes")),
|
|
189
|
+
"models": models,
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _ensure_model(models: dict[str, ModelStats], model_id: str) -> ModelStats:
|
|
194
|
+
if (existing := models.get(model_id)) is not None:
|
|
195
|
+
return existing
|
|
196
|
+
created: ModelStats = {
|
|
197
|
+
"model_id": model_id,
|
|
198
|
+
"rating": INITIAL_RATING,
|
|
199
|
+
"wins": 0,
|
|
200
|
+
"losses": 0,
|
|
201
|
+
"ties": 0,
|
|
202
|
+
"both_bad": 0,
|
|
203
|
+
"matches": 0,
|
|
204
|
+
}
|
|
205
|
+
models[model_id] = created
|
|
206
|
+
return created
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def record_vote(model_a: str, model_b: str, vote: str) -> tuple[float, float, float, float]:
|
|
210
|
+
"""Apply ``vote`` under a file lock and persist only aggregate stats via save_private."""
|
|
211
|
+
model_a, model_b = _clean_model_id(model_a, "Model A"), _clean_model_id(model_b, "Model B")
|
|
212
|
+
if model_a == model_b:
|
|
213
|
+
raise StackError("Arena requires two distinct model IDs.")
|
|
214
|
+
if vote not in VOTES:
|
|
215
|
+
raise StackError(f"Invalid arena vote: {vote}.")
|
|
216
|
+
if vote == "skip":
|
|
217
|
+
store = load_store()
|
|
218
|
+
saved_a, saved_b = store["models"].get(model_a), store["models"].get(model_b)
|
|
219
|
+
before_a = saved_a["rating"] if saved_a is not None else INITIAL_RATING
|
|
220
|
+
before_b = saved_b["rating"] if saved_b is not None else INITIAL_RATING
|
|
221
|
+
return before_a, before_a, before_b, before_b
|
|
222
|
+
with hosts.file_lock(hosts.state_dir() / "arena.lock"):
|
|
223
|
+
store = load_store()
|
|
224
|
+
entry_a = _ensure_model(store["models"], model_a)
|
|
225
|
+
entry_b = _ensure_model(store["models"], model_b)
|
|
226
|
+
before_a, before_b = entry_a["rating"], entry_b["rating"]
|
|
227
|
+
if vote in ("a", "b", "tie"):
|
|
228
|
+
actual_a = 1.0 if vote == "a" else 0.0 if vote == "b" else 0.5
|
|
229
|
+
expected_a = 1.0 / (1.0 + 10.0 ** ((before_b - before_a) / 400.0))
|
|
230
|
+
entry_a["rating"] = before_a + K_FACTOR * (actual_a - expected_a)
|
|
231
|
+
entry_b["rating"] = before_b + K_FACTOR * ((1.0 - actual_a) - (1.0 - expected_a))
|
|
232
|
+
if vote in ("a", "b"):
|
|
233
|
+
winner, loser = (entry_a, entry_b) if vote == "a" else (entry_b, entry_a)
|
|
234
|
+
winner["wins"] += 1
|
|
235
|
+
loser["losses"] += 1
|
|
236
|
+
store["votes"]["decisive"] += 1
|
|
237
|
+
elif vote == "tie":
|
|
238
|
+
entry_a["ties"] += 1
|
|
239
|
+
entry_b["ties"] += 1
|
|
240
|
+
store["votes"]["ties"] += 1
|
|
241
|
+
else:
|
|
242
|
+
entry_a["both_bad"] += 1
|
|
243
|
+
entry_b["both_bad"] += 1
|
|
244
|
+
store["votes"]["both_bad"] += 1
|
|
245
|
+
entry_a["matches"] += 1
|
|
246
|
+
entry_b["matches"] += 1
|
|
247
|
+
store["votes"]["total"] += 1
|
|
248
|
+
store["updated_at"] = utc_now()
|
|
249
|
+
hosts.save_private(arena_path(), store)
|
|
250
|
+
return before_a, entry_a["rating"], before_b, entry_b["rating"]
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _is_loopback_host(host: str) -> bool:
|
|
254
|
+
lowered = host.lower()
|
|
255
|
+
if lowered == "localhost":
|
|
256
|
+
return True
|
|
257
|
+
try:
|
|
258
|
+
return ipaddress.ip_address(lowered.split("%", 1)[0]).is_loopback
|
|
259
|
+
except ValueError:
|
|
260
|
+
return False
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def _chat_url(raw: str, label: str) -> str:
|
|
264
|
+
text = raw.strip()
|
|
265
|
+
try:
|
|
266
|
+
parsed = urllib.parse.urlsplit(text)
|
|
267
|
+
_ = parsed.port
|
|
268
|
+
except ValueError:
|
|
269
|
+
raise StackError(
|
|
270
|
+
f"{label} must be a loopback http:// URL without credentials, query or fragment."
|
|
271
|
+
) from None
|
|
272
|
+
if (
|
|
273
|
+
parsed.scheme not in ("http", "https")
|
|
274
|
+
or not parsed.hostname
|
|
275
|
+
or parsed.username is not None
|
|
276
|
+
or parsed.password is not None
|
|
277
|
+
or parsed.query
|
|
278
|
+
or parsed.fragment
|
|
279
|
+
or not _is_loopback_host(parsed.hostname)
|
|
280
|
+
):
|
|
281
|
+
raise StackError(
|
|
282
|
+
f"{label} must be a loopback http:// URL without credentials, query or fragment."
|
|
283
|
+
)
|
|
284
|
+
base, path = text.rstrip("/"), parsed.path.rstrip("/")
|
|
285
|
+
if path.endswith("/chat/completions"):
|
|
286
|
+
return base
|
|
287
|
+
return f"{base}/v1/chat/completions" if not path else f"{base}/chat/completions"
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def _clean_model_id(raw: str, label: str) -> str:
|
|
291
|
+
cleaned = raw.strip()
|
|
292
|
+
if not cleaned or len(cleaned) > 256 or any(ord(ch) < 32 for ch in cleaned):
|
|
293
|
+
raise StackError(f"{label} must be a non-empty single-line model ID (up to 256 chars).")
|
|
294
|
+
return cleaned
|
|
295
|
+
|
|
296
|
+
|
|
297
|
+
def _target_from_plan(part: Plan, model_id: str, label: str) -> ArenaTarget:
|
|
298
|
+
return ArenaTarget(
|
|
299
|
+
model_id=_clean_model_id(model_id, label),
|
|
300
|
+
wire_model=str(part["endpoint"].get("model") or part["model"]["model_id"] or model_id),
|
|
301
|
+
chat_url=_chat_url(str(part["endpoint"]["base_url"]), part["name"]),
|
|
302
|
+
api_key=stack_verify.key(part),
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
|
|
306
|
+
def _targets_from_plans(part_a: Plan, part_b: Plan) -> tuple[ArenaTarget, ArenaTarget]:
|
|
307
|
+
id_a, id_b = part_a["model"]["id"], part_b["model"]["id"]
|
|
308
|
+
if id_a == id_b:
|
|
309
|
+
id_a, id_b = part_a["model"]["model_id"], part_b["model"]["model_id"]
|
|
310
|
+
target_a = _target_from_plan(part_a, id_a, "Model A")
|
|
311
|
+
target_b = _target_from_plan(part_b, id_b, "Model B")
|
|
312
|
+
if target_a.model_id == target_b.model_id or (
|
|
313
|
+
target_a.chat_url == target_b.chat_url and target_a.wire_model == target_b.wire_model
|
|
314
|
+
):
|
|
315
|
+
raise StackError("Arena requires two distinct local LLM targets.")
|
|
316
|
+
return target_a, target_b
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
def _explicit_targets(args: argparse.Namespace) -> tuple[ArenaTarget, ArenaTarget]:
|
|
320
|
+
if not all((args.endpoint_a, args.model_a, args.endpoint_b, args.model_b)):
|
|
321
|
+
raise StackError(
|
|
322
|
+
"Pass --endpoint-a, --model-a, --endpoint-b and --model-b together, "
|
|
323
|
+
"or omit them to compare the installed stack."
|
|
324
|
+
)
|
|
325
|
+
id_a = _clean_model_id(args.model_a, "--model-a")
|
|
326
|
+
id_b = _clean_model_id(args.model_b, "--model-b")
|
|
327
|
+
if id_a == id_b:
|
|
328
|
+
raise StackError("Arena requires two distinct model IDs (--model-a and --model-b).")
|
|
329
|
+
url_a = _chat_url(args.endpoint_a, "--endpoint-a")
|
|
330
|
+
url_b = _chat_url(args.endpoint_b, "--endpoint-b")
|
|
331
|
+
key_a = args.api_key_a.strip() or None if args.api_key_a is not None else None
|
|
332
|
+
key_b = args.api_key_b.strip() or None if args.api_key_b is not None else None
|
|
333
|
+
return (
|
|
334
|
+
ArenaTarget(id_a, id_a, url_a, key_a),
|
|
335
|
+
ArenaTarget(id_b, id_b, url_b, key_b),
|
|
336
|
+
)
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _resolve_targets(args: argparse.Namespace) -> tuple[ArenaTarget, ArenaTarget]:
|
|
340
|
+
if any(
|
|
341
|
+
getattr(args, name) is not None
|
|
342
|
+
for name in ("endpoint_a", "model_a", "api_key_a", "endpoint_b", "model_b", "api_key_b")
|
|
343
|
+
):
|
|
344
|
+
return _explicit_targets(args)
|
|
345
|
+
by_name = {r["plan"]["name"]: r["plan"] for r in hosts.records(hosts.LOCAL_ID) if r.get("ok")}
|
|
346
|
+
plan = stack_up.accepted()
|
|
347
|
+
if plan is not None and plan.get("llm_fast") is not None:
|
|
348
|
+
if stack_up.drift(plan):
|
|
349
|
+
raise StackError(
|
|
350
|
+
f"The installed stack changed; run {command()} install --route fastest "
|
|
351
|
+
"--decision auto to review it."
|
|
352
|
+
)
|
|
353
|
+
fast = plan["llm_fast"]
|
|
354
|
+
assert fast is not None
|
|
355
|
+
return _targets_from_plans(
|
|
356
|
+
by_name.get(plan["llm"]["name"], plan["llm"]),
|
|
357
|
+
by_name.get(fast["name"], fast),
|
|
358
|
+
)
|
|
359
|
+
chat_plans = [p for p in by_name.values() if p["endpoint"].get("contract") in _CHAT_CONTRACTS]
|
|
360
|
+
if len(chat_plans) == 2:
|
|
361
|
+
return _targets_from_plans(chat_plans[0], chat_plans[1])
|
|
362
|
+
if len(chat_plans) > 2:
|
|
363
|
+
raise StackError(
|
|
364
|
+
"More than two local LLM deployments are recorded; pass --endpoint-a/--model-a "
|
|
365
|
+
"and --endpoint-b/--model-b to choose two."
|
|
366
|
+
)
|
|
367
|
+
raise StackError(
|
|
368
|
+
"Arena requires two local LLM targets; install a routed stack with "
|
|
369
|
+
f"'{command()} install --route fastest --decision auto' or pass "
|
|
370
|
+
"--endpoint-a/--model-a and --endpoint-b/--model-b."
|
|
371
|
+
)
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def _strip_thinking(text: str) -> str:
|
|
375
|
+
return _THINK_TAIL.sub("", _THINK_BLOCK.sub("", text)).strip()
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _extract_text(doc: object) -> str | None:
|
|
379
|
+
if not isinstance(doc, dict):
|
|
380
|
+
return None
|
|
381
|
+
choices = doc.get("choices")
|
|
382
|
+
if not isinstance(choices, list) or not choices or not isinstance(choices[0], dict):
|
|
383
|
+
return None
|
|
384
|
+
message = choices[0].get("message")
|
|
385
|
+
if not isinstance(message, dict):
|
|
386
|
+
return None
|
|
387
|
+
content = message.get("content")
|
|
388
|
+
if content is None:
|
|
389
|
+
return ""
|
|
390
|
+
if isinstance(content, str):
|
|
391
|
+
return _strip_thinking(content)
|
|
392
|
+
if isinstance(content, list):
|
|
393
|
+
parts = [
|
|
394
|
+
part["text"]
|
|
395
|
+
for part in content
|
|
396
|
+
if isinstance(part, dict)
|
|
397
|
+
and part.get("type") == "text"
|
|
398
|
+
and isinstance(part.get("text"), str)
|
|
399
|
+
]
|
|
400
|
+
return _strip_thinking("".join(parts))
|
|
401
|
+
return None
|
|
402
|
+
|
|
403
|
+
|
|
404
|
+
def _http_status_label(code: int) -> str:
|
|
405
|
+
if 300 <= code < 400:
|
|
406
|
+
return f"redirect refused (HTTP {code})"
|
|
407
|
+
if code in _HTTP_LABELS:
|
|
408
|
+
return _HTTP_LABELS[code]
|
|
409
|
+
return f"server error (HTTP {code})" if 500 <= code < 600 else f"request failed (HTTP {code})"
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def _query_side(target: ArenaTarget, prompt: str, max_tokens: int) -> SideResult:
|
|
413
|
+
"""Query one loopback OpenAI-compatible chat endpoint without proxies, redirects or logging."""
|
|
414
|
+
headers = {"Content-Type": "application/json"}
|
|
415
|
+
if target.api_key:
|
|
416
|
+
headers["Authorization"] = f"Bearer {target.api_key}"
|
|
417
|
+
payload = {
|
|
418
|
+
"model": target.wire_model,
|
|
419
|
+
"messages": [{"role": "user", "content": prompt}],
|
|
420
|
+
"max_tokens": max_tokens,
|
|
421
|
+
"stream": False,
|
|
422
|
+
}
|
|
423
|
+
request = urllib.request.Request( # noqa: S310 - validated loopback http(s) URL
|
|
424
|
+
target.chat_url, data=json.dumps(payload).encode("utf-8"), headers=headers, method="POST"
|
|
425
|
+
)
|
|
426
|
+
opener = urllib.request.build_opener(
|
|
427
|
+
urllib.request.ProxyHandler({}), http_local.NoRedirectHandler()
|
|
428
|
+
)
|
|
429
|
+
started = time.monotonic()
|
|
430
|
+
err: str | None = None
|
|
431
|
+
content = ""
|
|
432
|
+
try:
|
|
433
|
+
with opener.open(request, timeout=REQUEST_TIMEOUT_S) as response:
|
|
434
|
+
raw = response.read(MAX_RESPONSE_BYTES + 1)
|
|
435
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
436
|
+
err = "response too large"
|
|
437
|
+
else:
|
|
438
|
+
text = _extract_text(json.loads(raw.decode("utf-8")))
|
|
439
|
+
if text is None:
|
|
440
|
+
err = "invalid response"
|
|
441
|
+
elif not text:
|
|
442
|
+
err = "empty response"
|
|
443
|
+
else:
|
|
444
|
+
content = text
|
|
445
|
+
except urllib.error.HTTPError as exc:
|
|
446
|
+
exc.close()
|
|
447
|
+
err = _http_status_label(exc.code)
|
|
448
|
+
except TimeoutError:
|
|
449
|
+
err = "request timed out"
|
|
450
|
+
except urllib.error.URLError as exc:
|
|
451
|
+
err = "request timed out" if isinstance(exc.reason, TimeoutError) else "connection failed"
|
|
452
|
+
except (UnicodeDecodeError, ValueError, RecursionError, OverflowError):
|
|
453
|
+
err = "invalid response"
|
|
454
|
+
except (OSError, http.client.HTTPException):
|
|
455
|
+
err = "connection failed"
|
|
456
|
+
return SideResult(target.model_id, content, (time.monotonic() - started) * 1000.0, err)
|
|
457
|
+
|
|
458
|
+
|
|
459
|
+
def _ask_user(prompt_label: str, *, as_json: bool) -> str:
|
|
460
|
+
if as_json:
|
|
461
|
+
sys.stderr.write(prompt_label)
|
|
462
|
+
sys.stderr.flush()
|
|
463
|
+
return input("")
|
|
464
|
+
return input(prompt_label)
|
|
465
|
+
|
|
466
|
+
|
|
467
|
+
def _resolve_prompt(args: argparse.Namespace) -> str:
|
|
468
|
+
if args.prompt is not None and args.prompt_text is not None:
|
|
469
|
+
raise StackError("Pass either positional PROMPT or --prompt, not both.")
|
|
470
|
+
raw = args.prompt_text if args.prompt_text is not None else args.prompt
|
|
471
|
+
if raw is None:
|
|
472
|
+
if not sys.stdin.isatty():
|
|
473
|
+
raise StackError(
|
|
474
|
+
"Prompt required when standard input is not a terminal; pass PROMPT or --prompt."
|
|
475
|
+
)
|
|
476
|
+
try:
|
|
477
|
+
raw = _ask_user("Arena prompt: ", as_json=bool(args.json))
|
|
478
|
+
except EOFError:
|
|
479
|
+
raise StackError("No prompt provided.") from None
|
|
480
|
+
if not raw.strip() or len(raw) > MAX_PROMPT_CHARS:
|
|
481
|
+
raise StackError(f"Prompt must contain 1 to {MAX_PROMPT_CHARS} characters.")
|
|
482
|
+
return str(raw)
|
|
483
|
+
|
|
484
|
+
|
|
485
|
+
def _collect_vote(explicit_vote: str | None, *, as_json: bool) -> str:
|
|
486
|
+
if explicit_vote is not None:
|
|
487
|
+
return explicit_vote
|
|
488
|
+
if not sys.stdin.isatty():
|
|
489
|
+
return "skip"
|
|
490
|
+
for prompt_label in (
|
|
491
|
+
"Vote [a/b/tie/both-bad/skip]: ",
|
|
492
|
+
"Please enter a, b, tie, both-bad, or skip: ",
|
|
493
|
+
):
|
|
494
|
+
try:
|
|
495
|
+
answer = _ask_user(prompt_label, as_json=as_json).strip().lower()
|
|
496
|
+
except EOFError:
|
|
497
|
+
return "skip"
|
|
498
|
+
if answer == "both_bad":
|
|
499
|
+
answer = "both-bad"
|
|
500
|
+
if answer in VOTES:
|
|
501
|
+
return answer
|
|
502
|
+
return "skip"
|
|
503
|
+
|
|
504
|
+
|
|
505
|
+
def _emit_match_json(
|
|
506
|
+
ok: bool,
|
|
507
|
+
vote: str,
|
|
508
|
+
res_a: SideResult,
|
|
509
|
+
res_b: SideResult,
|
|
510
|
+
ratings: tuple[float, float, float, float],
|
|
511
|
+
) -> None:
|
|
512
|
+
def side(slot: str, res: SideResult, before: float, after: float) -> dict[str, object]:
|
|
513
|
+
return {
|
|
514
|
+
"slot": slot,
|
|
515
|
+
"model_id": res.model_id,
|
|
516
|
+
"latency_ms": round(res.latency_ms, 1),
|
|
517
|
+
"error": res.error,
|
|
518
|
+
"rating_before": round(before, 2),
|
|
519
|
+
"rating_after": round(after, 2),
|
|
520
|
+
"delta": round(after - before, 2),
|
|
521
|
+
"content": res.content,
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
doc = {
|
|
525
|
+
"schema": MATCH_SCHEMA,
|
|
526
|
+
"ok": ok,
|
|
527
|
+
"vote": vote,
|
|
528
|
+
"slot_a": side("A", res_a, ratings[0], ratings[1]),
|
|
529
|
+
"slot_b": side("B", res_b, ratings[2], ratings[3]),
|
|
530
|
+
}
|
|
531
|
+
print(json.dumps(doc, ensure_ascii=False, indent=1))
|
|
532
|
+
|
|
533
|
+
|
|
534
|
+
def _print_reveal_side(slot: str, result: SideResult, before: float, after: float) -> None:
|
|
535
|
+
err = f"error: {result.error}, " if result.error is not None else ""
|
|
536
|
+
print(
|
|
537
|
+
f" Model {slot}: {result.model_id} "
|
|
538
|
+
f"({result.latency_ms:.1f} ms, {err}Elo {after:.1f} ({after - before:+.1f}))"
|
|
539
|
+
)
|
|
540
|
+
|
|
541
|
+
|
|
542
|
+
def _run_match(args: argparse.Namespace) -> int:
|
|
543
|
+
target_a, target_b = _resolve_targets(args)
|
|
544
|
+
prompt = _resolve_prompt(args)
|
|
545
|
+
slot_a, slot_b = (target_b, target_a) if secrets.randbelow(2) else (target_a, target_b)
|
|
546
|
+
res_a, res_b = (
|
|
547
|
+
_query_side(slot_a, prompt, args.max_tokens),
|
|
548
|
+
_query_side(slot_b, prompt, args.max_tokens),
|
|
549
|
+
)
|
|
550
|
+
if res_a.error is not None and res_b.error is not None:
|
|
551
|
+
ratings = record_vote(res_a.model_id, res_b.model_id, "skip")
|
|
552
|
+
if args.json:
|
|
553
|
+
_emit_match_json(False, "skip", res_a, res_b, ratings)
|
|
554
|
+
else:
|
|
555
|
+
print(
|
|
556
|
+
f"stack arena: Both model requests failed (Model A: {res_a.error}; "
|
|
557
|
+
f"Model B: {res_b.error}).",
|
|
558
|
+
file=sys.stderr,
|
|
559
|
+
)
|
|
560
|
+
return 1
|
|
561
|
+
blind_out = (
|
|
562
|
+
sys.stdout
|
|
563
|
+
if not args.json
|
|
564
|
+
else (sys.stderr if args.vote is None and sys.stdin.isatty() else None)
|
|
565
|
+
)
|
|
566
|
+
if blind_out is not None:
|
|
567
|
+
for slot, res in (("A", res_a), ("B", res_b)):
|
|
568
|
+
shown = res.content if res.error is None else "(request failed)"
|
|
569
|
+
print(f"=== Model {slot} ===\n{shown}\n", file=blind_out)
|
|
570
|
+
blind_out.flush()
|
|
571
|
+
vote = _collect_vote(args.vote, as_json=bool(args.json))
|
|
572
|
+
ok = res_a.error is None and res_b.error is None
|
|
573
|
+
effective_vote = vote if ok else "skip"
|
|
574
|
+
ratings = record_vote(res_a.model_id, res_b.model_id, effective_vote)
|
|
575
|
+
if args.json:
|
|
576
|
+
_emit_match_json(ok, effective_vote, res_a, res_b, ratings)
|
|
577
|
+
else:
|
|
578
|
+
print("--- Reveal ---")
|
|
579
|
+
print(f"Vote: {vote}" + ("" if ok else " (Elo unchanged because one side failed)"))
|
|
580
|
+
_print_reveal_side("A", res_a, ratings[0], ratings[1])
|
|
581
|
+
_print_reveal_side("B", res_b, ratings[2], ratings[3])
|
|
582
|
+
return 0 if ok else 1
|
|
583
|
+
|
|
584
|
+
|
|
585
|
+
def _run_leaderboard(*, as_json: bool) -> int:
|
|
586
|
+
store = load_store()
|
|
587
|
+
ordered = sorted(
|
|
588
|
+
store["models"].values(),
|
|
589
|
+
key=lambda item: (-item["rating"], -item["wins"], item["model_id"]),
|
|
590
|
+
)
|
|
591
|
+
rows: list[LeaderboardRow] = [{**row, "rank": idx} for idx, row in enumerate(ordered, 1)]
|
|
592
|
+
if as_json:
|
|
593
|
+
doc = {
|
|
594
|
+
"schema": LEADERBOARD_SCHEMA,
|
|
595
|
+
"updated_at": store["updated_at"],
|
|
596
|
+
"k_factor": store["k_factor"],
|
|
597
|
+
"initial_rating": store["initial_rating"],
|
|
598
|
+
"votes": store["votes"],
|
|
599
|
+
"leaderboard": rows,
|
|
600
|
+
}
|
|
601
|
+
print(json.dumps(doc, ensure_ascii=False, indent=1))
|
|
602
|
+
return 0
|
|
603
|
+
if not rows:
|
|
604
|
+
print("No arena matches recorded yet.")
|
|
605
|
+
return 0
|
|
606
|
+
header = ["#", "model", "rating", "wins", "losses", "ties", "both-bad", "matches"]
|
|
607
|
+
keys: tuple[Literal["wins", "losses", "ties", "both_bad", "matches"], ...] = (
|
|
608
|
+
"wins",
|
|
609
|
+
"losses",
|
|
610
|
+
"ties",
|
|
611
|
+
"both_bad",
|
|
612
|
+
"matches",
|
|
613
|
+
)
|
|
614
|
+
body = [
|
|
615
|
+
[str(r["rank"]), r["model_id"], f"{r['rating']:.1f}", *(str(r[k]) for k in keys)]
|
|
616
|
+
for r in rows
|
|
617
|
+
]
|
|
618
|
+
print("\n".join(console.columns([header, *body], frozenset({0, 2, 3, 4, 5, 6, 7}))))
|
|
619
|
+
return 0
|
|
620
|
+
|
|
621
|
+
|
|
622
|
+
class _ArenaParser(cli_help.Parser):
|
|
623
|
+
"""Allow optional positional PROMPT while still supporting the ``leaderboard`` subcommand."""
|
|
624
|
+
|
|
625
|
+
def _first_positional_is_subcommand(self, args: list[str]) -> bool:
|
|
626
|
+
value_opts = {flag for a in self._actions if a.nargs != 0 for flag in a.option_strings}
|
|
627
|
+
skip_next = False
|
|
628
|
+
for token in args:
|
|
629
|
+
if skip_next:
|
|
630
|
+
skip_next = False
|
|
631
|
+
continue
|
|
632
|
+
if token == "--":
|
|
633
|
+
break
|
|
634
|
+
if token.startswith("-"):
|
|
635
|
+
if "=" not in token and token in value_opts:
|
|
636
|
+
skip_next = True
|
|
637
|
+
continue
|
|
638
|
+
return token == "leaderboard"
|
|
639
|
+
return False
|
|
640
|
+
|
|
641
|
+
def parse_known_args( # type: ignore[override]
|
|
642
|
+
self,
|
|
643
|
+
args: Sequence[str] | None = None,
|
|
644
|
+
namespace: argparse.Namespace | None = None,
|
|
645
|
+
) -> tuple[argparse.Namespace, list[str]]:
|
|
646
|
+
sub = cli_help.subcommands(self)
|
|
647
|
+
arg_list = sys.argv[1:] if args is None else list(args)
|
|
648
|
+
if sub is None or self._first_positional_is_subcommand(arg_list):
|
|
649
|
+
return super().parse_known_args(args, namespace)
|
|
650
|
+
self._actions.remove(sub)
|
|
651
|
+
self._positionals._group_actions.remove(sub)
|
|
652
|
+
try:
|
|
653
|
+
parsed, extras = super().parse_known_args(args, namespace)
|
|
654
|
+
finally:
|
|
655
|
+
self._actions.append(sub)
|
|
656
|
+
self._positionals._group_actions.append(sub)
|
|
657
|
+
if not hasattr(parsed, sub.dest):
|
|
658
|
+
setattr(parsed, sub.dest, None)
|
|
659
|
+
return parsed, extras
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _tokens(value: str) -> int:
|
|
663
|
+
try:
|
|
664
|
+
number = int(value)
|
|
665
|
+
except ValueError:
|
|
666
|
+
raise argparse.ArgumentTypeError("a whole number from 1 to 32768") from None
|
|
667
|
+
if not 1 <= number <= MAX_TOKENS_CAP:
|
|
668
|
+
raise argparse.ArgumentTypeError("a whole number from 1 to 32768")
|
|
669
|
+
return number
|
|
670
|
+
|
|
671
|
+
|
|
672
|
+
def add_parser(actions: argparse._SubParsersAction[argparse.ArgumentParser]) -> None:
|
|
673
|
+
orig = getattr(actions, "_parser_class", cli_help.Parser)
|
|
674
|
+
actions._parser_class = _ArenaParser
|
|
675
|
+
try:
|
|
676
|
+
parser = actions.add_parser(
|
|
677
|
+
"arena", help="blind A/B comparison of two local LLMs and Elo leaderboard"
|
|
678
|
+
)
|
|
679
|
+
finally:
|
|
680
|
+
actions._parser_class = orig
|
|
681
|
+
parser.add_argument("prompt", nargs="?", metavar="PROMPT", help="prompt for both models")
|
|
682
|
+
parser.add_argument(
|
|
683
|
+
"--prompt", dest="prompt_text", metavar="TEXT", help="prompt text (alternative to PROMPT)"
|
|
684
|
+
)
|
|
685
|
+
parser.add_argument("--endpoint-a", metavar="URL", help="first loopback base or chat URL")
|
|
686
|
+
parser.add_argument("--model-a", metavar="ID", help="model ID for the first endpoint")
|
|
687
|
+
parser.add_argument("--api-key-a", metavar="KEY", help="Bearer key for --endpoint-a (unsaved)")
|
|
688
|
+
parser.add_argument("--endpoint-b", metavar="URL", help="second loopback base or chat URL")
|
|
689
|
+
parser.add_argument("--model-b", metavar="ID", help="model ID for the second endpoint")
|
|
690
|
+
parser.add_argument("--api-key-b", metavar="KEY", help="Bearer key for --endpoint-b (unsaved)")
|
|
691
|
+
parser.add_argument(
|
|
692
|
+
"--max-tokens", type=_tokens, default=DEFAULT_MAX_TOKENS, help="max tokens (default: 512)"
|
|
693
|
+
)
|
|
694
|
+
parser.add_argument("--vote", choices=VOTES, help="cast vote: a, b, tie, both-bad, or skip")
|
|
695
|
+
parser.add_argument(
|
|
696
|
+
"--json", action="store_true", help="output localmodels.stack-arena-match/v1 JSON"
|
|
697
|
+
)
|
|
698
|
+
sub = parser.add_subparsers(dest="arena_command", metavar="ACTION")
|
|
699
|
+
board = sub.add_parser("leaderboard", help="show the local Elo leaderboard (read-only)")
|
|
700
|
+
board.add_argument(
|
|
701
|
+
"--json", action="store_true", default=argparse.SUPPRESS, help="output leaderboard JSON"
|
|
702
|
+
)
|
|
703
|
+
cli_help.document(
|
|
704
|
+
parser,
|
|
705
|
+
"Run a blind A/B comparison between two local LLMs and track Elo ratings locally. "
|
|
706
|
+
"Without --endpoint-a/--endpoint-b, compares the installed routed stack's primary and "
|
|
707
|
+
"fastest models. Slots A/B are randomized and revealed only after voting. Only model IDs "
|
|
708
|
+
"and numeric Elo counts are saved in arena.json; prompts, replies, keys and endpoints stay "
|
|
709
|
+
"out of disk logs.",
|
|
710
|
+
examples=[
|
|
711
|
+
('%(prog)s "Explain flash attention."', "blind match on installed stack"),
|
|
712
|
+
("%(prog)s leaderboard", "show the local Elo leaderboard"),
|
|
713
|
+
(
|
|
714
|
+
"%(prog)s --endpoint-a http://127.0.0.1:8001 --model-a m1 "
|
|
715
|
+
'--endpoint-b http://127.0.0.1:8002 --model-b m2 "Hello"',
|
|
716
|
+
"compare two explicit loopback endpoints",
|
|
717
|
+
),
|
|
718
|
+
],
|
|
719
|
+
sections=[("exit status", "0 success · 1 request failed · 2 missing targets or bad input")],
|
|
720
|
+
)
|
|
721
|
+
cli_help.document(
|
|
722
|
+
board,
|
|
723
|
+
"Read-only view of the local Elo leaderboard in arena.json, sorted by rating, wins and "
|
|
724
|
+
"model ID. Installs, starts and sends nothing.",
|
|
725
|
+
examples=[("%(prog)s", "show the Elo table"), ("%(prog)s --json", "leaderboard JSON")],
|
|
726
|
+
)
|
|
727
|
+
|
|
728
|
+
|
|
729
|
+
def cli(args: argparse.Namespace) -> int:
|
|
730
|
+
if getattr(args, "arena_command", None) == "leaderboard":
|
|
731
|
+
return _run_leaderboard(as_json=bool(getattr(args, "json", False)))
|
|
732
|
+
return _run_match(args)
|