Download code/oncallval/harness.py from Fektor/OnCallVal: direct link, hf CLI and curl.
- Browser
- Download file 7.52 kB
-
https://huggingface.co/datasets/Fektor/OnCallVal/resolve/main/code/oncallval/harness.py
- Command line
-
hf download hf://datasets/Fektor/OnCallVal/code/oncallval/harness.py
-
curl -L -o harness.py https://huggingface.co/datasets/Fektor/OnCallVal/resolve/main/code/oncallval/harness.py
7.52 kB
| """Episode runner. | |
| Agents: | |
| oracle -- executes the answer key's minimal fix (wiring check, NOT a baseline) | |
| random -- random walk + random report (floor check) | |
| llm -- any OpenAI-compatible chat endpoint; the agent replies with one JSON | |
| action per turn, the environment replies with one JSON observation. | |
| Usage: | |
| python -m oncallval.harness --agent oracle --limit 20 | |
| python -m oncallval.harness --agent llm --model gpt-4.1 --base-url https://api.openai.com/v1 | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import random | |
| import re | |
| import urllib.request | |
| from .env import Episode | |
| from .score import score_episode, summarize, truth_from_spec | |
| from .world import stable_hash | |
| FENCE = re.compile(r"```(?:json)?\s*(.*?)```", re.DOTALL) | |
| def load_jsonl(path): | |
| with open(path, encoding="utf-8") as f: | |
| return [json.loads(line) for line in f if line.strip()] | |
| def extract_action(text: str) -> dict | None: | |
| m = FENCE.search(text) | |
| if m: | |
| text = m.group(1) | |
| dec = json.JSONDecoder() | |
| for i, ch in enumerate(text): | |
| if ch == "{": | |
| try: | |
| obj, _ = dec.raw_decode(text[i:]) | |
| if isinstance(obj, dict) and "action" in obj: | |
| return obj | |
| except json.JSONDecodeError: | |
| continue | |
| return None | |
| class LLMAgent: | |
| def __init__(self, model: str, base_url: str, api_key: str, temperature: float = 0.0): | |
| self.model, self.base_url, self.key, self.temperature = model, base_url.rstrip("/"), api_key, temperature | |
| self.turns = 0 | |
| def chat(self, system: str, messages: list[dict]) -> str: | |
| body = json.dumps({"model": self.model, "temperature": self.temperature, "messages": | |
| [{"role": "system", "content": system}] + messages}).encode() | |
| req = urllib.request.Request( | |
| self.base_url + "/chat/completions", data=body, | |
| headers={"Content-Type": "application/json", "Authorization": f"Bearer {self.key}"}) | |
| with urllib.request.urlopen(req, timeout=180) as r: | |
| data = json.loads(r.read()) | |
| return data["choices"][0]["message"]["content"] | |
| def run(self, ep: Episode, max_turns: int) -> list[dict]: | |
| system = ep.system_prompt() | |
| messages = [{"role": "user", "content": f"ALERT: {ep.task['alert']}\nBegin. Reply with one JSON action."}] | |
| transcript = [] | |
| for _ in range(max_turns): | |
| text = self.chat(system, messages) | |
| action = extract_action(text) | |
| if action is None: | |
| messages.append({"role": "assistant", "content": text}) | |
| messages.append({"role": "user", "content": "Reply with exactly one JSON action object."}) | |
| continue | |
| obs = ep.step(action) | |
| transcript.append({"action": action, "observation": json.loads(obs)}) | |
| if ep.done: | |
| return transcript | |
| messages.append({"role": "assistant", "content": json.dumps(action)}) | |
| messages.append({"role": "user", "content": obs}) | |
| ep.step({"action": "submit_report", "cause": "unknown:unknown", "fix_summary": "budget exhausted"}) | |
| return transcript | |
| def oracle_agent(answer: dict): | |
| steps = list(answer["actions"]) + [ | |
| {"action": "submit_report", "cause": answer["cause"], "fix_summary": "answer key fix"}] | |
| def run(ep: Episode, max_turns: int) -> list[dict]: | |
| transcript = [] | |
| for act in steps: | |
| if ep.done: | |
| break | |
| obs = ep.step(act) | |
| transcript.append({"action": act, "observation": json.loads(obs)}) | |
| return transcript | |
| return run | |
| def random_agent(seed: int): | |
| rng = random.Random(seed) | |
| def run(ep: Episode, max_turns: int) -> list[dict]: | |
| transcript = [] | |
| svcs = [n for n, s in ep.w["services"].items() if s["kind"] != "external"] | |
| submit_at = rng.randint(5, max(6, ep.budget - 2)) | |
| for _ in range(max_turns): | |
| if ep.done: | |
| return transcript | |
| if ep.used >= submit_at: | |
| act = {"action": "submit_report", "cause": f"bad_deploy:{rng.choice(svcs)}", | |
| "fix_summary": "guess"} | |
| else: | |
| pick = rng.random() | |
| svc = rng.choice(svcs) | |
| if pick < 0.75: | |
| act = {"action": rng.choice(["get_metrics", "get_service", "query_logs"]), | |
| "service": svc} | |
| if act["action"] == "query_logs": | |
| act["limit"] = 20 | |
| else: | |
| act = rng.choice([ | |
| {"action": "restart", "service": svc}, | |
| {"action": "rollback", "service": svc}, | |
| {"action": "scale", "service": svc, "replicas": rng.randint(2, 10)}, | |
| {"action": "set_config", "service": svc, "key": "timeout_ms", "value": 500}, | |
| ]) | |
| obs = ep.step(act) | |
| transcript.append({"action": act, "observation": json.loads(obs)}) | |
| return transcript | |
| return run | |
| def main(): | |
| ap = argparse.ArgumentParser() | |
| ap.add_argument("--tasks", default="data/tasks.jsonl") | |
| ap.add_argument("--answers", default="", help="optional; truth is derived from the task spec if omitted") | |
| ap.add_argument("--agent", choices=["oracle", "random", "llm"], required=True) | |
| ap.add_argument("--model", default=os.environ.get("ONCALLVAL_MODEL", "gpt-4.1")) | |
| ap.add_argument("--base-url", default=os.environ.get("OPENAI_BASE_URL", "https://api.openai.com/v1")) | |
| ap.add_argument("--api-key", default=os.environ.get("OPENAI_API_KEY", "")) | |
| ap.add_argument("--limit", type=int, default=0, help="run only the first N tasks") | |
| ap.add_argument("--out", default="", help="write per-episode results JSONL here") | |
| args = ap.parse_args() | |
| tasks = load_jsonl(args.tasks) | |
| answers = {a["task_id"]: a for a in load_jsonl(args.answers)} if args.answers else {} | |
| if args.limit: | |
| tasks = tasks[:args.limit] | |
| results, transcripts = [], {} | |
| for t in tasks: | |
| ep = Episode(t) | |
| answer = answers.get(t["task_id"]) or truth_from_spec(t) | |
| if args.agent == "oracle": | |
| if "actions" not in answer: | |
| raise SystemExit("oracle agent requires --answers (it replays the answer-key fix)") | |
| tr = oracle_agent(answers[t["task_id"]])(ep, ep.budget + 4) | |
| elif args.agent == "random": | |
| tr = random_agent(stable_hash(t["task_id"]))(ep, ep.budget + 4) | |
| else: | |
| tr = LLMAgent(args.model, args.base_url, args.api_key).run(ep, ep.budget + 4) | |
| r = score_episode(ep, answer) | |
| r["difficulty"] = t["difficulty"] | |
| r["family"] = t["family"] | |
| results.append(r) | |
| transcripts[t["task_id"]] = tr | |
| summary = summarize(results) | |
| print(json.dumps(summary, indent=2)) | |
| if args.out: | |
| with open(args.out, "w", encoding="utf-8") as f: | |
| for r in results: | |
| f.write(json.dumps(r, ensure_ascii=False) + "\n") | |
| tpath = args.out.replace(".jsonl", ".transcripts.jsonl") | |
| with open(tpath, "w", encoding="utf-8") as f: | |
| for tid, tr in transcripts.items(): | |
| f.write(json.dumps({"task_id": tid, "transcript": tr}, ensure_ascii=False) + "\n") | |
| print(f"wrote {args.out} and {tpath}") | |
| if __name__ == "__main__": | |
| main() | |