Coverage for app / services / swarms / topologies / experts.py: 92%

166 statements  

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

1"""A router over a panel of experts — a mixture of experts. 

2 

3The router splits the task into questions and sends each to the experts best 

4suited to it — the first ``top_k`` it ranks, by what each agent says it is 

5for and the note its builder gave it — who answer in parallel; the router 

6then writes the answer from their answers, question by question. With 

7``samples`` above one each chosen expert answers its question several times 

8on its own; with two ``layers`` each expert answers again having read every 

9expert's first answer to its question, as a mixture-of-agents layer does. 

10 

11The literature behind it: mixtures of agents gain from layered proposers and 

12an aggregator (Wang et al., ICLR 2025), but sampling one strong model several 

13times beats mixing in weaker ones (Self-MoA, Li et al., TMLR 2026) — hence 

14gating to the best-suited experts rather than asking all, and a Self-MoA 

15preset. The presets: 

16 

17* **Routed experts** — up to four questions, each to its two best experts. 

18* **Mixture of agents** — the whole task to the three best experts, who each 

19 answer again having read the others. 

20* **Self-MoA** — the whole task to the one best expert, three times over. 

21 

22A routing of one question to one expert, answered once, is that expert's 

23answer, as a plan of one piece is: no aggregation. 

24""" 

25 

26from __future__ import annotations 

27 

28from dataclasses import replace 

29from decimal import Decimal 

30from typing import Any 

31 

32from pydantic import ValidationError 

33 

34from app.db.postgres.models import SwarmTask 

35from app.services.swarms import budget, prompts, schemas 

36from app.services.swarms.roster import Member 

37from app.services.swarms.schemas import Approach, SwarmRouting, TaskBrief 

38from app.services.swarms.topologies import ( 

39 SETTLED, 

40 Ask, 

41 AskContext, 

42 NewTask, 

43 Param, 

44 PlanSpec, 

45 Preset, 

46 RoleSlot, 

47 RunState, 

48 Step, 

49 TaskKind, 

50 TaskStatus, 

51 Topology, 

52 register_topology, 

53) 

54from app.services.swarms.topologies.units import ( 

55 COST_PROFILE_CHOICES, 

56 FINAL_KEY, 

57 TIER_CHOICES, 

58 Tier, 

59) 

60 

61ROUTER = "router" 

62EXPERT = "expert" 

63 

64ROUTE_HANDLE = "P1" 

65ANSWER_HANDLE = "S1" 

66 

67#: Which question an answer is to, which layer it is in, and which of an 

68#: expert's samples it is. 

69QUESTION_KEY = "question" 

70LAYER_KEY = "layer" 

71SAMPLE_KEY = "sample" 

72 

73#: The most answers a run's settings may ask for, leaving room within the 

74#: engine's ``MAX_TASKS``. 

75MAX_ANSWERS = 40 

76 

77 

78def _extra(task: SwarmTask, key: str, default: int) -> int: 

79 value = TaskBrief.from_stored(task.brief).extra.get(key, default) 

80 try: 

81 return int(value) 

82 except (TypeError, ValueError): 

83 return default 

84 

85 

86def _with_extra(brief: TaskBrief, **extra: Any) -> TaskBrief: 

87 return replace(brief, extra={**brief.extra, **extra}) 

88 

89 

90@register_topology 

91class MixtureOfExperts(Topology): 

92 key = "mixture_of_experts" 

93 label = "Mixture of experts" 

94 description = ( 

95 "A router sends each part of the task to the experts best suited to " 

96 "it, who answer in parallel; the router writes the answer from theirs." 

97 ) 

98 roles = ( 

99 RoleSlot( 

100 ROUTER, 

101 "Router", 

102 "Splits the task into questions, sends each to the experts best " 

103 "suited to it, and writes the answer from their answers.", 

104 min_members=1, 

105 max_members=1, 

106 ), 

107 RoleSlot( 

108 EXPERT, 

109 "Experts", 

110 "Answer the questions the router sends them. Chosen by what each " 

111 "agent says it is for, and by your note. A template is briefed as " 

112 "a different specialist for each question.", 

113 min_members=1, 

114 max_members=12, 

115 spawn_allowed=True, 

116 ), 

117 ) 

118 params = ( 

119 Param( 

120 "questions", 

121 "Questions", 

122 "The most questions the router may split the task into.", 

123 "int", 

124 3, 

125 minimum=1, 

126 maximum=6, 

127 ), 

128 Param( 

129 "top_k", 

130 "Experts per question", 

131 "How many of the best-suited experts answer each question.", 

132 "int", 

133 2, 

134 minimum=1, 

135 maximum=4, 

136 ), 

137 Param( 

138 "samples", 

139 "Answers per expert", 

140 "How many times each chosen expert answers its question, each on its own.", 

141 "int", 

142 1, 

143 minimum=1, 

144 maximum=4, 

145 ), 

146 Param( 

147 "layers", 

148 "Layers", 

149 "One: each expert answers once. Two: each answers again, having " 

150 "read every expert's first answer to its question.", 

151 "int", 

152 1, 

153 minimum=1, 

154 maximum=2, 

155 ), 

156 Param( 

157 "expert_tier", 

158 "Experts' model", 

159 "The model experts answer on.", 

160 "choice", 

161 Tier.as_configured.value, 

162 choices=TIER_CHOICES, 

163 ), 

164 Param( 

165 "expert_cost_profile", 

166 "Experts' effort", 

167 "How much checking each expert's own turn does; empty for each " 

168 "agent's own setting.", 

169 "choice", 

170 None, 

171 choices=COST_PROFILE_CHOICES, 

172 ), 

173 ) 

174 presets = ( 

175 Preset( 

176 "routed", 

177 "Routed experts", 

178 "Up to four questions, each answered by its two best-suited experts.", 

179 {"questions": 4, "top_k": 2, "samples": 1, "layers": 1}, 

180 ), 

181 Preset( 

182 "mixture_of_agents", 

183 "Mixture of agents", 

184 "The whole task to the three best-suited experts, who each answer " 

185 "again having read the others' answers.", 

186 {"questions": 1, "top_k": 3, "samples": 1, "layers": 2}, 

187 ), 

188 Preset( 

189 "self_moa", 

190 "Self-MoA", 

191 "The whole task to the one best-suited expert, answered three times " 

192 "on its own: one strong model sampled beats mixing in weaker ones.", 

193 {"questions": 1, "top_k": 1, "samples": 3, "layers": 1}, 

194 ), 

195 ) 

196 

197 # ── Settings ───────────────────────────────────────────────────────────── 

198 

199 @staticmethod 

200 def _settings(params: dict[str, Any]) -> tuple[int, int, int, int]: 

201 return ( 

202 int(params.get("questions") or 1), 

203 int(params.get("top_k") or 1), 

204 int(params.get("samples") or 1), 

205 int(params.get("layers") or 1), 

206 ) 

207 

208 def params_problems(self, params: dict[str, Any]) -> list[str]: 

209 questions, top_k, samples, layers = self._settings(params) 

210 answers = questions * top_k * samples * layers 

211 if answers > MAX_ANSWERS: 

212 return [ 

213 ( 

214 f"These settings could ask for {answers} answers; a mixture of " 

215 f"experts gives {MAX_ANSWERS} at most. Lower one of them." 

216 ) 

217 ] 

218 return [] 

219 

220 def _level(self, params: dict[str, Any]) -> dict[str, Any]: 

221 return { 

222 "tier": params.get("expert_tier") or Tier.as_configured.value, 

223 "cost_profile": params.get("expert_cost_profile") or None, 

224 } 

225 

226 # ── Reading the run ────────────────────────────────────────────────────── 

227 

228 def _router(self, state: RunState) -> Member: 

229 router = state.roster.first(ROUTER) 

230 assert router is not None # the roster was checked at dispatch 

231 return router 

232 

233 def _member(self, state: RunState, task: SwarmTask) -> Member | None: 

234 return next( 

235 ( 

236 m 

237 for m in state.roster.members 

238 if m.agent_id == str(task.agent_id) and m.role == task.role 

239 ), 

240 None, 

241 ) 

242 

243 def _answers(self, state: RunState, question: int, layer: int) -> list[SwarmTask]: 

244 return [ 

245 t 

246 for t in state.of_kind(TaskKind.work) 

247 if _extra(t, QUESTION_KEY, 0) == question 

248 and _extra(t, LAYER_KEY, 1) == layer 

249 and t.status != TaskStatus.cancelled 

250 ] 

251 

252 def _questions(self, state: RunState) -> list[int]: 

253 return sorted( 

254 {_extra(t, QUESTION_KEY, 0) for t in state.of_kind(TaskKind.work)} - {0} 

255 ) 

256 

257 def final_answers(self, state: RunState, question: int) -> list[SwarmTask]: 

258 """What a question came to: its second layer's answers where any was 

259 finished, else its first's.""" 

260 second = self._answers(state, question, 2) 

261 if any(t.status == TaskStatus.done for t in second): 

262 return second 

263 return self._answers(state, question, 1) 

264 

265 # ── What the engine asks ───────────────────────────────────────────────── 

266 

267 def seed(self, state: RunState) -> list[NewTask]: 

268 router = self._router(state) 

269 return [ 

270 NewTask( 

271 kind=TaskKind.route, 

272 handle=ROUTE_HANDLE, 

273 title="Route the task", 

274 role=ROUTER, 

275 member=router.handle, 

276 brief=TaskBrief(objective=state.run.task), 

277 ) 

278 ] 

279 

280 def plan_spec(self, state: RunState, task: SwarmTask) -> PlanSpec: 

281 questions, _, _, _ = self._settings(state.params) 

282 return PlanSpec( 

283 planner=self._router(state), 

284 members=tuple(state.roster.of_role(EXPERT)), 

285 span=questions, 

286 ) 

287 

288 def work_pool(self, state: RunState) -> Decimal: 

289 """The first layer's share: a second layer's answers take the same 

290 again (``_second_layer``).""" 

291 _, _, _, layers = self._settings(state.params) 

292 return (budget.work_pool(state.run) / layers).quantize(Decimal("0.000001")) 

293 

294 def ask(self, state: RunState, task: SwarmTask, ctx: AskContext) -> Ask | None: 

295 run = state.run 

296 if task.kind == TaskKind.route: 

297 questions, top_k, samples, layers = self._settings(state.params) 

298 experts = state.roster.of_role(EXPERT) 

299 return Ask( 

300 prompt=prompts.route( 

301 run, 

302 self._router(state), 

303 experts, 

304 questions=questions, 

305 top_k=top_k, 

306 samples=samples, 

307 layers=layers, 

308 ), 

309 schema=schemas.routing_schema( 

310 tuple(m.handle for m in experts), questions 

311 ), 

312 ) 

313 if task.kind == TaskKind.work and _extra(task, LAYER_KEY, 1) > 1: 

314 firsts = [t for t in state.tasks if str(t.id) in set(task.depends_on or [])] 

315 return Ask( 

316 prompt=prompts.refine(run, state.roster, task), 

317 documents=_marked(prompts.work_documents(firsts), task, firsts), 

318 ) 

319 if task.kind == TaskKind.synthesise: 

320 answers = [ 

321 a for n in self._questions(state) for a in self.final_answers(state, n) 

322 ] 

323 finished = [a for a in answers if a.status == TaskStatus.done] 

324 documents = prompts.work_documents(finished) 

325 if not documents: 

326 return Ask(skip="There was no finished answer to read.") 

327 groups = [] 

328 for number in self._questions(state): 

329 done = [ 

330 a 

331 for a in self.final_answers(state, number) 

332 if a.status == TaskStatus.done 

333 ] 

334 if done: 

335 groups.append((done[0], done)) 

336 return Ask( 

337 prompt=prompts.aggregate( 

338 run, 

339 state.roster, 

340 groups, 

341 [a for a in answers if a.status != TaskStatus.done], 

342 ), 

343 documents=documents, 

344 ) 

345 if task.kind == TaskKind.work: 

346 others = len(self._answers(state, _extra(task, QUESTION_KEY, 0), 1)) - 1 

347 return Ask( 

348 prompt=prompts.expert( 

349 run, state.roster, task, others=others, answers=ctx.answers 

350 ), 

351 may_ask=ctx.may_ask, 

352 ) 

353 return None 

354 

355 def advance(self, state: RunState, finished: SwarmTask) -> Step: 

356 if finished.kind == TaskKind.route: 

357 return self._after_routing(state, finished) 

358 if finished.kind == TaskKind.synthesise: 

359 return ( 

360 Step(final=finished) if finished.status == TaskStatus.done else Step() 

361 ) 

362 if finished.kind != TaskKind.work: 

363 return Step() 

364 brief = TaskBrief.from_stored(finished.brief) 

365 if brief.extra.get(FINAL_KEY): 

366 return ( 

367 Step(final=finished) if finished.status == TaskStatus.done else Step() 

368 ) 

369 _, _, _, layers = self._settings(state.params) 

370 if layers > 1 and _extra(finished, LAYER_KEY, 1) == 1: 

371 return self._second_layer(state, _extra(finished, QUESTION_KEY, 0)) 

372 return Step() 

373 

374 # ── After the routing ──────────────────────────────────────────────────── 

375 

376 def _after_routing(self, state: RunState, route: SwarmTask) -> Step: 

377 if route.status != TaskStatus.done or not route.result: 

378 return Step() 

379 try: 

380 routing = SwarmRouting.model_validate(route.result) 

381 except ValidationError: 

382 return Step(warnings=["The router's routing could not be read."]) 

383 most, top_k, samples, _ = self._settings(state.params) 

384 experts = {m.handle: m for m in state.roster.of_role(EXPERT)} 

385 chosen: list[tuple[schemas.RoutedQuestion, list[Member]]] = [] 

386 for question in routing.questions[:most]: 

387 # Its best-suited experts, in the router's order, each once. 

388 ranked = list(dict.fromkeys(h for h in question.experts if h in experts)) 

389 if ranked: 

390 chosen.append((question, [experts[h] for h in ranked[:top_k]])) 

391 ledger = { 

392 "facts": list(routing.facts), 

393 "assumptions": list(routing.assumptions), 

394 } 

395 if not chosen: 

396 return Step( 

397 ledger=ledger, 

398 warnings=["The router sent no question to an expert."], 

399 ) 

400 total = sum(len(members) * samples for _, members in chosen) 

401 answers: list[NewTask] = [] 

402 for number, (question, members) in enumerate(chosen, start=1): 

403 brief = TaskBrief.from_proposal(question) 

404 place = 0 

405 for member in members: 

406 # A fixed expert keeps the role it was given. 

407 own = brief if member.spawn else replace(brief, specialism="") 

408 for sample in range(1, samples + 1): 

409 place += 1 

410 extra: dict[str, Any] = {QUESTION_KEY: number, LAYER_KEY: 1} 

411 if samples > 1: 

412 extra[SAMPLE_KEY] = sample 

413 if total == 1: 

414 extra[FINAL_KEY] = True 

415 answers.append( 

416 NewTask( 

417 kind=TaskKind.work, 

418 handle=f"Q{number}.{place}", 

419 title=question.title.strip()[:255] or f"Question {number}", 

420 role=EXPERT, 

421 member=member.handle, 

422 brief=_with_extra(own, **extra), 

423 parent=ROUTE_HANDLE, 

424 depth=1, 

425 **self._level(state.params), 

426 ) 

427 ) 

428 step = Step( 

429 add=answers, 

430 ledger=ledger, 

431 approve=True, 

432 plan=_shown(routing, answers, one=total == 1), 

433 pool=self.work_pool(state), 

434 ) 

435 if total > 1: 

436 step.add.append( 

437 NewTask( 

438 kind=TaskKind.synthesise, 

439 handle=ANSWER_HANDLE, 

440 title="Write the answer", 

441 role=ROUTER, 

442 member=self._router(state).handle, 

443 brief=TaskBrief(objective=state.run.task), 

444 after=tuple(a.handle for a in answers), 

445 parent=ROUTE_HANDLE, 

446 ) 

447 ) 

448 return step 

449 

450 # ── A second layer ─────────────────────────────────────────────────────── 

451 

452 def _second_layer(self, state: RunState, question: int) -> Step: 

453 """Once every first answer to ``question`` has settled: each expert 

454 answers it again, every finished first answer in hand — within the 

455 share its first answer had.""" 

456 firsts = self._answers(state, question, 1) 

457 if not firsts or any(t.status not in SETTLED for t in firsts): 

458 return Step() 

459 if self._answers(state, question, 2): 

460 return Step() 

461 if not any(t.status == TaskStatus.done for t in firsts): 

462 return Step() 

463 seconds = [] 

464 for first in firsts: 

465 member = self._member(state, first) 

466 if member is None or first.status not in ( 

467 TaskStatus.done, 

468 TaskStatus.failed, 

469 ): 

470 continue 

471 brief = TaskBrief.from_stored(first.brief) 

472 seconds.append( 

473 NewTask( 

474 kind=TaskKind.work, 

475 handle=f"{first.handle}r", 

476 title=first.title, 

477 role=first.role, 

478 member=member.handle, 

479 brief=_with_extra(brief, **{LAYER_KEY: 2}), 

480 after=tuple(t.handle for t in firsts), 

481 parent=ROUTE_HANDLE, 

482 depth=2, 

483 budget_usd=first.budget_usd, 

484 estimate_usd=first.estimate_usd, 

485 tier=first.tier, 

486 cost_profile=first.cost_profile, 

487 ) 

488 ) 

489 return Step( 

490 add=seconds, 

491 wait_also={ANSWER_HANDLE: [t.handle for t in seconds]}, 

492 ) 

493 

494 

495def _marked(documents: list, task: SwarmTask, firsts: list[SwarmTask]) -> list: 

496 """The first answers an expert reads again, its own named as its.""" 

497 own = {str(t.id) for t in firsts if t.handle == task.handle.removesuffix("r")} 

498 return [ 

499 replace(d, name=f"{d.name} (yours)"[:200]) if d.id in own else d 

500 for d in documents 

501 ] 

502 

503 

504def _shown(routing: SwarmRouting, answers: list[NewTask], *, one: bool) -> dict: 

505 """The routing as a person approves it: each expert's answer to each 

506 question.""" 

507 return { 

508 "approach": (Approach.one_agent if one else Approach.team).value, 

509 "assumptions": list(routing.assumptions), 

510 "tasks": [ 

511 { 

512 "handle": task.handle, 

513 "title": task.title, 

514 "member": task.member, 

515 "after": [], 

516 **task.brief.stored(), 

517 } 

518 for task in answers 

519 ], 

520 }