Coverage for app / agents / conditions.py: 88%

247 statements  

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

1""" 

2Conditional-edge evaluation — deterministic, data-driven routing for skill 

3graphs. 

4 

5A conditional edge source declares ordered ``branches``; the first branch 

6whose ``when`` predicate holds against the current graph variables wins. 

7Predicates reference variables by dotted path:: 

8 

9 {"var": "assess.risk_level", "op": "eq", "value": "high"} 

10 {"all": [{"var": "assess.score", "op": "lt", "value": 0.7}, 

11 {"var": "assess.flags", "op": "not_empty"}]} 

12 {"any": [...]}, {"not": {...}} 

13 

14The variable namespace a skill node sees (see ``graph_variables``): 

15 

16 input — the original user task 

17 <state_key> — every user-declared / node-written state variable 

18 <node_id> — each completed node's result (dict for structured 

19 workers, so ``{node_id.field}`` addresses one field) 

20 

21Evaluation never raises: an unresolvable path or a type mismatch simply 

22makes the predicate false, and the source's ``default`` branch applies. 

23""" 

24 

25from __future__ import annotations 

26 

27import re 

28from typing import Any, Callable 

29 

30from pydantic import BaseModel, Field, model_validator 

31 

32from app.util import safe_json 

33from app.util.logger import get_logger 

34 

35logger = get_logger(__name__) 

36 

37DEFAULT_BRANCH_KEY = "__default__" 

38 

39UNARY_OPS: frozenset[str] = frozenset( 

40 {"exists", "not_exists", "empty", "not_empty", "truthy", "falsy"} 

41) 

42BINARY_OPS: frozenset[str] = frozenset( 

43 { 

44 "eq", 

45 "ne", 

46 "gt", 

47 "gte", 

48 "lt", 

49 "lte", 

50 "in", 

51 "not_in", 

52 "contains", 

53 "not_contains", 

54 "starts_with", 

55 "ends_with", 

56 "matches", 

57 } 

58) 

59CONDITION_OPS: frozenset[str] = UNARY_OPS | BINARY_OPS 

60 

61_PATH_RE = re.compile(r"^[a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*$") 

62 

63 

64# --------------------------------------------------------------------------- 

65# Path resolution 

66# --------------------------------------------------------------------------- 

67 

68 

69def resolve_path(path: str, variables: dict[str, Any]) -> tuple[bool, Any]: 

70 """Resolve a dotted path against ``variables``. 

71 

72 Segments index dicts by key, lists/tuples by integer, Pydantic models and 

73 plain objects by attribute. A string encountered mid-path is parsed as 

74 JSON once (tool and transform outputs are often JSON text) so 

75 ``{fetch.items.0.title}`` works without an explicit parse step. 

76 Returns ``(found, value)`` so callers can distinguish "missing" from a 

77 legitimate ``None``. 

78 """ 

79 if not path: 

80 return False, None 

81 current: Any = variables 

82 for segment in path.split("."): 

83 if isinstance(current, str): 

84 # Whole or not at all: tool and transform output is machine JSON. 

85 try: 

86 current = safe_json.loads_exact(current) 

87 except (ValueError, TypeError): 

88 return False, None 

89 if isinstance(current, dict): 

90 if segment not in current: 

91 return False, None 

92 current = current[segment] 

93 elif isinstance(current, (list, tuple)): 

94 try: 

95 current = current[int(segment)] 

96 except (ValueError, IndexError): 

97 return False, None 

98 elif isinstance(getattr(type(current), "model_fields", None), dict): 

99 if segment not in type(current).model_fields: 

100 return False, None 

101 current = getattr(current, segment) 

102 elif not segment.startswith("_") and hasattr(current, segment): 

103 current = getattr(current, segment) 

104 else: 

105 return False, None 

106 return True, current 

107 

108 

109def is_valid_path(path: str) -> bool: 

110 return bool(_PATH_RE.fullmatch(path or "")) 

111 

112 

113# --------------------------------------------------------------------------- 

114# Condition model 

115# --------------------------------------------------------------------------- 

116 

117 

118class Condition(BaseModel): 

119 """One predicate — a leaf comparison or a boolean composition.""" 

120 

121 var: str | None = None 

122 op: str | None = None 

123 value: Any = None 

124 all: list["Condition"] | None = None 

125 any: list["Condition"] | None = None 

126 not_: "Condition | None" = Field(default=None, alias="not") 

127 

128 model_config = {"populate_by_name": True} 

129 

130 @model_validator(mode="after") 

131 def _shape(self) -> "Condition": 

132 composites = [c for c in (self.all, self.any, self.not_) if c is not None] 

133 if len(composites) > 1: 

134 raise ValueError("a condition may use only one of all / any / not") 

135 if composites: 

136 if self.var is not None or self.op is not None: 

137 raise ValueError("composite conditions cannot also set var/op") 

138 if isinstance(composites[0], list) and not composites[0]: 

139 raise ValueError("all/any require at least one sub-condition") 

140 return self 

141 if not self.var: 

142 raise ValueError("leaf conditions require 'var'") 

143 if not is_valid_path(self.var): 

144 raise ValueError(f"invalid variable path {self.var!r}") 

145 if self.op not in CONDITION_OPS: 

146 raise ValueError( 

147 f"unknown op {self.op!r} — expected one of {sorted(CONDITION_OPS)}" 

148 ) 

149 if self.op in BINARY_OPS and self.value is None: 

150 raise ValueError(f"op {self.op!r} requires a 'value'") 

151 return self 

152 

153 def referenced_paths(self) -> list[str]: 

154 if self.all: 

155 return [p for c in self.all for p in c.referenced_paths()] 

156 if self.any: 

157 return [p for c in self.any for p in c.referenced_paths()] 

158 if self.not_: 

159 return self.not_.referenced_paths() 

160 return [self.var] if self.var else [] 

161 

162 

163Condition.model_rebuild() 

164 

165 

166class Branch(BaseModel): 

167 """One ordered branch of a conditional edge.""" 

168 

169 key: str 

170 target: str 

171 when: Condition | None = None # None → unconditional (always matches) 

172 description: str = "" 

173 

174 

175# --------------------------------------------------------------------------- 

176# Evaluation 

177# --------------------------------------------------------------------------- 

178 

179 

180def _as_number(value: Any) -> float | None: 

181 if isinstance(value, bool): 

182 return None 

183 if isinstance(value, (int, float)): 

184 return float(value) 

185 if isinstance(value, str): 

186 try: 

187 return float(value.strip()) 

188 except ValueError: 

189 return None 

190 return None 

191 

192 

193def _compare(op: str, left: Any, right: Any) -> bool: 

194 if op in ("eq", "ne"): 

195 equal = _loose_equal(left, right) 

196 return equal if op == "eq" else not equal 

197 if op in ("gt", "gte", "lt", "lte"): 

198 a, b = _as_number(left), _as_number(right) 

199 if a is None or b is None: 

200 # Fall back to string ordering only when both are strings 

201 if isinstance(left, str) and isinstance(right, str): 

202 a, b = left, right # type: ignore[assignment] 

203 else: 

204 return False 

205 return { 

206 "gt": a > b, 

207 "gte": a >= b, 

208 "lt": a < b, 

209 "lte": a <= b, 

210 }[op] 

211 if op in ("in", "not_in"): 

212 options = right if isinstance(right, (list, tuple, set)) else [right] 

213 hit = any(_loose_equal(left, o) for o in options) 

214 if not hit and isinstance(right, str) and isinstance(left, str): 

215 hit = left in right 

216 return hit if op == "in" else not hit 

217 if op in ("contains", "not_contains"): 

218 if isinstance(left, str): 

219 hit = str(right) in left 

220 elif isinstance(left, (list, tuple, set)): 

221 hit = any(_loose_equal(item, right) for item in left) 

222 elif isinstance(left, dict): 

223 hit = str(right) in left 

224 else: 

225 hit = False 

226 return hit if op == "contains" else not hit 

227 if op == "starts_with": 

228 return isinstance(left, str) and left.startswith(str(right)) 

229 if op == "ends_with": 

230 return isinstance(left, str) and left.endswith(str(right)) 

231 if op == "matches": 

232 try: 

233 return bool(re.search(str(right), str(left), re.IGNORECASE | re.DOTALL)) 

234 except re.error: 

235 return False 

236 return False 

237 

238 

239def _loose_equal(left: Any, right: Any) -> bool: 

240 if left == right: 

241 return True 

242 ln, rn = _as_number(left), _as_number(right) 

243 if ln is not None and rn is not None: 

244 return ln == rn 

245 if isinstance(left, bool) or isinstance(right, bool): 

246 lb = _as_bool(left) 

247 rb = _as_bool(right) 

248 return lb is not None and lb == rb 

249 if isinstance(left, str) and isinstance(right, str): 

250 return left.strip().lower() == right.strip().lower() 

251 return False 

252 

253 

254def _as_bool(value: Any) -> bool | None: 

255 if isinstance(value, bool): 

256 return value 

257 if isinstance(value, str): 

258 s = value.strip().lower() 

259 if s in ("true", "yes", "1"): 

260 return True 

261 if s in ("false", "no", "0", ""): 

262 return False 

263 if isinstance(value, (int, float)): 

264 return bool(value) 

265 return None 

266 

267 

268def _is_empty(value: Any) -> bool: 

269 if value is None: 

270 return True 

271 if isinstance(value, str): 

272 return not value.strip() 

273 if isinstance(value, (list, tuple, set, dict)): 

274 return len(value) == 0 

275 return False 

276 

277 

278def evaluate_condition( 

279 condition: Condition | dict[str, Any] | None, variables: dict[str, Any] 

280) -> bool: 

281 """Evaluate a predicate against the variable namespace. Never raises.""" 

282 if condition is None: 

283 return True 

284 try: 

285 cond = condition if isinstance(condition, Condition) else Condition(**condition) 

286 except Exception as exc: # noqa: BLE001 — malformed → false, logged 

287 logger.warning("[conditions] malformed condition %r: %s", condition, exc) 

288 return False 

289 if cond.all is not None: 

290 return all(evaluate_condition(c, variables) for c in cond.all) 

291 if cond.any is not None: 

292 return any(evaluate_condition(c, variables) for c in cond.any) 

293 if cond.not_ is not None: 

294 return not evaluate_condition(cond.not_, variables) 

295 

296 found, value = resolve_path(cond.var or "", variables) 

297 op = cond.op or "" 

298 if op == "exists": 

299 return found 

300 if op == "not_exists": 

301 return not found 

302 if not found: 

303 return op in ("empty", "falsy") 

304 if op == "empty": 

305 return _is_empty(value) 

306 if op == "not_empty": 

307 return not _is_empty(value) 

308 if op == "truthy": 

309 b = _as_bool(value) 

310 return bool(value) if b is None else b 

311 if op == "falsy": 

312 b = _as_bool(value) 

313 return (not value) if b is None else (not b) 

314 try: 

315 return _compare(op, value, cond.value) 

316 except Exception as exc: # noqa: BLE001 

317 logger.warning( 

318 "[conditions] %s %s %r failed: %s", cond.var, op, cond.value, exc 

319 ) 

320 return False 

321 

322 

323# --------------------------------------------------------------------------- 

324# Router factories (LangGraph conditional-edge functions) 

325# --------------------------------------------------------------------------- 

326 

327 

328def graph_variables(state: Any) -> dict[str, Any]: 

329 """The unified variable namespace for templates, bindings and conditions. 

330 

331 Precedence (later wins): node results → declared/written state → input. 

332 Node results are exposed under the node id so ``{node.field}`` works 

333 for structured workers; Pydantic results are dumped to dicts. 

334 """ 

335 variables: dict[str, Any] = {} 

336 for node_id, result in (getattr(state, "results", None) or {}).items(): 

337 if hasattr(result, "model_dump"): 

338 try: 

339 variables[node_id] = result.model_dump() 

340 continue 

341 except Exception: # noqa: BLE001 

342 pass 

343 variables[node_id] = result 

344 variables.update(getattr(state, "state_vars", None) or {}) 

345 variables["input"] = getattr(state, "input", "") 

346 return variables 

347 

348 

349def build_branch_router( 

350 source_id: str, 

351 branches: list[Branch | dict[str, Any]], 

352 default: str | None, 

353) -> tuple[Callable[[Any], str], dict[str, str]]: 

354 """Build a LangGraph conditional-edge function plus its path map. 

355 

356 The function returns the matched branch key (or ``DEFAULT_BRANCH_KEY``); 

357 the returned map translates keys to target node ids (``"end"`` allowed). 

358 A source without a default falls through to its first branch — the 

359 graph never dead-ends silently. 

360 """ 

361 parsed = [b if isinstance(b, Branch) else Branch(**b) for b in branches] 

362 if not parsed: 

363 raise ValueError(f"conditional edge {source_id!r} declares no branches") 

364 edge_map: dict[str, str] = {b.key: b.target for b in parsed} 

365 fallback_key = DEFAULT_BRANCH_KEY if default else parsed[0].key 

366 if default: 

367 edge_map[DEFAULT_BRANCH_KEY] = default 

368 

369 def route(state: Any) -> str: 

370 variables = graph_variables(state) 

371 for branch in parsed: 

372 if evaluate_condition(branch.when, variables): 

373 logger.info( 

374 "[conditions] %s → %r (branch %r)", 

375 source_id, 

376 branch.target, 

377 branch.key, 

378 ) 

379 return branch.key 

380 logger.info( 

381 "[conditions] %s → default %r", source_id, edge_map.get(fallback_key) 

382 ) 

383 return fallback_key 

384 

385 return route, edge_map 

386 

387 

388def build_field_router( 

389 source_id: str, 

390 route_field: str, 

391 route_keys: list[str], 

392 default: str | None = None, 

393) -> tuple[Callable[[Any], str], dict[str, str]]: 

394 """Route on a field of the source node's structured output. 

395 

396 ``route_field`` is a dotted path relative to the node result 

397 (e.g. ``"category"``); its value must be one of ``route_keys``. Anything 

398 else routes to ``default`` (when given) or the first key. 

399 """ 

400 if not route_keys: 

401 raise ValueError(f"conditional edge {source_id!r} declares no route_keys") 

402 fallback = DEFAULT_BRANCH_KEY if default else route_keys[0] 

403 

404 def route(state: Any) -> str: 

405 variables = graph_variables(state) 

406 found, value = resolve_path(f"{source_id}.{route_field}", variables) 

407 if found and value is not None: 

408 text = str(value).strip() 

409 for key in route_keys: 

410 if key == text or key.lower() == text.lower(): 

411 logger.info( 

412 "[conditions] %s.%s=%r → %r", source_id, route_field, text, key 

413 ) 

414 return key 

415 logger.warning( 

416 "[conditions] %s.%s=%r not in %s — using fallback %r", 

417 source_id, 

418 route_field, 

419 value if found else "<missing>", 

420 route_keys, 

421 fallback, 

422 ) 

423 return fallback 

424 

425 edge_map_extra = {DEFAULT_BRANCH_KEY: default} if default else {} 

426 return route, edge_map_extra