File size: 7,523 Bytes
6655381
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""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()