Coverage for app / agents / loop.py: 100%
43 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-31 11:23 +0000
1"""
2LoopAgent — orchestrates iterative refinement within an agent graph.
4Rather than executing a primary task itself, LoopAgent inspects the
5current graph state to decide whether to continue iterating (routing
6back to an earlier node) or to exit the loop and proceed downstream.
7It pairs naturally with ReviewerAgent: Reviewer flags issues →
8LoopAgent decides whether to retry or finalise.
9"""
11from __future__ import annotations
13from typing import Any
15from pydantic import BaseModel
17from app.agents.base import WorkerAgent, AgentCapability, reply_text
18from app.agents.enums import AgentRole
19from app import prompts
22class LoopDecision(BaseModel):
23 should_continue: bool = False
24 iteration: int = 0
25 max_iterations: int = 3
26 reason: str = ""
27 raw_output: str = ""
30class LoopAgent(WorkerAgent):
31 """
32 Decides whether to loop back for another iteration or exit.
34 Reads the graph state to determine:
35 - How many iterations have already occurred
36 - Whether the last review/validation passed
37 - Whether max_iterations has been reached
39 Return value (LoopDecision) is inspected by conditional edges:
40 - should_continue=True → route back to the worker/executor node
41 - should_continue=False → proceed to the terminal node
43 Configuration keys recognised in system_prompt overrides:
44 max_iterations (int, default=3)
45 exit_on_approved (bool, default=True)
46 """
48 DEFAULT_ROLE = AgentRole.LOOP
49 DEFAULT_SYSTEM_PROMPT = prompts.LOOP_CONTROLLER
50 DEFAULT_MAX_ITERATIONS = 3
52 def __init__(
53 self,
54 *args: Any,
55 max_iterations: int | None = None,
56 **kwargs: Any,
57 ) -> None:
58 super().__init__(*args, **kwargs)
59 if max_iterations is not None:
60 self.max_iterations = max_iterations
61 self.add_capability(
62 AgentCapability(
63 name="loop_control",
64 description="Decides whether to continue iterating or exit the loop",
65 required=True,
66 )
67 )
69 async def execute(self, input_data: Any) -> LoopDecision:
70 """
71 Decide whether to continue looping based on the current state summary.
73 input_data should be a dict-like or string summarising the latest
74 review outcome and iteration count. When called from process_state,
75 the graph state dict is passed in.
76 """
77 # Extract iteration info from state context if available
78 iteration = 0
79 last_review = ""
80 if isinstance(input_data, dict):
81 iteration = input_data.get("loop_iteration", 0)
82 last_review = str(input_data.get("last_review", input_data))
83 else:
84 last_review = str(input_data)
86 if iteration >= self.max_iterations:
87 return LoopDecision(
88 should_continue=False,
89 iteration=iteration,
90 max_iterations=self.max_iterations,
91 reason="Maximum iterations reached",
92 raw_output="EXIT (max iterations reached)",
93 )
95 llm = self.resolve_llm()
96 prompt = (
97 f"Iteration {iteration + 1} of {self.max_iterations}.\n\n"
98 f"Latest output / review:\n{last_review}"
99 )
100 messages = self.build_messages(prompt)
101 response = await llm.ainvoke(messages)
102 content: str = (
103 reply_text(llm, response, self.name)
104 if hasattr(response, "content")
105 else str(response)
106 )
108 # Parse using the protocol constant from prompts so keyword changes propagate here automatically.
109 should_continue = content.strip().upper().startswith(prompts.LOOP_CONTINUE)
111 return LoopDecision(
112 should_continue=should_continue,
113 iteration=iteration + 1,
114 max_iterations=self.max_iterations,
115 reason=content.split("\n")[0] if content else "",
116 raw_output=content,
117 )
119 async def process_state(self, state: Any) -> LoopDecision:
120 """Pass full graph state context to the loop decision."""
121 context = getattr(state, "context", {})
122 results = getattr(state, "results", {})
123 iteration = context.get("loop_iteration", 0)
124 last_result = (
125 list(results.values())[-1] if results else getattr(state, "input", "")
126 )
127 return await self.process(
128 {"loop_iteration": iteration, "last_review": last_result}
129 )