Coverage for app / agents / planner / models.py: 99%

124 statements  

« prev     ^ index     » next       coverage.py v7.13.4, created at 2026-10-31 11:23 +0000

1from __future__ import annotations 

2 

3import uuid 

4from datetime import datetime 

5from typing import Annotated, Any 

6 

7from pydantic import BaseModel, Field, field_validator, model_validator 

8 

9from app.agents.enums import AgentType 

10from app.services.structured_output import ModelOutput 

11from .enums import StepStatus, ComplexityLevel, PlanStatus 

12 

13 

14class StepInput(BaseModel): 

15 """Structured input contract for a single plan step.""" 

16 

17 model_config = {"frozen": True} 

18 

19 key: str = Field(..., description="Input key name") 

20 description: str = Field(..., description="Human-readable description of the input") 

21 required: bool = Field(default=True) 

22 source_step: int | None = Field( 

23 default=None, 

24 description="Step number that produces this input (None = from original request)", 

25 ) 

26 

27 

28class StepOutput(BaseModel): 

29 """Structured output contract for a single plan step.""" 

30 

31 model_config = {"frozen": True} 

32 

33 key: str = Field(..., description="Output key name") 

34 description: str = Field( 

35 ..., description="Human-readable description of the output" 

36 ) 

37 schema_hint: str | None = Field( 

38 default=None, description="Optional JSON schema or type hint as a string" 

39 ) 

40 

41 

42class PlanStep(BaseModel): 

43 """ 

44 Individual step within an execution plan. 

45 

46 Each step is atomic, independently executable (given its dependencies), 

47 and carries explicit input/output contracts. 

48 """ 

49 

50 model_config = {"frozen": True} 

51 

52 step_id: str = Field( 

53 default_factory=lambda: str(uuid.uuid4()), 

54 description="Unique identifier for this step", 

55 ) 

56 step_number: Annotated[int, Field(ge=1)] = Field( 

57 ..., description="1-based sequential position in the plan" 

58 ) 

59 agent_type: AgentType = Field(..., description="Agent responsible for this step") 

60 task: str = Field(..., min_length=10, description="Clear description of the task") 

61 rationale: str = Field( 

62 default="", 

63 description="Why this step is needed and how it contributes to the goal", 

64 ) 

65 dependencies: list[Annotated[int, Field(ge=1)]] = Field( 

66 default_factory=list, 

67 description="step_number values that must complete before this step runs", 

68 ) 

69 estimated_complexity: ComplexityLevel = Field( 

70 default=ComplexityLevel.MODERATE, 

71 description="Estimated complexity on a 1-5 scale", 

72 ) 

73 inputs: list[StepInput] = Field( 

74 default_factory=list, 

75 description="Expected inputs for this step", 

76 ) 

77 outputs: list[StepOutput] = Field( 

78 default_factory=list, 

79 description="Outputs this step will produce", 

80 ) 

81 status: StepStatus = Field(default=StepStatus.PENDING) 

82 error: str | None = Field(default=None, description="Error message if step failed") 

83 started_at: datetime | None = None 

84 completed_at: datetime | None = None 

85 

86 @field_validator("dependencies") 

87 @classmethod 

88 def no_self_dependency(cls, deps: list[int], info: Any) -> list[int]: 

89 step_num = info.data.get("step_number") 

90 if step_num is not None and step_num in deps: 

91 raise ValueError(f"Step {step_num} cannot depend on itself") 

92 return sorted(set(deps)) # deduplicate and sort 

93 

94 @property 

95 def duration_seconds(self) -> float | None: 

96 if self.started_at and self.completed_at: 

97 return (self.completed_at - self.started_at).total_seconds() 

98 return None 

99 

100 

101class ExecutionPlan(BaseModel): 

102 """ 

103 Complete decomposed execution plan produced by the PlannerAgent. 

104 

105 Invariants enforced at construction time: 

106 - Step numbers are unique and contiguous starting at 1 

107 - Dependency references point to existing steps 

108 - Dependency graph is a DAG (no cycles) 

109 """ 

110 

111 plan_id: str = Field(default_factory=lambda: str(uuid.uuid4())) 

112 goal: str = Field(..., min_length=5, description="The high-level objective") 

113 context: dict[str, Any] = Field( 

114 default_factory=dict, 

115 description="Supplementary context from the original request", 

116 ) 

117 steps: list[PlanStep] = Field(..., min_length=1) 

118 estimated_total_steps: int = Field(..., ge=1) 

119 reasoning: str = Field( 

120 ..., min_length=10, description="Planner's reasoning narrative" 

121 ) 

122 status: PlanStatus = Field(default=PlanStatus.DRAFT) 

123 created_at: datetime = Field(default_factory=datetime.utcnow) 

124 updated_at: datetime = Field(default_factory=datetime.utcnow) 

125 metadata: dict[str, Any] = Field( 

126 default_factory=dict, 

127 description="Arbitrary metadata (e.g. model used, prompt tokens)", 

128 ) 

129 

130 @model_validator(mode="after") 

131 def validate_plan_integrity(self) -> "ExecutionPlan": 

132 step_numbers = [s.step_number for s in self.steps] 

133 

134 # Unique step numbers 

135 if len(step_numbers) != len(set(step_numbers)): 

136 raise ValueError("Duplicate step numbers found in plan") 

137 

138 step_number_set = set(step_numbers) 

139 

140 # All dependency references are valid 

141 for step in self.steps: 

142 invalid = set(step.dependencies) - step_number_set 

143 if invalid: 

144 raise ValueError( 

145 f"Step {step.step_number} references unknown dependencies: {invalid}" 

146 ) 

147 

148 # Estimated total matches actual 

149 if self.estimated_total_steps != len(self.steps): 

150 # Coerce rather than reject — planner LLMs often estimate loosely 

151 object.__setattr__(self, "estimated_total_steps", len(self.steps)) 

152 

153 # Cycle detection via Kahn's algorithm 

154 _assert_dag(self.steps) 

155 

156 return self 

157 

158 def get_step(self, step_number: int) -> PlanStep | None: 

159 return next((s for s in self.steps if s.step_number == step_number), None) 

160 

161 def execution_order(self) -> list[list[PlanStep]]: 

162 """ 

163 Return steps grouped into parallel execution waves. 

164 

165 Each wave contains steps whose dependencies have all been 

166 satisfied by previous waves. 

167 """ 

168 completed: set[int] = set() 

169 waves: list[list[PlanStep]] = [] 

170 remaining = list(self.steps) 

171 

172 while remaining: 

173 wave = [s for s in remaining if set(s.dependencies) <= completed] 

174 if not wave: 

175 raise RuntimeError("Cycle detected during execution ordering") 

176 waves.append(wave) 

177 completed.update(s.step_number for s in wave) 

178 remaining = [s for s in remaining if s not in wave] 

179 

180 return waves 

181 

182 

183def _assert_dag(steps: list[PlanStep]) -> None: 

184 """Raise ValueError if the dependency graph contains a cycle.""" 

185 graph: dict[int, list[int]] = {s.step_number: list(s.dependencies) for s in steps} 

186 visited: set[int] = set() 

187 in_stack: set[int] = set() 

188 

189 def dfs(node: int) -> None: 

190 visited.add(node) 

191 in_stack.add(node) 

192 for neighbour in graph.get(node, []): 

193 if neighbour not in visited: 

194 dfs(neighbour) 

195 elif neighbour in in_stack: 

196 raise ValueError( 

197 f"Cycle detected in dependency graph at step {neighbour}" 

198 ) 

199 in_stack.discard(node) 

200 

201 for step_number in graph: 

202 if step_number not in visited: 

203 dfs(step_number) 

204 

205 

206# ── What the model is asked to fill ────────────────────────────────────────── 

207# 

208# ``ExecutionPlan`` is the domain object: it carries a plan_id, a status, 

209# timestamps and metadata that only this service may set. It used to be the 

210# schema the model filled, so the model was shown — and could invent — all of 

211# them, and a field like ``context: dict[str, Any]`` cannot be decoded 

212# strictly at all. The model fills ``ProposedPlan``; ``to_plan`` builds the 

213# domain object from it in code. 

214 

215 

216class ProposedInput(ModelOutput): 

217 key: str = Field(description="Input key name") 

218 description: str = Field(default="", description="What the input is") 

219 source_step: int | None = Field( 

220 default=None, 

221 description="step_number that produces this input; null when it comes from the request", 

222 ) 

223 

224 

225class ProposedOutput(ModelOutput): 

226 key: str = Field(description="Output key name") 

227 description: str = Field(default="", description="What the output is") 

228 schema_hint: str = Field( 

229 default="", description="Optional type or shape of the output" 

230 ) 

231 

232 

233class ProposedStep(ModelOutput): 

234 step_number: int = Field(description="1-based sequential position in the plan") 

235 agent_type: AgentType = Field(description="Agent responsible for this step") 

236 task: str = Field(description="What this step must do, specifically") 

237 # Not "rationale": Claude 5.x can refuse an output field asking for its reasoning. 

238 purpose: str = Field( 

239 default="", description="Why the step is needed and what its output feeds" 

240 ) 

241 dependencies: list[int] = Field( 

242 default_factory=list, 

243 description="step_number values that must complete before this step runs", 

244 ) 

245 estimated_complexity: ComplexityLevel = Field( 

246 default=ComplexityLevel.MODERATE, description="Estimated complexity, 1–5" 

247 ) 

248 inputs: list[ProposedInput] = Field(default_factory=list) 

249 outputs: list[ProposedOutput] = Field(default_factory=list) 

250 

251 

252class ProposedPlan(ModelOutput): 

253 goal: str = Field(description="The high-level objective") 

254 summary: str = Field( 

255 default="", 

256 description="Two or three sentences on how the plan reaches the goal", 

257 ) 

258 steps: list[ProposedStep] = Field(description="The plan's steps, in order") 

259 

260 def to_plan(self) -> ExecutionPlan: 

261 """The domain plan. Raises ``ValidationError`` when the proposal breaks 

262 a plan invariant (unknown dependency, a cycle, too-short text).""" 

263 return ExecutionPlan( 

264 goal=self.goal, 

265 reasoning=self.summary or f"Plan for: {self.goal}", 

266 steps=[ 

267 PlanStep( 

268 step_number=step.step_number, 

269 agent_type=step.agent_type, 

270 task=step.task, 

271 rationale=step.purpose, 

272 dependencies=step.dependencies, 

273 estimated_complexity=step.estimated_complexity, 

274 inputs=[ 

275 StepInput( 

276 key=i.key, 

277 description=i.description or i.key, 

278 source_step=i.source_step, 

279 ) 

280 for i in step.inputs 

281 ], 

282 outputs=[ 

283 StepOutput( 

284 key=o.key, 

285 description=o.description or o.key, 

286 schema_hint=o.schema_hint or None, 

287 ) 

288 for o in step.outputs 

289 ], 

290 ) 

291 for step in self.steps 

292 ], 

293 estimated_total_steps=max(len(self.steps), 1), 

294 )