File size: 2,882 Bytes
32030e4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Minimal environment for multi-step EJBench tasks served from stored results.

The same interface is what the MCP server / SDK will expose later:
    env = StoredDataEnv(task)
    obs = env.reset()                       # prompt + tool list, no hidden state
    out = env.step("get_run_result", {"run_id": "R3"})
    result = env.submit({...})              # scores and ends the episode
"""

from __future__ import annotations

from .scoring import score_task


class BudgetExceeded(Exception):
    pass


class StoredDataEnv:
    def __init__(self, task: dict):
        if task.get("interaction") != "multi_step":
            raise ValueError("StoredDataEnv only serves multi_step tasks")
        self.task = task
        self.env = task["environment"]
        self.used: dict[str, int] = {}
        self.trajectory: list[dict] = []
        self.done = False

    def reset(self) -> dict:
        self.used, self.trajectory, self.done = {}, [], False
        return {"prompt": self.task["prompt"], "tools": self.env["tools"],
                "budget": self.env["budget"], "output_schema": self.task["output_schema"]}

    def step(self, tool: str, args: dict) -> dict:
        if self.done:
            raise RuntimeError("episode finished")
        if tool == "submit":
            return self.submit(args)
        if tool not in self.env["budget"]:
            out = {"error": f"unknown tool {tool}"}
        elif self.used.get(tool, 0) >= self.env["budget"][tool]:
            out = {"error": f"budget exhausted for {tool}"}
        else:
            self.used[tool] = self.used.get(tool, 0) + 1
            out = self._serve(tool, args or {})
        self.trajectory.append({"tool": tool, "args": args, "observation": out})
        return out

    def _serve(self, tool: str, args: dict) -> dict:
        hidden = self.env["hidden_state"]
        if tool == "get_run_result":
            run = hidden["runs"].get(str(args.get("run_id")))
            return {"error": "unknown run_id"} if run is None else {"run_id": args["run_id"], **run["results"]}
        if tool == "get_report_section":
            sec = hidden["sections"].get(str(args.get("section")))
            return {"error": "unknown section"} if sec is None else {"section": args["section"], **sec}
        return {"error": f"no handler for {tool}"}

    def submit(self, payload: dict) -> dict:
        if self.done:
            raise RuntimeError("episode finished")
        self.done = True
        result = score_task(self.task, payload)
        result["tool_calls"] = dict(self.used)
        diag = self.env.get("diagnostics", {})
        if "most_similar_runs" in diag:
            chosen = [t["args"].get("run_id") for t in self.trajectory if t["tool"] == "get_run_result"]
            result["evidence_overlap_with_most_similar"] = len(set(chosen) & set(diag["most_similar_runs"]))
        return result