"""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