Coverage for app / agents / planner / __init__.py: 100%
50 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"""
2PlannerAgent — decomposes complex goals into validated ExecutionPlans.
4This package also re-exports the rich planning models so callers can do:
6 from app.agents.planner import PlannerAgent, ExecutionPlan, PlanStep
7"""
9from __future__ import annotations
11from typing import Any
13from langchain_core.language_models import BaseLanguageModel
14from langchain_core.messages import AIMessage, BaseMessage
15from langchain_core.tools import StructuredTool
17from app.agents.base import WorkerAgent, AgentCapability
18from app.agents.enums import AgentRole
19from app.agents.planner.models import ExecutionPlan, PlanStep, ProposedPlan
20from app.services import model_errors
21from app.services.structured_output import structured_call
22from app.util import safe_json
23from app.util.logger import get_logger
24from app.agents.planner.enums import ComplexityLevel
25from app import prompts
27logger = get_logger(__name__)
30class PlannerAgent(WorkerAgent):
31 """
32 Decomposes a complex goal into a validated ExecutionPlan.
34 The model fills ``ProposedPlan`` — only what it decides — through
35 ``structured_call``; ``ProposedPlan.to_plan`` builds the ``ExecutionPlan``
36 (and its DAG check) in code. Falls back to a stub plan when no valid
37 proposal comes back.
39 The planner is typically the entry (start) node of an execution graph.
40 Its output — an ExecutionPlan — is stored in GraphState.results and
41 can be read by downstream agents via ``state.results["planner"]``.
42 """
44 DEFAULT_ROLE = AgentRole.PLANNER
45 DEFAULT_SYSTEM_PROMPT = prompts.build_planner_prompt(AgentRole, ComplexityLevel)
47 DEFAULT_MAX_ITERATIONS = 5
49 def __init__(
50 self,
51 name: str = "planner",
52 role: AgentRole = DEFAULT_ROLE,
53 llm: BaseLanguageModel | None = None,
54 system_prompt: str | None = None,
55 tools: list[StructuredTool] | None = None,
56 ) -> None:
57 super().__init__(
58 name=name, role=role, llm=llm, system_prompt=system_prompt, tools=tools
59 )
60 self.add_capability(
61 AgentCapability(
62 "task_decomposition",
63 "Break complex tasks into atomic subtasks",
64 required=True,
65 )
66 )
67 self.add_capability(
68 AgentCapability(
69 "dependency_analysis",
70 "Identify and validate dependencies between steps",
71 required=True,
72 )
73 )
74 self.add_capability(
75 AgentCapability(
76 "agent_routing",
77 "Assign the appropriate agent type to each step",
78 required=True,
79 )
80 )
82 async def execute(self, input_data: Any) -> ExecutionPlan:
83 """
84 Call the LLM to produce a validated ExecutionPlan.
86 Attempts structured-output generation first; falls back to a
87 minimal stub plan if the model doesn't support it or returns
88 unparseable output.
89 """
90 if isinstance(input_data, dict):
91 goal = str(input_data.get("goal", input_data))
92 context: dict[str, Any] = input_data.get("context", {})
93 else:
94 goal = str(input_data)
95 context = {}
97 llm = self.resolve_llm()
98 messages = self._build_messages(goal, context)
100 try:
101 result = await structured_call(
102 llm, ProposedPlan, messages, purpose=self.name
103 )
104 plan = result.unwrap().to_plan()
105 except Exception as exc: # noqa: BLE001 — a stub plan, never a crash
106 model_errors.raise_if_fatal(exc)
107 logger.warning(
108 "[planner:%s] no valid plan (%s) — using the stub plan",
109 self.name,
110 model_errors.describe(exc),
111 )
112 plan = self._stub_plan(goal)
114 self.state.add_message(
115 AIMessage(
116 content=f"Plan created: {plan.plan_id} ({len(plan.steps)} steps)",
117 name=self.name,
118 )
119 )
120 return plan
122 def _build_messages(self, goal: str, context: dict[str, Any]) -> list[BaseMessage]:
123 user_content = f"Goal:\n{goal}"
124 if context:
125 user_content += f"\n\nContext:\n{safe_json.dumps(context, indent=2)}"
126 return self.build_messages(user_content)
128 @staticmethod
129 def _stub_plan(goal: str) -> ExecutionPlan:
130 """Minimal valid plan used as a fallback when structured output fails."""
131 return ExecutionPlan(
132 goal=goal,
133 steps=[
134 PlanStep(
135 step_number=1,
136 agent_type=AgentRole.ANALYZER,
137 task="Analyse the request and extract key information",
138 estimated_complexity=ComplexityLevel.MODERATE,
139 ),
140 PlanStep(
141 step_number=2,
142 agent_type=AgentRole.EXECUTOR,
143 task="Execute the primary task based on the analysis",
144 dependencies=[1],
145 estimated_complexity=ComplexityLevel.MODERATE,
146 ),
147 PlanStep(
148 step_number=3,
149 agent_type=AgentRole.VALIDATOR,
150 task="Validate the result and ensure quality",
151 dependencies=[2],
152 estimated_complexity=ComplexityLevel.SIMPLE,
153 ),
154 ],
155 estimated_total_steps=3,
156 reasoning="Default analysis → execution → validation pipeline (stub fallback)",
157 )
160__all__ = [
161 "PlannerAgent",
162 "ExecutionPlan",
163 "PlanStep",
164 "ComplexityLevel",
165]