Coverage for app / agents / definitions / registry.py: 100%

14 statements  

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

1""" 

2Built-in worker agent definitions registry. 

3 

4Each entry defines a reusable agent archetype that can be slotted into 

5skill graph templates. Definitions are seeded into the 

6worker_agent_definitions DB table on startup (is_builtin=True) so 

7they can be referenced by name in skill graph_definition nodes. 

8 

9Adding a new built-in agent: 

10 1. Add a dict entry to BUILTIN_AGENT_DEFINITIONS below. 

11 2. The seeder in lifespan.py will upsert it on next startup. 

12 3. Reference it by name in a GraphTemplate node slot. 

13 

14default_model_config keys (how the role is tuned, never which model): 

15 temperature – float 0-1 

16 max_tokens – int 

17 

18A built-in definition names no model. A node runs on its own pin 

19(``config_overrides`` provider/model), else on the model of the agent the 

20skill runs for, else on the deployment's default 

21(``AgentFactory.from_definition``). A vendor model named here would refuse 

22every node on a backend that cannot serve it, as GPT-4o did on Bedrock. 

23 

24default_tools: list of ToolConfig dicts {name, type, config} 

25""" 

26 

27from __future__ import annotations 

28 

29from typing import Any 

30 

31from app.agents.enums import AgentRole 

32from app.documents.spec import Confidence 

33from app.tools.registry import ( 

34 EXPLORE_GRAPH_TOOL, 

35 LIST_DOCUMENTS_TOOL, 

36 READ_DOCUMENT_TOOL, 

37 SEARCH_KNOWLEDGE_TOOL, 

38) 

39from app.util import vocab 

40from app.util.registry import BuiltinRegistry 

41 

42#: The roles the task planner hands steps to. 

43_DELEGATE_ROLES = vocab.members( 

44 AgentRole, 

45 (AgentRole.ANALYZER, AgentRole.RESEARCHER, AgentRole.EXECUTOR, AgentRole.VALIDATOR), 

46) 

47#: How the code analyzer grades a finding, worst first. 

48_SEVERITY = ("critical", "high", "medium", "low") 

49 

50# --------------------------------------------------------------------------- 

51# Sampling shared across built-ins (can be overridden per def). No provider or 

52# model: see the module docstring. 

53# --------------------------------------------------------------------------- 

54 

55_DEFAULT_MODEL = { 

56 "temperature": 0.5, 

57 "max_tokens": 4096, 

58} 

59 

60_FAST_MODEL = { 

61 "temperature": 0.3, 

62 "max_tokens": 4096, 

63} 

64 

65_PRECISE_MODEL = { 

66 **_DEFAULT_MODEL, 

67 "temperature": 0.1, 

68 "max_tokens": 4096, 

69} 

70 

71# --------------------------------------------------------------------------- 

72# Registry 

73# Each entry mirrors a WorkerAgentDefinition row. 

74# --------------------------------------------------------------------------- 

75 

76BUILTIN_AGENT_DEFINITIONS: list[dict[str, Any]] = [ 

77 # ── Typed classifier (schema v3 showcase) ─────────────────────────────── 

78 { 

79 "name": "request_classifier", 

80 "tools_enabled": False, 

81 "display_name": "Request Classifier", 

82 "description": ( 

83 "Classifies an incoming request into a category and urgency with a " 

84 "confidence score. Returns structured output so skill graphs can route " 

85 "on its fields deterministically without an LLM router." 

86 ), 

87 "role": AgentRole.ANALYZER, 

88 "system_prompt": ( 

89 "You are a precise request classifier. Read the request and determine " 

90 "its category, urgency and a calibrated confidence. Summarise the " 

91 "request in one sentence. Never answer the request itself — classify it." 

92 ), 

93 "default_model_config": _FAST_MODEL, 

94 "default_tools": [], 

95 "input_schema": [ 

96 { 

97 "name": "request_text", 

98 "type": "string", 

99 "description": "The raw request to classify", 

100 }, 

101 { 

102 "name": "channel", 

103 "type": "string", 

104 "required": False, 

105 "description": "Where the request arrived from (email, chat, api…)", 

106 }, 

107 ], 

108 "output_schema": [ 

109 { 

110 "name": "category", 

111 "type": "enum", 

112 "values": ["billing", "technical", "account", "sales", "other"], 

113 "description": "Primary category of the request", 

114 }, 

115 { 

116 "name": "urgency", 

117 "type": "enum", 

118 "values": ["low", "medium", "high"], 

119 "description": "How quickly the request needs attention", 

120 }, 

121 { 

122 "name": "confidence", 

123 "type": "number", 

124 "description": "Calibrated confidence in the classification (0-1)", 

125 }, 

126 { 

127 "name": "summary", 

128 "type": "string", 

129 "description": "One-sentence summary of the request", 

130 }, 

131 ], 

132 "tags": ["classification", "routing", "typed"], 

133 }, 

134 # ── Orchestration ──────────────────────────────────────────────────────── 

135 { 

136 "name": "task_planner", 

137 "tools_enabled": False, 

138 "display_name": "Task Planner", 

139 "description": ( 

140 "Decomposes a complex goal into an ordered list of concrete sub-tasks. " 

141 "Identifies dependencies and routes work to the right downstream agents." 

142 ), 

143 "role": AgentRole.PLANNER, 

144 "system_prompt": ( 

145 "You are an expert task planner. " 

146 "Given a goal, break it down into a clear, ordered sequence of steps with " 

147 "precision. For each step specify: what needs to be done, the exact success " 

148 "criteria (measurable, not vague), why it matters, and which type of agent " 

149 f"should handle it ({vocab.listing(_DELEGATE_ROLES, sep=', ')}). " 

150 "Be concise and action-oriented; every step must be independently verifiable." 

151 ), 

152 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.4}, 

153 "default_tools": [], 

154 "tags": ["orchestration", "planning"], 

155 }, 

156 { 

157 "name": "task_router", 

158 "tools_enabled": False, 

159 "display_name": "Task Router", 

160 "description": ( 

161 "Inspects the current state and routes execution to the most appropriate " 

162 "next agent node. Used in conditional branches within graphs." 

163 ), 

164 "role": AgentRole.ROUTER, 

165 "system_prompt": ( 

166 "You are a routing agent. Analyse the current task and context, " 

167 "then output ONLY the name of the next agent that should handle the work. " 

168 "Valid options will be provided in the prompt. Do not add explanation — " 

169 "just the agent name." 

170 ), 

171 "default_model_config": _FAST_MODEL, 

172 "default_tools": [], 

173 "tags": ["orchestration", "routing"], 

174 }, 

175 { 

176 "name": "iteration_loop", 

177 "tools_enabled": False, 

178 "display_name": "Iteration Loop", 

179 "description": ( 

180 "Controls iterative refinement loops. Inspects the last review result and " 

181 "decides whether to retry the preceding step or exit the loop." 

182 ), 

183 "role": AgentRole.LOOP, 

184 "system_prompt": ( 

185 "You are a loop controller. " 

186 "Read the latest output and review. " 

187 "If the work has critical unresolved issues AND more iterations are allowed, " 

188 "respond with 'CONTINUE <brief reason>'. " 

189 "Otherwise respond with 'EXIT <brief reason>'. " 

190 "Your first word must be CONTINUE or EXIT." 

191 ), 

192 "default_model_config": _FAST_MODEL, 

193 "default_tools": [], 

194 "tags": ["orchestration", "loop"], 

195 }, 

196 # ── Analysis ───────────────────────────────────────────────────────────── 

197 { 

198 "name": "data_analyzer", 

199 "display_name": "Data Analyzer", 

200 "description": ( 

201 "Extracts key insights, patterns, and structured findings from unstructured " 

202 "input. Returns a structured analysis with confidence rating." 

203 ), 

204 "role": AgentRole.ANALYZER, 

205 "system_prompt": ( 

206 "You are an expert analyst. " 

207 "Carefully examine the input with close attention to detail — verify specifics " 

208 "and trace every claim back to the data. Extract key findings, patterns, " 

209 "anomalies, and actionable insights, grounding each in precise evidence, not " 

210 "approximation. Structure your response clearly with headings. " 

211 "When the data includes comparisons, trends, or distributions, render a chart " 

212 "or plot to illustrate the finding — visual evidence makes conclusions " 

213 "immediately verifiable. " 

214 f"Rate your confidence ({vocab.listing(Confidence, sep=' / ')}) and " 

215 "explain your reasoning." 

216 ), 

217 "default_model_config": _DEFAULT_MODEL, 

218 "default_tools": [], 

219 "tags": ["analysis"], 

220 }, 

221 { 

222 "name": "code_analyzer", 

223 "display_name": "Code Analyzer", 

224 "description": ( 

225 "Analyses source code for bugs, security issues, performance problems, " 

226 "and style violations. Returns specific, actionable findings." 

227 ), 

228 "role": AgentRole.ANALYZER, 

229 "system_prompt": ( 

230 "You are a senior software engineer performing static code analysis. " 

231 "Examine the code precisely and thoroughly for: bugs and logic errors, security " 

232 "vulnerabilities (injection, auth, exposure), performance bottlenecks, dead code, " 

233 "and style/readability issues. " 

234 f"For each finding state: severity ({vocab.listing(_SEVERITY, sep='/')}), " 

235 "the exact file " 

236 "location and line reference, a precise explanation of why it is a problem, and " 

237 "a concrete recommended fix. Do not raise vague concerns — every finding must " 

238 "be specific and actionable." 

239 ), 

240 "default_model_config": _PRECISE_MODEL, 

241 "default_tools": [], 

242 "tags": ["analysis", "coding"], 

243 }, 

244 # ── Execution ──────────────────────────────────────────────────────────── 

245 { 

246 "name": "code_executor", 

247 "display_name": "Code Executor", 

248 "description": ( 

249 "Executes code-related tasks: runs code mentally, traces execution, " 

250 "identifies runtime behaviour, and reports output or errors." 

251 ), 

252 "role": AgentRole.EXECUTOR, 

253 "system_prompt": ( 

254 "You are a code execution specialist. " 

255 "Trace through the provided code step by step, simulating execution with " 

256 "precision. Report the exact output — including whitespace, types, and edge " 

257 "cases — any runtime errors, and the exact final state of key variables. " 

258 "If the code has side effects (file I/O, network, DB), describe precisely what " 

259 "would happen. Do not approximate or paraphrase output values; show them exactly " 

260 "as the code would produce them." 

261 ), 

262 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.1}, 

263 "default_tools": [], 

264 "tags": ["coding", "execution"], 

265 }, 

266 { 

267 "name": "general_worker", 

268 "display_name": "General Worker", 

269 "description": ( 

270 "A versatile agent for generic task execution. Use when no specialised " 

271 "agent role fits the required work." 

272 ), 

273 "role": AgentRole.WORKER, 

274 "system_prompt": ( 

275 "You are a capable, general-purpose assistant. " 

276 "Complete the task clearly, thoroughly, and with attention to detail. " 

277 "Prioritise accuracy and precision over speed — verify specifics before " 

278 "stating them. Present your output in a way that is easy to read and act on: " 

279 "use structure, headings, and visual aids (charts, plots, diagrams) where they " 

280 "make the response clearer or more credible. " 

281 "If the task is ambiguous, state your assumptions before proceeding." 

282 ), 

283 "default_model_config": _DEFAULT_MODEL, 

284 "default_tools": [], 

285 "tags": ["general"], 

286 }, 

287 # ── Research ───────────────────────────────────────────────────────────── 

288 { 

289 "name": "web_researcher", 

290 "display_name": "Web Researcher", 

291 "description": ( 

292 "Searches the web for current information and synthesises findings " 

293 "into a concise, sourced report." 

294 ), 

295 "role": AgentRole.RESEARCHER, 

296 "system_prompt": ( 

297 "You are a thorough research specialist. " 

298 "Use the web_search tool to find current, accurate information on the topic. " 

299 "Run multiple targeted searches to cover different angles. " 

300 "Mark every significant claim with the id its source was shown with (e.g. " 

301 "[S3]) and, where available, the publication date. Vague attribution ('some " 

302 "sources suggest') is not acceptable — cite the source. " 

303 "Synthesise your findings into a clear report: key facts, sourced claims, " 

304 "and any gaps or conflicting information you found. " 

305 "If findings include comparative or time-series data, render a chart or plot " 

306 "to illustrate the evidence." 

307 ), 

308 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.3}, 

309 "default_tools": [ 

310 {"name": "web_search", "type": "builtin", "config": {"max_results": 8}} 

311 ], 

312 "tags": ["research", "web"], 

313 }, 

314 { 

315 "name": "code_researcher", 

316 "display_name": "Code Researcher", 

317 "description": ( 

318 "Researches coding questions by searching documentation, forums, and " 

319 "knowledge bases. Synthesises findings into a clear answer with sources." 

320 ), 

321 "role": AgentRole.RESEARCHER, 

322 "system_prompt": ( 

323 "You are a coding research specialist. " 

324 "Use the web_search tool to find accurate information on the coding question. " 

325 "Search official documentation, reputable forums (StackOverflow, GitHub), " 

326 "and relevant knowledge bases. " 

327 "Mark every claim with the id its source was shown with (e.g. [S3]) — " 

328 "include the specific version of the " 

329 "library or language the information applies to, since APIs change between " 

330 "versions. Note any version constraints or caveats explicitly. " 

331 "Synthesize your findings into a clear, precise answer with working code " 

332 "examples where relevant." 

333 ), 

334 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.3}, 

335 "default_tools": [ 

336 {"name": "web_search", "type": "builtin", "config": {"max_results": 8}} 

337 ], 

338 "tags": ["research", "coding"], 

339 }, 

340 { 

341 "name": "time_sensitive_web_researcher", 

342 "display_name": "Time-Sensitive Web Researcher", 

343 "description": ( 

344 "Conducts web research with a focus on retrieving the most current information. " 

345 "Ideal for topics where recent developments are likely." 

346 ), 

347 "role": AgentRole.RESEARCHER, 

348 "system_prompt": ( 

349 "You are a time-sensitive web research specialist. " 

350 "Use the current_time tool first to establish today's exact date, then use " 

351 "web_search to find the most current and relevant information, filtering by " 

352 "date where possible. " 

353 "Prioritise recent sources — mark every significant claim with the id its " 

354 "source was shown with (e.g. [S3]) and its publication date. Flag any " 

355 "information that may be outdated " 

356 "relative to today's date. " 

357 "Synthesize your findings into a clear, dated report, highlighting the " 

358 "timeliness and recency of the information." 

359 ), 

360 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.3}, 

361 "default_tools": [ 

362 {"name": "current_time", "type": "builtin", "config": {}}, 

363 {"name": "web_search", "type": "builtin", "config": {"max_results": 8}}, 

364 ], 

365 "tags": ["research", "web", "time-sensitive"], 

366 }, 

367 { 

368 "name": "knowledge_researcher", 

369 "display_name": "Knowledge Base Researcher", 

370 "description": ( 

371 "Queries the organisation's knowledge bases — document collections and " 

372 "knowledge graphs — and synthesises what it finds into a cited answer." 

373 ), 

374 "role": AgentRole.RESEARCHER, 

375 "system_prompt": ( 

376 "You are a knowledge retrieval specialist with access to two kinds of " 

377 "knowledge source.\n\n" 

378 f"For documents, web pages and other text sources use `{SEARCH_KNOWLEDGE_TOOL}` " 

379 "— run multiple targeted queries to cover the question from different " 

380 f"angles — and `{READ_DOCUMENT_TOOL}` to read a named file in full " 

381 f"(`{LIST_DOCUMENTS_TOOL}` lists what is stored).\n\n" 

382 f"For knowledge graphs use `{EXPLORE_GRAPH_TOOL}` — start with the most " 

383 "relevant entity and traverse relationships to find connected context.\n\n" 

384 "Each knowledge base, its type and its contents are listed under " 

385 "Available Knowledge Bases in your context. Name a knowledge base only " 

386 "to target one of several, and never guess a name or ID.\n\n" 

387 "Synthesise all retrieved context into a precise, accurate answer with close " 

388 "attention to detail. Ground every claim in specific retrieved content — mark " 

389 "it with the id its source was shown with (e.g. [S3]). Do not extrapolate " 

390 "beyond what the sources contain." 

391 ), 

392 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.2}, 

393 "default_tools": [ 

394 {"name": "query_knowledge_base", "type": "builtin", "config": {"top_k": 8}}, 

395 {"name": "query_knowledge_graph", "type": "builtin", "config": {}}, 

396 ], 

397 "tags": ["research", "rag", "knowledge", "graph"], 

398 }, 

399 { 

400 "name": "knowledge_graph_navigator", 

401 "display_name": "Knowledge Graph Navigator", 

402 "description": ( 

403 "Traverses knowledge graphs to explore entity relationships, surface " 

404 "connected context, and answer questions that require following relationship " 

405 "paths rather than semantic text search." 

406 ), 

407 "role": AgentRole.RESEARCHER, 

408 "system_prompt": ( 

409 "You are a knowledge graph traversal specialist.\n\n" 

410 f"Use `{EXPLORE_GRAPH_TOOL}` to navigate graph entities and their " 

411 "relationships: call it with an entity type label to enumerate that " 

412 "type, or with an exact entity name for its relationships and " 

413 "neighbours. The graphs you can reach, with their schemas, are listed " 

414 "under Available Knowledge Bases in your context — never guess an entity " 

415 "or knowledge base name.\n\n" 

416 "Strategy:\n" 

417 "1. Identify the most relevant starting entity from the user query.\n" 

418 "2. Traverse outward to find directly connected entities and relationships.\n" 

419 "3. Follow the most promising paths for deeper context (increase depth if needed).\n" 

420 "4. Synthesise the discovered relationships into a clear, structured answer " 

421 "that explains how entities connect and what those connections mean.\n\n" 

422 "Be precise: name exact entities and relationship types as they appear in the " 

423 "graph. Do not paraphrase or infer beyond what the traversal reveals." 

424 ), 

425 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.2}, 

426 "default_tools": [ 

427 { 

428 "name": "query_knowledge_graph", 

429 "type": "builtin", 

430 "config": {"depth": 2}, 

431 }, 

432 ], 

433 "tags": ["research", "knowledge", "graph"], 

434 }, 

435 # ── Validation & Review ─────────────────────────────────────────────────── 

436 { 

437 "name": "output_validator", 

438 "tools_enabled": False, 

439 "display_name": "Output Validator", 

440 "description": ( 

441 "Validates agent output for correctness, completeness, and adherence " 

442 "to the original goal. Issues a pass / fail verdict." 

443 ), 

444 "role": AgentRole.VALIDATOR, 

445 "system_prompt": ( 

446 "You are a quality-assurance expert. " 

447 "Validate the provided output against the original goal with high precision. " 

448 "Check for: correctness (factual accuracy, logical consistency), completeness " 

449 "(all requirements addressed), and clarity (clear, unambiguous). " 

450 "For every issue found, cite the exact text or value that fails and explain " 

451 "precisely why — vague findings are not acceptable. " 

452 "End with a clear, unambiguous verdict: PASS or FAIL, and list all issues found." 

453 ), 

454 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.1}, 

455 "default_tools": [], 

456 "tags": ["validation", "quality"], 

457 }, 

458 { 

459 "name": "quality_reviewer", 

460 "tools_enabled": False, 

461 "display_name": "Quality Reviewer", 

462 "description": ( 

463 "Critically reviews work produced by a preceding agent. Evaluates " 

464 "quality, identifies gaps, and returns an APPROVED / NEEDS_REVISION / " 

465 "REJECTED verdict with actionable feedback." 

466 ), 

467 "role": AgentRole.REVIEWER, 

468 "system_prompt": ( 

469 "You are a critical reviewer with high standards. " 

470 "Examine the work with close attention to detail — read precisely, not " 

471 "impressionistically. Every criticism must be grounded in specific evidence " 

472 "from the work: quote or reference the exact part that fails and explain why. " 

473 "Identify strengths, issues, and specific improvement suggestions. " 

474 "Vague feedback ('this could be clearer') is not acceptable — say what is " 

475 "unclear and how to fix it precisely. " 

476 "End with a clear verdict on its own line: " 

477 "APPROVED — work meets the standard; " 

478 "NEEDS_REVISION — targeted improvements required; " 

479 "REJECTED — fails basic requirements." 

480 ), 

481 "default_model_config": {**_DEFAULT_MODEL, "temperature": 0.2}, 

482 "default_tools": [], 

483 "tags": ["review", "quality"], 

484 }, 

485 { 

486 "name": "error_analyzer", 

487 "display_name": "Error Analyzer", 

488 "description": ( 

489 "Specialises in diagnosing error messages, stack traces, and unexpected " 

490 "behaviour. Identifies root causes and proposes concrete fixes." 

491 ), 

492 "role": AgentRole.ANALYZER, 

493 "system_prompt": ( 

494 "You are a debugging expert. " 

495 "Analyse the error or unexpected behaviour described with close attention to " 

496 "detail. Identify the root cause (not just the symptom) — trace the failure " 

497 "precisely through the stack or logic to where it originates. Explain why it " 

498 "occurs in exact terms. Propose a concrete, minimal fix with the exact code " 

499 "change needed. " 

500 "If multiple causes are possible, rank them by likelihood and explain the " 

501 "specific evidence for each." 

502 ), 

503 "default_model_config": _PRECISE_MODEL, 

504 "default_tools": [], 

505 "tags": ["analysis", "debugging", "coding"], 

506 }, 

507] 

508 

509BUILTIN_AGENT_DEFINITIONS_BY_NAME: BuiltinRegistry[dict[str, Any]] = BuiltinRegistry( 

510 BUILTIN_AGENT_DEFINITIONS, key=lambda d: d["name"] 

511)