File size: 10,603 Bytes
6d5c79f | 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 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 | """ReAct (Reason + Act) loop — the core agent execution engine.
Each iteration:
1. REASON — CoT produces a thought chain for the current task
2. ACT — Select and call the appropriate tool
3. OBSERVE — Read the tool's output
4. REFLECT — Decide to continue, retry, or backtrack
Design reference:
- Claude Opus: patient, thorough observation before next action
- GPT Codex: tight code-execute-fix feedback loop
- Gemini Pro: explicit state tracking across iterations
"""
from __future__ import annotations
import logging
import os
import time
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Any, Callable
from agent.core.chain_of_thought import ChainOfThoughtReasoner
from agent.core.planner import Task, TaskGraph, TaskStatus
if TYPE_CHECKING:
from agent.memory.audit_log import AuditLog
from agent.memory.short_term import ShortTermMemory
from agent.tools.base import BaseTool
LOGGER = logging.getLogger(__name__)
try:
from prometheus_client import Counter, Histogram
REACT_TASKS_TOTAL = Counter(
"zenex_react_tasks_total",
"Total number of task executions in React loop",
["tool", "status"],
)
REACT_TOOL_SECONDS = Histogram(
"zenex_react_tool_seconds",
"Tool execution duration in seconds",
["tool"],
buckets=(0.05, 0.1, 0.25, 0.5, 1, 2, 5, 10, 30, 60),
)
except Exception: # pragma: no cover - metrics optional
REACT_TASKS_TOTAL = None
REACT_TOOL_SECONDS = None
MAX_REACT_ITERATIONS = 50 # global guard
MAX_TASK_RETRIES = 3
MAX_RETRY_BACKOFF_SECONDS = 5.0
@dataclass
class Observation:
"""Result of a tool call."""
tool: str
args: dict
stdout: str = ""
stderr: str = ""
exit_code: int = 0
elapsed: float = 0.0
success: bool = True
error: str = ""
@property
def summary(self) -> str:
if not self.success:
return f"[FAIL] {self.tool}: {self.error or self.stderr[:200]}"
return f"[OK] {self.tool}: {(self.stdout or '').strip()[:200]}"
@dataclass
class ReactStep:
"""A single Reason→Act→Observe step recorded in the loop."""
iteration: int
task_id: str
thought: str
action: str
tool: str
tool_args: dict
observation: Observation
timestamp: float = field(default_factory=time.time)
class ReactLoop:
"""Main agent execution loop.
Runs the Reason→Act→Observe cycle until the task graph is done or
a hard limit is hit. On task failure it retries up to MAX_TASK_RETRIES
times with re-planning before giving up.
"""
def __init__(
self,
tools: dict[str, "BaseTool"],
memory: "ShortTermMemory",
audit_log: "AuditLog",
router: Any = None,
should_cancel: Callable[[], bool] | None = None,
) -> None:
self.tools = tools
self.memory = memory
self.audit = audit_log
self.router = router # ModelRouter — available for future code-gen steps
self.should_cancel = should_cancel
self.reasoner = ChainOfThoughtReasoner()
self.history: list[ReactStep] = []
self._retry_backoff = float(os.environ.get("ZENEX_RETRY_BACKOFF", "0.5"))
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def run(self, graph: TaskGraph) -> bool:
"""Execute the full task graph. Returns True if all tasks succeeded."""
LOGGER.info("ReactLoop starting for: %s", graph.goal)
iteration = 0
while not graph.is_done() and iteration < MAX_REACT_ITERATIONS:
if self._is_cancelled():
LOGGER.warning("ReactLoop cancellation requested. Stopping execution.")
return False
iteration += 1
ready = graph.ready_tasks()
if not ready:
if graph.has_failures():
LOGGER.warning("No runnable tasks — some tasks failed permanently.")
break
LOGGER.warning("No ready tasks but graph not done — possible cycle.")
break
for task in ready:
if self._is_cancelled():
LOGGER.warning("Cancellation requested before task '%s'.", task.title)
return False
self._execute_task(task, graph, iteration)
success = not graph.has_failures()
LOGGER.info("ReactLoop done. success=%s iterations=%d", success, iteration)
return success
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _execute_task(self, task: Task, graph: TaskGraph, iteration: int) -> None:
task.status = TaskStatus.IN_PROGRESS
task.attempts += 1
# 1. REASON
cot = self.reasoner.reason(
goal=task.description,
context=self.memory.context_summary(),
available_tools=list(self.tools.keys()),
history=[{"action": s.action, "observation": s.observation.summary} for s in self.history[-5:]],
)
cot.chosen_tool = task.tool if task.tool in self.tools else self._pick_tool(task)
cot.chosen_action = f"Run {cot.chosen_tool} for task '{task.title}'"
LOGGER.info(
"[iter=%d] Task '%s' → tool=%s (attempt %d/%d)",
iteration, task.title, cot.chosen_tool, task.attempts, task.max_attempts,
)
# 2. ACT
observation = self._call_tool(cot.chosen_tool, task, graph)
# 3. OBSERVE
step = ReactStep(
iteration=iteration,
task_id=task.id,
thought=cot.conclusion,
action=cot.chosen_action,
tool=cot.chosen_tool,
tool_args=task.tool_args,
observation=observation,
)
self.history.append(step)
self.audit.record(step)
self.memory.update(task, observation)
# 4. REFLECT
if observation.success:
graph.mark_complete(task.id, result=observation.stdout[:500])
LOGGER.info(" ✓ Task '%s' completed.", task.title)
if REACT_TASKS_TOTAL:
REACT_TASKS_TOTAL.labels(tool=cot.chosen_tool, status="success").inc()
else:
failure_type = self._classify_failure(observation)
self.memory.set("last_failure_type", failure_type)
LOGGER.warning(" ✗ Task '%s' failed (%s): %s", task.title, failure_type, observation.error)
# Failure-specific backoff reduces flapping on external/transient failures.
if task.attempts < task.max_attempts:
delay = min(MAX_RETRY_BACKOFF_SECONDS, self._retry_backoff * (2 ** (task.attempts - 1)))
if failure_type == "external":
delay = min(MAX_RETRY_BACKOFF_SECONDS, delay * 2)
time.sleep(delay)
# Retry: mark_failed increments counter; if < max_attempts it resets to PENDING
graph.mark_failed(task.id)
if task.failed_permanently:
LOGGER.error(" Task '%s' exceeded max retries.", task.title)
skipped = graph.skip_downstream_of(task.id)
if skipped:
LOGGER.warning(
" Skipped %d downstream task(s) blocked by '%s'.",
len(skipped),
task.title,
)
if REACT_TASKS_TOTAL:
REACT_TASKS_TOTAL.labels(tool=cot.chosen_tool, status="failure").inc()
def _call_tool(self, tool_name: str, task: Task, graph: TaskGraph) -> Observation:
tool = self.tools.get(tool_name)
if tool is None:
return Observation(
tool=tool_name, args={},
success=False, error=f"Tool '{tool_name}' not registered.",
)
t0 = time.time()
try:
# Enrich args with task context
args = {
**task.tool_args,
"_task": task,
"_graph": graph,
"_memory": self.memory,
"_audit": self.audit,
"_should_cancel": self.should_cancel,
}
result = tool.run(args)
elapsed = time.time() - t0
if REACT_TOOL_SECONDS:
REACT_TOOL_SECONDS.labels(tool=tool_name).observe(elapsed)
return Observation(
tool=tool_name, args=task.tool_args,
stdout=result.get("stdout", ""),
stderr=result.get("stderr", ""),
exit_code=result.get("exit_code", 0),
elapsed=elapsed,
success=result.get("success", True),
error=result.get("error", ""),
)
except Exception as exc:
elapsed = time.time() - t0
if REACT_TOOL_SECONDS:
REACT_TOOL_SECONDS.labels(tool=tool_name).observe(elapsed)
return Observation(
tool=tool_name, args=task.tool_args,
success=False, error=str(exc),
elapsed=elapsed,
)
def _pick_tool(self, task: Task) -> str:
"""Fallback tool selection when task.tool is not registered."""
for keyword, tool_name in [
("test", "test_runner"),
("lint", "linter"),
("install", "package_manager"),
("file", "filesystem"),
("git", "git"),
("readme", "readme_gen"),
("zip", "archiver"),
("search", "web_search"),
]:
if keyword in task.title.lower() and tool_name in self.tools:
return tool_name
return "executor"
def _is_cancelled(self) -> bool:
return bool(self.should_cancel and self.should_cancel())
@staticmethod
def _classify_failure(observation: Observation) -> str:
stderr = (observation.stderr or "").lower()
error = (observation.error or "").lower()
text = f"{stderr} {error}"
if any(x in text for x in ["timeout", "connection", "503", "429", "temporar"]):
return "external"
if any(x in text for x in ["syntaxerror", "typeerror", "nameerror", "assertionerror"]):
return "code"
if any(x in text for x in ["lint", "format", "mypy", "ruff", "eslint"]):
return "quality"
return "unknown"
|