Coverage for app / routers / agent_setup.py: 97%

402 statements  

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

1""" 

2One-shot generative agent setup. 

3 

4svc-core sends a user's problem description together with catalogs of the 

5tenant's existing skills/knowledge bases/repositories/skillsets and the 

6builtin skill/agent-definition registries; a single structured-output LLM 

7call returns a complete proposed agent configuration for the user to review. 

8 

9svc-ai stays stateless with respect to tenant data — everything the generator 

10may select from arrives in the request (same contract as KnowledgeBaseSpec 

11passing at execution time). 

12""" 

13 

14from typing import Any, Literal 

15 

16from fastapi import APIRouter, Depends, HTTPException 

17from langchain_core.messages import HumanMessage, SystemMessage 

18from pydantic import BaseModel, Field, field_validator 

19from sqlalchemy.orm import Session 

20 

21from app import prompts 

22from app.services.structured_output import ModelOutput 

23from app.db.postgres.enums import InvocationEnum 

24from app.dependency.base import get_db 

25from app.mcp import is_available as mcp_available 

26from app.models.spec import ModelConfig 

27from app.services.conversation import persist_llm_invocation 

28from app.routers.knowledge_setup import CatalogSourceType 

29from app.services import rule_catalogue 

30from app.services.llm import build_langchain_llm 

31from app.services.structured_generation import ( 

32 generate, 

33) 

34from app.util import knowledge_categories, vocab 

35from app.util.knowledge_categories import KnowledgeCategory 

36from app.util.logger import get_logger 

37 

38logger = get_logger(__name__) 

39 

40router = APIRouter(prefix="/agents", tags=["agent-setup"]) 

41 

42# Wall-clock budget for the whole generation call (all attempts combined). 

43# Must undercut svc-core's 120s client timeout — anything slower is answering 

44# a caller that has already given up, while still holding an LLM connection. 

45# Read at call time by generate, so patching this constant 

46# in tests still takes effect. 

47GENERATION_BUDGET_S = 100.0 

48# A retry is only worth starting if this much budget remains; a truncated 

49# second attempt cannot produce a full config and just doubles token spend. 

50 

51 

52# --------------------------------------------------------------------------- 

53# Request models — catalogs passed in by svc-core 

54# --------------------------------------------------------------------------- 

55 

56 

57class CatalogSkill(BaseModel): 

58 id: str 

59 name: str 

60 description: str = "" 

61 tags: list[str] = [] 

62 #: Provided by the platform (svc-core ``is_system``): usable by reference, 

63 #: never to be re-proposed as a new skill. 

64 built_in: bool = False 

65 

66 

67class CatalogKnowledge(BaseModel): 

68 id: str 

69 name: str 

70 description: str = "" 

71 source_type: str = "file" 

72 

73 

74class CatalogAgentDefinition(BaseModel): 

75 name: str 

76 role: str = "worker" 

77 description: str = "" 

78 

79 

80class CatalogRepository(BaseModel): 

81 id: str 

82 name: str 

83 description: str = "" 

84 member_names: list[str] = [] 

85 #: What kind of knowledge it holds (``app/util/knowledge_categories.py``). 

86 category: str = knowledge_categories.DEFAULT.value 

87 #: A built-in repository (svc-core ``is_system``: News, the reference and 

88 #: update repositories read from publishers, the Reasoning frameworks), 

89 #: granted by reference, never re-proposed. 

90 built_in: bool = False 

91 

92 

93class CatalogSkillset(BaseModel): 

94 """Skills-only — Skillset dropped its tool/MCP-server bundling in 

95 favour of Toolkit (see CatalogToolkit below).""" 

96 

97 id: str 

98 name: str 

99 description: str = "" 

100 skill_names: list[str] = [] 

101 #: A built-in skillset (svc-core ``is_system``), grantable to any agent. 

102 built_in: bool = False 

103 

104 

105class CatalogTool(BaseModel): 

106 id: str 

107 name: str 

108 description: str = "" 

109 

110 

111class CatalogMCPServerRef(BaseModel): 

112 id: str 

113 name: str 

114 description: str = "" 

115 

116 

117class CatalogToolkit(BaseModel): 

118 id: str 

119 name: str 

120 description: str = "" 

121 tool_names: list[str] = [] 

122 mcp_server_names: list[str] = [] 

123 

124 

125class AgentConfigGenerationRequest(BaseModel): 

126 problem_description: str = Field(min_length=1) 

127 provider: str 

128 model: str 

129 # llm_models.id of the generation model, for the invocation trace 

130 model_id: str | None = None 

131 existing_skills: list[CatalogSkill] = [] 

132 existing_knowledge: list[CatalogKnowledge] = [] 

133 existing_repositories: list[CatalogRepository] = [] 

134 existing_skillsets: list[CatalogSkillset] = [] 

135 existing_tools: list[CatalogTool] = [] 

136 existing_mcp_servers: list[CatalogMCPServerRef] = [] 

137 existing_toolkits: list[CatalogToolkit] = [] 

138 agent_definitions: list[CatalogAgentDefinition] = [] 

139 # Vocabularies svc-core owns and clamps every proposed value back to — 

140 # sent with the request rather than copied here, so the prompt names 

141 # exactly what will be accepted. 

142 agent_icons: list[str] = [] 

143 repository_icons: list[str] = [] 

144 accents: list[str] = [] 

145 default_accent: str = "" 

146 source_types: list[CatalogSourceType] = [] 

147 default_source_type: str = "" 

148 rule_vocabulary: rule_catalogue.RuleVocabulary = Field( 

149 default_factory=rule_catalogue.RuleVocabulary 

150 ) 

151 user_id: str = "system" 

152 

153 

154# --------------------------------------------------------------------------- 

155# Structured-output schema 

156# 

157# Deliberately constrained: proposed skill graphs are limited to agent-type 

158# nodes with an agent_name from the request catalog. Free-form dicts and 

159# tool/transform/conditional constructs generate unreliably via function 

160# calling and are excluded from v1 — builtin templates cover those shapes. 

161# --------------------------------------------------------------------------- 

162 

163 

164class ProposedGraphNode(BaseModel): 

165 id: str = Field(description="Short snake_case node id, unique in the graph") 

166 agent_name: str = Field( 

167 description="Agent definition to run at this node (from the provided list)" 

168 ) 

169 prompt_template: str = Field( 

170 default="", description="Task for this node; {placeholders} render state" 

171 ) 

172 input_keys: list[str] = Field( 

173 default_factory=list, 

174 description='State keys surfaced to this node: "input" or upstream output_keys', 

175 ) 

176 output_key: str = Field( 

177 default="", description="Distinct state key this node writes its result to" 

178 ) 

179 description: str = "" 

180 

181 

182class ProposedGraphDefinition(BaseModel): 

183 nodes: list[ProposedGraphNode] = Field(min_length=1) 

184 edges: list[list[str]] = Field( 

185 default_factory=list, description="[from_id, to_id] pairs forming a DAG" 

186 ) 

187 start_node: str 

188 end_nodes: list[str] = Field(min_length=1) 

189 

190 

191class ProposedSkill(BaseModel): 

192 name: str 

193 description: str = "" 

194 tags: list[str] = [] 

195 graph: ProposedGraphDefinition 

196 

197 

198class ProposedKnowledgeStub(BaseModel): 

199 name: str 

200 description: str = Field( 

201 description="Must tell the user exactly what content to upload" 

202 ) 

203 source_type: str = Field( 

204 default="", description="One of the source types the system prompt lists" 

205 ) 

206 

207 

208class ProposedWorker(BaseModel): 

209 """A custom worker agent — usable as an agent_name in proposed skill graphs.""" 

210 

211 name: str 

212 description: str = "" 

213 role: str = Field( 

214 default="worker", description="Short role label, e.g. worker | researcher" 

215 ) 

216 system_prompt: str = Field( 

217 default="", 

218 description="Full system prompt; required unless base_worker is set", 

219 ) 

220 base_worker: str = Field( 

221 default="", 

222 description="Agent definition to clone defaults from (from the provided " 

223 "list); empty = built from scratch", 

224 ) 

225 tags: list[str] = [] 

226 

227 

228# Presentation and knowledge vocabularies are svc-core's and arrive with the 

229# request; the fields below are plain strings, and svc-core clamps each one 

230# back to its own lists before it reaches a row. 

231 

232 

233class ProposedRepository(BaseModel): 

234 """A named collection of knowledge bases attached to the agent as one grant.""" 

235 

236 name: str 

237 description: str = "" 

238 icon: str = Field(default="", description="One of the repository icons listed") 

239 accent: str = Field(default="", description="One of the accents listed") 

240 category: Literal[knowledge_categories.keys()] = Field( # type: ignore[valid-type] 

241 default=knowledge_categories.DEFAULT.value, 

242 description=( 

243 "What kind of knowledge it holds, which decides how the agent " 

244 "uses it:\n" + vocab.guide(knowledge_categories.PURPOSE, KnowledgeCategory) 

245 ), 

246 ) 

247 

248 @field_validator("category", mode="before") 

249 @classmethod 

250 def _unknown_kind_is_domain(cls, value: Any) -> str: 

251 # A kind the strict schema did not hold the reply to (a salvaged 

252 # one) reads as domain rather than costing the repository. 

253 return knowledge_categories.of(value).value 

254 

255 member_knowledge_ids: list[str] = Field( 

256 default_factory=list, 

257 description="Existing knowledge base ids (verbatim from the catalog)", 

258 ) 

259 member_proposed_knowledge_names: list[str] = Field( 

260 default_factory=list, 

261 description="Names of entries in proposed_knowledge to include", 

262 ) 

263 

264 

265class ProposedSkillset(BaseModel): 

266 """A named collection of skills attached to the agent as one grant. 

267 

268 Skills-only — Toolkit (see ProposedToolkit below) is the bundle type for 

269 tools/MCP servers instead. 

270 """ 

271 

272 name: str 

273 description: str = "" 

274 member_skill_ids: list[str] = Field( 

275 default_factory=list, 

276 description="Existing skill ids (verbatim from the catalog)", 

277 ) 

278 member_proposed_skill_names: list[str] = Field( 

279 default_factory=list, 

280 description="Names of entries in proposed_skills to include", 

281 ) 

282 

283 

284class ProposedToolkit(BaseModel): 

285 """A named collection of tools/MCP servers attached to the agent as one 

286 grant. 

287 

288 Existing members only: unlike ProposedSkillset (which may include 

289 newly-proposed skills), this flow can NEVER invent a new tool or MCP 

290 server — both carry live credentials only a human can configure. So 

291 there is no member_proposed_*_names field here at all. 

292 """ 

293 

294 name: str 

295 description: str = "" 

296 member_tool_ids: list[str] = Field( 

297 default_factory=list, 

298 description="Existing tool ids (verbatim from the catalog)", 

299 ) 

300 member_mcp_server_ids: list[str] = Field( 

301 default_factory=list, 

302 description="Existing MCP server ids (verbatim from the catalog)", 

303 ) 

304 

305 

306class ProposedRule(BaseModel): 

307 """A governance rule scoped to the generated agent. 

308 

309 Written in the rule catalogue svc-core sent (``rule_vocabulary``) and 

310 checked against it there — plain strings here, as in rule setup. 

311 """ 

312 

313 name: str 

314 description: str = "" 

315 layer: str 

316 conditions: list[rule_catalogue.ProposedCondition] = [] 

317 actions: list[rule_catalogue.ProposedAction] = Field(min_length=1) 

318 priority: int = 0 

319 

320 

321class GeneratedAgentConfig(ModelOutput): 

322 """The complete proposal the LLM must produce.""" 

323 

324 name: str 

325 description: str = "" 

326 icon: str = Field(default="", description="One of the agent icons listed") 

327 accent: str = Field(default="", description="One of the accents listed") 

328 system_prompt: str 

329 explanation: str = Field( 

330 default="", 

331 description="Why this proposal — written to the user.", 

332 # The model fills "explanation" (a field named for its reasoning can 

333 # be refused by Claude 5.x); svc-core reads it as "reasoning". 

334 serialization_alias="reasoning", 

335 ) 

336 selected_skill_ids: list[str] = [] 

337 selected_knowledge_ids: list[str] = [] 

338 selected_repository_ids: list[str] = [] 

339 selected_skillset_ids: list[str] = [] 

340 proposed_skills: list[ProposedSkill] = [] 

341 proposed_knowledge: list[ProposedKnowledgeStub] = [] 

342 proposed_workers: list[ProposedWorker] = [] 

343 proposed_repositories: list[ProposedRepository] = [] 

344 proposed_skillsets: list[ProposedSkillset] = [] 

345 proposed_rules: list[ProposedRule] = [] 

346 

347 

348class GeneratedAgentConfigWithToolkits(GeneratedAgentConfig): 

349 """The proposal plus toolkits — offered only while MCP servers are 

350 available (``app.mcp``). The schema is part of the prompt: a model shown 

351 a toolkit field proposes toolkits, whatever the instructions say.""" 

352 

353 selected_toolkit_ids: list[str] = [] 

354 proposed_toolkits: list[ProposedToolkit] = [] 

355 

356 

357# --------------------------------------------------------------------------- 

358# Response models — proposed skill graphs converted to storable form 

359# --------------------------------------------------------------------------- 

360 

361 

362class ProposedSkillOut(BaseModel): 

363 name: str 

364 description: str = "" 

365 tags: list[str] = [] 

366 graph_definition: dict[str, Any] 

367 

368 

369class GeneratedAgentConfigOut(BaseModel): 

370 name: str 

371 description: str = "" 

372 icon: str = "" 

373 accent: str = "" 

374 system_prompt: str 

375 reasoning: str = "" 

376 selected_skill_ids: list[str] = [] 

377 selected_knowledge_ids: list[str] = [] 

378 selected_repository_ids: list[str] = [] 

379 selected_skillset_ids: list[str] = [] 

380 selected_toolkit_ids: list[str] = [] 

381 proposed_skills: list[ProposedSkillOut] = [] 

382 proposed_knowledge: list[ProposedKnowledgeStub] = [] 

383 proposed_workers: list[ProposedWorker] = [] 

384 proposed_repositories: list[ProposedRepository] = [] 

385 proposed_skillsets: list[ProposedSkillset] = [] 

386 proposed_toolkits: list[ProposedToolkit] = [] 

387 proposed_rules: list[ProposedRule] = [] 

388 

389 

390class GenerateConfigResponse(BaseModel): 

391 config: GeneratedAgentConfigOut 

392 warnings: list[str] = [] 

393 

394 

395# --------------------------------------------------------------------------- 

396# Graph validation + conversion 

397# --------------------------------------------------------------------------- 

398 

399 

400def _validate_proposed_graph( 

401 graph: ProposedGraphDefinition, valid_agent_names: set[str] 

402) -> list[str]: 

403 """Return a list of problems; an empty list means the graph is usable.""" 

404 problems: list[str] = [] 

405 node_ids = [n.id for n in graph.nodes] 

406 id_set = set(node_ids) 

407 

408 if len(node_ids) != len(id_set): 

409 problems.append("duplicate node ids") 

410 

411 if not valid_agent_names: 

412 problems.append("no agent definitions available for proposed skill graphs") 

413 return problems 

414 

415 for node in graph.nodes: 

416 if node.agent_name not in valid_agent_names: 

417 problems.append(f"unknown agent_name '{node.agent_name}'") 

418 if graph.start_node not in id_set: 

419 problems.append(f"start_node '{graph.start_node}' is not a node") 

420 for end in graph.end_nodes: 

421 if end not in id_set: 

422 problems.append(f"end_node '{end}' is not a node") 

423 

424 output_keys = {n.output_key for n in graph.nodes if n.output_key} 

425 for node in graph.nodes: 

426 for key in node.input_keys: 

427 if key != "input" and key not in output_keys: 

428 problems.append( 

429 f"node '{node.id}' input_key '{key}' matches no output_key" 

430 ) 

431 

432 # Edge endpoints must resolve; a "to" of "end" is normalised away later. 

433 adjacency: dict[str, list[str]] = {nid: [] for nid in id_set} 

434 for edge in graph.edges: 

435 if len(edge) != 2: 

436 problems.append(f"malformed edge {edge}") 

437 continue 

438 src, dst = edge 

439 if src not in id_set: 

440 problems.append(f"edge source '{src}' is not a node") 

441 continue 

442 if dst == "end": 

443 continue 

444 if dst not in id_set: 

445 problems.append(f"edge target '{dst}' is not a node") 

446 continue 

447 adjacency[src].append(dst) 

448 

449 # Cycle check (iterative DFS) — a cyclic graph would loop at execution. 

450 if not problems: 

451 visiting: set[str] = set() 

452 done: set[str] = set() 

453 for root in id_set: 

454 if root in done: 

455 continue 

456 stack: list[tuple[str, int]] = [(root, 0)] 

457 visiting.add(root) 

458 while stack: 

459 node_id, idx = stack[-1] 

460 if idx < len(adjacency[node_id]): 

461 stack[-1] = (node_id, idx + 1) 

462 child = adjacency[node_id][idx] 

463 if child in visiting: 

464 problems.append("graph contains a cycle") 

465 stack.clear() 

466 break 

467 if child not in done: 

468 visiting.add(child) 

469 stack.append((child, 0)) 

470 else: 

471 stack.pop() 

472 visiting.discard(node_id) 

473 done.add(node_id) 

474 if problems: 

475 break 

476 

477 # Reachability — a node the start cannot reach never runs, so its 

478 # output_key never materialises and downstream placeholders render empty. 

479 if not problems: 

480 reachable: set[str] = set() 

481 frontier: list[str] = [graph.start_node] 

482 while frontier: 

483 current = frontier.pop() 

484 if current in reachable: 

485 continue 

486 reachable.add(current) 

487 frontier.extend(adjacency[current]) 

488 unreachable = sorted(id_set - reachable) 

489 if unreachable: 

490 problems.append( 

491 "nodes unreachable from start_node: " + ", ".join(unreachable) 

492 ) 

493 

494 # Dataflow — an input_key must be written by a strict ancestor. The 

495 # existence check above cannot catch a key produced by a later or 

496 # parallel node, which would render as an empty placeholder at runtime. 

497 if not problems: 

498 producer_by_key: dict[str, str] = {} 

499 for node in graph.nodes: 

500 if not node.output_key: 

501 continue 

502 if node.output_key in producer_by_key: 

503 problems.append( 

504 f"output_key '{node.output_key}' is written by more than one node" 

505 ) 

506 producer_by_key[node.output_key] = node.id 

507 

508 def _descendants(root: str) -> set[str]: 

509 seen: set[str] = set() 

510 stack = list(adjacency[root]) 

511 while stack: 

512 current = stack.pop() 

513 if current in seen: 

514 continue 

515 seen.add(current) 

516 stack.extend(adjacency[current]) 

517 return seen 

518 

519 for node in graph.nodes: 

520 for key in node.input_keys: 

521 if key == "input": 

522 continue 

523 producer = producer_by_key.get(key) 

524 if producer and node.id not in _descendants(producer): 

525 problems.append( 

526 f"node '{node.id}' input_key '{key}' is produced by " 

527 f"'{producer}', which does not run before it" 

528 ) 

529 

530 return problems 

531 

532 

533def _to_graph_definition(graph: ProposedGraphDefinition) -> dict[str, Any]: 

534 """Convert to the storable v2 dict consumed by 

535 AgentFactory.from_graph_definition.""" 

536 end_nodes = list(dict.fromkeys(graph.end_nodes)) 

537 edges: list[list[str]] = [] 

538 for src, dst in (e for e in graph.edges if len(e) == 2): 

539 if dst == "end": 

540 # Termination is expressed via end_nodes, not an "end" pseudo-node. 

541 if src not in end_nodes: 

542 end_nodes.append(src) 

543 continue 

544 edges.append([src, dst]) 

545 return { 

546 "nodes": { 

547 node.id: { 

548 "type": "agent", 

549 "agent_name": node.agent_name, 

550 "prompt_template": node.prompt_template, 

551 "input_keys": node.input_keys, 

552 "output_key": node.output_key, 

553 "description": node.description, 

554 } 

555 for node in graph.nodes 

556 }, 

557 "edges": edges, 

558 "start_node": graph.start_node, 

559 "end_nodes": end_nodes, 

560 } 

561 

562 

563# --------------------------------------------------------------------------- 

564# Worker / repository / rule validation 

565# --------------------------------------------------------------------------- 

566 

567 

568def _validate_proposed_workers( 

569 workers: list[ProposedWorker], valid_base_names: set[str] 

570) -> tuple[list[ProposedWorker], list[str]]: 

571 """Keep only usable worker proposals; duplicates and unknown bases drop.""" 

572 kept: list[ProposedWorker] = [] 

573 warnings: list[str] = [] 

574 seen_names: set[str] = set() 

575 for worker in workers: 

576 if worker.name in seen_names: 

577 warnings.append(f"Dropped duplicate proposed worker '{worker.name}'.") 

578 continue 

579 if worker.base_worker and worker.base_worker not in valid_base_names: 

580 warnings.append( 

581 f"Dropped proposed worker '{worker.name}': unknown base_worker " 

582 f"'{worker.base_worker}'." 

583 ) 

584 continue 

585 if not worker.base_worker and not worker.system_prompt.strip(): 

586 warnings.append( 

587 f"Dropped proposed worker '{worker.name}': a worker built from " 

588 "scratch needs a system_prompt." 

589 ) 

590 continue 

591 seen_names.add(worker.name) 

592 kept.append(worker) 

593 return kept, warnings 

594 

595 

596def _validate_proposed_repositories( 

597 repositories: list[ProposedRepository], 

598 known_knowledge_ids: set[str], 

599 proposed_knowledge_names: set[str], 

600) -> tuple[list[ProposedRepository], list[str]]: 

601 """Drop hallucinated members; a repository with no members left drops too.""" 

602 kept: list[ProposedRepository] = [] 

603 warnings: list[str] = [] 

604 for repo in repositories: 

605 member_ids = [i for i in repo.member_knowledge_ids if i in known_knowledge_ids] 

606 for unknown in set(repo.member_knowledge_ids) - set(member_ids): 

607 warnings.append( 

608 f"Dropped unknown knowledge id '{unknown}' from proposed " 

609 f"repository '{repo.name}'." 

610 ) 

611 member_names = [ 

612 n 

613 for n in repo.member_proposed_knowledge_names 

614 if n in proposed_knowledge_names 

615 ] 

616 for unknown in set(repo.member_proposed_knowledge_names) - set(member_names): 

617 warnings.append( 

618 f"Dropped unknown proposed knowledge '{unknown}' from proposed " 

619 f"repository '{repo.name}'." 

620 ) 

621 if not member_ids and not member_names: 

622 warnings.append( 

623 f"Dropped proposed repository '{repo.name}': no valid members." 

624 ) 

625 continue 

626 kept.append( 

627 ProposedRepository( 

628 name=repo.name, 

629 description=repo.description, 

630 icon=repo.icon, 

631 accent=repo.accent, 

632 category=repo.category, 

633 member_knowledge_ids=member_ids, 

634 member_proposed_knowledge_names=member_names, 

635 ) 

636 ) 

637 return kept, warnings 

638 

639 

640def _validate_proposed_skillsets( 

641 skillsets: list[ProposedSkillset], 

642 known_skill_ids: set[str], 

643 proposed_skill_names: set[str], 

644) -> tuple[list[ProposedSkillset], list[str]]: 

645 """Drop hallucinated members; a skillset with no members left drops too.""" 

646 kept: list[ProposedSkillset] = [] 

647 warnings: list[str] = [] 

648 for skillset in skillsets: 

649 member_ids = [i for i in skillset.member_skill_ids if i in known_skill_ids] 

650 for unknown in set(skillset.member_skill_ids) - set(member_ids): 

651 warnings.append( 

652 f"Dropped unknown skill id '{unknown}' from proposed " 

653 f"skillset '{skillset.name}'." 

654 ) 

655 member_names = [ 

656 n for n in skillset.member_proposed_skill_names if n in proposed_skill_names 

657 ] 

658 for unknown in set(skillset.member_proposed_skill_names) - set(member_names): 

659 warnings.append( 

660 f"Dropped unknown proposed skill '{unknown}' from proposed " 

661 f"skillset '{skillset.name}'." 

662 ) 

663 if not member_ids and not member_names: 

664 warnings.append( 

665 f"Dropped proposed skillset '{skillset.name}': no valid members." 

666 ) 

667 continue 

668 kept.append( 

669 ProposedSkillset( 

670 name=skillset.name, 

671 description=skillset.description, 

672 member_skill_ids=member_ids, 

673 member_proposed_skill_names=member_names, 

674 ) 

675 ) 

676 return kept, warnings 

677 

678 

679def _validate_proposed_toolkits( 

680 toolkits: list[ProposedToolkit], 

681 known_tool_ids: set[str], 

682 known_mcp_server_ids: set[str], 

683) -> tuple[list[ProposedToolkit], list[str]]: 

684 """Drop hallucinated members; a toolkit with no members left drops too. 

685 

686 Unlike skillsets, there is no proposed-name matching here — a toolkit's 

687 members are always existing tools/MCP servers (see ProposedToolkit). 

688 """ 

689 kept: list[ProposedToolkit] = [] 

690 warnings: list[str] = [] 

691 for toolkit in toolkits: 

692 tool_ids = [i for i in toolkit.member_tool_ids if i in known_tool_ids] 

693 for unknown in set(toolkit.member_tool_ids) - set(tool_ids): 

694 warnings.append( 

695 f"Dropped unknown tool id '{unknown}' from proposed " 

696 f"toolkit '{toolkit.name}'." 

697 ) 

698 mcp_server_ids = [ 

699 i for i in toolkit.member_mcp_server_ids if i in known_mcp_server_ids 

700 ] 

701 for unknown in set(toolkit.member_mcp_server_ids) - set(mcp_server_ids): 

702 warnings.append( 

703 f"Dropped unknown MCP server id '{unknown}' from proposed " 

704 f"toolkit '{toolkit.name}'." 

705 ) 

706 if not tool_ids and not mcp_server_ids: 

707 warnings.append( 

708 f"Dropped proposed toolkit '{toolkit.name}': no valid members." 

709 ) 

710 continue 

711 kept.append( 

712 ProposedToolkit( 

713 name=toolkit.name, 

714 description=toolkit.description, 

715 member_tool_ids=tool_ids, 

716 member_mcp_server_ids=mcp_server_ids, 

717 ) 

718 ) 

719 return kept, warnings 

720 

721 

722# --------------------------------------------------------------------------- 

723# Endpoint 

724# --------------------------------------------------------------------------- 

725 

726 

727def _build_user_content(req: AgentConfigGenerationRequest) -> str: 

728 def section(title: str, items: list[BaseModel]) -> str: 

729 if not items: 

730 return f"{title}: (none)" 

731 lines = "\n".join(f" - {item.model_dump_json()}" for item in items) 

732 return f"{title}:\n{lines}" 

733 

734 # Toolkits bundle MCP servers, which are not available in this release: 

735 # their catalogs stay out of the prompt, as the toolkit sections do. 

736 toolkit_catalogs = ( 

737 section("Existing tools catalog", req.existing_tools) 

738 + "\n\n" 

739 + section("Existing MCP servers catalog", req.existing_mcp_servers) 

740 + "\n\n" 

741 + section("Existing toolkits catalog", req.existing_toolkits) 

742 + "\n\n" 

743 if mcp_available() 

744 else "" 

745 ) 

746 return ( 

747 f"Problem description:\n{req.problem_description}\n\n" 

748 + section("Existing skills catalog", req.existing_skills) 

749 + "\n\n" 

750 + section("Existing knowledge bases catalog", req.existing_knowledge) 

751 + "\n\n" 

752 + section("Existing knowledge repositories catalog", req.existing_repositories) 

753 + "\n\n" 

754 + section("Existing skillsets catalog", req.existing_skillsets) 

755 + "\n\n" 

756 + toolkit_catalogs 

757 + section( 

758 "Available agent definitions for new skill graphs and worker bases", 

759 req.agent_definitions, 

760 ) 

761 ) 

762 

763 

764@router.post("/generate-config", response_model=GenerateConfigResponse) 

765async def generate_config( 

766 req: AgentConfigGenerationRequest, db: Session = Depends(get_db) 

767) -> GenerateConfigResponse: 

768 """Generate a complete proposed agent configuration in one structured call.""" 

769 system_prompt = prompts.build_agent_config_generator_prompt( 

770 [d.name for d in req.agent_definitions], 

771 agent_icons=req.agent_icons, 

772 repository_icons=req.repository_icons, 

773 accents=req.accents, 

774 default_accent=req.default_accent, 

775 source_types=[(t.key, t.description) for t in req.source_types], 

776 default_source_type=req.default_source_type, 

777 rule_vocabulary=rule_catalogue.render_vocabulary(req.rule_vocabulary), 

778 include_toolkits=mcp_available(), 

779 ) 

780 llm = build_langchain_llm( 

781 ModelConfig( 

782 provider=req.provider, 

783 model=req.model, 

784 temperature=0.2, 

785 max_tokens=8192, 

786 ) 

787 ) 

788 schema: type[GeneratedAgentConfig] = ( 

789 GeneratedAgentConfigWithToolkits if mcp_available() else GeneratedAgentConfig 

790 ) 

791 messages = [ 

792 SystemMessage(content=system_prompt), 

793 HumanMessage(content=_build_user_content(req)), 

794 ] 

795 

796 outcome = await generate( 

797 llm, schema, messages, purpose="agent-setup", budget_s=GENERATION_BUDGET_S 

798 ) 

799 config = outcome.config 

800 

801 # The generation call is a real LLM invocation — trace it (success or 

802 # failure) so it appears in the activity view like any execution. 

803 persist_llm_invocation( 

804 db, 

805 purpose="agent_generation", 

806 provider=req.provider, 

807 model=req.model, 

808 user_id=req.user_id, 

809 latency_ms=outcome.latency_ms, 

810 status=InvocationEnum.Status.success 

811 if config is not None 

812 else InvocationEnum.Status.error, 

813 error_detail=outcome.failure if config is None else None, 

814 request_config={ 

815 "provider": req.provider, 

816 "model": req.model, 

817 "temperature": 0.2, 

818 "max_tokens": 8192, 

819 "flow": "agent_setup.generate_config", 

820 }, 

821 # The produced output of this call is the generated configuration. 

822 output_preview=config.model_dump_json(indent=2) if config else None, 

823 ) 

824 

825 if config is None: 

826 raise HTTPException( 

827 status_code=422, 

828 detail=f"Agent configuration generation failed: {outcome.user_message}", 

829 ) 

830 

831 warnings: list[str] = [] 

832 definition_names = {d.name for d in req.agent_definitions} 

833 

834 proposed_workers, worker_warnings = _validate_proposed_workers( 

835 config.proposed_workers, definition_names 

836 ) 

837 warnings.extend(worker_warnings) 

838 

839 # Skill graphs may run kept proposed workers by name — svc-core rewrites 

840 # those references to the registered definition names on creation. 

841 valid_agent_names = definition_names | {w.name for w in proposed_workers} 

842 proposed_skills: list[ProposedSkillOut] = [] 

843 for skill in config.proposed_skills: 

844 problems = _validate_proposed_graph(skill.graph, valid_agent_names) 

845 if problems: 

846 warnings.append( 

847 f"Dropped proposed skill '{skill.name}': {'; '.join(problems)}" 

848 ) 

849 continue 

850 proposed_skills.append( 

851 ProposedSkillOut( 

852 name=skill.name, 

853 description=skill.description, 

854 tags=skill.tags, 

855 graph_definition=_to_graph_definition(skill.graph), 

856 ) 

857 ) 

858 

859 proposed_repositories, repo_warnings = _validate_proposed_repositories( 

860 config.proposed_repositories, 

861 {k.id for k in req.existing_knowledge}, 

862 {k.name for k in config.proposed_knowledge}, 

863 ) 

864 warnings.extend(repo_warnings) 

865 

866 # Validate proposed-skill membership against the skills that survived 

867 # graph validation above — a skill dropped for an invalid graph must not 

868 # remain referenceable as a skillset member either. 

869 proposed_skillsets, skillset_warnings = _validate_proposed_skillsets( 

870 config.proposed_skillsets, 

871 {s.id for s in req.existing_skills}, 

872 {s.name for s in proposed_skills}, 

873 ) 

874 warnings.extend(skillset_warnings) 

875 

876 # Toolkits bundle only existing tools/MCP servers — no proposed-name 

877 # matching needed, unlike skillsets. While MCP servers are unavailable 

878 # neither the prompt nor the schema offers toolkits at all. 

879 if schema is GeneratedAgentConfigWithToolkits: 

880 selected_toolkit_ids = getattr(config, "selected_toolkit_ids", []) 

881 proposed_toolkits, toolkit_warnings = _validate_proposed_toolkits( 

882 getattr(config, "proposed_toolkits", []), 

883 {t.id for t in req.existing_tools}, 

884 {m.id for m in req.existing_mcp_servers}, 

885 ) 

886 warnings.extend(toolkit_warnings) 

887 else: 

888 selected_toolkit_ids, proposed_toolkits = [], [] 

889 

890 # Rules are svc-core's to check: it owns the vocabulary they are written 

891 # in and drops, with a warning, any rule it cannot enforce. 

892 

893 return GenerateConfigResponse( 

894 config=GeneratedAgentConfigOut( 

895 name=config.name, 

896 description=config.description, 

897 icon=config.icon, 

898 accent=config.accent, 

899 system_prompt=config.system_prompt, 

900 reasoning=config.explanation, 

901 selected_skill_ids=config.selected_skill_ids, 

902 selected_knowledge_ids=config.selected_knowledge_ids, 

903 selected_repository_ids=config.selected_repository_ids, 

904 selected_skillset_ids=config.selected_skillset_ids, 

905 selected_toolkit_ids=selected_toolkit_ids, 

906 proposed_skills=proposed_skills, 

907 proposed_knowledge=config.proposed_knowledge, 

908 proposed_workers=proposed_workers, 

909 proposed_repositories=proposed_repositories, 

910 proposed_skillsets=proposed_skillsets, 

911 proposed_toolkits=proposed_toolkits, 

912 proposed_rules=config.proposed_rules, 

913 ), 

914 warnings=warnings, 

915 )