File size: 10,791 Bytes
e4cff4b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
import argparse
import json
import re
import shutil
import time
from datetime import datetime
from pathlib import Path
from typing import Any

from agent_core.config import ARTIFACT_ROOT, WORKDIR, get_model_id
from agent_core.eval.checks import evaluate_hard_metrics, load_hard_checks, resolve_existing_path
from agent_core.outputs import workspace_relative
from agent_core.service import run_chat_turn


DEFAULT_BENCHMARK = WORKDIR / "benchmarks" / "cad_v1" / "cases.jsonl"
DEFAULT_CHECKS = WORKDIR / "benchmarks" / "cad_v1" / "hard_checks.json"


def slugify(value: str) -> str:
    slug = re.sub(r"[^A-Za-z0-9._-]+", "-", value).strip("-._")
    return slug[:80] or "unknown-model"


def build_eval_id(case_count: int, model_id: str, created_at: datetime) -> str:
    timestamp = created_at.strftime("%Y%m%d_%H%M%S")
    return f"{case_count}cases-{slugify(model_id)}-{timestamp}"


def load_cases(path: Path) -> list[dict[str, Any]]:
    cases = []
    with path.open(encoding="utf-8") as handle:
        for line_number, line in enumerate(handle, start=1):
            line = line.strip()
            if not line:
                continue
            case = json.loads(line)
            if "id" not in case or "prompt" not in case:
                raise ValueError(f"Invalid benchmark case at line {line_number}: missing id or prompt.")
            cases.append(case)
    return cases


def select_cases(cases: list[dict[str, Any]], case_ids: list[str] | None, limit: int | None) -> list[dict[str, Any]]:
    if case_ids:
        wanted = set(case_ids)
        selected = [case for case in cases if case["id"] in wanted]
        missing = wanted - {case["id"] for case in selected}
        if missing:
            raise ValueError(f"Unknown case id(s): {', '.join(sorted(missing))}")
    else:
        selected = list(cases)

    if limit is not None:
        selected = selected[:limit]
    return selected


def to_jsonable(value: Any) -> Any:
    if value is None or isinstance(value, (str, int, float, bool)):
        return value
    if isinstance(value, Path):
        return str(value)
    if isinstance(value, list):
        return [to_jsonable(item) for item in value]
    if isinstance(value, dict):
        return {str(key): to_jsonable(item) for key, item in value.items()}
    if hasattr(value, "model_dump"):
        return to_jsonable(value.model_dump())
    if hasattr(value, "__dict__"):
        return {key: to_jsonable(item) for key, item in vars(value).items() if not key.startswith("_")}
    return str(value)


def write_json(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8")


def append_jsonl(path: Path, payload: dict[str, Any]) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    with path.open("a", encoding="utf-8") as handle:
        handle.write(json.dumps(payload, ensure_ascii=False) + "\n")


def copy_if_exists(source: Path | None, target: Path) -> str | None:
    if not source:
        return None
    target.parent.mkdir(parents=True, exist_ok=True)
    shutil.copy2(source, target)
    return workspace_relative(target)


def copy_artifacts(tool_payload: dict[str, Any], attempt_dir: Path) -> dict[str, str | None]:
    output_path = resolve_existing_path(tool_payload.get("output_path"))
    preview_path = resolve_existing_path(tool_payload.get("preview_path"))
    manifest_path = resolve_existing_path(tool_payload.get("manifest_path"))

    output_target = None
    if output_path:
        suffix = output_path.suffix or ".step"
        output_target = attempt_dir / f"model{suffix}"

    return {
        "output_path": copy_if_exists(output_path, output_target) if output_target else None,
        "preview_path": copy_if_exists(preview_path, attempt_dir / "preview.stl"),
        "manifest_path": copy_if_exists(manifest_path, attempt_dir / "manifest.json"),
        "source_output_path": workspace_relative(output_path) if output_path else None,
        "source_preview_path": workspace_relative(preview_path) if preview_path else None,
        "source_manifest_path": workspace_relative(manifest_path) if manifest_path else None,
    }


def run_attempt(
    case: dict[str, Any],
    attempt_index: int,
    eval_dir: Path,
    hard_checks: dict[str, Any],
) -> dict[str, Any]:
    attempt_id = f"attempt_{attempt_index + 1:02d}"
    attempt_dir = eval_dir / "cases" / case["id"] / attempt_id
    messages: list[dict[str, Any]] = []
    started_at = datetime.now().astimezone().isoformat(timespec="seconds")
    started = time.monotonic()

    error = None
    result: dict[str, Any] = {
        "tool_payload": {},
        "assistant_text": "",
    }

    try:
        result = run_chat_turn(messages, case["prompt"])
    except Exception as exc:
        error = {
            "error_type": type(exc).__name__,
            "error": str(exc),
        }

    latency_seconds = round(time.monotonic() - started, 3)
    finished_at = datetime.now().astimezone().isoformat(timespec="seconds")
    tool_payload = result.get("tool_payload") or {}
    artifact_paths = copy_artifacts(tool_payload, attempt_dir)
    metrics = evaluate_hard_metrics(case, tool_payload, hard_checks)
    if error:
        metrics["error_type"] = error["error_type"]
        metrics["error"] = error["error"]

    record = {
        "case_id": case["id"],
        "attempt_id": attempt_id,
        "started_at": started_at,
        "finished_at": finished_at,
        "latency_seconds": latency_seconds,
        "category": case.get("category"),
        "difficulty": case.get("difficulty"),
        "language": case.get("language"),
        "prompt": case["prompt"],
        "run_id": tool_payload.get("run_id"),
        "source_generator": case.get("source_generator"),
        "tool_payload": tool_payload,
        "artifact_paths": artifact_paths,
        "metrics": metrics,
        "exception": error,
    }

    write_json(attempt_dir / "transcript.json", {"messages": to_jsonable(messages)})
    write_json(attempt_dir / "score.json", record)
    return record


def summarize(eval_id: str, benchmark_path: Path, results: list[dict[str, Any]], repeat: int, results_path: Path) -> dict[str, Any]:
    total = len(results)

    def rate(metric_name: str) -> float | None:
        if total == 0:
            return None
        passed = sum(1 for result in results if result["metrics"].get(metric_name) is True)
        return round(passed / total, 4)

    bbox_checked = [result for result in results if result["metrics"].get("bbox_check", {}).get("checked")]
    bbox_passed = sum(1 for result in bbox_checked if result["metrics"]["bbox_check"].get("passed") is True)
    error_counts: dict[str, int] = {}
    for result in results:
        error_type = result["metrics"].get("error_type")
        if error_type:
            error_counts[error_type] = error_counts.get(error_type, 0) + 1

    return {
        "eval_id": eval_id,
        "benchmark_path": workspace_relative(benchmark_path),
        "model_id": get_model_id(),
        "repeat": repeat,
        "total_attempts": total,
        "case_count": len({result["case_id"] for result in results}),
        "metrics": {
            "tool_success_rate": rate("tool_success"),
            "manifest_written_rate": rate("manifest_written"),
            "manifest_json_ok_rate": rate("manifest_json_ok"),
            "step_export_rate": rate("step_export"),
            "stl_preview_rate": rate("stl_preview"),
            "step_loadable_rate": rate("step_loadable"),
            "bbox_checked_attempts": len(bbox_checked),
            "bbox_passed_attempts": bbox_passed,
            "bbox_pass_rate": round(bbox_passed / len(bbox_checked), 4) if bbox_checked else None,
        },
        "error_counts": error_counts,
        "results_path": workspace_relative(results_path),
    }


def parse_args() -> argparse.Namespace:
    parser = argparse.ArgumentParser(description="Run CAD benchmark cases through the active agent.")
    parser.add_argument("--benchmark", type=Path, default=DEFAULT_BENCHMARK, help="Path to benchmark cases JSONL.")
    parser.add_argument("--checks", type=Path, default=DEFAULT_CHECKS, help="Path to hard metric checks JSON.")
    parser.add_argument("--eval-root", type=Path, default=ARTIFACT_ROOT / "evals", help="Directory for benchmark outputs.")
    parser.add_argument("--backend", choices=["build123d"], default="build123d", help="Active CAD backend label.")
    parser.add_argument("--case-id", action="append", help="Run only this case id. Can be repeated.")
    parser.add_argument("--limit", type=int, help="Run only the first N selected cases.")
    parser.add_argument("--repeat", type=int, default=1, help="Number of attempts per case.")
    return parser.parse_args()


def main() -> None:
    args = parse_args()
    if args.repeat < 1:
        raise ValueError("--repeat must be >= 1")
    if args.limit is not None and args.limit < 1:
        raise ValueError("--limit must be >= 1")

    benchmark_path = args.benchmark if args.benchmark.is_absolute() else WORKDIR / args.benchmark
    checks_path = args.checks if args.checks.is_absolute() else WORKDIR / args.checks
    eval_root = args.eval_root if args.eval_root.is_absolute() else WORKDIR / args.eval_root

    cases = select_cases(load_cases(benchmark_path), args.case_id, args.limit)
    hard_checks = load_hard_checks(checks_path)
    model_id = get_model_id()
    created_at = datetime.now().astimezone()
    eval_id = build_eval_id(len(cases), model_id, created_at)
    eval_dir = eval_root / eval_id
    results_path = eval_dir / "results.jsonl"

    metadata = {
        "eval_id": eval_id,
        "created_at": created_at.isoformat(timespec="seconds"),
        "backend": args.backend,
        "model_id": model_id,
        "benchmark_path": workspace_relative(benchmark_path),
        "checks_path": workspace_relative(checks_path),
        "case_count": len(cases),
        "repeat": args.repeat,
    }
    write_json(eval_dir / "metadata.json", metadata)

    results = []
    for case in cases:
        for attempt_index in range(args.repeat):
            print(f"[{len(results) + 1}/{len(cases) * args.repeat}] {case['id']} attempt {attempt_index + 1}")
            record = run_attempt(case, attempt_index, eval_dir, hard_checks)
            results.append(record)
            append_jsonl(results_path, record)

    summary = summarize(eval_id, benchmark_path, results, args.repeat, results_path)
    summary["finished_at"] = datetime.now().astimezone().isoformat(timespec="seconds")
    write_json(eval_dir / "summary.json", summary)
    print(json.dumps(summary, ensure_ascii=False, indent=2))


if __name__ == "__main__":
    main()