Coverage for little_loops / fsm / evaluators.py: 96%

156 statements  

« prev     ^ index     » next       coverage.py v7.12.0, created at 2026-03-04 01:17 -0600

1"""FSM Evaluators for loop execution. 

2 

3This module provides evaluators that interpret action output and produce 

4verdicts for state transitions. 

5 

6Supported evaluator types: 

7 

8Tier 1 (Deterministic - no API calls): 

9 exit_code: Map Unix exit codes to verdicts (0=success, 1=failure, 2+=error) 

10 output_numeric: Compare numeric output to target value 

11 output_json: Extract and compare JSON path values 

12 output_contains: Pattern matching on stdout 

13 convergence: Track progress toward a target value 

14 

15Tier 2 (LLM-based): 

16 llm_structured: Use LLM with structured output for natural language evaluation 

17""" 

18 

19from __future__ import annotations 

20 

21import json 

22import re 

23from dataclasses import dataclass 

24from typing import Any 

25 

26from little_loops.fsm.schema import DEFAULT_LLM_MODEL 

27 

28import subprocess 

29 

30from little_loops.fsm.interpolation import ( 

31 InterpolationContext, 

32 InterpolationError, 

33 interpolate, 

34) 

35from little_loops.fsm.schema import EvaluateConfig 

36 

37 

38@dataclass 

39class EvaluationResult: 

40 """Result from an evaluator. 

41 

42 Attributes: 

43 verdict: The routing key for state transitions 

44 details: Evaluator-specific metadata for debugging/logging 

45 """ 

46 

47 verdict: str 

48 details: dict[str, Any] 

49 

50 

51# Default schema for LLM structured evaluation 

52DEFAULT_LLM_SCHEMA: dict[str, Any] = { 

53 "type": "object", 

54 "properties": { 

55 "verdict": { 

56 "type": "string", 

57 "enum": ["success", "failure", "blocked", "partial"], 

58 "description": ( 

59 "- success: The action completed its goal\n" 

60 "- failure: The action failed, should retry\n" 

61 "- blocked: Cannot proceed without external help\n" 

62 "- partial: Made progress but not complete" 

63 ), 

64 }, 

65 "confidence": { 

66 "type": "number", 

67 "minimum": 0, 

68 "maximum": 1, 

69 "description": "Confidence in this verdict (0-1)", 

70 }, 

71 "reason": { 

72 "type": "string", 

73 "description": "Brief explanation", 

74 }, 

75 }, 

76 "required": ["verdict", "confidence", "reason"], 

77} 

78 

79DEFAULT_LLM_PROMPT = "Evaluate whether this action succeeded based on its output." 

80 

81 

82def evaluate_exit_code(exit_code: int) -> EvaluationResult: 

83 """Map Unix exit code to verdict. 

84 

85 Args: 

86 exit_code: The process exit code 

87 

88 Returns: 

89 EvaluationResult with verdict: 

90 - 0 -> success 

91 - 1 -> failure 

92 - 2+ -> error 

93 """ 

94 if exit_code == 0: 

95 verdict = "success" 

96 elif exit_code == 1: 

97 verdict = "failure" 

98 else: 

99 verdict = "error" 

100 

101 return EvaluationResult(verdict=verdict, details={"exit_code": exit_code}) 

102 

103 

104def evaluate_output_numeric( 

105 output: str, 

106 operator: str, 

107 target: float, 

108) -> EvaluationResult: 

109 """Parse stdout as number and compare to target. 

110 

111 Args: 

112 output: The action stdout to parse as a number 

113 operator: Comparison operator (eq, ne, lt, le, gt, ge) 

114 target: Target value to compare against 

115 

116 Returns: 

117 EvaluationResult with verdict: 

118 - Condition met -> success 

119 - Condition not met -> failure 

120 - Parse error -> error 

121 """ 

122 try: 

123 value = float(output.strip()) 

124 except ValueError: 

125 return EvaluationResult( 

126 verdict="error", 

127 details={"error": f"Cannot parse as number: {output[:100]}"}, 

128 ) 

129 

130 operators = { 

131 "eq": lambda v, t: v == t, 

132 "ne": lambda v, t: v != t, 

133 "lt": lambda v, t: v < t, 

134 "le": lambda v, t: v <= t, 

135 "gt": lambda v, t: v > t, 

136 "ge": lambda v, t: v >= t, 

137 } 

138 

139 if operator not in operators: 

140 return EvaluationResult( 

141 verdict="error", 

142 details={"error": f"Unknown operator: {operator}"}, 

143 ) 

144 

145 condition_met = operators[operator](value, target) 

146 return EvaluationResult( 

147 verdict="success" if condition_met else "failure", 

148 details={"value": value, "target": target, "operator": operator}, 

149 ) 

150 

151 

152def _extract_json_path(data: Any, path: str) -> Any: 

153 """Extract value from dict using jq-style path like '.summary.failed'. 

154 

155 Args: 

156 data: The parsed JSON data (dict or list) 

157 path: Dot-separated path, optionally starting with '.' 

158 

159 Returns: 

160 The value at the specified path 

161 

162 Raises: 

163 KeyError: If path not found in data 

164 """ 

165 if path.startswith("."): 

166 path = path[1:] 

167 parts = path.split(".") 

168 current = data 

169 for part in parts: 

170 if isinstance(current, dict) and part in current: 

171 current = current[part] 

172 elif isinstance(current, list) and part.isdigit(): 

173 idx = int(part) 

174 if 0 <= idx < len(current): 

175 current = current[idx] 

176 else: 

177 raise KeyError(path) 

178 else: 

179 raise KeyError(path) 

180 return current 

181 

182 

183def _compare_values( 

184 value: int | float, operator: str, target: int | float, path: str 

185) -> EvaluationResult: 

186 """Compare numeric values using operator. 

187 

188 Args: 

189 value: The extracted value to compare 

190 operator: Comparison operator 

191 target: Target value 

192 path: JSON path for details 

193 

194 Returns: 

195 EvaluationResult with comparison result 

196 """ 

197 operators = { 

198 "eq": lambda v, t: v == t, 

199 "ne": lambda v, t: v != t, 

200 "lt": lambda v, t: v < t, 

201 "le": lambda v, t: v <= t, 

202 "gt": lambda v, t: v > t, 

203 "ge": lambda v, t: v >= t, 

204 } 

205 

206 if operator not in operators: 

207 return EvaluationResult( 

208 verdict="error", 

209 details={"error": f"Unknown operator: {operator}"}, 

210 ) 

211 

212 condition_met = operators[operator](value, target) 

213 return EvaluationResult( 

214 verdict="success" if condition_met else "failure", 

215 details={"value": value, "path": path, "target": target, "operator": operator}, 

216 ) 

217 

218 

219def evaluate_output_json( 

220 output: str, 

221 path: str, 

222 operator: str, 

223 target: Any, 

224) -> EvaluationResult: 

225 """Parse JSON and extract value at path, then compare. 

226 

227 Args: 

228 output: The action stdout containing JSON 

229 path: jq-style dot notation path (e.g., '.summary.failed') 

230 operator: Comparison operator (eq, ne, lt, le, gt, ge) 

231 target: Target value for comparison 

232 

233 Returns: 

234 EvaluationResult with verdict: 

235 - Condition met -> success 

236 - Condition not met -> failure 

237 - Parse/path error -> error 

238 """ 

239 try: 

240 data = json.loads(output) 

241 except json.JSONDecodeError as e: 

242 return EvaluationResult( 

243 verdict="error", 

244 details={"error": f"Invalid JSON: {e}"}, 

245 ) 

246 

247 try: 

248 value = _extract_json_path(data, path) 

249 except KeyError: 

250 return EvaluationResult( 

251 verdict="error", 

252 details={"error": f"Path not found: {path}"}, 

253 ) 

254 

255 # Use numeric comparison if both values are numeric 

256 if isinstance(value, (int, float)) and isinstance(target, (int, float)): 

257 return _compare_values(value, operator, target, path) 

258 

259 # For non-numeric values, only eq and ne are supported 

260 if operator == "eq": 

261 verdict = "success" if value == target else "failure" 

262 elif operator == "ne": 

263 verdict = "success" if value != target else "failure" 

264 else: 

265 return EvaluationResult( 

266 verdict="error", 

267 details={"error": f"Operator {operator} not supported for non-numeric values"}, 

268 ) 

269 

270 return EvaluationResult( 

271 verdict=verdict, 

272 details={"value": value, "path": path, "target": target, "operator": operator}, 

273 ) 

274 

275 

276def evaluate_output_contains( 

277 output: str, 

278 pattern: str, 

279 negate: bool = False, 

280) -> EvaluationResult: 

281 """Check if pattern exists in output. 

282 

283 Pattern can be regex or substring. If regex fails to compile, 

284 falls back to substring matching. 

285 

286 Args: 

287 output: The action stdout to search 

288 pattern: Regex pattern or substring 

289 negate: If True, invert the match result 

290 

291 Returns: 

292 EvaluationResult with verdict: 

293 - Found (negate=False) -> success 

294 - Found (negate=True) -> failure 

295 - Not found (negate=False) -> failure 

296 - Not found (negate=True) -> success 

297 """ 

298 # Try regex first, fall back to substring 

299 try: 

300 matched = bool(re.search(pattern, output)) 

301 except re.error: 

302 matched = pattern in output 

303 

304 if negate: 

305 verdict = "failure" if matched else "success" 

306 else: 

307 verdict = "success" if matched else "failure" 

308 

309 return EvaluationResult( 

310 verdict=verdict, 

311 details={"matched": matched, "pattern": pattern, "negate": negate}, 

312 ) 

313 

314 

315def evaluate_convergence( 

316 current: float, 

317 previous: float | None, 

318 target: float, 

319 tolerance: float = 0, 

320 direction: str = "minimize", 

321) -> EvaluationResult: 

322 """Compare current value to target and previous. 

323 

324 Args: 

325 current: Current metric value 

326 previous: Previous metric value (None if first iteration) 

327 target: Target value to reach 

328 tolerance: Acceptable distance from target 

329 direction: 'minimize' or 'maximize' 

330 

331 Returns: 

332 EvaluationResult with verdict: 

333 - Value within tolerance of target -> target 

334 - Value improved toward target -> progress 

335 - Value unchanged or worsened -> stall 

336 """ 

337 # Check if target reached (within tolerance) 

338 if abs(current - target) <= tolerance: 

339 return EvaluationResult( 

340 verdict="target", 

341 details={"current": current, "target": target, "delta": 0}, 

342 ) 

343 

344 # First iteration has no previous value 

345 if previous is None: 

346 return EvaluationResult( 

347 verdict="progress", 

348 details={ 

349 "current": current, 

350 "previous": None, 

351 "target": target, 

352 "delta": None, 

353 }, 

354 ) 

355 

356 # Calculate progress 

357 delta = current - previous 

358 

359 if direction == "minimize": 

360 # For minimizing, negative delta is progress 

361 made_progress = delta < 0 

362 else: 

363 # For maximizing, positive delta is progress 

364 made_progress = delta > 0 

365 

366 verdict = "progress" if made_progress else "stall" 

367 

368 return EvaluationResult( 

369 verdict=verdict, 

370 details={ 

371 "current": current, 

372 "previous": previous, 

373 "target": target, 

374 "delta": delta, 

375 "direction": direction, 

376 }, 

377 ) 

378 

379 

380def evaluate_llm_structured( 

381 output: str, 

382 prompt: str | None = None, 

383 schema: dict[str, Any] | None = None, 

384 min_confidence: float = 0.5, 

385 uncertain_suffix: bool = False, 

386 model: str = DEFAULT_LLM_MODEL, 

387 max_tokens: int = 256, 

388 timeout: int = 30, 

389) -> EvaluationResult: 

390 """Evaluate action output using LLM with structured output via Claude CLI. 

391 

392 This is the ONLY place in the FSM system that uses LLM structured output. 

393 Requires the ``claude`` CLI to be installed and authenticated. 

394 

395 Args: 

396 output: Action stdout to evaluate 

397 prompt: Custom evaluation prompt (defaults to basic success check) 

398 schema: Custom JSON schema for structured response 

399 min_confidence: Minimum confidence threshold (0-1) 

400 uncertain_suffix: If True, append _uncertain to low-confidence verdicts 

401 model: Model identifier (CLI aliases like "sonnet" or full names) 

402 max_tokens: Maximum tokens for response (passed to --max-turns is not 

403 applicable; kept for signature compat) 

404 timeout: Timeout in seconds 

405 

406 Returns: 

407 EvaluationResult with verdict from LLM and confidence/reason in details 

408 """ 

409 effective_schema = schema or DEFAULT_LLM_SCHEMA 

410 effective_prompt = prompt or DEFAULT_LLM_PROMPT 

411 

412 # Truncate output to avoid context limits (keep last 4000 chars) 

413 truncated = output[-4000:] if len(output) > 4000 else output 

414 

415 user_prompt = f"{effective_prompt}\n\n<action_output>\n{truncated}\n</action_output>" 

416 

417 cmd = [ 

418 "claude", 

419 "-p", user_prompt, 

420 "--output-format", "json", 

421 "--model", model, 

422 "--json-schema", json.dumps(effective_schema), 

423 "--dangerously-skip-permissions", 

424 "--no-session-persistence", 

425 ] 

426 

427 try: 

428 proc = subprocess.run(cmd, capture_output=True, text=True, timeout=timeout) 

429 except subprocess.TimeoutExpired: 

430 return EvaluationResult( 

431 verdict="error", 

432 details={"error": "LLM evaluation timeout", "timeout": True}, 

433 ) 

434 except FileNotFoundError: 

435 return EvaluationResult( 

436 verdict="error", 

437 details={ 

438 "error": "claude CLI not found. Install from https://docs.anthropic.com/en/docs/claude-code", 

439 "missing_dependency": True, 

440 }, 

441 ) 

442 

443 if proc.returncode != 0: 

444 return EvaluationResult( 

445 verdict="error", 

446 details={"error": f"Claude CLI error: {proc.stderr.strip()}", "api_error": True}, 

447 ) 

448 

449 # Parse the CLI JSON envelope and extract structured result 

450 try: 

451 envelope = json.loads(proc.stdout) 

452 llm_text = envelope.get("result", "") 

453 llm_result: dict[str, Any] = json.loads(llm_text) 

454 except (json.JSONDecodeError, TypeError, ValueError) as e: 

455 return EvaluationResult( 

456 verdict="error", 

457 details={"error": f"Failed to parse LLM response: {e}"}, 

458 ) 

459 

460 # Build result with confidence handling 

461 verdict = str(llm_result.get("verdict", "error")) 

462 confidence = float(llm_result.get("confidence", 1.0)) 

463 confident = confidence >= min_confidence 

464 

465 # Optionally modify verdict for low confidence 

466 if uncertain_suffix and not confident: 

467 verdict = f"{verdict}_uncertain" 

468 

469 return EvaluationResult( 

470 verdict=verdict, 

471 details={ 

472 "confidence": confidence, 

473 "confident": confident, 

474 "reason": llm_result.get("reason", ""), 

475 "raw": llm_result, 

476 }, 

477 ) 

478 

479 

480def evaluate( 

481 config: EvaluateConfig, 

482 output: str, 

483 exit_code: int, 

484 context: InterpolationContext, 

485) -> EvaluationResult: 

486 """Dispatch to appropriate evaluator based on config type. 

487 

488 Args: 

489 config: Evaluator configuration with type and parameters 

490 output: Action stdout 

491 exit_code: Action exit code 

492 context: Runtime context for variable interpolation 

493 

494 Returns: 

495 EvaluationResult from the appropriate evaluator 

496 

497 Raises: 

498 ValueError: If evaluator type is unknown 

499 """ 

500 eval_type = config.type 

501 

502 if eval_type == "exit_code": 

503 return evaluate_exit_code(exit_code) 

504 

505 elif eval_type == "output_numeric": 

506 # Target must be numeric 

507 numeric_target = float(config.target) if config.target is not None else 0.0 

508 return evaluate_output_numeric( 

509 output=output, 

510 operator=config.operator or "eq", 

511 target=numeric_target, 

512 ) 

513 

514 elif eval_type == "output_json": 

515 return evaluate_output_json( 

516 output=output, 

517 path=config.path or "", 

518 operator=config.operator or "eq", 

519 target=config.target, 

520 ) 

521 

522 elif eval_type == "output_contains": 

523 return evaluate_output_contains( 

524 output=output, 

525 pattern=config.pattern or "", 

526 negate=config.negate, 

527 ) 

528 

529 elif eval_type == "convergence": 

530 # Resolve previous value from interpolation if configured 

531 previous: float | None = None 

532 if config.previous: 

533 try: 

534 previous = float(interpolate(config.previous, context)) 

535 except (InterpolationError, ValueError): 

536 # Previous unavailable on first iteration, continue with None 

537 pass 

538 

539 # Parse current value from output 

540 try: 

541 current = float(output.strip()) 

542 except ValueError: 

543 return EvaluationResult( 

544 verdict="error", 

545 details={"error": f"Cannot parse output as number: {output[:100]}"}, 

546 ) 

547 

548 # Resolve target (may be interpolated string like "${context.target}") 

549 convergence_target: float 

550 if isinstance(config.target, str): 

551 try: 

552 convergence_target = float(interpolate(config.target, context)) 

553 except (InterpolationError, ValueError) as e: 

554 return EvaluationResult( 

555 verdict="error", 

556 details={"error": f"Cannot resolve target: {e}"}, 

557 ) 

558 else: 

559 convergence_target = float(config.target) if config.target is not None else 0.0 

560 

561 # Resolve tolerance (may be interpolated string) 

562 tolerance: float = 0.0 

563 if config.tolerance is not None: 

564 if isinstance(config.tolerance, str): 

565 try: 

566 tolerance = float(interpolate(config.tolerance, context)) 

567 except (InterpolationError, ValueError): 

568 tolerance = 0.0 

569 else: 

570 tolerance = float(config.tolerance) 

571 

572 return evaluate_convergence( 

573 current=current, 

574 previous=previous, 

575 target=convergence_target, 

576 tolerance=tolerance, 

577 direction=config.direction, 

578 ) 

579 

580 elif eval_type == "llm_structured": 

581 return evaluate_llm_structured( 

582 output=output, 

583 prompt=config.prompt, 

584 schema=config.schema, 

585 min_confidence=config.min_confidence, 

586 uncertain_suffix=config.uncertain_suffix, 

587 ) 

588 

589 else: 

590 raise ValueError(f"Unknown evaluator type: {eval_type}")