Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
246 lines (207 loc) · 8.82 KB
/
Copy pathcli.py
File metadata and controls
246 lines (207 loc) · 8.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
"""Minival CLI — built with Typer."""
from __future__ import annotations
import json
import sys
from pathlib import Path
from typing import Annotated, Literal, Optional
import typer
from rich.console import Console
app = typer.Typer(
name="minival",
help="A lightweight, DAG-based LLM evaluation framework.",
add_completion=False,
)
console = Console()
err_console = Console(stderr=True)
# Path where the last run result is persisted for `show`
_RESULTS_PATH = Path(".minival") / "last_run.json"
# ---------------------------------------------------------------------------
# minival init
# ---------------------------------------------------------------------------
@app.command()
def init() -> None:
"""Scaffold a new Minival project in the current directory."""
config_path = Path("minival_config.py")
tests_dir = Path("tests")
sample_json = tests_dir / "sample_cases.json"
env_example = Path(".env.example")
if config_path.exists():
err_console.print(f"[yellow]Warning:[/] {config_path} already exists — skipping.")
else:
config_path.write_text(
'from minival.metrics import AnswerRelevancy, Faithfulness\n\n'
'metrics = [\n'
' AnswerRelevancy(threshold=0.7),\n'
' Faithfulness(threshold=0.7),\n'
']\n'
)
console.print(f"[green]Created[/] {config_path}")
tests_dir.mkdir(exist_ok=True)
if sample_json.exists():
err_console.print(f"[yellow]Warning:[/] {sample_json} already exists — skipping.")
else:
import json as _json
sample_json.write_text(_json.dumps([
{
"name": "example_qa",
"input": "What is your return policy?",
"output": "We offer a 30-day full refund at no extra cost.",
"expected_output": "You are eligible for a 30-day full refund.",
"retrieval_context": [
"All customers are eligible for a 30-day full refund at no extra cost.",
"Refunds are processed within 5-7 business days.",
],
"tags": ["refund", "policy"],
},
{
"name": "shipping_qa",
"input": "How long does shipping take?",
"output": "Standard shipping takes 5-7 business days.",
"retrieval_context": [
"Standard shipping: 5-7 business days. Express: 2-3 business days.",
],
},
], indent=2) + "\n")
console.print(f"[green]Created[/] {sample_json}")
if env_example.exists():
err_console.print(f"[yellow]Warning:[/] {env_example} already exists — skipping.")
else:
env_example.write_text(
"OPENAI_API_KEY=sk-...\n"
"ANTHROPIC_API_KEY=sk-ant-...\n"
"# MINIVAL_MODEL=gpt-4.1\n"
)
console.print(f"[green]Created[/] {env_example}")
console.print("\n[bold green]Done![/] Run [cyan]minival run[/] to start evaluating.")
# ---------------------------------------------------------------------------
# minival run
# ---------------------------------------------------------------------------
@app.command()
def run(
config: Annotated[Path, typer.Option("--config", "-c", help="Path to Python config file")] = Path("minival_config.py"),
tests: Annotated[Path, typer.Option("--tests", "-t", help="Path to test-case file or directory")] = Path("tests"),
model: Annotated[Optional[str], typer.Option("--model", "-m", help="Override LLM judge model globally")] = None,
output: Annotated[
Literal["table", "json", "csv"],
typer.Option("--output", "-o", help="Output format: table, json, or csv"),
] = "table",
verbose: Annotated[bool, typer.Option("--verbose", "-v", help="Print intermediate evaluation steps")] = False,
threshold: Annotated[Optional[float], typer.Option("--threshold", help="Override passing threshold globally")] = None,
strict: Annotated[bool, typer.Option("--strict", help="Enable strict binary scoring for all metrics")] = False,
fail_fast: Annotated[bool, typer.Option("--fail-fast", help="Stop on first failing test case")] = False,
) -> None:
"""Execute evaluations against a set of test cases."""
from minival.config import load_config
from minival.runner import load_test_cases, run as _run
from minival.output import print_table, format_json, format_csv
# Load config
try:
metrics = load_config(config)
except Exception as exc:
err_console.print(f"[red]Config error:[/] {exc}")
raise typer.Exit(code=2)
# Load test cases
try:
test_cases = load_test_cases(tests)
except Exception as exc:
err_console.print(f"[red]Test-case loading error:[/] {exc}")
raise typer.Exit(code=2)
if not test_cases:
err_console.print("[yellow]No test cases found.[/]")
raise typer.Exit(code=2)
header = f"[bold]Minival v0.1.0[/] — Running {len(metrics)} metric(s) against {len(test_cases)} test case(s)\n"
if output == "table":
console.print(header)
else:
err_console.print(header)
# Run
try:
run_result = _run(
test_cases=test_cases,
metrics=metrics,
verbose=verbose,
fail_fast=fail_fast,
model_override=model,
threshold_override=threshold,
strict=strict,
)
except Exception as exc:
err_console.print(f"[red]Runtime error:[/] {exc}")
raise typer.Exit(code=2)
# Persist results for `show`
_persist_results(run_result)
# Output
if output == "json":
print(format_json(run_result))
elif output == "csv":
print(format_csv(run_result))
else:
print_table(run_result, console)
exit_code = 0 if run_result.failed == 0 else 1
raise typer.Exit(code=exit_code)
# ---------------------------------------------------------------------------
# minival show
# ---------------------------------------------------------------------------
@app.command()
def show(
case: Annotated[Optional[str], typer.Option("--case", help="Show detailed results for a specific test case")] = None,
metric: Annotated[Optional[str], typer.Option("--metric", help="Metric name to inspect")] = None,
dag: Annotated[bool, typer.Option("--dag", help="Render the DAG structure of a metric")] = False,
config: Annotated[Path, typer.Option("--config", "-c", help="Path to Python config file (needed for --dag)")] = Path("minival_config.py"),
) -> None:
"""Inspect results from the most recent run, or show a metric's DAG structure."""
if dag:
if not metric:
err_console.print("[red]Usage error:[/] `--dag` requires `--metric <name>`.")
raise typer.Exit(code=2)
_show_dag(config, metric)
return
if not _RESULTS_PATH.exists():
err_console.print("[yellow]No saved results found. Run [cyan]minival run[/] first.[/]")
raise typer.Exit(code=2)
with open(_RESULTS_PATH) as f:
data = json.load(f)
results = data.get("results", [])
if case:
results = [r for r in results if r["test_case"] == case]
if not results:
err_console.print(f"[yellow]No results found for test case '{case}'.[/]")
raise typer.Exit(code=1)
from rich.table import Table
table = Table(show_header=True, header_style="bold")
table.add_column("Test Case", style="dim")
table.add_column("Metric")
table.add_column("Score", justify="right")
table.add_column("Result", justify="center")
table.add_column("Reason")
for r in results:
result_str = "[green]✅ PASS[/]" if r["passed"] else "[red]❌ FAIL[/]"
table.add_row(
r["test_case"],
r["metric"],
f"{r['score']:.2f}",
result_str,
(r.get("reason") or "")[:80],
)
console.print(table)
def _show_dag(config: Path, metric_name: str) -> None:
from minival.config import load_config
from minival.metrics.dag_metric import DAGMetric
try:
metrics = load_config(config)
except Exception as exc:
err_console.print(f"[red]Config error:[/] {exc}")
raise typer.Exit(code=2)
for m in metrics:
if m.name == metric_name:
if not isinstance(m, DAGMetric):
err_console.print(f"[yellow]Metric '{metric_name}' is not a DAGMetric — no DAG to show.[/]")
raise typer.Exit(code=1)
console.print(m.dag.render_ascii())
return
err_console.print(f"[red]Metric '{metric_name}' not found in config.[/]")
raise typer.Exit(code=2)
def _persist_results(run_result) -> None:
from minival.output.json_out import format_json
_RESULTS_PATH.parent.mkdir(parents=True, exist_ok=True)
_RESULTS_PATH.write_text(format_json(run_result))