Coverage for app / agents / operations.py: 96%

111 statements  

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

1""" 

2Operation nodes — deterministic, non-LLM nodes for skill graphs. 

3 

4A skill graph node does not have to be a full agent invocation. Operation 

5nodes run simple, deterministic work — a single builtin tool call or a pure 

6state transformation — at zero LLM cost. They read from and write to the 

7user-visible ``GraphState.state_vars`` dict, which is how skill graphs carry 

8typed state across nodes (mirroring LangGraph's state-channel model). 

9 

10Node types (graph_definition ``type`` field): 

11 

12 "tool" ToolOperationAgent — one builtin tool call with 

13 state-templated arguments. 

14 "transform" TransformOperationAgent — pure state operation: 

15 template | merge | select. 

16 

17Both are ``WorkerAgent`` subclasses so they slot into ``AgentGraphBuilder`` 

18unchanged, but the graph's skill-node wrapper detects ``is_operation`` and 

19executes ``run_operation(state)`` directly — skipping prompt assembly, 

20conversation threading, and the LLM tool loop entirely. 

21""" 

22 

23from __future__ import annotations 

24 

25import re 

26from collections.abc import Mapping 

27from typing import Any 

28 

29from app.agents.base import WorkerAgent 

30from app.agents.enums import AgentRole 

31from app.util import safe_json 

32from app.util.logger import get_logger 

33 

34logger = get_logger(__name__) 

35 

36 

37# --------------------------------------------------------------------------- 

38# State templating 

39# --------------------------------------------------------------------------- 

40 

41# Matches {key} / {key.path.0.field} placeholders with identifier-like names 

42# only. A regex substitution (rather than str.format) means braces that are 

43# NOT known state keys — JSON literals, code snippets, prompt examples — pass 

44# through intact. Dotted paths address fields of structured worker outputs 

45# and nested state (see app.agents.conditions.resolve_path). 

46_PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*)\}") 

47_SINGLE_PLACEHOLDER_RE = re.compile( 

48 r"^\s*\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z0-9_]+)*)\}\s*$" 

49) 

50 

51 

52def _stringify(value: Any) -> str: 

53 """Render a resolved value for text insertion. 

54 

55 Structured values (dicts / lists / Pydantic models) render as JSON so a 

56 downstream prompt sees a faithful, parseable representation rather than 

57 Python repr; ``None`` renders as "". 

58 """ 

59 if value is None: 

60 return "" 

61 if hasattr(value, "model_dump"): 

62 value = value.model_dump() 

63 if isinstance(value, (dict, list)): 

64 return safe_json.dumps(value, ensure_ascii=False, indent=2) 

65 return str(value) 

66 

67 

68def render_state_template(template: str, variables: dict[str, Any]) -> str: 

69 """Substitute ``{key}`` / ``{key.path}`` placeholders from ``variables``. 

70 

71 Unknown placeholders are left untouched so templates can safely contain 

72 literal braces. Values are stringified (JSON for structured values); 

73 ``None`` renders as "". 

74 """ 

75 from app.agents.conditions import resolve_path 

76 

77 def _sub(match: re.Match[str]) -> str: 

78 path = match.group(1) 

79 found, value = resolve_path(path, variables) 

80 if not found: 

81 return match.group(0) 

82 return _stringify(value) 

83 

84 return _PLACEHOLDER_RE.sub(_sub, template) 

85 

86 

87def template_placeholders(template: str) -> list[str]: 

88 """All ``{path}`` references in a template, in order of appearance.""" 

89 return [m.group(1) for m in _PLACEHOLDER_RE.finditer(template or "")] 

90 

91 

92def render_binding(value: Any, variables: dict[str, Any]) -> Any: 

93 """Render a node input / tool-argument binding, preserving types. 

94 

95 A string that is exactly one placeholder (``"{analysis.score}"``) resolves 

96 to the raw variable value — a number stays a number, a dict stays a dict — 

97 so typed worker inputs and tool arguments receive real values. Any other 

98 string is treated as a text template; dicts and lists are rendered 

99 recursively; every other value passes through unchanged. 

100 """ 

101 from app.agents.conditions import resolve_path 

102 

103 if isinstance(value, str): 

104 single = _SINGLE_PLACEHOLDER_RE.match(value) 

105 if single: 

106 found, resolved = resolve_path(single.group(1), variables) 

107 return resolved if found else value 

108 return render_state_template(value, variables) 

109 if isinstance(value, dict): 

110 return {k: render_binding(v, variables) for k, v in value.items()} 

111 if isinstance(value, list): 

112 return [render_binding(v, variables) for v in value] 

113 return value 

114 

115 

116def render_state_structure(value: Any, variables: dict[str, Any]) -> Any: 

117 """Recursively render string leaves of a dict/list structure. 

118 

119 Used for tool argument dicts: every string value is treated as a state 

120 binding (see ``render_binding``) so single-placeholder arguments keep 

121 their type; non-string leaves pass through unchanged. 

122 """ 

123 return render_binding(value, variables) 

124 

125 

126# --------------------------------------------------------------------------- 

127# Base class 

128# --------------------------------------------------------------------------- 

129 

130 

131class OperationAgent(WorkerAgent): 

132 """Base for deterministic skill-graph nodes that never call an LLM. 

133 

134 The graph's skill-node wrapper checks ``is_operation`` and calls 

135 ``run_operation(variables)`` with the merged state variables 

136 (``{"input": state.input, **state.state_vars}``) instead of the full 

137 agent execution path. 

138 """ 

139 

140 is_operation: bool = True 

141 

142 def __init__(self, name: str, description: str = "") -> None: 

143 # role/system_prompt feed the recon/planner node descriptors so the 

144 # system LLMs know what this node does without treating it as an agent. 

145 super().__init__( 

146 name=name, 

147 role=AgentRole.EXECUTOR, 

148 llm=None, 

149 system_prompt=description, 

150 tools=None, 

151 ) 

152 

153 async def run_operation( 

154 self, 

155 variables: dict[str, Any], 

156 *, 

157 web_config: Mapping[str, Any] | None = None, 

158 ) -> Any: 

159 """``web_config``: the run's web_search config, whose domain policy a 

160 tool that fetches takes (``registry.run_tool_config``).""" 

161 raise NotImplementedError 

162 

163 async def execute(self, input_data: Any) -> Any: 

164 # Fallback for direct invocation outside the graph (tests, ad-hoc use): 

165 # run with only the input variable available. 

166 return await self.run_operation({"input": str(input_data)}) 

167 

168 

169# --------------------------------------------------------------------------- 

170# Tool operation 

171# --------------------------------------------------------------------------- 

172 

173 

174class ToolOperationAgent(OperationAgent): 

175 """One deterministic builtin tool call with state-templated arguments. 

176 

177 graph_definition node form:: 

178 

179 { 

180 "type": "tool", 

181 "tool": { 

182 "name": "web_search", 

183 "args": {"query": "current status of {service}"}, 

184 "config": {"max_results": 5} 

185 }, 

186 "output_key": "web_news" 

187 } 

188 

189 ``args`` string values are rendered against the state variables before 

190 the call. The tool's raw string output becomes the node result. 

191 """ 

192 

193 def __init__( 

194 self, 

195 name: str, 

196 tool_name: str, 

197 args: dict[str, Any] | None = None, 

198 config: dict[str, Any] | None = None, 

199 description: str = "", 

200 ) -> None: 

201 super().__init__( 

202 name=name, 

203 description=description or f"Deterministic call to the '{tool_name}' tool.", 

204 ) 

205 self.tool_name = tool_name 

206 self.args = dict(args or {}) 

207 self.config = dict(config or {}) 

208 # An evaluation case's script for this tool (``app/agents/fixtures``): 

209 # called in its place, so nothing is fetched. 

210 self.scripted: Any = None 

211 

212 async def run_operation( 

213 self, 

214 variables: dict[str, Any], 

215 *, 

216 web_config: Mapping[str, Any] | None = None, 

217 ) -> str: 

218 from app.tools.registry import resolve_tool, run_tool_config 

219 

220 tool = ( 

221 self.scripted 

222 if self.scripted is not None 

223 else resolve_tool( 

224 self.tool_name, run_tool_config(self.tool_name, web_config, self.config) 

225 ) 

226 ) 

227 rendered_args = render_state_structure(self.args, variables) 

228 logger.info( 

229 "[operation:%s] tool=%s args=%s", 

230 self.name, 

231 self.tool_name, 

232 # The argument names, never their values (``app/util/logger.py``). 

233 sorted(rendered_args) if isinstance(rendered_args, dict) else "…", 

234 ) 

235 result = await tool.ainvoke(rendered_args) 

236 return result if isinstance(result, str) else str(result) 

237 

238 

239# --------------------------------------------------------------------------- 

240# Transform operation 

241# --------------------------------------------------------------------------- 

242 

243 

244class TransformOperationAgent(OperationAgent): 

245 """Pure state transformation — no I/O, no LLM. 

246 

247 graph_definition node form:: 

248 

249 {"type": "transform", "operation": {...}, "output_key": "report_input"} 

250 

251 Supported operations: 

252 

253 {"op": "template", "template": "KB findings:\\n{kb}\\n\\nWeb:\\n{web}"} 

254 Render a string template from state variables (dotted paths 

255 such as ``{analysis.summary}`` reach into structured outputs). 

256 

257 {"op": "merge", "keys": ["kb", "web"], "separator": "\\n\\n---\\n\\n"} 

258 Join the stringified values of the listed state keys, skipping 

259 keys that are absent or empty. 

260 

261 {"op": "select", "key": "analysis.score", "default": ""} 

262 Copy one variable (dotted path allowed) — keeps its type, so a 

263 number stays a number. Useful for renaming / narrowing state. 

264 

265 {"op": "compose", "fields": {"title": "{draft.title}", "n": "{count}"}} 

266 Build a structured object: every field is a binding (see 

267 ``render_binding``), so single-placeholder fields keep their 

268 type. The node result is a dict — downstream nodes and 

269 conditions can address ``{node_id.title}``. 

270 

271 {"op": "parse", "key": "raw_json"} 

272 Parse a JSON string held in a variable into a structured value. 

273 

274 {"op": "literal", "value": ...} 

275 Emit a constant (any JSON value) — handy for seeding state. 

276 """ 

277 

278 SUPPORTED_OPS = frozenset( 

279 {"template", "merge", "select", "compose", "parse", "literal"} 

280 ) 

281 

282 def __init__( 

283 self, 

284 name: str, 

285 operation: dict[str, Any], 

286 description: str = "", 

287 ) -> None: 

288 op = str(operation.get("op", "")) 

289 if op not in self.SUPPORTED_OPS: 

290 raise ValueError( 

291 f"Unsupported transform op {op!r} — expected one of " 

292 f"{sorted(self.SUPPORTED_OPS)}" 

293 ) 

294 super().__init__( 

295 name=name, 

296 description=description or f"State transform ({op}).", 

297 ) 

298 self.operation = dict(operation) 

299 

300 async def run_operation( 

301 self, 

302 variables: dict[str, Any], 

303 *, 

304 web_config: Mapping[str, Any] | None = None, 

305 ) -> Any: 

306 from app.agents.conditions import resolve_path 

307 

308 op = self.operation["op"] 

309 if op == "template": 

310 return render_state_template( 

311 str(self.operation.get("template", "")), variables 

312 ) 

313 if op == "merge": 

314 keys: list[str] = list(self.operation.get("keys", [])) 

315 separator = str(self.operation.get("separator", "\n\n")) 

316 parts = [] 

317 for key in keys: 

318 found, value = resolve_path(key, variables) 

319 if not found or value is None: 

320 continue 

321 text = _stringify(value) 

322 if text.strip(): 

323 parts.append(text) 

324 return separator.join(parts) 

325 if op == "compose": 

326 fields: dict[str, Any] = dict(self.operation.get("fields") or {}) 

327 return {k: render_binding(v, variables) for k, v in fields.items()} 

328 if op == "parse": 

329 found, value = resolve_path(str(self.operation.get("key", "")), variables) 

330 if not found or value is None: 

331 return self.operation.get("default") 

332 if isinstance(value, str): 

333 # The variable is usually a model's answer, which wraps JSON 

334 # in a ```json fence or a sentence often enough that a bare 

335 # json.loads aborted whole runs on valid output. 

336 try: 

337 return safe_json.loads_lenient(value) 

338 except ValueError as exc: 

339 raise ValueError( 

340 f"parse: variable {self.operation.get('key')!r} holds no JSON" 

341 ) from exc 

342 return value 

343 if op == "literal": 

344 return self.operation.get("value") 

345 # op == "select" 

346 found, value = resolve_path(str(self.operation.get("key", "")), variables) 

347 if not found or value is None: 

348 return self.operation.get("default", "") 

349 return value