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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion llmsql/_cli/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,11 +108,19 @@ def _execute(args: argparse.Namespace) -> None:
if not isinstance(run_metadata, dict):
raise ValueError("--run-metadata file must contain a mapping")

save_report = args.save_report
if save_report is None:
# evaluate() 本身不再默认落盘,但 CLI 一行命令跑完总得留下报告。
# 这里用与 --outputs 对应的确定性文件名,而不是随机名,
# 重跑同一份预测会覆盖旧报告而不是堆一地文件。
save_report = f"{args.outputs}.eval.json"
log.info("No --save-report given; writing report to %s", save_report)

evaluate(
outputs=args.outputs,
version=args.version,
workdir_path=args.workdir_path,
save_report=args.save_report,
save_report=save_report,
show_mismatches=args.show_mismatches,
max_mismatches=args.max_mismatches,
model_name=args.model_name,
Expand Down
5 changes: 3 additions & 2 deletions llmsql/evaluation/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ evaluate(
| ----------------- | ----------------------------------------------------------------------------------------------------------------------------------------------- |
| `outputs` | **Required**. Either a path to a JSONL file or a list of dicts with predictions. |
| `workdir_path` | Directory used to cache downloaded benchmark files. If omitted, a temporary directory is created automatically. |
| `save_report` | Optional path to save detailed JSON report. Defaults to `evaluation_results_{uuid}.json`. |
| `save_report` | Optional path to save a detailed JSON report. Default: `None` (no file written — the report is returned as a dict). |
| `show_mismatches` | Print mismatches while evaluating. Default: `True`. |
| `max_mismatches` | Maximum number of mismatches to print. Default: `5`. |
| `model_name` | Name of the evaluated model (e.g. `Qwen/Qwen3-0.6B`). Stored in the JSON report and the leaderboard YAML. Default: `None`. |
Expand Down Expand Up @@ -106,7 +106,8 @@ Total: 100 | Matches: 82 | Pred None: 5 | Gold None: 3 | SQL Errors: 2

**Report Saving**

* By default, the report is saved as `evaluation_results_{uuid}.json` in the current directory.
* No file is written unless you pass `save_report`; `evaluate()` always returns the report as a dict.
* The CLI (`llmsql evaluate`) still writes a report by default, to `outputs.eval.json` next to `--outputs` (override with `--save-report`).
* Includes timestamp and input mode (JSONL path or dict list).
* You can override the save path via the `save_report` argument.

Expand Down
47 changes: 24 additions & 23 deletions llmsql/evaluation/evaluate.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,9 @@
See the documentation for full usage details.
"""

from contextlib import closing
from datetime import datetime, timezone
from typing import Any
import uuid

from rich.progress import track

Expand Down Expand Up @@ -53,7 +53,8 @@ def evaluate(
outputs: Either a JSONL file path or a list of dicts.
workdir_path: Directory to store downloaded benchmark files. If omitted, a
temporary directory is created automatically.
save_report: Optional manual save path. If None → auto-generated.
save_report: Optional manual save path. If None → no report file is
written (the report dict is still returned).
show_mismatches: Print mismatches while evaluating.
max_mismatches: Max mismatches to print.
model_name: Name of the evaluated model (e.g. ``Qwen/Qwen3-0.6B``).
Expand Down Expand Up @@ -116,9 +117,6 @@ def evaluate(
f"accuracy is computed over {coverage['answered']} answer(s) only."
)

# --- Connect to DB ---
conn = connect_sqlite(db_path)

# --- Evaluation loop ---
metrics = {
"total": 0,
Expand All @@ -130,21 +128,25 @@ def evaluate(
}
mismatches: list[dict] = []

for item in track(outputs_list, description="Evaluating"):
metrics["total"] += 1
# --- Connect to DB ---
# closing() 保证 evaluate_sample 抛异常时连接也会被关掉:原来只有函数末尾
# 一句 conn.close(),中途报错就把连接漏在那儿。
with closing(connect_sqlite(db_path)) as conn:
for item in track(outputs_list, description="Evaluating"):
metrics["total"] += 1

is_match, mismatch_info, m = evaluate_sample(item, questions, conn)
is_match, mismatch_info, m = evaluate_sample(item, questions, conn)

metrics["matches"] += is_match
metrics["pred_none"] += m["pred_none"]
metrics["gold_none"] += m["gold_none"]
metrics["sql_errors"] += m["sql_error"]
metrics["exact_string_matches"] += m["exact_string_match"]
metrics["matches"] += is_match
metrics["pred_none"] += m["pred_none"]
metrics["gold_none"] += m["gold_none"]
metrics["sql_errors"] += m["sql_error"]
metrics["exact_string_matches"] += m["exact_string_match"]

if mismatch_info:
mismatches.append(mismatch_info)
if show_mismatches and len(mismatches) <= max_mismatches:
log_mismatch(**mismatch_info)
if mismatch_info:
mismatches.append(mismatch_info)
if show_mismatches and len(mismatches) <= max_mismatches:
log_mismatch(**mismatch_info)

print_summary(
metrics["total"],
Expand Down Expand Up @@ -179,11 +181,11 @@ def evaluate(
"input_mode": input_mode,
}

# --- Auto-generate report filename (if not provided) ---
if save_report is None:
save_report = f"evaluation_results_{uuid.uuid4()}.json"

save_json_report(save_report, report)
# 只有显式传入路径才落盘。以前 None 会生成一个随机名的文件写在当前目录,
# 每次 notebook / 测试 / 循环调用都会多留一个可能几十 MB 的报告;
# 报告字典本来就会作为返回值交回调用方,CLI 侧自己会补一个确定性的路径。
if save_report is not None:
save_json_report(save_report, report)

if save_leaderboard_yaml is not None:
# The leaderboard ranks models on the whole benchmark: unanswered
Expand All @@ -198,5 +200,4 @@ def evaluate(
)
write_leaderboard_yaml(save_leaderboard_yaml, record)

conn.close()
return report
50 changes: 49 additions & 1 deletion tests/cli/test_cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,4 +261,52 @@ async def test_evaluate_command_called(monkeypatch):
call_kwargs = mock_evaluate.call_args.kwargs
assert call_kwargs["outputs"] == "dummy_file.jsonl"
assert call_kwargs["show_mismatches"] is True
assert call_kwargs["max_mismatches"] == 10
assert call_kwargs["max_mismatches"] == 10


@pytest.mark.asyncio
async def test_evaluate_default_report_path_is_deterministic(monkeypatch):
"""
CLI 没传 --save-report 时仍然要出报告,但文件名要可预测。

evaluate() 本身不再默认落盘,CLI 这里补一个由 --outputs 推导出来的
确定性路径,重跑同一份预测会覆盖旧报告,而不是每次多一个随机文件。
"""
mock_evaluate = MagicMock(return_value={})
monkeypatch.setattr("llmsql._cli.evaluate.evaluate", mock_evaluate)

monkeypatch.setattr(
sys, "argv", ["llmsql", "evaluate", "--outputs", "dummy_file.jsonl"]
)

cli = ParserCLI()
args = cli.parse_args()
cli.execute(args)

assert mock_evaluate.call_args.kwargs["save_report"] == "dummy_file.jsonl.eval.json"


@pytest.mark.asyncio
async def test_evaluate_explicit_report_path_is_preserved(monkeypatch):
"""显式传了 --save-report 时用调用方给的路径,不覆盖成默认名"""
mock_evaluate = MagicMock(return_value={})
monkeypatch.setattr("llmsql._cli.evaluate.evaluate", mock_evaluate)

monkeypatch.setattr(
sys,
"argv",
[
"llmsql",
"evaluate",
"--outputs",
"dummy_file.jsonl",
"--save-report",
"custom/report.json",
],
)

cli = ParserCLI()
args = cli.parse_args()
cli.execute(args)

assert mock_evaluate.call_args.kwargs["save_report"] == "custom/report.json"
29 changes: 22 additions & 7 deletions tests/evaluation/test_evaluator_stability.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,7 +236,12 @@ def test_download_occurs_if_files_missing(mock_utils, mocker):
assert dl.call_count == 2 # questions + sqlite


def test_saves_report_with_auto_filename(mock_utils, mocker):
def test_no_report_file_is_written_when_save_report_is_none(mock_utils, mocker):
"""save_report=None 时不能再往当前目录丢一个随机名的报告文件

报告字典本来就会作为返回值交回调用方,没必要每次调用都落盘一份
(里面带全部 mismatch 的模型输出,完整跑一次能到几十 MB)。
"""
save = mocker.patch("llmsql.evaluation.evaluate.save_json_report")

report = evaluate(
Expand All @@ -245,15 +250,25 @@ def test_saves_report_with_auto_filename(mock_utils, mocker):
save_report=None,
)

# automatic UUID-based filename
args, kwargs = save.call_args
auto_filename = args[0]
assert auto_filename.startswith("evaluation_results_")
assert auto_filename.endswith(".json")

save.assert_not_called()
assert report["total"] == 1


def test_report_is_written_to_the_given_path(mock_utils, mocker, tmp_path):
"""显式给了 save_report 时才落盘,且写到指定的路径"""
save = mocker.patch("llmsql.evaluation.evaluate.save_json_report")
report_path = tmp_path / "report.json"

evaluate(
[{"question_id": 1, "completion": "SELECT 1"}],
workdir_path=str(mock_utils),
save_report=str(report_path),
)

args, kwargs = save.call_args
assert args[0] == str(report_path)


def test_mismatch_handling(mock_utils, mocker):
"""Test branch where a mismatch is returned."""
mocker.patch(
Expand Down
Loading