File size: 4,821 Bytes
ad14139
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""ReAct loop: parses Thought/Action turns, dispatches tools, records steps."""
from __future__ import annotations

import json
import re
from typing import Any, Dict, List, Optional

from versalit_rca.agent.trajectory import Hypothesis, Step, Trajectory
from versalit_rca.simulation.environment import RCAEnv
from versalit_rca.utils import logger

_DECODER = json.JSONDecoder()
_THOUGHT_RE = re.compile(r"Thought\s*:\s*(.*?)(?=Action\s*:|$)", re.DOTALL)
_ACTION_RE = re.compile(r"Action\s*:\s*", re.DOTALL)


def parse_assistant(text: str) -> Dict[str, Any]:
    """Parse one assistant turn into {thought, tool, args, flags}."""
    out: Dict[str, Any] = {
        "thought": "", "tool": None, "args": {},
        "parse_error": False, "fabricated_obs": False,
    }
    if "Observation:" in text:
        out["fabricated_obs"] = True

    m = _THOUGHT_RE.search(text)
    if m:
        out["thought"] = m.group(1).strip()

    a = _ACTION_RE.search(text)
    if not a:
        out["parse_error"] = True
        return out
    try:
        obj, _ = _DECODER.raw_decode(text[a.end():].lstrip())
        if isinstance(obj, dict):
            out["tool"] = obj.get("tool")
            out["args"] = obj.get("args") or {}
        else:
            out["parse_error"] = True
    except json.JSONDecodeError:
        out["parse_error"] = True
    return out


def _coerce_hypotheses(raw: Any, top_k: int) -> List[Hypothesis]:
    """Best-effort normalization of the final_answer hypotheses list."""
    hyps: List[Hypothesis] = []
    if not isinstance(raw, list):
        return hyps
    for h in raw[:top_k]:
        if not isinstance(h, dict):
            continue
        fault_id = h.get("fault_id") or h.get("cause") or ""
        if not fault_id:
            continue
        hyps.append(Hypothesis(
            fault_id=str(fault_id),
            node=str(h.get("node") or h.get("element") or ""),
            category=str(h.get("category") or ""),
            confidence=float(h.get("confidence", 0.0) or 0.0),
        ))
    return hyps


class ReActRunner:
    """Runs one diagnosis episode: policy ↔ env until final_answer or limits."""

    def __init__(self, max_steps: int = 12, max_tool_calls: int = 15, top_k: int = 3):
        self.max_steps = max_steps
        self.max_tool_calls = max_tool_calls
        self.top_k = top_k

    def run(self, env: RCAEnv, policy, policy_name: str = "policy",
            include_dump: bool = False) -> Trajectory:
        traj = Trajectory(scenario_id=env.scenario.scenario_id, policy_name=policy_name)

        history: List[Dict[str, Any]] = [
            {"role": "observation", "content": env.reset_observation()}
        ]
        if include_dump:
            # agentless baselines receive the whole (public) alarm storm upfront
            history.append({"role": "observation", "content": {
                "alarms": [
                    {k: a[k] for k in ("alarm_id", "ts", "node", "type", "severity",
                                       "probable_cause", "specific_problem")}
                    for a in env.scenario.alarms
                ]}})
        tool_calls = 0

        for _ in range(self.max_steps):
            text = policy.act(history)
            parsed = parse_assistant(text)
            step = Step(
                thought=parsed["thought"],
                action=parsed["tool"] or "",
                action_args=parsed["args"],
                raw_text=text,
                parse_error=parsed["parse_error"],
                fabricated_obs=parsed["fabricated_obs"],
            )
            history.append({"role": "assistant", "content": text})

            if step.parse_error or not step.action:
                step.observation = {"error": "could not parse action; reply with "
                                    "'Thought:' + 'Action: {\"tool\": ..., \"args\": {...}}'"}
                traj.steps.append(step)
                history.append({"role": "observation", "content": step.observation})
                continue

            result = env.call(step.action, step.action_args)
            step.observation = result
            step.invalid_call = "error" in result
            traj.steps.append(step)
            history.append({"role": "observation", "content": result})

            if step.action == "final_answer":
                traj.hypotheses = _coerce_hypotheses(
                    step.action_args.get("hypotheses"), self.top_k)
                traj.finished = True
                break

            tool_calls += 1
            if tool_calls >= self.max_tool_calls:
                traj.truncated = True
                break
        else:
            traj.truncated = True

        if not traj.finished:
            logger.debug("episode %s ended without final_answer", traj.scenario_id)
        return traj