Skip to content

Open source CapCut alternative.

TypeScript

Keep local LLM candidates in eval fixtures

David Ledf4d19ad09e7
diff --git a/.gitignore b/.gitignore
index fe252a30..b7960fbe 100644
--- a/.gitignore
+++ b/.gitignore
@@ -12,5 +12,9 @@ xcuserdata/
## Build artifacts
/dist/
+## Eval artifacts
+/evals/task-intent/model-cache/
+/evals/task-intent/model-comparison/
+
## Project policy
# Keep Package.resolved tracked for reproducible dependency resolution.
diff --git a/evals/task-intent/README.md b/evals/task-intent/README.md
index f6112096..5007febe 100644
--- a/evals/task-intent/README.md
+++ b/evals/task-intent/README.md
@@ -43,7 +43,7 @@ Run a small live sidecar sample against the local LLM sidecar:
```bash
DONKEY_RUNTIME_ID=local-llm \
-DONKEY_MODEL_ID=qwen3-0.6b-q4_0 \
+DONKEY_MODEL_ID=qwen2.5-0.5b-instruct-q4_k_m \
python3 scripts/evals/run_task_intent_sidecar_evals.py --app Safari --limit 3
```
@@ -51,10 +51,36 @@ Run the full suite:
```bash
DONKEY_RUNTIME_ID=local-llm \
-DONKEY_MODEL_ID=qwen3-0.6b-q4_0 \
+DONKEY_MODEL_ID=qwen2.5-0.5b-instruct-q4_k_m \
python3 scripts/evals/run_task_intent_sidecar_evals.py
```
+Compare the small local-model candidates before changing the packaged default:
+
+```bash
+python3 scripts/evals/run_task_intent_sidecar_evals.py \
+ --compare-default-candidates
+```
+
+For a quick smoke test, keep the same comparison path but limit the suite:
+
+```bash
+python3 scripts/evals/run_task_intent_sidecar_evals.py \
+ --compare-default-candidates \
+ --limit 10
+```
+
+Candidate GGUF downloads are stored under the gitignored
+`evals/task-intent/model-cache/` directory. Per-model reports and the ranked
+comparison summary are written under the gitignored
+`evals/task-intent/model-comparison/` directory. The comparison decision ranks
+models by pass rate first, then failed count, average latency, and model size.
+The candidate list comes from
+`evals/task-intent/local-llm-model-candidates.json`; pass
+`--candidate-config path/to/candidates.json` to test another candidate set. The
+single-model default comes from `config/local-llm-models.json`; pass
+`--model-config path/to/config.json` to test another packaged-default config.
+
The runner writes a JSON report to
`evals/task-intent/macos-default-apps-v1.latest-report.json` by default. That
report is generated output and should normally be treated as a local artifact,
diff --git a/evals/task-intent/local-llm-model-candidates.json b/evals/task-intent/local-llm-model-candidates.json
new file mode 100644
index 00000000..8854a9dc
--- /dev/null
+++ b/evals/task-intent/local-llm-model-candidates.json
@@ -0,0 +1,70 @@
+{
+ "candidates": [
+ {
+ "id": "qwen2.5-0.5b-instruct-q4_k_m",
+ "displayName": "Qwen2.5 0.5B Instruct Q4_K_M current",
+ "modelID": "qwen2.5-0.5b-instruct-q4_k_m",
+ "filename": "qwen2.5-0.5b-instruct-q4_k_m.gguf",
+ "downloadURL": "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/df5bf01389a39c743ab467d734bf501681e041c5/qwen2.5-0.5b-instruct-q4_k_m.gguf",
+ "sha256": "74a4da8c9fdbcd15bd1f6d01d621410d31c6fc00986f5eb687824e7b93d7a9db",
+ "expectedSizeMB": 491,
+ "notes": "Packaged default; instruction-tuned Qwen2.5 small model."
+ },
+ {
+ "id": "qwen3-0.6b-q4_0-previous",
+ "displayName": "Qwen3 0.6B Q4_0 previous",
+ "modelID": "qwen3-0.6b-q4_0",
+ "filename": "Qwen3-0.6B-Q4_0.gguf",
+ "downloadURL": "https://huggingface.co/ggml-org/Qwen3-0.6B-GGUF/resolve/main/Qwen3-0.6B-Q4_0.gguf",
+ "sha256": "da2572f16c06133561ce56accaa822216f2391ef4d37fba427801cd6736417d4",
+ "expectedSizeMB": 429,
+ "notes": "Previous packaged default; legacy Q4_0 quant."
+ },
+ {
+ "id": "qwen3-0.6b-q4_k_m",
+ "displayName": "Qwen3 0.6B Q4_K_M",
+ "modelID": "qwen3-0.6b-q4_k_m",
+ "filename": "Qwen_Qwen3-0.6B-Q4_K_M.gguf",
+ "downloadURL": "https://huggingface.co/bartowski/Qwen_Qwen3-0.6B-GGUF/resolve/main/Qwen_Qwen3-0.6B-Q4_K_M.gguf",
+ "expectedSizeMB": 484,
+ "notes": "Same model family as the previous default, better quantization than Q4_0."
+ },
+ {
+ "id": "qwen3-0.6b-q5_k_m",
+ "displayName": "Qwen3 0.6B Q5_K_M",
+ "modelID": "qwen3-0.6b-q5_k_m",
+ "filename": "Qwen_Qwen3-0.6B-Q5_K_M.gguf",
+ "downloadURL": "https://huggingface.co/bartowski/Qwen_Qwen3-0.6B-GGUF/resolve/main/Qwen_Qwen3-0.6B-Q5_K_M.gguf",
+ "expectedSizeMB": 551,
+ "notes": "Slightly larger Qwen3 quant that may reduce malformed JSON."
+ },
+ {
+ "id": "smollm2-360m-instruct-q4_k_m",
+ "displayName": "SmolLM2 360M Instruct Q4_K_M",
+ "modelID": "smollm2-360m-instruct-q4_k_m",
+ "filename": "SmolLM2-360M-Instruct.Q4_K_M.gguf",
+ "downloadURL": "https://huggingface.co/jc-builds/SmolLM2-360M-Instruct-Q4_K_M-GGUF/resolve/main/SmolLM2-360M-Instruct.Q4_K_M.gguf",
+ "expectedSizeMB": 271,
+ "notes": "Very small baseline; useful if download size matters more than quality."
+ },
+ {
+ "id": "llama3.2-1b-instruct-q3_k_m",
+ "displayName": "Llama 3.2 1B Instruct Q3_K_M",
+ "modelID": "llama3.2-1b-instruct-q3_k_m",
+ "filename": "Llama3.2-1B-Instruct-Q3_K_M.gguf",
+ "downloadURL": "https://huggingface.co/tensorblock/Llama3.2-1B-Instruct-GGUF/resolve/main/Llama3.2-1B-Instruct-Q3_K_M.gguf",
+ "sha256": "7a20775ef3b2b4329e1798e11259a0427236ba71d8bfcb4795a4a61cd52807e7",
+ "expectedSizeMB": 691,
+ "notes": "Larger 1B baseline with lower quantization."
+ },
+ {
+ "id": "llama3.2-1b-instruct-q4_k_m",
+ "displayName": "Llama 3.2 1B Instruct Q4_K_M",
+ "modelID": "llama3.2-1b-instruct-q4_k_m",
+ "filename": "Llama3.2-1B-Instruct-Q4_K_M.gguf",
+ "downloadURL": "https://huggingface.co/tensorblock/Llama3.2-1B-Instruct-GGUF/resolve/main/Llama3.2-1B-Instruct-Q4_K_M.gguf",
+ "expectedSizeMB": 808,
+ "notes": "Larger 1B baseline with recommended Q4_K_M quant."
+ }
+ ]
+}
diff --git a/scripts/evals/run_task_intent_sidecar_evals.py b/scripts/evals/run_task_intent_sidecar_evals.py
index 025f7e43..a5cc4341 100644
--- a/scripts/evals/run_task_intent_sidecar_evals.py
+++ b/scripts/evals/run_task_intent_sidecar_evals.py
@@ -9,11 +9,13 @@ local task-intent runtime and scores the returned structured JSON.
from __future__ import annotations
import argparse
+import hashlib
import json
import os
import subprocess
import sys
import time
+import urllib.request
from dataclasses import dataclass
from pathlib import Path
from typing import Any
@@ -21,8 +23,12 @@ from typing import Any
DEFAULT_EVAL_PATH = Path("evals/task-intent/macos-default-apps-v1.jsonl")
DEFAULT_REPORT_PATH = Path("evals/task-intent/macos-default-apps-v1.latest-report.json")
+DEFAULT_MODEL_CACHE_DIR = Path("evals/task-intent/model-cache")
+DEFAULT_COMPARISON_DIR = Path("evals/task-intent/model-comparison")
+DEFAULT_COMPARISON_REPORT_PATH = DEFAULT_COMPARISON_DIR / "comparison.latest.json"
+DEFAULT_MODEL_CONFIG_PATH = Path("config/local-llm-models.json")
+DEFAULT_CANDIDATE_CONFIG_PATH = Path("evals/task-intent/local-llm-model-candidates.json")
DEFAULT_SIDECAR = Path("scripts/local-runtime-runners/donkey_runtime_runner.py")
-DEFAULT_MODEL_ID = "qwen3-0.6b-q4_0"
SCHEMA_ID = "task_intent_v1"
@@ -129,6 +135,18 @@ TASK_DEFINITIONS = [
]
+@dataclass
+class ModelCandidate:
+ id: str
+ display_name: str
+ model_id: str
+ filename: str
+ download_url: str
+ expected_size_mb: float
+ expected_sha256: str = ""
+ notes: str = ""
+
+
@dataclass
class EvalResult:
case_id: str
@@ -143,6 +161,55 @@ class EvalResult:
stderr: str
+@dataclass
+class LocalLLMModelConfig:
+ runtime_requirements: list[str]
+ default_model: ModelCandidate
+
+
+@dataclass
+class ModelCandidateConfig:
+ candidates: list[ModelCandidate]
+
+
+def load_model_config(path: Path) -> LocalLLMModelConfig:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ raw_model = payload.get("defaultModel")
+ if not isinstance(raw_model, dict):
+ raise ValueError(f"{path}: defaultModel is required")
+ requirements = payload.get("runtimeRequirements") if isinstance(payload.get("runtimeRequirements"), list) else []
+ return LocalLLMModelConfig(
+ runtime_requirements=[str(item) for item in requirements if str(item).strip()],
+ default_model=model_candidate_from_json(raw_model),
+ )
+
+
+def load_candidate_config(path: Path) -> ModelCandidateConfig:
+ payload = json.loads(path.read_text(encoding="utf-8"))
+ raw_candidates = payload.get("candidates") if isinstance(payload.get("candidates"), list) else []
+ candidates = [model_candidate_from_json(item) for item in raw_candidates if isinstance(item, dict)]
+ if not candidates:
+ raise ValueError(f"{path}: no local LLM model candidates configured")
+ return ModelCandidateConfig(candidates=candidates)
+
+
+def model_candidate_from_json(payload: dict[str, Any]) -> ModelCandidate:
+ return ModelCandidate(
+ id=str(payload.get("id") or ""),
+ display_name=str(payload.get("displayName") or payload.get("id") or ""),
+ model_id=str(payload.get("modelID") or payload.get("id") or ""),
+ filename=str(payload.get("filename") or "model.gguf"),
+ download_url=str(payload.get("downloadURL") or ""),
+ expected_size_mb=float(payload.get("expectedSizeMB") or 0),
+ expected_sha256=str(payload.get("sha256") or payload.get("expectedSHA256") or ""),
+ notes=str(payload.get("notes") or ""),
+ )
+
+
+def default_model_candidate(config: LocalLLMModelConfig) -> ModelCandidate:
+ return config.default_model
+
+
def load_cases(path: Path) -> list[dict[str, Any]]:
cases: list[dict[str, Any]] = []
for line_number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1):
@@ -168,7 +235,12 @@ def context_snippets(cases: list[dict[str, Any]]) -> dict[str, str]:
return snippets
-def build_request(case: dict[str, Any], model_id: str, snippets: dict[str, str]) -> dict[str, Any]:
+def build_request(
+ case: dict[str, Any],
+ model_id: str,
+ snippets: dict[str, str],
+ cache_directory: Path | None = None,
+) -> dict[str, Any]:
app_info = case.get("app") or {}
expected = case.get("expected") or {}
app_name = str(app_info.get("name") or "")
@@ -184,7 +256,7 @@ def build_request(case: dict[str, Any], model_id: str, snippets: dict[str, str])
seen_context.add(snippet)
local_context.append(snippet)
fallback_context = [item for item in snippets.values() if item not in seen_context]
- return {
+ request = {
"command": case["command"],
"taskDefinitions": TASK_DEFINITIONS,
"contextSnippets": (local_context + fallback_context)[:8],
@@ -196,6 +268,9 @@ def build_request(case: dict[str, Any], model_id: str, snippets: dict[str, str])
"evalSuiteID": case.get("suiteID", ""),
},
}
+ if cache_directory is not None:
+ request["cacheDirectory"] = str(cache_directory)
+ return request
def run_sidecar(
@@ -521,6 +596,194 @@ def average(values: list[float]) -> float | None:
return sum(values) / len(values)
+def candidate_by_id(config: ModelCandidateConfig) -> dict[str, ModelCandidate]:
+ return {candidate.id: candidate for candidate in config.candidates}
+
+
+def selected_candidates(config: ModelCandidateConfig, candidate_ids: list[str]) -> list[ModelCandidate]:
+ candidates = candidate_by_id(config)
+ if not candidate_ids:
+ return config.candidates
+ selected: list[ModelCandidate] = []
+ for candidate_id in candidate_ids:
+ candidate = candidates.get(candidate_id)
+ if candidate is None:
+ valid = ", ".join(sorted(candidates))
+ raise ValueError(f"unknown candidate {candidate_id!r}; valid candidates: {valid}")
+ selected.append(candidate)
+ return selected
+
+
+def candidate_model_dir(model_cache_dir: Path, candidate: ModelCandidate) -> Path:
+ return model_cache_dir / candidate.id
+
+
+def candidate_model_path(model_cache_dir: Path, candidate: ModelCandidate) -> Path:
+ return candidate_model_dir(model_cache_dir, candidate) / candidate.filename
+
+
+def download_candidate_model(
+ candidate: ModelCandidate,
+ model_cache_dir: Path,
+ *,
+ force: bool,
+ skip_download: bool,
+) -> dict[str, Any]:
+ model_path = candidate_model_path(model_cache_dir, candidate)
+ if skip_download:
+ if not model_path.is_file():
+ raise FileNotFoundError(f"{candidate.id}: cached model not found at {model_path}")
+ return model_file_info(model_path, candidate)
+
+ if model_path.is_file() and not force:
+ info = model_file_info(model_path, candidate)
+ if not candidate.expected_sha256 or info["sha256"] == candidate.expected_sha256:
+ return info
+ print(
+ f"{candidate.id}: cached checksum mismatch; re-downloading {model_path.name}",
+ file=sys.stderr,
+ )
+
+ model_path.parent.mkdir(parents=True, exist_ok=True)
+ tmp_path = model_path.with_suffix(model_path.suffix + ".download")
+ tmp_path.unlink(missing_ok=True)
+ print(f"{candidate.id}: downloading {candidate.download_url}", file=sys.stderr)
+ digest = hashlib.sha256()
+ size_bytes = 0
+ with urllib.request.urlopen(candidate.download_url, timeout=60) as response, tmp_path.open("wb") as output:
+ while True:
+ chunk = response.read(1024 * 1024)
+ if not chunk:
+ break
+ output.write(chunk)
+ digest.update(chunk)
+ size_bytes += len(chunk)
+ if size_bytes and size_bytes % (64 * 1024 * 1024) < len(chunk):
+ print(f"{candidate.id}: downloaded {size_bytes / 1_000_000:.0f} MB", file=sys.stderr)
+
+ actual_sha256 = digest.hexdigest()
+ if candidate.expected_sha256 and actual_sha256 != candidate.expected_sha256:
+ tmp_path.unlink(missing_ok=True)
+ raise RuntimeError(
+ f"{candidate.id}: checksum mismatch: expected {candidate.expected_sha256}, got {actual_sha256}"
+ )
+ tmp_path.replace(model_path)
+ return model_file_info(model_path, candidate, sha256=actual_sha256, size_bytes=size_bytes)
+
+
+def model_file_info(
+ model_path: Path,
+ candidate: ModelCandidate,
+ sha256: str | None = None,
+ size_bytes: int | None = None,
+) -> dict[str, Any]:
+ size_bytes = model_path.stat().st_size if size_bytes is None else size_bytes
+ sha256 = sha256 or sha256_file(model_path)
+ return {
+ "candidateID": candidate.id,
+ "modelID": candidate.model_id,
+ "displayName": candidate.display_name,
+ "filename": candidate.filename,
+ "path": str(model_path),
+ "downloadURL": candidate.download_url,
+ "expectedSizeMB": candidate.expected_size_mb,
+ "sizeBytes": size_bytes,
+ "sizeMB": size_bytes / 1_000_000,
+ "sha256": sha256,
+ "expectedSHA256": candidate.expected_sha256,
+ "notes": candidate.notes,
+ }
+
+
+def sha256_file(path: Path) -> str:
+ digest = hashlib.sha256()
+ with path.open("rb") as input_file:
+ for chunk in iter(lambda: input_file.read(1024 * 1024), b""):
+ digest.update(chunk)
+ return digest.hexdigest()
+
+
+def run_eval_suite(
+ *,
+ cases: list[dict[str, Any]],
+ all_cases: list[dict[str, Any]],
+ sidecar: Path,
+ python_executable: str,
+ model_id: str,
+ timeout_seconds: int,
+ dry_run: bool,
+ report_path: Path,
+ print_failures: bool,
+ model_path: Path | None = None,
+ cache_directory: Path | None = None,
+ model_filename: str | None = None,
+ runtime_state_dir: Path | None = None,
+) -> tuple[dict[str, Any], list[EvalResult]]:
+ snippets = context_snippets(all_cases)
+ results: list[EvalResult] = []
+ extra_env = {"DONKEY_LOCAL_LLM_TIMEOUT_SECONDS": str(timeout_seconds)}
+ if model_path is not None:
+ cache_directory = model_path.parent
+ model_filename = model_path.name
+ if model_filename:
+ extra_env["DONKEY_MODEL_FILENAME"] = model_filename
+ if runtime_state_dir is not None:
+ extra_env["DONKEY_RUNTIME_STATE_DIR"] = str(runtime_state_dir)
+
+ for index, case in enumerate(cases, start=1):
+ request = build_request(case, model_id, snippets, cache_directory)
+ if dry_run:
+ response, stderr, latency_ms = dry_run_response(case)
+ else:
+ print(f"[{index}/{len(cases)}] {model_id} :: {case['id']} :: {case['command']}", file=sys.stderr)
+ response, stderr, latency_ms = run_sidecar(
+ sidecar,
+ request,
+ model_id=model_id,
+ timeout_seconds=timeout_seconds,
+ python_executable=python_executable,
+ extra_env=extra_env,
+ )
+ results.append(score_case(case, response, stderr, latency_ms))
+
+ suite_id = str(cases[0].get("suiteID") or report_path.stem)
+ summary = summarize(results, suite_id, model_id, dry_run)
+ write_report(report_path, summary, results)
+ if print_failures:
+ for failure in summary["failures"]:
+ print(json.dumps(failure, indent=2, sort_keys=True), file=sys.stderr)
+ return summary, results
+
+
+def dry_run_response(case: dict[str, Any]) -> tuple[dict[str, Any], str, float]:
+ intent = {
+ "taskType": case["expected"]["taskType"],
+ "targetAppName": case["expected"]["targetAppName"],
+ "confidence": 1.0,
+ "needsConfirmation": False,
+ "entities": {
+ "appName": case["expected"]["appName"],
+ "query": " ".join(case["expected"].get("queryContainsAny") or []),
+ },
+ "normalizedEntities": {
+ "appName": case["expected"]["appName"],
+ "query": " ".join(case["expected"].get("queryContainsAny") or []),
+ },
+ "actionPlan": {
+ "tools": case["expected"]["requiredTools"],
+ "inputEntity": "query",
+ "controlID": "",
+ "focusKey": "",
+ "verification": "commandAttempted",
+ },
+ "metadata": {},
+ }
+ if case["expected"].get("requiredAppChain"):
+ intent["metadata"]["appChain"] = json.dumps(case["expected"]["requiredAppChain"])
+ intent["metadata"]["sourceApps"] = json.dumps(case["expected"].get("requiredSourceApps", []))
+ return {"outputText": json.dumps(intent), "metadata": {"dryRun": "true"}}, "", 0.0
+
+
def write_report(path: Path, summary: dict[str, Any], results: list[EvalResult]) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
report = {
@@ -543,76 +806,219 @@ def write_report(path: Path, summary: dict[str, Any], results: list[EvalResult])
path.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+def write_comparison_report(path: Path, payload: dict[str, Any]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8")
+
+
+def comparison_decision(model_summaries: list[dict[str, Any]]) -> dict[str, Any]:
+ completed = [item for item in model_summaries if item.get("status") == "completed"]
+ if not completed:
+ return {
+ "recommendedCandidateID": "",
+ "recommendedModelID": "",
+ "reason": "No candidate completed evaluation.",
+ "policy": "passRate desc, failed asc, averageLatencyMS asc, sizeMB asc",
+ }
+
+ def sort_key(item: dict[str, Any]) -> tuple[float, int, float, float]:
+ average_latency = item.get("averageLatencyMS")
+ size_mb = item.get("sizeMB")
+ return (
+ -float(item.get("passRate") or 0),
+ int(item.get("failed") or 0),
+ float(average_latency) if average_latency is not None else float("inf"),
+ float(size_mb) if size_mb is not None else float("inf"),
+ )
+
+ ranked = sorted(completed, key=sort_key)
+ winner = ranked[0]
+ return {
+ "recommendedCandidateID": winner["candidateID"],
+ "recommendedModelID": winner["modelID"],
+ "recommendedDisplayName": winner["displayName"],
+ "reason": (
+ f"Selected highest pass rate ({winner['passRate']:.3f}); ties break on failures, "
+ "average latency, then model size."
+ ),
+ "policy": "passRate desc, failed asc, averageLatencyMS asc, sizeMB asc",
+ }
+
+
+def run_candidate_comparison(
+ args: argparse.Namespace,
+ candidate_config: ModelCandidateConfig,
+ cases: list[dict[str, Any]],
+ all_cases: list[dict[str, Any]],
+) -> int:
+ candidates = selected_candidates(candidate_config, args.candidate)
+ runtime_state_dir = args.model_cache_dir / ".runtime-python" / "local-llm"
+ model_summaries: list[dict[str, Any]] = []
+
+ for candidate in candidates:
+ model_info: dict[str, Any] = {
+ "candidateID": candidate.id,
+ "modelID": candidate.model_id,
+ "displayName": candidate.display_name,
+ "expectedSizeMB": candidate.expected_size_mb,
+ "notes": candidate.notes,
+ }
+ model_path: Path | None = None
+ try:
+ if args.dry_run:
+ model_info.update({"status": "dryRun", "sizeMB": None, "sha256": ""})
+ else:
+ model_info.update(
+ download_candidate_model(
+ candidate,
+ args.model_cache_dir,
+ force=args.force_download,
+ skip_download=args.skip_download,
+ )
+ )
+ model_path = Path(str(model_info["path"]))
+ except Exception as exc: # noqa: BLE001
+ model_info.update({"status": "downloadFailed", "error": str(exc)})
+ model_summaries.append(model_info)
+ print(f"{candidate.id}: download failed: {exc}", file=sys.stderr)
+ continue
+
+ if args.download_only:
+ model_info["status"] = "downloaded"
+ model_summaries.append(model_info)
+ continue
+
+ report_path = args.comparison_dir / f"{candidate.id}.report.json"
+ try:
+ summary, _ = run_eval_suite(
+ cases=cases,
+ all_cases=all_cases,
+ sidecar=args.sidecar,
+ python_executable=args.python,
+ model_id=candidate.model_id,
+ timeout_seconds=args.timeout_seconds,
+ dry_run=args.dry_run,
+ report_path=report_path,
+ print_failures=args.print_failures,
+ model_path=model_path,
+ runtime_state_dir=runtime_state_dir,
+ )
+ except Exception as exc: # noqa: BLE001
+ model_info.update({"status": "evalFailed", "error": str(exc), "reportPath": str(report_path)})
+ model_summaries.append(model_info)
+ print(f"{candidate.id}: eval failed: {exc}", file=sys.stderr)
+ continue
+
+ model_info.update(
+ {
+ "status": "completed",
+ "caseCount": summary["caseCount"],
+ "passed": summary["passed"],
+ "failed": summary["failed"],
+ "passRate": summary["passRate"],
+ "averageLatencyMS": summary["averageLatencyMS"],
+ "reportPath": str(report_path),
+ }
+ )
+ model_summaries.append(model_info)
+
+ comparison = {
+ "suiteID": str(cases[0].get("suiteID") or args.evals.stem),
+ "caseCount": len(cases),
+ "dryRun": args.dry_run,
+ "downloadOnly": args.download_only,
+ "modelCacheDir": str(args.model_cache_dir),
+ "comparisonDir": str(args.comparison_dir),
+ "models": sorted(
+ model_summaries,
+ key=lambda item: (
+ -float(item.get("passRate") or 0),
+ int(item.get("failed") or 0),
+ optional_float(item.get("averageLatencyMS")),
+ optional_float(item.get("sizeMB")),
+ ),
+ ),
+ }
+ if not args.download_only:
+ comparison["decision"] = comparison_decision(model_summaries)
+ write_comparison_report(args.comparison_report, comparison)
+ print(json.dumps(comparison, indent=2, sort_keys=True))
+ print(f"comparison report: {args.comparison_report}")
+ return 0 if any(item.get("status") in {"completed", "downloaded", "dryRun"} for item in model_summaries) else 1
+
+
+def optional_float(value: Any) -> float:
+ if value is None:
+ return float("inf")
+ try:
+ return float(value)
+ except (TypeError, ValueError):
+ return float("inf")
+
+
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--evals", type=Path, default=DEFAULT_EVAL_PATH)
parser.add_argument("--sidecar", type=Path, default=DEFAULT_SIDECAR)
parser.add_argument("--python", default=sys.executable)
- parser.add_argument("--model-id", default=DEFAULT_MODEL_ID)
+ parser.add_argument("--model-config", type=Path, default=DEFAULT_MODEL_CONFIG_PATH)
+ parser.add_argument("--candidate-config", type=Path, default=DEFAULT_CANDIDATE_CONFIG_PATH)
+ parser.add_argument("--model-id")
+ parser.add_argument("--model-file", type=Path, help="GGUF file to use for a single-model run")
+ parser.add_argument("--cache-directory", type=Path, help="cacheDirectory to pass to the sidecar for a single-model run")
parser.add_argument("--timeout-seconds", type=int, default=35)
parser.add_argument("--limit", type=int)
parser.add_argument("--app", help="run only cases for one app name")
parser.add_argument("--report", type=Path, default=DEFAULT_REPORT_PATH)
parser.add_argument("--dry-run", action="store_true", help="build requests and validate case selection without invoking sidecar")
parser.add_argument("--print-failures", action="store_true")
+ parser.add_argument("--compare-default-candidates", action="store_true", help="download and evaluate the configured eval model candidates")
+ parser.add_argument("--candidate", action="append", default=[], help="candidate id to include when comparing; repeatable")
+ parser.add_argument("--model-cache-dir", type=Path, default=DEFAULT_MODEL_CACHE_DIR)
+ parser.add_argument("--comparison-dir", type=Path, default=DEFAULT_COMPARISON_DIR)
+ parser.add_argument("--comparison-report", type=Path, default=DEFAULT_COMPARISON_REPORT_PATH)
+ parser.add_argument("--download-only", action="store_true", help="download selected comparison candidates without running evals")
+ parser.add_argument("--force-download", action="store_true")
+ parser.add_argument("--skip-download", action="store_true", help="use cached models only")
args = parser.parse_args()
all_cases = load_cases(args.evals)
cases = select_cases(all_cases, args.app, args.limit)
- snippets = context_snippets(all_cases)
if not cases:
print("No eval cases selected.", file=sys.stderr)
return 2
- results: list[EvalResult] = []
- extra_env = {"DONKEY_LOCAL_LLM_TIMEOUT_SECONDS": str(args.timeout_seconds)}
- for index, case in enumerate(cases, start=1):
- request = build_request(case, args.model_id, snippets)
- if args.dry_run:
- intent = {
- "taskType": case["expected"]["taskType"],
- "targetAppName": case["expected"]["targetAppName"],
- "confidence": 1.0,
- "needsConfirmation": False,
- "entities": {"appName": case["expected"]["appName"], "query": " ".join(case["expected"].get("queryContainsAny") or [])},
- "normalizedEntities": {"appName": case["expected"]["appName"], "query": " ".join(case["expected"].get("queryContainsAny") or [])},
- "actionPlan": {
- "tools": case["expected"]["requiredTools"],
- "inputEntity": "query",
- "controlID": "",
- "focusKey": "",
- "verification": "commandAttempted",
- },
- "metadata": {},
- }
- if case["expected"].get("requiredAppChain"):
- intent["metadata"]["appChain"] = json.dumps(case["expected"]["requiredAppChain"])
- intent["metadata"]["sourceApps"] = json.dumps(case["expected"].get("requiredSourceApps", []))
- response = {"outputText": json.dumps(intent), "metadata": {"dryRun": "true"}}
- stderr = ""
- latency_ms = 0.0
- else:
- print(f"[{index}/{len(cases)}] {case['id']} :: {case['command']}", file=sys.stderr)
- response, stderr, latency_ms = run_sidecar(
- args.sidecar,
- request,
- model_id=args.model_id,
- timeout_seconds=args.timeout_seconds,
- python_executable=args.python,
- extra_env=extra_env,
- )
- results.append(score_case(case, response, stderr, latency_ms))
-
- suite_id = str(cases[0].get("suiteID") or args.evals.stem)
- summary = summarize(results, suite_id, args.model_id, args.dry_run)
- write_report(args.report, summary, results)
+ if args.compare_default_candidates or args.candidate:
+ candidate_config = load_candidate_config(args.candidate_config)
+ return run_candidate_comparison(args, candidate_config, cases, all_cases)
+
+ model_config = load_model_config(args.model_config)
+ default_candidate = default_model_candidate(model_config)
+ if args.model_id is None:
+ args.model_id = default_candidate.model_id
+
+ model_path = args.model_file
+ cache_directory = args.cache_directory
+ if model_path is not None and cache_directory is None:
+ cache_directory = model_path.parent
+ runtime_state_dir = args.model_cache_dir / ".runtime-python" / "local-llm" if model_path is not None else None
+ summary, _ = run_eval_suite(
+ cases=cases,
+ all_cases=all_cases,
+ sidecar=args.sidecar,
+ python_executable=args.python,
+ model_id=args.model_id,
+ timeout_seconds=args.timeout_seconds,
+ dry_run=args.dry_run,
+ report_path=args.report,
+ print_failures=args.print_failures,
+ model_path=model_path,
+ cache_directory=cache_directory,
+ runtime_state_dir=runtime_state_dir,
+ )
print(json.dumps(summary, indent=2, sort_keys=True))
print(f"report: {args.report}")
- if args.print_failures:
- for failure in summary["failures"]:
- print(json.dumps(failure, indent=2, sort_keys=True), file=sys.stderr)
-
return 0 if summary["failed"] == 0 else 1