File size: 1,811 Bytes
e37c33f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Reuse W2-01 sampling, adding terminal traces and opt-in evaluation feedback."""
import asyncio
import json
import math
import time

from rl_env.common import SOCKET_LIMIT, json_bytes
from rl_env.consistency_scorer import guard_feedback, guard_phase, rule_library
from rl_env.sandbox_env import SandboxAgentLoop


class GuidedAgentLoop(SandboxAgentLoop):
    def handle_tool_result(self, key, initial, steps, name, args, result, forced):
        if guard_phase(key["phase"]) and name == "submit_diagnosis" and result.get("status") == "accepted":
            return guard_feedback(initial, steps, args, forced, rule_library()) or result
        return result

    async def score_episode(self, key, step, trace):
        train = key["phase"] == "train"
        path = "/ipc/score.sock" if train else "/ipc/eval.sock"
        began = time.monotonic_ns()
        body = json_bytes(key | {"step": step, "trace": trace})
        encode_ns = time.monotonic_ns() - began
        reader, writer = await asyncio.open_unix_connection(path, limit=SOCKET_LIMIT)
        try:
            # Separate serialization, socket delivery, and scorer work in the ledger.
            sent_ns = time.monotonic_ns()
            header = f'{{"sent_ns":{sent_ns},"encode_ns":{encode_ns},'.encode()
            writer.write(header + body[1:])
            await writer.drain()
            line = await asyncio.wait_for(reader.readline(), 120)
            result = json.loads(line)
            score = result.get("score")
            if type(score) not in (float, int) or not math.isfinite(score) or not (
                score == -0.1 or 0 <= score <= 1
            ):
                raise RuntimeError("invalid_isolated_score")
            return score
        finally:
            writer.close()
            await writer.wait_closed()