Coverage for app / skills / registry.py: 98%

54 statements  

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

1""" 

2Skills registry — modular graph workflow templates. 

3 

4A skill is a named, reusable multi-agent graph workflow. The registry 

5defines *templates*: lightweight blueprints that specify which agent 

6definition sits at each node, how nodes connect, and where the graph 

7starts and ends. 

8 

9Key concepts 

10------------ 

11GraphNodeSlot 

12 A single node position in a template. References a built-in agent 

13 definition by name (``default_agent_name``) while allowing per-node 

14 overrides. Users can swap ``default_agent_name`` for any compatible 

15 definition when customising a skill. 

16 

17GraphTemplate 

18 A complete workflow blueprint: ordered node slots, edges, start/end 

19 pointers, and human-readable metadata. 

20 

21graph_definition (stored in svc-core Skill table) 

22 The serialised form of a resolved template, stored as JSON: 

23 

24 { 

25 "nodes": { 

26 "<node_id>": { 

27 "agent_name": "<WorkerAgentDefinition.name>", 

28 "config_overrides": { 

29 "system_prompt": "...", // optional — overrides definition prompt 

30 "temperature": 0.1, // optional — overrides model config 

31 ... 

32 } 

33 } 

34 }, 

35 "edges": [["<from>", "<to>"], ...], 

36 "start_node": "<node_id>", 

37 "end_nodes": ["<node_id>", ...] 

38 } 

39 

40 ``agent_name`` is resolved to a WorkerAgentDefinition at execution 

41 time, keeping the stored definition lightweight. ``system_prompt`` 

42 inside ``config_overrides`` overrides the definition's system prompt for 

43 that node only — all other keys are forwarded to the model config. 

44 

45Adding a new template 

46--------------------- 

471. Add a ``GraphTemplate`` to ``BUILTIN_SKILL_TEMPLATES`` below. 

482. Reference only agent names that exist in 

49 ``BUILTIN_AGENT_DEFINITIONS_BY_NAME`` (a transform / tool node leaves 

50 ``default_agent_name`` empty). 

513. Call ``template.to_graph_definition()`` to get the storable dict. 

524. A template is a *pattern* to start a skill from — it is copied, never run 

53 or granted. Something useful to run as it stands is a built-in skill 

54 instead (svc-core ``system_resources/skillsets.py``). Keep the set small: 

55 one template per graph technique worth learning, each with a declared 

56 ``interface`` so a skill started from it has a Run form. 

57""" 

58 

59from __future__ import annotations 

60 

61from dataclasses import dataclass, field 

62from typing import Any 

63 

64from app.agents.definitions.registry import BUILTIN_AGENT_DEFINITIONS_BY_NAME 

65from app.util.registry import BuiltinRegistry 

66 

67 

68# --------------------------------------------------------------------------- 

69# Data structures 

70# --------------------------------------------------------------------------- 

71 

72 

73@dataclass 

74class GraphNodeSlot: 

75 """ 

76 A single node position within a graph template. 

77 

78 Attributes 

79 ---------- 

80 node_id: 

81 Unique identifier for this node within the template (e.g. "planner"). 

82 default_agent_name: 

83 Name of the default WorkerAgentDefinition to use at this slot. 

84 description: 

85 What this node is responsible for in the workflow. 

86 config_overrides: 

87 Optional model config overrides (temperature, max_tokens, etc.) applied 

88 on top of the agent definition's defaults. 

89 system_prompt_override: 

90 Optional system prompt that replaces the definition's default prompt for 

91 this node. Use this to specialise the agent's role within the skill's 

92 specific workflow context. 

93 """ 

94 

95 node_id: str 

96 default_agent_name: str 

97 description: str 

98 config_overrides: dict[str, Any] = field(default_factory=dict) 

99 system_prompt_override: str = "" 

100 # Schema v2/v3 node fields merged verbatim into the graph_definition 

101 # node: type / tool / operation / inputs / output_key / prompt_template / 

102 # input_keys / output_schema … (agent_name comes from default_agent_name) 

103 node_config: dict[str, Any] = field(default_factory=dict) 

104 

105 

106@dataclass 

107class GraphTemplate: 

108 """ 

109 A reusable multi-agent graph workflow blueprint. 

110 

111 Attributes 

112 ---------- 

113 name: 

114 Canonical snake_case identifier (e.g. "debugging"). 

115 display_name: 

116 Human-readable label shown in the UI. 

117 description: 

118 What the workflow accomplishes. 

119 use_case: 

120 Broad category (e.g. "coding", "research", "quality"). 

121 tags: 

122 Free-form labels for filtering. 

123 nodes: 

124 Ordered list of GraphNodeSlots — one per graph node. 

125 edges: 

126 Unconditional edges as (from_node_id, to_node_id) pairs. 

127 start_node: 

128 ID of the entry node. 

129 end_nodes: 

130 IDs of terminal nodes. 

131 """ 

132 

133 name: str 

134 display_name: str 

135 description: str 

136 use_case: str 

137 tags: list[str] 

138 nodes: list[GraphNodeSlot] 

139 edges: list[tuple[str, str]] 

140 start_node: str 

141 end_nodes: list[str] 

142 # Schema v2/v3 graph-level blocks (all optional) 

143 state: dict[str, Any] = field(default_factory=dict) 

144 conditional_edges: dict[str, Any] = field(default_factory=dict) 

145 interface: dict[str, Any] = field(default_factory=dict) 

146 

147 # ------------------------------------------------------------------ 

148 # Serialisation helpers 

149 # ------------------------------------------------------------------ 

150 

151 def to_graph_definition(self) -> dict[str, Any]: 

152 """ 

153 Produce the ``graph_definition`` dict stored in svc-core's Skill table. 

154 

155 The format is deliberately lightweight — agent names rather than 

156 full AgentConfig blobs — so the stored definition stays stable 

157 even when agent system prompts or model configs are updated. 

158 """ 

159 nodes: dict[str, Any] = {} 

160 for slot in self.nodes: 

161 overrides = dict(slot.config_overrides) 

162 if slot.system_prompt_override: 

163 overrides["system_prompt"] = slot.system_prompt_override 

164 node: dict[str, Any] = { 

165 "agent_name": slot.default_agent_name, 

166 "config_overrides": overrides, 

167 } 

168 if slot.description and slot.node_config: 

169 node["description"] = slot.description 

170 node.update(slot.node_config) 

171 nodes[slot.node_id] = node 

172 definition: dict[str, Any] = { 

173 "nodes": nodes, 

174 "edges": [list(e) for e in self.edges], 

175 "start_node": self.start_node, 

176 "end_nodes": self.end_nodes, 

177 } 

178 if self.state: 

179 definition["state"] = dict(self.state) 

180 if self.conditional_edges: 

181 definition["conditional_edges"] = dict(self.conditional_edges) 

182 if self.interface: 

183 definition["interface"] = dict(self.interface) 

184 return definition 

185 

186 def node_slots_with_definitions(self) -> list[dict[str, Any]]: 

187 """ 

188 Return each node slot enriched with its default agent definition metadata. 

189 Used by the /skills/available endpoint to give the frontend full context. 

190 """ 

191 result = [] 

192 for slot in self.nodes: 

193 defn = BUILTIN_AGENT_DEFINITIONS_BY_NAME.get(slot.default_agent_name, {}) 

194 result.append( 

195 { 

196 "node_id": slot.node_id, 

197 "description": slot.description, 

198 "default_agent_name": slot.default_agent_name, 

199 "default_agent_display_name": defn.get( 

200 "display_name", slot.default_agent_name 

201 ), 

202 "default_agent_role": defn.get("role", "worker"), 

203 "default_agent_description": defn.get("description", ""), 

204 "config_overrides": slot.config_overrides, 

205 } 

206 ) 

207 return result 

208 

209 

210# --------------------------------------------------------------------------- 

211# Built-in templates 

212# --------------------------------------------------------------------------- 

213 

214_BUILTIN_SKILL_TEMPLATES: dict[str, GraphTemplate] = { 

215 # ── Classify and route: a structured output decides the path ─────────── 

216 "request_triage": GraphTemplate( 

217 name="request_triage", 

218 display_name="Classify and route", 

219 description=( 

220 "Classify an incoming request with a typed classifier, then route " 

221 "deterministically on its structured output: urgent requests go to an " 

222 "escalation writer, everything else to a specialist responder. " 

223 "Demonstrates typed worker interfaces, input bindings and conditional " 

224 "branches — no LLM router call is needed to pick the path." 

225 ), 

226 use_case="pattern", 

227 tags=["triage", "routing", "support", "typed"], 

228 interface={ 

229 "inputs": [ 

230 { 

231 "name": "channel", 

232 "type": "enum", 

233 "values": ["email", "chat", "api"], 

234 "required": False, 

235 "default": "chat", 

236 "description": "Where the request arrived from", 

237 } 

238 ], 

239 "outputs": [ 

240 {"name": "category", "from": "classify.category"}, 

241 {"name": "urgency", "from": "classify.urgency"}, 

242 {"name": "response", "from": "final_response"}, 

243 ], 

244 }, 

245 nodes=[ 

246 GraphNodeSlot( 

247 node_id="classify", 

248 default_agent_name="request_classifier", 

249 description=( 

250 "Classify the request into a category and urgency with a " 

251 "confidence score (structured output)." 

252 ), 

253 node_config={ 

254 "inputs": {"request_text": "{input}", "channel": "{channel}"}, 

255 "output_key": "classification", 

256 }, 

257 ), 

258 GraphNodeSlot( 

259 node_id="escalate", 

260 default_agent_name="general_worker", 

261 description="Write an escalation brief for urgent or low-confidence requests.", 

262 system_prompt_override=( 

263 "You write concise escalation briefs for a human on-call team. " 

264 "State the category, why it is urgent, what is known, and the " 

265 "recommended next action. Be factual and brief." 

266 ), 

267 node_config={ 

268 "inputs": { 

269 "classification": "{classify}", 

270 "request_text": "{input}", 

271 }, 

272 "output_key": "final_response", 

273 }, 

274 ), 

275 GraphNodeSlot( 

276 node_id="respond", 

277 default_agent_name="general_worker", 

278 description="Draft a direct response for routine requests.", 

279 system_prompt_override=( 

280 "You are a helpful support specialist. Using the classification " 

281 "provided, draft a clear, complete answer to the request." 

282 ), 

283 node_config={ 

284 "inputs": { 

285 "category": "{classify.category}", 

286 "summary": "{classify.summary}", 

287 "request_text": "{input}", 

288 }, 

289 "output_key": "final_response", 

290 }, 

291 ), 

292 ], 

293 edges=[], 

294 start_node="classify", 

295 end_nodes=["escalate", "respond"], 

296 conditional_edges={ 

297 "classify": { 

298 "branches": [ 

299 { 

300 "key": "urgent", 

301 "target": "escalate", 

302 "description": "High urgency always escalates", 

303 "when": { 

304 "var": "classify.urgency", 

305 "op": "eq", 

306 "value": "high", 

307 }, 

308 }, 

309 { 

310 "key": "low_confidence", 

311 "target": "escalate", 

312 "description": "Unsure classifications get a human", 

313 "when": { 

314 "var": "classify.confidence", 

315 "op": "lt", 

316 "value": 0.5, 

317 }, 

318 }, 

319 ], 

320 "default": "respond", 

321 } 

322 }, 

323 ), 

324 # ── Draft, review, revise: a structured verdict branches ─────────────── 

325 "draft_review_revise": GraphTemplate( 

326 name="draft_review_revise", 

327 display_name="Draft, review, revise", 

328 description=( 

329 "Draft the work, have a reviewer judge it against the request with a " 

330 "structured verdict, and revise only when the reviewer asks for it. " 

331 "Shows a node's typed output driving a conditional branch, and two " 

332 "branches writing the same result." 

333 ), 

334 use_case="pattern", 

335 tags=["review", "quality", "branching", "typed"], 

336 interface={ 

337 "inputs": [ 

338 { 

339 "name": "task", 

340 "type": "string", 

341 "required": True, 

342 "description": "What to produce", 

343 }, 

344 { 

345 "name": "criteria", 

346 "type": "string", 

347 "required": False, 

348 "description": "What a good result must satisfy", 

349 }, 

350 ], 

351 "outputs": [ 

352 {"name": "response", "from": "final_response"}, 

353 {"name": "verdict", "from": "review.verdict"}, 

354 {"name": "issues", "from": "review.issues"}, 

355 ], 

356 }, 

357 nodes=[ 

358 GraphNodeSlot( 

359 node_id="draft", 

360 default_agent_name="general_worker", 

361 description="Produce a complete first draft of the requested work.", 

362 system_prompt_override=( 

363 "Produce the requested work in full. Meet every requirement " 

364 "and criterion stated in the request." 

365 ), 

366 node_config={"prompt_template": "{input}", "output_key": "draft"}, 

367 ), 

368 GraphNodeSlot( 

369 node_id="review", 

370 default_agent_name="quality_reviewer", 

371 description="Judge the draft and list what must change (structured).", 

372 config_overrides={"temperature": 0.1}, 

373 system_prompt_override=( 

374 "You review a draft against the request and any criteria in " 

375 "it. List only concrete, fixable issues. Answer 'approve' when " 

376 "nothing material needs to change, otherwise 'revise'." 

377 ), 

378 node_config={ 

379 "prompt_template": "Request:\n{input}\n\nDraft:\n{draft}", 

380 "output_schema": [ 

381 { 

382 "name": "verdict", 

383 "type": "enum", 

384 "values": ["approve", "revise"], 

385 "required": True, 

386 }, 

387 { 

388 "name": "issues", 

389 "type": "array", 

390 "items": "string", 

391 "description": "Each issue to fix, one per item", 

392 }, 

393 ], 

394 "output_key": "assessment", 

395 }, 

396 ), 

397 GraphNodeSlot( 

398 node_id="revise", 

399 default_agent_name="general_worker", 

400 description="Rewrite the draft, fixing every issue the reviewer raised.", 

401 system_prompt_override=( 

402 "Revise the draft to fix every listed issue. Change nothing " 

403 "else, and return the complete revised work." 

404 ), 

405 node_config={ 

406 "prompt_template": ( 

407 "Request:\n{input}\n\nDraft:\n{draft}\n\n" 

408 "Issues to fix:\n{review.issues}" 

409 ), 

410 "output_key": "final_response", 

411 }, 

412 ), 

413 GraphNodeSlot( 

414 node_id="publish", 

415 default_agent_name="", 

416 description="Approved as drafted: the draft is the result (no model call).", 

417 node_config={ 

418 "type": "transform", 

419 "operation": {"op": "select", "key": "draft"}, 

420 "output_key": "final_response", 

421 }, 

422 ), 

423 ], 

424 edges=[("draft", "review")], 

425 start_node="draft", 

426 end_nodes=["revise", "publish"], 

427 conditional_edges={ 

428 "review": { 

429 "branches": [ 

430 { 

431 "key": "revise", 

432 "target": "revise", 

433 "description": "The reviewer asked for changes", 

434 "when": { 

435 "var": "review.verdict", 

436 "op": "eq", 

437 "value": "revise", 

438 }, 

439 } 

440 ], 

441 "default": "publish", 

442 } 

443 }, 

444 ), 

445 # ── Fan out and merge: parallel branches, one synthesis ──────────────── 

446 "fan_out_and_merge": GraphTemplate( 

447 name="fan_out_and_merge", 

448 display_name="Research in parallel, then merge", 

449 description=( 

450 "Frame the question, research three angles at the same time — the " 

451 "evidence, the competing views and the risks — and merge them into " 

452 "one answer. Shows fan-out from one node and fan-in to another." 

453 ), 

454 use_case="pattern", 

455 tags=["research", "parallel", "synthesis"], 

456 interface={ 

457 "inputs": [ 

458 { 

459 "name": "question", 

460 "type": "string", 

461 "required": True, 

462 "description": "The question to research", 

463 } 

464 ], 

465 "outputs": [{"name": "answer", "from": "final_response"}], 

466 }, 

467 nodes=[ 

468 GraphNodeSlot( 

469 node_id="frame", 

470 default_agent_name="task_planner", 

471 description="Pin down the question and what each angle should find.", 

472 config_overrides={"temperature": 0.2}, 

473 system_prompt_override=( 

474 "Restate the question precisely, then say in one or two lines " 

475 "each what the evidence, the competing views and the risks " 

476 "research should establish. Be brief." 

477 ), 

478 node_config={"prompt_template": "{input}", "output_key": "brief"}, 

479 ), 

480 GraphNodeSlot( 

481 node_id="evidence", 

482 default_agent_name="web_researcher", 

483 description="Gather the facts and figures, with sources.", 

484 node_config={ 

485 "prompt_template": ( 

486 "Question:\n{input}\n\nBrief:\n{brief}\n\n" 

487 "Your angle: the facts, figures and primary evidence." 

488 ), 

489 "output_key": "evidence", 

490 }, 

491 ), 

492 GraphNodeSlot( 

493 node_id="perspectives", 

494 default_agent_name="web_researcher", 

495 description="Gather expert views, disagreements and critiques.", 

496 node_config={ 

497 "prompt_template": ( 

498 "Question:\n{input}\n\nBrief:\n{brief}\n\n" 

499 "Your angle: what informed people argue, where they " 

500 "disagree, and the strongest critiques." 

501 ), 

502 "output_key": "perspectives", 

503 }, 

504 ), 

505 GraphNodeSlot( 

506 node_id="risks", 

507 default_agent_name="general_worker", 

508 description="Think through risks, limits and unknowns.", 

509 node_config={ 

510 "prompt_template": ( 

511 "Question:\n{input}\n\nBrief:\n{brief}\n\n" 

512 "Your angle: the risks, limitations, failure modes and " 

513 "open unknowns. Reason it through; say what you assume." 

514 ), 

515 "output_key": "risk_notes", 

516 }, 

517 ), 

518 GraphNodeSlot( 

519 node_id="merge", 

520 default_agent_name="general_worker", 

521 description="Merge the three angles into one sourced answer.", 

522 system_prompt_override=( 

523 "Merge the research into one clear answer. Keep every " 

524 "source citation, say where the angles disagree, and end " 

525 "with the main risks and unknowns." 

526 ), 

527 node_config={ 

528 "prompt_template": ( 

529 "Question:\n{input}\n\nEvidence:\n{evidence}\n\n" 

530 "Perspectives:\n{perspectives}\n\nRisks:\n{risk_notes}" 

531 ), 

532 "output_key": "final_response", 

533 }, 

534 ), 

535 ], 

536 edges=[ 

537 ("frame", "evidence"), 

538 ("frame", "perspectives"), 

539 ("frame", "risks"), 

540 ("evidence", "merge"), 

541 ("perspectives", "merge"), 

542 ("risks", "merge"), 

543 ], 

544 start_node="frame", 

545 end_nodes=["merge"], 

546 ), 

547 # ── Draft, approve, finalise: a person signs off mid-run ─────────────── 

548 "approval_gate": GraphTemplate( 

549 name="approval_gate", 

550 display_name="Draft, approve, finalise", 

551 description=( 

552 "Draft the work, pause for a person to approve it — with feedback, " 

553 "or reject it to stop — and only then produce the final version. " 

554 "Shows a human-in-the-loop approval gate on a node." 

555 ), 

556 use_case="pattern", 

557 tags=["approval", "human-in-the-loop", "review"], 

558 interface={ 

559 "inputs": [ 

560 { 

561 "name": "task", 

562 "type": "string", 

563 "required": True, 

564 "description": "What to draft for approval", 

565 } 

566 ], 

567 "outputs": [ 

568 {"name": "draft", "from": "draft"}, 

569 {"name": "response", "from": "final_response"}, 

570 ], 

571 }, 

572 nodes=[ 

573 GraphNodeSlot( 

574 node_id="draft", 

575 default_agent_name="general_worker", 

576 description="Draft the work for a person to check.", 

577 node_config={"prompt_template": "{input}", "output_key": "draft"}, 

578 ), 

579 GraphNodeSlot( 

580 node_id="finalise", 

581 default_agent_name="general_worker", 

582 description="After approval: produce the final version, applying any feedback.", 

583 system_prompt_override=( 

584 "A person has approved the draft, possibly with feedback. " 

585 "Produce the final version, applying every point of the " 

586 "feedback and changing nothing else." 

587 ), 

588 node_config={ 

589 "prompt_template": "Request:\n{input}\n\nApproved draft:\n{draft}", 

590 "approval": { 

591 "message": ( 

592 "Check the draft before it is finalised. Approve to " 

593 "continue (feedback shapes the final version) or " 

594 "reject to stop the run." 

595 ) 

596 }, 

597 "output_key": "final_response", 

598 }, 

599 ), 

600 ], 

601 edges=[("draft", "finalise")], 

602 start_node="draft", 

603 end_nodes=["finalise"], 

604 ), 

605} 

606 

607BUILTIN_SKILL_TEMPLATES: BuiltinRegistry[GraphTemplate] = BuiltinRegistry( 

608 _BUILTIN_SKILL_TEMPLATES.values(), key=lambda t: t.name 

609)