Buckets:

download
raw
8.46 kB
"""
ReActAgent – Reason → Act → Observe → Reflect Loop.
Basis-Klasse für alle 11 spezialisierten Agenten.
"""
import json
import os
import time
import traceback
from enum import Enum
from typing import Any, Callable
from agents.guardrails import (
GuardrailViolation,
check_target,
validate_timeout,
sanitize_command,
RISK_SAFE,
RISK_NORMAL,
RISK_ELEVATED,
RISK_AGGRESSIVE,
)
OMNIROUTE_URL = os.environ.get("OMNIROUTE_URL", "http://omniroute:20128/v1")
AI_MODEL = os.environ.get("AI_MODEL", "oc/deepseek-v4-flash-free")
OPENCODE_API_KEY = os.environ.get("OPENCODE_API_KEY") or ""
class AgentState(Enum):
IDLE = "IDLE"
PLANNING = "PLANNING"
EXECUTING = "EXECUTING"
OBSERVING = "OBSERVING"
REFLECTING = "REFLECTING"
COMPLETED = "COMPLETED"
FAILED = "FAILED"
class ToolResult:
def __init__(self, ok: bool, output: str, tool: str = "", error: str = ""):
self.ok = ok
self.output = output
self.tool = tool
self.error = error
def to_dict(self) -> dict:
return {"ok": self.ok, "tool": self.tool, "output": self.output[:500], "error": self.error}
def __repr__(self):
return f"<ToolResult {self.tool} ok={self.ok}>"
class ReActAgent:
"""Base ReAct agent with Reason → Act → Observe → Reflect loop."""
def __init__(
self,
persona: str,
tools: list[str] | None = None,
risk_level: int = RISK_NORMAL,
timeout: int = 600,
max_retries: int = 3,
llm: str = AI_MODEL,
executor: Callable | None = None,
):
self.persona = persona
self.tools = tools or []
self.risk_level = risk_level
self.timeout = validate_timeout(timeout)
self.max_retries = max_retries
self.llm = llm
self.executor = executor or self._default_executor
self.state = AgentState.IDLE
self.memory: dict[str, Any] = {
"short_term": [],
"long_term": {},
"context": [],
}
self.task = ""
self.iteration = 0
self.errors = 0
self.result: dict | None = None
# --- State Machine ---
def _transition(self, new_state: AgentState):
self.state = new_state
# --- Default Executor (via OmniRoute) ---
def _default_executor(self, tool: str, args: str) -> ToolResult:
prompt = f"""You are a {self.persona} agent executing: {tool}
Args: {args}
Return ONLY the JSON result with keys: status, output, error"""
try:
import urllib.request
import urllib.error
body = json.dumps(
{
"model": self.llm,
"messages": [
{"role": "system", "content": prompt},
{"role": "user", "content": f"Execute {tool} with {args}"},
],
"max_tokens": 2048,
}
).encode()
req = urllib.request.Request(
f"{OMNIROUTE_URL}/chat/completions",
data=body,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {OPENCODE_API_KEY}",
},
method="POST",
)
with urllib.request.urlopen(req, timeout=30) as resp:
data = json.loads(resp.read())
content = data["choices"][0]["message"]["content"]
return ToolResult(ok=True, output=content, tool=tool)
except Exception as e:
return ToolResult(ok=False, output="", tool=tool, error=str(e))
# --- ReAct Loop ---
async def run(self, task: str) -> dict:
self.task = task
self._transition(AgentState.PLANNING)
self.memory["short_term"] = []
self.iteration = 0
self.errors = 0
while self.iteration < self.max_retries and self.state not in (AgentState.COMPLETED, AgentState.FAILED):
try:
self.iteration += 1
# === REASON ===
plan = self._reason()
if not plan:
self._transition(AgentState.FAILED)
break
# === ACT ===
self._transition(AgentState.EXECUTING)
result = self._act(plan)
# === OBSERVE ===
self._transition(AgentState.OBSERVING)
observation = self._observe(result)
# === REFLECT ===
self._transition(AgentState.REFLECTING)
done = self._reflect(observation)
if done:
self._transition(AgentState.COMPLETED)
else:
self._transition(AgentState.PLANNING)
except GuardrailViolation as e:
self.errors += 1
self.memory["short_term"].append({"error": str(e)})
if self.errors >= self.max_retries:
self._transition(AgentState.FAILED)
else:
self._transition(AgentState.PLANNING)
except Exception as e:
self.errors += 1
self.memory["short_term"].append({"error": str(e)})
if self.errors >= self.max_retries:
self._transition(AgentState.FAILED)
self._build_result()
return self.result or {"state": self.state.value, "task": self.task, "error": "No result"}
def _reason(self) -> str:
"""PLANNING: Analyze task, create execution plan via LLM."""
prompt = f"""You are {self.persona}. Task: {self.task}
Tools available: {", ".join(self.tools)}
Context: {json.dumps(self.memory["short_term"][-3:])}
Create a step-by-step execution plan. Return the NEXT tool to call and its arguments as JSON.
{{"tool": "...", "args": "...", "reasoning": "..."}}"""
try:
result = self._default_executor("reason", prompt)
if result.ok:
return result.output
except Exception:
pass
return ""
def _act(self, plan: str) -> ToolResult:
"""EXECUTING: Run the tool with guardrails."""
try:
parsed = json.loads(plan)
tool = parsed.get("tool", "")
args = parsed.get("args", "")
# Guardrails
if "target" in args.lower() or "host" in args.lower():
check_target(args, self.risk_level)
cmd = f"{tool} {args}"
sanitize_command(cmd)
return self.executor(tool, args)
except (json.JSONDecodeError, KeyError):
# Plan not JSON – try raw execution
return self.executor("analyze", plan)
def _observe(self, result: ToolResult) -> str:
"""OBSERVING: Collect and parse execution output."""
self.memory["short_term"].append(
{
"iteration": self.iteration,
"result": result.to_dict(),
}
)
return result.output
def _reflect(self, observation: str) -> bool:
"""REFLECTING: Evaluate if task is done or needs next iteration."""
prompt = f"""You are {self.persona}. Task: {self.task}
Observation: {observation[:1000]}
Context: {json.dumps(self.memory["short_term"][-3:])}
Has the task been completed successfully? Answer: YES/NO + brief reason."""
try:
result = self._default_executor("reflect", prompt)
return "yes" in result.output.lower().split("\n")[0]
except Exception:
return self.iteration >= self.max_retries
def _build_result(self):
self.result = {
"state": self.state.value,
"task": self.task,
"iterations": self.iteration,
"errors": self.errors,
"persona": self.persona,
"memory": {
"short_term_count": len(self.memory["short_term"]),
"last_action": self.memory["short_term"][-1] if self.memory["short_term"] else None,
},
}
def get_state(self) -> dict:
return {
"state": self.state.value,
"persona": self.persona,
"task": self.task,
"iteration": self.iteration,
"errors": self.errors,
"tools": self.tools,
"risk_level": self.risk_level,
}

Xet Storage Details

Size:
8.46 kB
·
Xet hash:
b9b3e386c295ca0e7a0c75ceb403a1a7ad1a90e2ccc8be873d99877b78276e3b

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.