Datasets:
File size: 6,549 Bytes
bd43184 | 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 | #!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import os
import shutil
import subprocess
import time
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_EVALS = ROOT / "data" / "opencode_tool_calling_eval.jsonl"
DEFAULT_CONFIG = ROOT / "configs" / "opencode-qwen35.json"
WORK_ROOT = ROOT / "tmp" / "opencode-eval"
def iter_jsonl(path: Path):
with path.open() as f:
for line in f:
if line.strip():
yield json.loads(line)
def seed_workspace(case: dict, workdir: Path) -> None:
if workdir.exists():
shutil.rmtree(workdir)
workdir.mkdir(parents=True)
for rel, text in case["files"].items():
path = workdir / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
def apply_expected_outputs(case: dict, workdir: Path) -> None:
for rel, text in (case.get("verify") or {}).items():
path = workdir / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(text)
for rel, needles in (case.get("verify_contains") or {}).items():
path = workdir / rel
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text("\n".join(needles) + "\n")
for rel in case.get("verify_missing") or []:
path = workdir / rel
if path.exists():
path.unlink()
def verify_case(case: dict, workdir: Path) -> list[str]:
errors: list[str] = []
for rel, expected in (case.get("verify") or {}).items():
path = workdir / rel
if not path.exists():
errors.append(f"{rel} is missing")
elif path.read_text() != expected:
errors.append(f"{rel} did not match expected content")
for rel, needles in (case.get("verify_contains") or {}).items():
path = workdir / rel
if not path.exists():
errors.append(f"{rel} is missing")
continue
text = path.read_text().lower()
for needle in needles:
if needle.lower() not in text:
errors.append(f"{rel} does not contain {needle!r}")
for rel in case.get("verify_missing") or []:
if (workdir / rel).exists():
errors.append(f"{rel} still exists")
command = case.get("verify_command")
if command:
proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=120)
if proc.returncode != 0:
errors.append(f"verify_command failed: {proc.stdout}{proc.stderr}")
return errors
def parse_tool_mentions(text: str, expected_tools: list[str]) -> list[str]:
found: list[str] = []
lower = text.lower()
for name in expected_tools:
if name.lower() in lower:
found.append(name)
return found
def self_check_case(case: dict) -> dict:
workdir = WORK_ROOT / f"self-check-{case['id']}"
seed_workspace(case, workdir)
apply_expected_outputs(case, workdir)
errors = verify_case(case, workdir)
return {"id": case["id"], "passed": not errors, "verify_errors": errors}
def run_case(case: dict, args: argparse.Namespace) -> dict:
workdir = WORK_ROOT / case["id"]
seed_workspace(case, workdir)
config_content = args.config.read_text()
command = [
"bunx",
"opencode-ai@latest",
"run",
"--model",
args.model,
"--format",
"json",
"--dir",
str(workdir),
]
if args.dangerously_skip_permissions:
command.append("--dangerously-skip-permissions")
command.append(case["prompt"])
env = os.environ.copy()
env["OPENCODE_CONFIG_CONTENT"] = config_content
env.setdefault("OPENAI_API_KEY", "omlx")
start = time.time()
proc = subprocess.run(command, cwd=workdir, text=True, capture_output=True, timeout=args.timeout, env=env)
verify_errors = verify_case(case, workdir) if proc.returncode == 0 else ["opencode exited nonzero"]
combined = f"{proc.stdout}\n{proc.stderr}"
return {
"id": case["id"],
"returncode": proc.returncode,
"seconds": round(time.time() - start, 3),
"passed": proc.returncode == 0 and not verify_errors,
"verify_errors": verify_errors,
"expected_tools": case.get("expected_tools") or [],
"observed_tool_mentions": parse_tool_mentions(combined, case.get("expected_tools") or []),
"stdout_tail": proc.stdout[-4000:],
"stderr_tail": proc.stderr[-4000:],
}
def main() -> int:
parser = argparse.ArgumentParser()
parser.add_argument("--evals", type=Path, default=DEFAULT_EVALS)
parser.add_argument("--config", type=Path, default=DEFAULT_CONFIG)
parser.add_argument("--model", default="qwen35/qwen35")
parser.add_argument("--timeout", type=int, default=300)
parser.add_argument("--limit", type=int)
parser.add_argument("--self-check", action="store_true", help="Verify eval seed/check logic without invoking opencode.")
parser.add_argument("--dangerously-skip-permissions", action="store_true", help="Pass opencode's non-interactive permission bypass flag for disposable eval workspaces.")
args = parser.parse_args()
WORK_ROOT.mkdir(parents=True, exist_ok=True)
cases = list(iter_jsonl(args.evals))
if args.limit is not None:
cases = cases[: args.limit]
results = []
for case in cases:
if args.self_check:
result = self_check_case(case)
else:
print(f"running {case['id']}")
try:
result = run_case(case, args)
except subprocess.TimeoutExpired as exc:
result = {
"id": case["id"],
"returncode": None,
"seconds": args.timeout,
"passed": False,
"verify_errors": ["opencode timed out"],
"expected_tools": case.get("expected_tools") or [],
"observed_tool_mentions": [],
"stdout_tail": (exc.stdout or "")[-4000:],
"stderr_tail": (exc.stderr or "")[-4000:],
}
print(json.dumps(result, indent=2))
results.append(result)
out = ROOT / "tmp" / "opencode-eval-results.json"
out.write_text(json.dumps(results, indent=2) + "\n")
failed = [row for row in results if not row["passed"]]
print(f"passed {len(results) - len(failed)}/{len(results)}")
return 1 if failed else 0
if __name__ == "__main__":
raise SystemExit(main())
|