modelswapbench 0.1.0a1__py3-none-any.whl

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.
Files changed (69) hide show
  1. model_swap_bench/__init__.py +28 -0
  2. model_swap_bench/_version.py +3 -0
  3. model_swap_bench/cli/__init__.py +3 -0
  4. model_swap_bench/cli/app.py +305 -0
  5. model_swap_bench/cli/commands.py +310 -0
  6. model_swap_bench/cli/doctor.py +124 -0
  7. model_swap_bench/cli/output.py +47 -0
  8. model_swap_bench/config/__init__.py +50 -0
  9. model_swap_bench/config/loader.py +59 -0
  10. model_swap_bench/config/models.py +269 -0
  11. model_swap_bench/config/schema.py +35 -0
  12. model_swap_bench/config/validation.py +79 -0
  13. model_swap_bench/errors.py +70 -0
  14. model_swap_bench/evaluators/__init__.py +34 -0
  15. model_swap_bench/evaluators/base.py +133 -0
  16. model_swap_bench/evaluators/citation.py +41 -0
  17. model_swap_bench/evaluators/contains.py +36 -0
  18. model_swap_bench/evaluators/cost.py +25 -0
  19. model_swap_bench/evaluators/exact_match.py +29 -0
  20. model_swap_bench/evaluators/field_match.py +55 -0
  21. model_swap_bench/evaluators/json_parse.py +22 -0
  22. model_swap_bench/evaluators/json_schema.py +53 -0
  23. model_swap_bench/evaluators/latency.py +27 -0
  24. model_swap_bench/evaluators/policy.py +54 -0
  25. model_swap_bench/evaluators/regex.py +39 -0
  26. model_swap_bench/evaluators/rubric.py +40 -0
  27. model_swap_bench/evaluators/tool_selection.py +38 -0
  28. model_swap_bench/execution/__init__.py +8 -0
  29. model_swap_bench/execution/cascade.py +109 -0
  30. model_swap_bench/execution/context.py +78 -0
  31. model_swap_bench/execution/retry.py +50 -0
  32. model_swap_bench/execution/runner.py +220 -0
  33. model_swap_bench/execution/scheduler.py +28 -0
  34. model_swap_bench/pricing/__init__.py +7 -0
  35. model_swap_bench/pricing/default_pricing.yaml +41 -0
  36. model_swap_bench/pricing/registry.py +86 -0
  37. model_swap_bench/providers/__init__.py +27 -0
  38. model_swap_bench/providers/base.py +121 -0
  39. model_swap_bench/providers/deterministic.py +138 -0
  40. model_swap_bench/providers/forge.py +110 -0
  41. model_swap_bench/providers/ollama.py +93 -0
  42. model_swap_bench/providers/openai_compatible.py +133 -0
  43. model_swap_bench/py.typed +0 -0
  44. model_swap_bench/reports/__init__.py +21 -0
  45. model_swap_bench/reports/csv_report.py +38 -0
  46. model_swap_bench/reports/html.py +30 -0
  47. model_swap_bench/reports/json_report.py +12 -0
  48. model_swap_bench/reports/markdown.py +189 -0
  49. model_swap_bench/resources/benchmark.schema.json +851 -0
  50. model_swap_bench/results.py +227 -0
  51. model_swap_bench/scoring/__init__.py +15 -0
  52. model_swap_bench/scoring/aggregation.py +99 -0
  53. model_swap_bench/scoring/economics.py +58 -0
  54. model_swap_bench/scoring/metrics.py +39 -0
  55. model_swap_bench/scoring/replacement.py +145 -0
  56. model_swap_bench/security/__init__.py +8 -0
  57. model_swap_bench/security/paths.py +29 -0
  58. model_swap_bench/security/redaction.py +41 -0
  59. model_swap_bench/storage/__init__.py +8 -0
  60. model_swap_bench/storage/files.py +52 -0
  61. model_swap_bench/storage/manifests.py +84 -0
  62. model_swap_bench/storage/repository.py +92 -0
  63. model_swap_bench/storage/sqlite.py +76 -0
  64. modelswapbench-0.1.0a1.dist-info/METADATA +255 -0
  65. modelswapbench-0.1.0a1.dist-info/RECORD +69 -0
  66. modelswapbench-0.1.0a1.dist-info/WHEEL +4 -0
  67. modelswapbench-0.1.0a1.dist-info/entry_points.txt +2 -0
  68. modelswapbench-0.1.0a1.dist-info/licenses/LICENSE +21 -0
  69. modelswapbench-0.1.0a1.dist-info/licenses/NOTICE.md +22 -0
@@ -0,0 +1,28 @@
1
+ """ModelSwapBench — open-source model portability and replacement benchmark.
2
+
3
+ Run the same workflow across local, open-weight, self-hosted, and hosted models
4
+ and measure quality, latency, policy compliance, and cost per successful outcome
5
+ before committing to a vendor.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from model_swap_bench._version import __version__
11
+ from model_swap_bench.errors import (
12
+ ConfigError,
13
+ ExitCode,
14
+ ModelSwapBenchError,
15
+ ProviderError,
16
+ ProviderUnavailableError,
17
+ ValidationError,
18
+ )
19
+
20
+ __all__ = [
21
+ "__version__",
22
+ "ConfigError",
23
+ "ExitCode",
24
+ "ModelSwapBenchError",
25
+ "ProviderError",
26
+ "ProviderUnavailableError",
27
+ "ValidationError",
28
+ ]
@@ -0,0 +1,3 @@
1
+ """Single source of truth for the package version."""
2
+
3
+ __version__ = "0.1.0a1"
@@ -0,0 +1,3 @@
1
+ """Command-line interface for ModelSwapBench."""
2
+
3
+ from __future__ import annotations
@@ -0,0 +1,305 @@
1
+ """Typer CLI entry point for ``modelswapbench``.
2
+
3
+ Exit codes (stable contract): 0 success, 1 constraints failed, 2 invalid input,
4
+ 3 provider unavailable, 4 partial run, 5 internal error.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import functools
10
+ from collections.abc import Callable
11
+ from pathlib import Path
12
+ from typing import Annotated, Any
13
+
14
+ import typer
15
+
16
+ from model_swap_bench._version import __version__
17
+ from model_swap_bench.cli import commands, doctor, output
18
+ from model_swap_bench.cli.doctor import FAIL, PASS, WARN
19
+ from model_swap_bench.errors import ExitCode, ModelSwapBenchError
20
+
21
+ app = typer.Typer(
22
+ name="modelswapbench",
23
+ help="Open-source model portability and replacement benchmark.",
24
+ no_args_is_help=True,
25
+ add_completion=False,
26
+ )
27
+ runs_app = typer.Typer(help="Inspect stored runs.", no_args_is_help=True)
28
+ pricing_app = typer.Typer(help="Manage the pricing registry.", no_args_is_help=True)
29
+ examples_app = typer.Typer(help="Bundled examples.", no_args_is_help=True)
30
+ app.add_typer(runs_app, name="runs")
31
+ app.add_typer(pricing_app, name="pricing")
32
+ app.add_typer(examples_app, name="examples")
33
+
34
+ VERBOSE = {"on": False}
35
+
36
+
37
+ def guard(func: Callable[..., Any]) -> Callable[..., Any]:
38
+ """Translate ModelSwapBenchError into a clean message + stable exit code."""
39
+
40
+ @functools.wraps(func)
41
+ def wrapper(*args: Any, **kwargs: Any) -> Any:
42
+ try:
43
+ return func(*args, **kwargs)
44
+ except ModelSwapBenchError as exc:
45
+ output.error(str(exc))
46
+ raise typer.Exit(code=int(exc.exit_code)) from exc
47
+ except typer.Exit:
48
+ raise
49
+ except Exception as exc: # noqa: BLE001 - top-level safety net
50
+ if VERBOSE["on"]:
51
+ raise
52
+ output.error(f"internal error: {exc}")
53
+ raise typer.Exit(code=int(ExitCode.INTERNAL_ERROR)) from exc
54
+
55
+ return wrapper
56
+
57
+
58
+ def _version_callback(value: bool) -> None:
59
+ if value:
60
+ output.info(f"modelswapbench {__version__}")
61
+ raise typer.Exit()
62
+
63
+
64
+ @app.callback()
65
+ def main_callback(
66
+ version: Annotated[bool, typer.Option("--version", callback=_version_callback, is_eager=True)] = False,
67
+ verbose: Annotated[bool, typer.Option("--verbose", help="Show full tracebacks.")] = False,
68
+ ) -> None:
69
+ VERBOSE["on"] = verbose
70
+
71
+
72
+ @app.command("doctor")
73
+ @guard
74
+ def doctor_cmd() -> None:
75
+ """Diagnose the environment (read-only)."""
76
+ checks = doctor.run_checks()
77
+ style = {PASS: output.success, WARN: output.warn, FAIL: output.error}
78
+ for check in checks:
79
+ printer = style.get(check.status, output.info)
80
+ suffix = f" — fix: {check.fix}" if check.fix else ""
81
+ printer(f"[{check.status}] {check.name}: {check.detail}{suffix}")
82
+ if any(c.status == FAIL for c in checks):
83
+ raise typer.Exit(code=int(ExitCode.INTERNAL_ERROR))
84
+
85
+
86
+ @app.command()
87
+ @guard
88
+ def validate(file: Annotated[Path, typer.Argument(help="Benchmark YAML/JSON file.")]) -> None:
89
+ """Validate a benchmark file."""
90
+ commands.validate(file)
91
+
92
+
93
+ @app.command()
94
+ @guard
95
+ def schema(output_file: Annotated[Path | None, typer.Option("--output", help="Write schema here.")] = None) -> None:
96
+ """Print or export the benchmark JSON Schema."""
97
+ commands.print_schema(output_file)
98
+
99
+
100
+ @app.command()
101
+ @guard
102
+ def models(file: Annotated[Path, typer.Argument(help="Benchmark file.")]) -> None:
103
+ """List the models defined in a benchmark file."""
104
+ commands.list_models(file)
105
+
106
+
107
+ @app.command()
108
+ @guard
109
+ def providers() -> None:
110
+ """List supported providers and evaluators."""
111
+ commands.list_providers()
112
+
113
+
114
+ @app.command()
115
+ @guard
116
+ def run(
117
+ file: Annotated[Path, typer.Argument(help="Benchmark file.")],
118
+ model: Annotated[str | None, typer.Option("--model", help="Run only this model alias.")] = None,
119
+ output_dir: Annotated[Path | None, typer.Option("--output", help="Storage root (default: cwd).")] = None,
120
+ concurrency: Annotated[int | None, typer.Option("--concurrency")] = None,
121
+ timeout: Annotated[float | None, typer.Option("--timeout")] = None,
122
+ repetitions: Annotated[int | None, typer.Option("--repetitions")] = None,
123
+ seed: Annotated[int | None, typer.Option("--seed")] = None,
124
+ allow_hosted: Annotated[bool, typer.Option("--allow-hosted", help="Permit hosted providers (data may leave the machine).")] = False,
125
+ dry_run: Annotated[bool, typer.Option("--dry-run", help="Validate + health-check without executing.")] = False,
126
+ ) -> None:
127
+ """Run a benchmark suite."""
128
+ _run, code = commands.run(
129
+ file,
130
+ only_model=model,
131
+ output_root=output_dir,
132
+ concurrency=concurrency,
133
+ timeout=timeout,
134
+ repetitions=repetitions,
135
+ seed=seed,
136
+ allow_hosted=allow_hosted,
137
+ dry_run=dry_run,
138
+ )
139
+ if code is not ExitCode.SUCCESS:
140
+ raise typer.Exit(code=int(code))
141
+
142
+
143
+ @app.command()
144
+ @guard
145
+ def compare(
146
+ run_id: Annotated[str, typer.Argument(help="Run id or 'latest'.")] = "latest",
147
+ output_dir: Annotated[Path | None, typer.Option("--output")] = None,
148
+ ) -> None:
149
+ """Compare models in a stored run."""
150
+ code = commands.compare(run_id, root=output_dir)
151
+ if code is not ExitCode.SUCCESS:
152
+ raise typer.Exit(code=int(code))
153
+
154
+
155
+ @app.command()
156
+ @guard
157
+ def report(
158
+ run_id: Annotated[str, typer.Argument(help="Run id or 'latest'.")] = "latest",
159
+ fmt: Annotated[str, typer.Option("--format", help="markdown|json|csv|html")] = "markdown",
160
+ output_file: Annotated[Path | None, typer.Option("--output")] = None,
161
+ output_dir: Annotated[Path | None, typer.Option("--root", help="Storage root.")] = None,
162
+ ) -> None:
163
+ """Render a report for a stored run."""
164
+ commands.report(run_id, fmt=fmt, out=output_file, root=output_dir)
165
+
166
+
167
+ @app.command()
168
+ @guard
169
+ def reproduce(
170
+ run_id: Annotated[str, typer.Argument(help="Run id or 'latest'.")],
171
+ output_dir: Annotated[Path | None, typer.Option("--output")] = None,
172
+ ) -> None:
173
+ """Re-run a stored suite; warns on version drift."""
174
+ _run, code = commands.reproduce(run_id, output_dir)
175
+ if code is not ExitCode.SUCCESS:
176
+ raise typer.Exit(code=int(code))
177
+
178
+
179
+ @app.command()
180
+ @guard
181
+ def clean(
182
+ run_id: Annotated[str, typer.Argument(help="Run id or 'latest'.")],
183
+ yes: Annotated[bool, typer.Option("--yes", help="Skip confirmation.")] = False,
184
+ output_dir: Annotated[Path | None, typer.Option("--output")] = None,
185
+ ) -> None:
186
+ """Delete a stored run (only under the storage directory)."""
187
+ if not yes:
188
+ typer.confirm(f"Delete run {run_id!r}? This cannot be undone.", abort=True)
189
+ commands.clean(run_id, output_dir)
190
+
191
+
192
+ @app.command()
193
+ @guard
194
+ def init(
195
+ name: Annotated[str, typer.Argument(help="New benchmark directory name.")] = "my-benchmark",
196
+ ) -> None:
197
+ """Scaffold a runnable, fully-offline starter benchmark."""
198
+ commands_init(name)
199
+
200
+
201
+ @runs_app.command("list")
202
+ @guard
203
+ def runs_list(output_dir: Annotated[Path | None, typer.Option("--output")] = None) -> None:
204
+ """List stored runs."""
205
+ commands.runs_list(output_dir)
206
+
207
+
208
+ @runs_app.command("show")
209
+ @guard
210
+ def runs_show(run_id: str, output_dir: Annotated[Path | None, typer.Option("--output")] = None) -> None:
211
+ """Show a stored run's metadata."""
212
+ commands.runs_show(run_id, output_dir)
213
+
214
+
215
+ @pricing_app.command("show")
216
+ @guard
217
+ def pricing_show(path: Annotated[Path | None, typer.Option("--file")] = None) -> None:
218
+ """Show the pricing registry."""
219
+ commands.pricing_show(path)
220
+
221
+
222
+ @pricing_app.command("validate")
223
+ @guard
224
+ def pricing_validate(path: Annotated[Path | None, typer.Option("--file")] = None) -> None:
225
+ """Validate the pricing registry."""
226
+ code = commands.pricing_validate(path)
227
+ if code is not ExitCode.SUCCESS:
228
+ raise typer.Exit(code=int(code))
229
+
230
+
231
+ @pricing_app.command("set")
232
+ @guard
233
+ def pricing_set(
234
+ model: str,
235
+ provider: str,
236
+ input_price: float,
237
+ output_price: float,
238
+ path: Annotated[Path, typer.Option("--file")] = Path("pricing.yaml"),
239
+ ) -> None:
240
+ """Set a price entry (writes to a user pricing file)."""
241
+ commands.pricing_set(model, provider, input_price, output_price, path)
242
+
243
+
244
+ @examples_app.command("list")
245
+ @guard
246
+ def examples_list() -> None:
247
+ """List bundled examples."""
248
+ commands.examples_list()
249
+
250
+
251
+ _STARTER_SUITE = """name: {name}
252
+ version: "1.0"
253
+ description: Starter offline benchmark using the deterministic provider.
254
+ baseline_model: baseline
255
+
256
+ models:
257
+ - alias: baseline
258
+ provider: deterministic
259
+ model: baseline-fixture
260
+ deployment: test
261
+ metadata: {{strategy: oracle, latency_ms: 20}}
262
+ - alias: candidate
263
+ provider: deterministic
264
+ model: candidate-fixture
265
+ deployment: local
266
+ metadata: {{strategy: oracle, latency_ms: 5}}
267
+
268
+ cases:
269
+ - id: greeting
270
+ input: {{message: "Say hello and classify sentiment."}}
271
+ expected: {{sentiment: positive}}
272
+
273
+ evaluators: [json_parse, json_schema, field_match]
274
+
275
+ constraints:
276
+ minimum_success_rate: 0.8
277
+ require_valid_json_rate: 0.9
278
+
279
+ replacement:
280
+ baseline: baseline
281
+ candidates: [candidate]
282
+ maximum_quality_drop: 0.05
283
+ minimum_cost_reduction: 0.0
284
+ """
285
+
286
+
287
+ def commands_init(name: str) -> None:
288
+ target = Path(name)
289
+ target.mkdir(parents=True, exist_ok=True)
290
+ suite_file = target / "benchmark.yaml"
291
+ if suite_file.exists():
292
+ output.warn(f"{suite_file} already exists; not overwriting")
293
+ return
294
+ suite_file.write_text(_STARTER_SUITE.format(name=name), encoding="utf-8")
295
+ output.success(f"created {suite_file}")
296
+ output.info(f"Next: modelswapbench validate {suite_file} && modelswapbench run {suite_file}")
297
+
298
+
299
+ def main() -> None:
300
+ """Console-script entry point."""
301
+ app()
302
+
303
+
304
+ if __name__ == "__main__":
305
+ main()
@@ -0,0 +1,310 @@
1
+ """CLI command implementations (thin Typer wrappers live in app.py)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from pathlib import Path
7
+
8
+ from model_swap_bench.cli import output
9
+ from model_swap_bench.config import load_suite, schema_json
10
+ from model_swap_bench.config.models import BenchmarkSuite, ProviderKind
11
+ from model_swap_bench.errors import ExitCode, ProviderUnavailableError
12
+ from model_swap_bench.evaluators import registered_names
13
+ from model_swap_bench.execution import BenchmarkRunner
14
+ from model_swap_bench.pricing import WARNING, PricingRegistry
15
+ from model_swap_bench.providers.base import build_provider
16
+ from model_swap_bench.reports import RENDERERS
17
+ from model_swap_bench.results import BenchmarkRun, CaseStatus
18
+ from model_swap_bench.storage import RunRepository
19
+
20
+ # ---------------------------------------------------------------------------
21
+ # Inspection commands
22
+ # ---------------------------------------------------------------------------
23
+
24
+
25
+ def validate(file: Path) -> None:
26
+ suite = load_suite(file)
27
+ output.success(f"{file.name} is valid: {suite.name} v{suite.version}")
28
+ output.info(f" models: {len(suite.models)} | cases: {len(suite.cases)} | mode-hint: {suite.execution.mode or 'auto'}")
29
+
30
+
31
+ def print_schema(out: Path | None) -> None:
32
+ text = schema_json()
33
+ if out:
34
+ out.write_text(text + "\n", encoding="utf-8")
35
+ output.success(f"schema written to {out}")
36
+ else:
37
+ output.info(text)
38
+
39
+
40
+ def list_models(file: Path) -> None:
41
+ suite = load_suite(file)
42
+ rows = [
43
+ (m.alias, m.provider.value, m.model, m.deployment.value, "hosted" if m.is_hosted else "local")
44
+ for m in suite.models
45
+ ]
46
+ output.table(f"Models in {suite.name}", ["alias", "provider", "model", "deployment", "class"], rows)
47
+
48
+
49
+ def list_providers() -> None:
50
+ rows = [(k.value, "hosted" if k.value in {"openai", "anthropic", "bedrock"} else "local/self-hosted") for k in ProviderKind]
51
+ output.table("Providers", ["provider", "class"], rows)
52
+ output.info("Evaluators: " + ", ".join(registered_names()))
53
+
54
+
55
+ # ---------------------------------------------------------------------------
56
+ # Run
57
+ # ---------------------------------------------------------------------------
58
+
59
+
60
+ def _apply_overrides(
61
+ suite: BenchmarkSuite,
62
+ *,
63
+ concurrency: int | None,
64
+ timeout: float | None,
65
+ repetitions: int | None,
66
+ seed: int | None,
67
+ ) -> None:
68
+ if concurrency is not None:
69
+ suite.execution.concurrency = concurrency
70
+ if timeout is not None:
71
+ suite.execution.timeout_seconds = timeout
72
+ if repetitions is not None:
73
+ suite.execution.repetitions = repetitions
74
+ if seed is not None:
75
+ suite.execution.seed = seed
76
+
77
+
78
+ def _dry_run(suite: BenchmarkSuite, suite_dir: Path, allow_hosted: bool) -> ExitCode:
79
+ output.info(f"[bold]Dry run[/bold]: {suite.name} v{suite.version} — {len(suite.cases)} case(s)")
80
+ unavailable = False
81
+ for model in suite.models:
82
+ try:
83
+ provider = build_provider(model, suite_dir=suite_dir, allow_hosted=allow_hosted)
84
+ except ProviderUnavailableError as exc:
85
+ output.warn(f"{model.alias}: {exc}")
86
+ unavailable = True
87
+ continue
88
+ health = asyncio.run(provider.health())
89
+ asyncio.run(provider.aclose())
90
+ (output.success if health.available else output.warn)(f"{model.alias}: {health.detail}")
91
+ unavailable = unavailable or not (health.available or model.provider is ProviderKind.DETERMINISTIC)
92
+ return ExitCode.PROVIDER_UNAVAILABLE if unavailable else ExitCode.SUCCESS
93
+
94
+
95
+ def run(
96
+ file: Path,
97
+ *,
98
+ only_model: str | None = None,
99
+ output_root: Path | None = None,
100
+ concurrency: int | None = None,
101
+ timeout: float | None = None,
102
+ repetitions: int | None = None,
103
+ seed: int | None = None,
104
+ allow_hosted: bool = False,
105
+ dry_run: bool = False,
106
+ ) -> tuple[BenchmarkRun | None, ExitCode]:
107
+ suite = load_suite(file)
108
+ suite_dir = file.resolve().parent
109
+ _apply_overrides(suite, concurrency=concurrency, timeout=timeout, repetitions=repetitions, seed=seed)
110
+
111
+ if allow_hosted and not suite.privacy.allow_hosted_providers:
112
+ output.warn("--allow-hosted set but suite privacy.allow_hosted_providers is false; hosted models stay disabled.")
113
+ if any(m.is_hosted for m in suite.models) and (allow_hosted and suite.privacy.allow_hosted_providers):
114
+ output.warn("Hosted providers enabled: benchmark inputs may leave this machine.")
115
+
116
+ if dry_run:
117
+ return None, _dry_run(suite, suite_dir, allow_hosted)
118
+
119
+ only = {only_model} if only_model else None
120
+ runner = BenchmarkRunner(suite, suite_dir=suite_dir, allow_hosted=allow_hosted and suite.privacy.allow_hosted_providers)
121
+ run_result = asyncio.run(runner.run(only_models=only))
122
+
123
+ repo = RunRepository(output_root or Path.cwd())
124
+ repo.save(run_result, suite, suite_dir=suite_dir)
125
+ _print_run_summary(run_result)
126
+ return run_result, _run_exit_code(run_result)
127
+
128
+
129
+ def _run_exit_code(run_result: BenchmarkRun) -> ExitCode:
130
+ if any(r.status is CaseStatus.ERROR for r in run_result.case_results):
131
+ # Distinguish provider unavailability from ordinary constraint failure.
132
+ if all(r.status is CaseStatus.ERROR for r in run_result.case_results):
133
+ return ExitCode.PROVIDER_UNAVAILABLE
134
+ return ExitCode.PARTIAL_RUN
135
+ if not run_result.all_constraints_passed:
136
+ return ExitCode.CONSTRAINTS_FAILED
137
+ return ExitCode.SUCCESS
138
+
139
+
140
+ def _print_run_summary(run_result: BenchmarkRun) -> None:
141
+ output.success(f"run {run_result.run_id} complete ({run_result.mode})")
142
+ rows = [
143
+ (
144
+ s.model_alias,
145
+ f"{s.success_rate * 100:.0f}%",
146
+ f"{s.quality_score:.2f}",
147
+ f"{s.p95_latency_ms:.0f}ms",
148
+ "n/a" if s.cost_per_success_usd is None else f"${s.cost_per_success_usd:.6f}",
149
+ )
150
+ for s in run_result.model_summaries
151
+ ]
152
+ output.table("Summary", ["model", "success", "quality", "p95", "cost/success"], rows)
153
+ for d in run_result.replacement_decisions:
154
+ output.info(f"[bold]{d.candidate_model}[/bold] → {d.recommendation} (confidence {d.confidence:.0%})")
155
+ if not run_result.all_constraints_passed:
156
+ output.warn("one or more constraints FAILED (see `report`/`compare`)")
157
+
158
+
159
+ # ---------------------------------------------------------------------------
160
+ # Reporting / inspection of stored runs
161
+ # ---------------------------------------------------------------------------
162
+
163
+
164
+ def report(run_ref: str, *, fmt: str, out: Path | None, root: Path | None) -> None:
165
+ repo = RunRepository(root or Path.cwd())
166
+ run_result = repo.load(run_ref)
167
+ renderer = RENDERERS.get(fmt)
168
+ if renderer is None:
169
+ from model_swap_bench.errors import ConfigError
170
+
171
+ raise ConfigError(f"unknown format {fmt!r}; choose from {', '.join(RENDERERS)}")
172
+ text = renderer(run_result)
173
+ if out:
174
+ out.write_text(text, encoding="utf-8")
175
+ output.success(f"{fmt} report written to {out}")
176
+ else:
177
+ output.info(text)
178
+
179
+
180
+ def compare(run_ref: str, *, root: Path | None) -> ExitCode:
181
+ repo = RunRepository(root or Path.cwd())
182
+ run_result = repo.load(run_ref)
183
+ rows = [
184
+ (
185
+ s.model_alias,
186
+ f"{s.success_rate * 100:.0f}%",
187
+ f"{s.quality_score:.2f}",
188
+ f"{s.valid_json_rate * 100:.0f}%",
189
+ f"{s.p95_latency_ms:.0f}ms",
190
+ "n/a" if s.cost_per_success_usd is None else f"${s.cost_per_success_usd:.6f}",
191
+ )
192
+ for s in run_result.model_summaries
193
+ ]
194
+ output.table(f"Comparison — {run_result.suite_name}", ["model", "success", "quality", "json", "p95", "cost/succ"], rows)
195
+ for d in run_result.replacement_decisions:
196
+ output.info("")
197
+ output.info(f"[bold]{d.candidate_model} vs {d.baseline_model}[/bold]: {d.recommendation} (confidence {d.confidence:.0%})")
198
+ for e in d.evidence:
199
+ output.info(f" - {e}")
200
+ for f in d.failed_constraints:
201
+ output.warn(f" failed: {f}")
202
+ if run_result.cascade_summary is not None:
203
+ cs = run_result.cascade_summary
204
+ output.info("")
205
+ output.info(f"[bold]Cascade[/bold]: {cs.final_success_rate * 100:.0f}% final success, {cs.escalation_rate * 100:.0f}% escalated")
206
+ return ExitCode.SUCCESS if run_result.all_constraints_passed else ExitCode.CONSTRAINTS_FAILED
207
+
208
+
209
+ def runs_list(root: Path | None) -> None:
210
+ repo = RunRepository(root or Path.cwd())
211
+ runs = repo.list_runs()
212
+ if not runs:
213
+ output.warn("no runs found")
214
+ return
215
+ rows = [(r["run_id"], r["suite_name"], r["mode"], r["created_at"], "pass" if r["constraints_passed"] else "FAIL") for r in runs]
216
+ output.table("Runs", ["run_id", "suite", "mode", "created", "constraints"], rows)
217
+
218
+
219
+ def runs_show(run_ref: str, root: Path | None) -> None:
220
+ repo = RunRepository(root or Path.cwd())
221
+ run_result = repo.load(run_ref)
222
+ manifest = repo.load_manifest(run_ref)
223
+ output.info(f"[bold]{run_result.run_id}[/bold] — {run_result.suite_name} v{run_result.suite_version} ({run_result.mode})")
224
+ output.info(f" manifest hash: {run_result.manifest_hash[:16]} | cases: {len(run_result.case_results)}")
225
+ output.info(
226
+ f" package: {manifest.get('package_version')} | forge: {manifest.get('forge_version')} "
227
+ f"| python: {manifest.get('python_version')}"
228
+ )
229
+ output.info(f" git commit: {manifest.get('git_commit') or 'n/a'}")
230
+
231
+
232
+ def reproduce(run_ref: str, root: Path | None) -> tuple[BenchmarkRun, ExitCode]:
233
+ repo = RunRepository(root or Path.cwd())
234
+ old_manifest = repo.load_manifest(run_ref)
235
+ suite = repo.load_suite_snapshot(run_ref)
236
+ runner = BenchmarkRunner(suite)
237
+ new_run = asyncio.run(runner.run())
238
+ from model_swap_bench.storage.manifests import build_manifest
239
+
240
+ fresh = build_manifest(suite, new_run.run_id)
241
+ _warn_drift(old_manifest, fresh)
242
+ repo.save(new_run, suite)
243
+ output.success(f"reproduced as {new_run.run_id}")
244
+ _print_run_summary(new_run)
245
+ return new_run, _run_exit_code(new_run)
246
+
247
+
248
+ def _warn_drift(old: dict[str, object], new: dict[str, object]) -> None:
249
+ for key in ("package_version", "forge_version", "python_version"):
250
+ if old.get(key) != new.get(key):
251
+ output.warn(f"version drift: {key} was {old.get(key)!r}, now {new.get(key)!r} — results may differ")
252
+ if old.get("suite_hash") != new.get("suite_hash"):
253
+ output.warn("suite definition changed since the original run")
254
+
255
+
256
+ def clean(run_ref: str, root: Path | None) -> None:
257
+ repo = RunRepository(root or Path.cwd())
258
+ deleted = repo.delete(run_ref)
259
+ output.success(f"deleted run {deleted}")
260
+
261
+
262
+ # ---------------------------------------------------------------------------
263
+ # Pricing
264
+ # ---------------------------------------------------------------------------
265
+
266
+
267
+ def pricing_show(path: Path | None) -> None:
268
+ registry = PricingRegistry.load(path)
269
+ output.warn(WARNING)
270
+ rows = [
271
+ (e.model, e.provider, f"{e.input_price}", f"{e.output_price}", "measured" if e.measured else "estimate")
272
+ for e in registry.entries
273
+ ]
274
+ output.table(f"Pricing (v{registry.version})", ["model", "provider", "in/Mtok", "out/Mtok", "kind"], rows)
275
+
276
+
277
+ def pricing_validate(path: Path | None) -> ExitCode:
278
+ registry = PricingRegistry.load(path)
279
+ problems = registry.validate_entries()
280
+ if problems:
281
+ for p in problems:
282
+ output.error(p)
283
+ return ExitCode.INVALID_INPUT
284
+ output.success(f"pricing registry valid ({len(registry.entries)} entries)")
285
+ return ExitCode.SUCCESS
286
+
287
+
288
+ def pricing_set(model: str, provider: str, input_price: float, output_price: float, path: Path) -> None:
289
+ registry = PricingRegistry.load(path) if path.exists() else PricingRegistry()
290
+ registry.set_price(model, provider, input_price, output_price, source="set via CLI")
291
+ registry.save(path)
292
+ output.success(f"set {model} ({provider}) to in={input_price} out={output_price} in {path}")
293
+ output.warn(WARNING)
294
+
295
+
296
+ # ---------------------------------------------------------------------------
297
+ # Examples
298
+ # ---------------------------------------------------------------------------
299
+
300
+ EXAMPLES = [
301
+ ("support-ticket-triage", "Classify support tickets; JSON schema + field match + policy (offline)."),
302
+ ("local-rag-citations", "Grounded answers with citation checking (offline fixtures / local Ollama)."),
303
+ ("code-review-summary", "Structured severity + required remediation; forbids 'fully secure' claims."),
304
+ ("cascade-routing", "Cheap local model first, escalate failures to a stronger fixture model."),
305
+ ]
306
+
307
+
308
+ def examples_list() -> None:
309
+ rows = [(name, desc) for name, desc in EXAMPLES]
310
+ output.table("Bundled examples (examples/<name>/benchmark.yaml)", ["example", "description"], rows)