Download src/versalit_rca/simulation/environment.py from delvek/versalit-rca-1: direct link, hf CLI and curl.
- Browser
- Download file 6.42 kB
-
https://huggingface.co/delvek/versalit-rca-1/resolve/main/src/versalit_rca/simulation/environment.py
- Command line
-
hf download hf://delvek/versalit-rca-1/src/versalit_rca/simulation/environment.py
-
curl -L -o environment.py https://huggingface.co/delvek/versalit-rca-1/resolve/main/src/versalit_rca/simulation/environment.py
6.42 kB
| """RCAEnv: the interactive fault-diagnosis environment the agent acts on. | |
| Exposes four tools (query_alarms, get_KPI, check_topology, lookup_3gpp_spec) | |
| backed by the scenario's hidden state: the full alarm storm, KPI store, network | |
| topology and 3GPP spec KB. The agent only sees what the tools return. | |
| """ | |
| from __future__ import annotations | |
| import random | |
| from collections import Counter | |
| from typing import Any, Dict, List, Optional | |
| from versalit_rca.simulation.alarm_generator import Scenario | |
| from versalit_rca.simulation.spec_kb import lookup as spec_lookup | |
| from versalit_rca.simulation.topology import NetworkTopology, build_topology | |
| TOOL_NAMES = ["query_alarms", "get_KPI", "check_topology", "lookup_3gpp_spec", "final_answer"] | |
| class RCAEnv: | |
| """Environment wrapper around a :class:`Scenario`.""" | |
| def __init__(self, scenario: Scenario, spec_top_k: int = 3, default_alarm_limit: int = 25): | |
| self.scenario = scenario | |
| self.spec_top_k = spec_top_k | |
| self.default_alarm_limit = default_alarm_limit | |
| self.topology = self._rebuild_topology(scenario) | |
| self.calls: List[Dict[str, Any]] = [] # successful tool calls | |
| self.invalid_calls: List[Dict[str, Any]] = [] # malformed/unknown calls | |
| self.done = False | |
| # ------------------------------------------------------------------ # | |
| def _rebuild_topology(scenario: Scenario) -> NetworkTopology: | |
| p = scenario.topo_params or {} | |
| return build_topology( | |
| n_sites=int(p.get("n_sites", 6)), | |
| cells_per_site=int(p.get("cells_per_site", 3)), | |
| rng=random.Random(0), | |
| architecture=p.get("architecture", scenario.architecture), | |
| ) | |
| # ------------------------------------------------------------------ # | |
| def reset_observation(self) -> str: | |
| """Initial observation shown to the agent: the storm summary.""" | |
| alarms = self.scenario.alarms | |
| nodes = sorted({a["node"] for a in alarms}) | |
| sev = Counter(a["severity"] for a in alarms) | |
| types = Counter(a["type"] for a in alarms).most_common(5) | |
| tmax = max((a["ts"] for a in alarms), default=0.0) | |
| lines = [ | |
| "=== ALARM STORM DETECTED ===", | |
| f"Window: 0-{tmax:.0f}s | {len(alarms)} alarms across {len(nodes)} network elements", | |
| f"Severity mix: {dict(sev)}", | |
| "Top alarm types: " + ", ".join(f"{t}({c})" for t, c in types), | |
| "Elements involved: " + ", ".join(nodes[:8]) + (" ..." if len(nodes) > 8 else ""), | |
| "Task: diagnose the root cause. Use the tools, then emit final_answer " | |
| "with ranked hypotheses (fault_id, node, category).", | |
| ] | |
| return "\n".join(lines) | |
| # ------------------------------------------------------------------ # | |
| def call(self, tool: str, args: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: | |
| """Validate and dispatch a tool call; records valid/invalid usage.""" | |
| args = args or {} | |
| if tool not in TOOL_NAMES: | |
| self.invalid_calls.append({"tool": tool, "args": args, "error": "unknown_tool"}) | |
| return {"error": f"unknown tool '{tool}'. valid: {TOOL_NAMES}"} | |
| if tool == "final_answer": | |
| self.done = True | |
| self.calls.append({"tool": tool, "args": args}) | |
| return {"ok": True, "final": args} | |
| try: | |
| result = getattr(self, f"_tool_{tool.lower()}")(**args) | |
| self.calls.append({"tool": tool, "args": args, "result_size": len(str(result))}) | |
| return result | |
| except (KeyError, TypeError, ValueError) as exc: | |
| self.invalid_calls.append({"tool": tool, "args": args, "error": str(exc)}) | |
| return {"error": f"{tool} failed: {exc}"} | |
| def n_tool_calls(self) -> int: | |
| return len(self.calls) | |
| def n_invalid_calls(self) -> int: | |
| return len(self.invalid_calls) | |
| # ------------------------------------------------------------------ # | |
| # Tool implementations # | |
| # ------------------------------------------------------------------ # | |
| def _tool_query_alarms( | |
| self, | |
| node: Optional[str] = None, | |
| severity: Optional[str] = None, | |
| alarm_type: Optional[str] = None, | |
| since_ts: float = 0.0, | |
| limit: Optional[int] = None, | |
| ) -> Dict[str, Any]: | |
| alarms = self.scenario.alarms | |
| out = [ | |
| a for a in alarms | |
| if (node is None or a["node"] == node) | |
| and (severity is None or a["severity"] == severity) | |
| and (alarm_type is None or alarm_type.upper() in a["type"]) | |
| and a["ts"] >= since_ts | |
| ] | |
| out.sort(key=lambda a: a["ts"]) | |
| limit = limit or self.default_alarm_limit | |
| return { | |
| "count": len(out), | |
| "returned": min(len(out), limit), | |
| "alarms": [ | |
| {k: a[k] for k in ("alarm_id", "ts", "node", "type", "severity", | |
| "probable_cause", "specific_problem")} | |
| for a in out[:limit] | |
| ], | |
| } | |
| def _tool_get_kpi(self, node: str, kpi: Optional[str] = None) -> Dict[str, Any]: | |
| if node not in self.scenario.kpis: | |
| raise KeyError(f"unknown node '{node}'") | |
| store = self.scenario.kpis[node] | |
| names = [kpi] if kpi else list(store) | |
| if kpi and kpi not in store: | |
| raise KeyError(f"unknown kpi '{kpi}'") | |
| return { | |
| "node": node, | |
| "kpis": { | |
| name: { | |
| "baseline": store[name]["baseline"], | |
| "observed_mean": store[name]["observed_mean"], | |
| "delta_pct": store[name]["delta_pct"], | |
| "trend": "degraded" if abs(store[name]["delta_pct"]) > 5 else "nominal", | |
| } | |
| for name in names | |
| }, | |
| } | |
| def _tool_check_topology(self, node: str) -> Dict[str, Any]: | |
| return self.topology.describe(node) | |
| def _tool_lookup_3gpp_spec(self, query: str) -> Dict[str, Any]: | |
| hits = spec_lookup(query, top_k=self.spec_top_k) | |
| return { | |
| "query": query, | |
| "hits": [ | |
| {"doc_id": h["doc_id"], "title": h["title"], "excerpt": h["text"]} | |
| for h in hits | |
| ], | |
| } | |