Coverage for app / services / swarms / topologies / council.py: 93%
179 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-10-31 11:21 +0000
1"""Agents answering the same task on their own, then deciding — a council.
3Every seat answers the whole task without seeing the others' answers — each
4member once, or ``samples`` times — and then the council decides: by
5**vote**, each member choosing the answer that serves best (its own left out
6where there are others), the chair breaking a tie; or by the chair writing
7the answer from all of them. Optional debate rounds come first: each member
8reads every answer of the round before and writes its own again.
10The literature behind it: voting explains most of what multi-agent debate
11gains, and debate alone is a martingale — it does not improve answers in
12expectation (Choi et al., *Debate or Vote*, NeurIPS 2025) — so the council
13votes by default and debate is opt-in, two rounds at most. Self-consistency
14(one strong agent answering several times, the most-voted answer kept) is
15the same machinery with one seat sampled. The presets:
17* **Committee** — a top-heavy council of three to five strong agents, each
18 answering once, then voting.
19* **Deliberation** — one round of debate, then the chair writes the answer.
20* **Self-consistency** — each member answers three times; the council votes.
22A council plans nothing, so there is nothing to approve before it starts.
23"""
25from __future__ import annotations
27from collections import Counter
28from dataclasses import replace
29from decimal import Decimal
30from enum import StrEnum
31from typing import Any
33from app.db.postgres.models import SwarmTask
34from app.services.swarms import budget, prompts, schemas
35from app.services.swarms.roster import Member, Roster
36from app.services.swarms.schemas import TaskBrief
37from app.services.swarms.topologies import (
38 SETTLED,
39 Ask,
40 AskContext,
41 NewTask,
42 Param,
43 PlanSpec,
44 Preset,
45 RoleSlot,
46 RunState,
47 Step,
48 TaskKind,
49 TaskStatus,
50 Topology,
51 register_topology,
52)
54CHAIR = "chair"
55MEMBER = "member"
57ANSWER_HANDLE = "S1"
59#: Which round an answer belongs to, and which seat wrote it.
60ROUND_KEY = "round"
61SEAT_KEY = "seat"
63#: The most answers a council's settings may ask for, every round counted.
64MAX_ANSWERS = 40
67class Decision(StrEnum):
68 """How a council turns its answers into one."""
70 vote = "vote"
71 aggregate = "aggregate"
74DECISION_LABELS = {
75 Decision.vote: "Members vote for the best answer",
76 Decision.aggregate: "The chair writes the answer from all of them",
77}
80def _extra(task: SwarmTask, key: str, default: int) -> int:
81 value = TaskBrief.from_stored(task.brief).extra.get(key, default)
82 try:
83 return int(value)
84 except (TypeError, ValueError):
85 return default
88@register_topology
89class Council(Topology):
90 key = "council"
91 label = "Council"
92 description = (
93 "Several agents answer the task, each on its own, then vote for the "
94 "best answer — or the chair writes one from all of them."
95 )
96 plans = False
97 roles = (
98 RoleSlot(
99 CHAIR,
100 "Chair",
101 "Answers like every member, breaks a tied vote, and writes the "
102 "answer when the council does not vote.",
103 min_members=1,
104 max_members=1,
105 ),
106 RoleSlot(
107 MEMBER,
108 "Members",
109 "Each answers the task on its own, then votes. Your note gives a "
110 "member its angle on the task.",
111 min_members=0,
112 max_members=6,
113 ),
114 )
115 params = (
116 Param(
117 "decision",
118 "Deciding",
119 "How the council turns its answers into one.",
120 "choice",
121 Decision.vote.value,
122 choices=tuple((d.value, DECISION_LABELS[d]) for d in Decision),
123 ),
124 Param(
125 "debate_rounds",
126 "Debate rounds",
127 "Rounds in which each member reads every answer of the round before "
128 "and writes its own again, before the council decides.",
129 "int",
130 0,
131 minimum=0,
132 maximum=2,
133 ),
134 Param(
135 "samples",
136 "Answers per member",
137 "How many times each member answers, each on its own.",
138 "int",
139 1,
140 minimum=1,
141 maximum=3,
142 ),
143 )
144 presets = (
145 Preset(
146 "committee",
147 "Committee",
148 "A top-heavy council: three to five strong agents each answer once, "
149 "then vote.",
150 {"decision": Decision.vote.value, "debate_rounds": 0, "samples": 1},
151 ),
152 Preset(
153 "deliberation",
154 "Deliberation",
155 "Each member answers, reads the others' answers and answers again; "
156 "the chair writes the answer from them.",
157 {"decision": Decision.aggregate.value, "debate_rounds": 1, "samples": 1},
158 ),
159 Preset(
160 "self_consistency",
161 "Self-consistency",
162 "Each member answers three times on its own, and the council votes: "
163 "for one strong agent, or a few.",
164 {"decision": Decision.vote.value, "debate_rounds": 0, "samples": 3},
165 ),
166 )
168 # ── Settings ─────────────────────────────────────────────────────────────
170 @staticmethod
171 def _settings(params: dict[str, Any]) -> tuple[bool, int, int]:
172 """``(votes, debate rounds, samples)``."""
173 return (
174 (params.get("decision") or Decision.vote.value) == Decision.vote.value,
175 int(params.get("debate_rounds") or 0),
176 int(params.get("samples") or 1),
177 )
179 @staticmethod
180 def _sitting(roster: Roster) -> list[Member]:
181 """Who sits on the council, the chair first."""
182 return [*roster.of_role(CHAIR), *roster.of_role(MEMBER)]
184 def check(self, params: dict[str, Any], roster: Roster) -> list[str]:
185 _, rounds, samples = self._settings(params)
186 seats = len(self._sitting(roster)) * samples
187 if seats < 2:
188 return [
189 (
190 "A council needs at least two answers: add a member, or have "
191 "each answer more than once."
192 )
193 ]
194 if seats * (rounds + 1) > MAX_ANSWERS:
195 return [
196 (
197 f"These settings ask for {seats * (rounds + 1)} answers; a "
198 f"council gives {MAX_ANSWERS} at most."
199 )
200 ]
201 return []
203 # ── Reading the run ──────────────────────────────────────────────────────
205 def _seats(self, state: RunState) -> list[tuple[int, Member]]:
206 """Each seat, numbered from 1: each member once per sample."""
207 _, _, samples = self._settings(state.params)
208 seats = []
209 for member in self._sitting(state.roster):
210 for _ in range(samples):
211 seats.append((len(seats) + 1, member))
212 return seats
214 def _answers(self, state: RunState, round_no: int) -> list[SwarmTask]:
215 return [
216 t
217 for t in state.of_kind(TaskKind.work)
218 if _extra(t, ROUND_KEY, 1) == round_no
219 ]
221 def _last_round(self, state: RunState) -> int:
222 _, rounds, _ = self._settings(state.params)
223 return rounds + 1
225 def latest(self, state: RunState) -> list[SwarmTask]:
226 """Each seat's latest finished answer — or, for a seat with none,
227 its first answer, which reads as missing."""
228 out = []
229 for seat, _ in self._seats(state):
230 mine = [
231 t
232 for t in state.of_kind(TaskKind.work)
233 if _extra(t, SEAT_KEY, 0) == seat
234 ]
235 done = [t for t in mine if t.status == TaskStatus.done]
236 if done:
237 out.append(max(done, key=lambda t: _extra(t, ROUND_KEY, 1)))
238 elif mine:
239 out.append(min(mine, key=lambda t: _extra(t, ROUND_KEY, 1)))
240 return out
242 def _member(self, state: RunState, task: SwarmTask) -> Member | None:
243 return next(
244 (
245 m
246 for m in state.roster.members
247 if m.agent_id == str(task.agent_id) and m.role == task.role
248 ),
249 None,
250 )
252 def _chair(self, state: RunState) -> Member:
253 chair = state.roster.first(CHAIR)
254 assert chair is not None # the roster was checked at dispatch
255 return chair
257 # ── What the engine asks ─────────────────────────────────────────────────
259 def seed(self, state: RunState) -> list[NewTask]:
260 votes, rounds, _ = self._settings(state.params)
261 seats = self._seats(state)
262 made: list[NewTask] = []
263 before: list[str] = []
264 for round_no in range(1, rounds + 2):
265 this_round = []
266 for seat, member in seats:
267 handle = f"P{seat}" if round_no == 1 else f"P{seat}.{round_no}"
268 title = f"Answer {seat}" + (
269 f", round {round_no}" if round_no > 1 else ""
270 )
271 made.append(
272 NewTask(
273 kind=TaskKind.work,
274 handle=handle,
275 title=title,
276 role=member.role,
277 member=member.handle,
278 brief=TaskBrief(
279 objective=(
280 "Answer the whole task, on its own"
281 if round_no == 1
282 else "Answer again, having read every answer of "
283 "the round before"
284 ),
285 output_format="A complete answer to the task",
286 done_when="It answers the whole task, citing its sources",
287 effort=schemas.Effort.large.value,
288 extra={ROUND_KEY: round_no, SEAT_KEY: seat},
289 ),
290 after=tuple(before),
291 depth=1,
292 )
293 )
294 this_round.append(handle)
295 before = this_round
296 if votes:
297 voters = self._sitting(state.roster)
298 share = (budget.review_share(state.run) / len(voters)).quantize(
299 Decimal("0.000001")
300 )
301 for number, member in enumerate(voters, start=1):
302 made.append(
303 NewTask(
304 kind=TaskKind.vote,
305 handle=f"V{number}",
306 title=f"{member.agent_name}'s vote",
307 role=member.role,
308 member=member.handle,
309 brief=TaskBrief(objective=state.run.task),
310 after=tuple(before),
311 budget_usd=share,
312 )
313 )
314 else:
315 made.append(self._answer_task(state, before))
316 return made
318 def _answer_task(self, state: RunState, after: list[str]) -> NewTask:
319 return NewTask(
320 kind=TaskKind.synthesise,
321 handle=ANSWER_HANDLE,
322 title="Write the answer",
323 role=CHAIR,
324 member=self._chair(state).handle,
325 brief=TaskBrief(objective=state.run.task),
326 after=tuple(after),
327 )
329 def seed_pool(self, state: RunState) -> Decimal | None:
330 """A council that does not vote keeps nothing back for votes."""
331 votes, _, _ = self._settings(state.params)
332 return None if votes else budget.unreserved(state.run)
334 def plan_spec(self, state: RunState, task: SwarmTask) -> PlanSpec:
335 return PlanSpec(
336 planner=self._chair(state),
337 members=tuple(self._sitting(state.roster)),
338 span=len(self._seats(state)),
339 )
341 def ask(self, state: RunState, task: SwarmTask, ctx: AskContext) -> Ask | None:
342 run = state.run
343 votes, rounds, _ = self._settings(state.params)
344 seats = len(self._seats(state))
345 if task.kind == TaskKind.work:
346 member = self._member(state, task) or self._chair(state)
347 round_no = _extra(task, ROUND_KEY, 1)
348 if round_no == 1:
349 return Ask(
350 prompt=prompts.propose(
351 run,
352 member,
353 seats=seats,
354 votes=votes,
355 rounds=rounds,
356 answers=ctx.answers,
357 ),
358 may_ask=ctx.may_ask,
359 )
360 before = [
361 t
362 for t in self._answers(state, round_no - 1)
363 if t.status == TaskStatus.done
364 ]
365 seat = _extra(task, SEAT_KEY, 0)
366 return Ask(
367 prompt=prompts.revise(
368 run,
369 member,
370 seats=seats,
371 votes=votes,
372 rounds=rounds,
373 round_no=round_no,
374 ),
375 documents=_numbered(before, own_seat=seat),
376 )
377 if task.kind == TaskKind.vote:
378 choices = self._choices(state, task)
379 if not choices:
380 return Ask(skip="There were no answers to choose from.")
381 own_left_out = len(choices) < len(self._finished_last_round(state))
382 return Ask(
383 prompt=prompts.ballot(run, own_left_out=own_left_out),
384 schema=schemas.vote_schema(tuple(t.handle for t in choices)),
385 documents=_numbered(choices),
386 )
387 if task.kind == TaskKind.synthesise:
388 latest = self.latest(state)
389 done = [t for t in latest if t.status == TaskStatus.done]
390 if not done:
391 return Ask(skip="There were no finished answers to read.")
392 return Ask(
393 prompt=prompts.merge(
394 run,
395 fallback=votes,
396 missing=[t for t in latest if t.status != TaskStatus.done],
397 ),
398 documents=_numbered(done),
399 )
400 return None
402 def _finished_last_round(self, state: RunState) -> list[SwarmTask]:
403 return [
404 t
405 for t in self._answers(state, self._last_round(state))
406 if t.status == TaskStatus.done
407 ]
409 def _choices(self, state: RunState, vote: SwarmTask) -> list[SwarmTask]:
410 """What a voter chooses among: the last round's finished answers, its
411 own left out where there are others."""
412 finished = self._finished_last_round(state)
413 others = [
414 t
415 for t in finished
416 if not (str(t.agent_id) == str(vote.agent_id) and t.role == vote.role)
417 ]
418 return others or finished
420 def advance(self, state: RunState, finished: SwarmTask) -> Step:
421 if finished.kind == TaskKind.synthesise:
422 return (
423 Step(final=finished) if finished.status == TaskStatus.done else Step()
424 )
425 if finished.kind != TaskKind.vote:
426 return Step()
427 ballots = state.of_kind(TaskKind.vote)
428 if any(t.status not in SETTLED for t in ballots):
429 return Step()
430 return self._count(state, ballots)
432 # ── Counting the votes ───────────────────────────────────────────────────
434 def _count(self, state: RunState, ballots: list[SwarmTask]) -> Step:
435 """The answer most members chose — the chair's choice among a tie,
436 else the first-numbered — or, with no vote to count, the chair
437 writes the answer from them all."""
438 eligible = {t.handle: t for t in self._finished_last_round(state)}
439 counts: Counter[str] = Counter()
440 chair_choice = None
441 gaps: dict[str, list[str]] = {}
442 for ballot in ballots:
443 if ballot.status != TaskStatus.done or not isinstance(ballot.result, dict):
444 continue
445 choice = ballot.result.get("choice")
446 if choice not in eligible:
447 continue
448 counts[choice] += 1
449 gaps.setdefault(choice, []).extend(
450 str(g) for g in ballot.result.get("gaps") or [] if g
451 )
452 if ballot.role == CHAIR:
453 chair_choice = choice
454 if not counts:
455 if state.by_handle(ANSWER_HANDLE) is not None:
456 return Step()
457 return Step(
458 add=[self._answer_task(state, [t.handle for t in self.latest(state)])],
459 warnings=[
460 (
461 "No vote could be counted, so the chair wrote the answer "
462 "from the council's answers."
463 )
464 ],
465 )
466 top = max(counts.values())
467 tied = [h for h in eligible if counts.get(h) == top]
468 winner = chair_choice if chair_choice in tied else tied[0]
469 cast = sum(counts.values())
470 tie = (
471 " (a tie the chair broke)"
472 if len(tied) > 1 and winner == chair_choice
473 else ""
474 )
475 return Step(
476 final=eligible[winner],
477 ledger={
478 "facts": [
479 (
480 f"The council chose {winner}: {top} of {cast} vote"
481 f"{'s' if cast != 1 else ''}{tie}."
482 )
483 ],
484 "gaps": list(dict.fromkeys(gaps.get(winner, []))),
485 },
486 )
488 def wrap_up(self, state: RunState) -> list[NewTask]:
489 """A council stopped before its vote: the chair writes the answer
490 from what was answered."""
491 votes, _, _ = self._settings(state.params)
492 if not votes or state.by_handle(ANSWER_HANDLE) is not None:
493 return []
494 return [
495 self._answer_task(state, [t.handle for t in state.of_kind(TaskKind.work)])
496 ]
499def _numbered(answers: list[SwarmTask], own_seat: int | None = None) -> list:
500 """Answers as documents named by their handle and number only — never
501 by who wrote them — the reader's own marked."""
502 documents = prompts.work_documents(answers)
503 seats = {str(t.id): _extra(t, SEAT_KEY, 0) for t in answers}
504 return [
505 replace(doc, name=f"{doc.name} (yours)"[:200])
506 if own_seat and seats.get(doc.id) == own_seat
507 else doc
508 for doc in documents
509 ]