Coverage for app / services / swarms / topologies / pipeline.py: 91%
141 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 in a fixed order, each working on what the last handed it — a
2pipeline.
4The roster's stages run in the order they were put in, each with the job its
5note gives it ("research the sources", "draft the brief", "check every
6figure", "edit for the reader"), and each is handed the work of the stage
7before; the last stage's work is the answer. A stage that fails is passed
8over: the next starts from the latest work there is. Stopped early, the last
9stage writes the answer from the latest work.
11**Chain of agents** (Zhang et al., NeurIPS 2024) is the same shape over a
12long document: the stages read the documents the person attached a part at a
13time (``swarms.parts``), in turn, each writing notes for the next, and the
14last stage writes the answer from the last notes — so no agent need hold the
15whole document, which reads better than one agent reading it all at once.
17The literature's warning about multi-agent work on sequential tasks applies
18in full: every handover can lose something (Google Research and MIT,
19*Towards a Science of Scaling Agent Systems*, 2025). A pipeline earns its place where each stage is
20a different skill, and the person decides the stages; nothing is planned, so
21there is nothing to approve before it starts.
22"""
24from __future__ import annotations
26from decimal import Decimal
27from enum import StrEnum
28from typing import Any
30from app.db.postgres.models import SwarmTask
31from app.services.swarms import budget, parts, prompts
32from app.services.swarms.roster import Member, Roster
33from app.services.swarms.schemas import TaskBrief
34from app.services.swarms.topologies import (
35 Ask,
36 AskContext,
37 NewTask,
38 Param,
39 PlanSpec,
40 Preset,
41 RoleSlot,
42 RunState,
43 Step,
44 TaskKind,
45 TaskStatus,
46 Topology,
47 register_topology,
48)
50STAGE = "stage"
52ANSWER_HANDLE = "S1"
54#: Which stage a task is, and which part of the documents a reader read.
55STAGE_KEY = "stage"
56PART_KEY = "part"
59class Mode(StrEnum):
60 """What a pipeline's stages work through."""
62 stages = "stages"
63 chain = "chain"
66MODE_LABELS = {
67 Mode.stages: "Each stage works on the last stage's work",
68 Mode.chain: "Chain of agents: the stages read the attached documents part "
69 "by part, passing notes on",
70}
73def _extra(task: SwarmTask, key: str) -> int:
74 value = TaskBrief.from_stored(task.brief).extra.get(key, 0)
75 try:
76 return int(value)
77 except (TypeError, ValueError):
78 return 0
81@register_topology
82class Pipeline(Topology):
83 key = "pipeline"
84 label = "Pipeline"
85 description = (
86 "Agents in a fixed order, each working on what the stage before "
87 "handed it; the last stage's work is the answer."
88 )
89 plans = False
90 roles = (
91 RoleSlot(
92 STAGE,
93 "Stages",
94 "In the order they run. Your note is each stage's job; one agent "
95 "may take more than one stage.",
96 min_members=1,
97 max_members=8,
98 ordered=True,
99 ),
100 )
101 params = (
102 Param(
103 "mode",
104 "Working through",
105 "What the stages work through.",
106 "choice",
107 Mode.stages.value,
108 choices=tuple((m.value, MODE_LABELS[m]) for m in Mode),
109 ),
110 )
111 presets = (
112 Preset(
113 "editorial",
114 "Research, draft, check, edit",
115 "Stages that each do one job on the work so far — put your agents "
116 "in that order, each with its job as its note.",
117 {"mode": Mode.stages.value},
118 ),
119 Preset(
120 "chain_of_agents",
121 "Chain of agents",
122 "For long documents: the stages read the attached documents part "
123 "by part, passing notes on, and the last writes the answer.",
124 {"mode": Mode.chain.value},
125 ),
126 )
128 @staticmethod
129 def _chain(params: dict[str, Any]) -> bool:
130 return (params.get("mode") or Mode.stages.value) == Mode.chain.value
132 def check(self, params: dict[str, Any], roster: Roster) -> list[str]:
133 if not self._chain(params) and len(roster.of_role(STAGE)) < 2:
134 return ["A pipeline of stages needs at least two."]
135 return []
137 def dispatch_problems(
138 self, params: dict[str, Any], file_ids: list[str]
139 ) -> list[str]:
140 if self._chain(params) and not file_ids:
141 return [
142 (
143 "A chain of agents reads the documents attached to the task: "
144 "attach at least one."
145 )
146 ]
147 return []
149 # ── Reading the run ──────────────────────────────────────────────────────
151 @staticmethod
152 def _stages(roster: Roster) -> list[Member]:
153 return roster.of_role(STAGE)
155 def _readers(self, roster: Roster) -> list[Member]:
156 """Who reads in a chain: every stage but the last, which writes —
157 or the one stage, which does both."""
158 stages = self._stages(roster)
159 return stages[:-1] if len(stages) > 1 else stages
161 def _stage_tasks(self, state: RunState) -> list[SwarmTask]:
162 return sorted(
163 (t for t in state.of_kind(TaskKind.work) if _extra(t, STAGE_KEY)),
164 key=lambda t: _extra(t, STAGE_KEY),
165 )
167 def _reads(self, state: RunState) -> list[SwarmTask]:
168 return sorted(
169 (t for t in state.of_kind(TaskKind.work) if _extra(t, PART_KEY)),
170 key=lambda t: _extra(t, PART_KEY),
171 )
173 @staticmethod
174 def _latest_done(
175 tasks: list[SwarmTask], before: int | None = None
176 ) -> SwarmTask | None:
177 done = [t for t in tasks[:before] if t.status == TaskStatus.done]
178 return done[-1] if done else None
180 @staticmethod
181 def _parts(reads: list[SwarmTask]) -> int | None:
182 """How many parts the documents have, as the readers found."""
183 counts = [
184 int(t.result["parts"])
185 for t in reads
186 if isinstance(t.result, dict) and str(t.result.get("parts", "")).isdigit()
187 ]
188 return max(counts) if counts else None
190 # ── What the engine asks ─────────────────────────────────────────────────
192 def seed(self, state: RunState) -> list[NewTask]:
193 if self._chain(state.params):
194 return [self._reader(state, 1)]
195 stages = self._stages(state.roster)
196 made = []
197 for index, member in enumerate(stages, start=1):
198 job = member.note or (
199 f"Stage {index} of {len(stages)}: what {member.agent_name} does, "
200 "on the work so far"
201 )
202 made.append(
203 NewTask(
204 kind=TaskKind.work,
205 handle=f"T{index}",
206 title=(member.note or f"Stage {index}: {member.agent_name}")[:255],
207 role=STAGE,
208 member=member.handle,
209 brief=TaskBrief(
210 objective=job,
211 output_format=(
212 "The answer, for the person who asked"
213 if index == len(stages)
214 else "The work so far, for the next stage"
215 ),
216 extra={STAGE_KEY: index},
217 ),
218 after=(f"T{index - 1}",) if index > 1 else (),
219 depth=1,
220 )
221 )
222 return made
224 def _reader(self, state: RunState, part: int, after: str | None = None) -> NewTask:
225 readers = self._readers(state.roster)
226 member = readers[(part - 1) % len(readers)]
227 return NewTask(
228 kind=TaskKind.work,
229 handle=f"C{part}",
230 title=f"Read part {part}",
231 role=STAGE,
232 member=member.handle,
233 brief=TaskBrief(
234 objective=f"Notes on part {part} of the documents, for the task",
235 output_format="Notes for the next reader",
236 extra={PART_KEY: part},
237 ),
238 after=(after,) if after else (),
239 depth=1,
240 )
242 def _answer_task(self, state: RunState, after: list[str]) -> NewTask:
243 writer = self._stages(state.roster)[-1]
244 return NewTask(
245 kind=TaskKind.synthesise,
246 handle=ANSWER_HANDLE,
247 title="Write the answer",
248 role=STAGE,
249 member=writer.handle,
250 brief=TaskBrief(objective=state.run.task),
251 after=tuple(after),
252 )
254 def seed_pool(self, state: RunState) -> Decimal | None:
255 """Stages are reviewed by the stage after, not by a review of their
256 own: nothing is kept back for one."""
257 return budget.unreserved(state.run)
259 def plan_spec(self, state: RunState, task: SwarmTask) -> PlanSpec:
260 stages = self._stages(state.roster)
261 return PlanSpec(planner=stages[0], members=tuple(stages), span=len(stages))
263 def ask(self, state: RunState, task: SwarmTask, ctx: AskContext) -> Ask | None:
264 run = state.run
265 if task.kind == TaskKind.work and _extra(task, PART_KEY):
266 part = _extra(task, PART_KEY)
267 notes = self._latest_done(self._reads(state), before=part - 1)
268 member = self._member(state, task)
269 return Ask(
270 prompt=prompts.read_part(
271 run, member, part, has_notes=notes is not None
272 ),
273 documents=prompts.work_documents([notes] if notes else []),
274 part=part,
275 )
276 if task.kind == TaskKind.work:
277 stages = self._stage_tasks(state)
278 index = _extra(task, STAGE_KEY)
279 previous = self._latest_done(stages, before=index - 1)
280 return Ask(
281 prompt=prompts.stage(run, stages, task, previous, answers=ctx.answers),
282 documents=prompts.work_documents([previous] if previous else []),
283 may_ask=ctx.may_ask,
284 )
285 if task.kind == TaskKind.synthesise and self._chain(state.params):
286 reads = self._reads(state)
287 notes = self._latest_done(reads)
288 return Ask(
289 prompt=prompts.write_from_notes(run, notes, self._parts(reads)),
290 documents=prompts.work_documents([notes] if notes else []),
291 # From the notes, as a chain's last agent writes; the
292 # documents themselves only when no notes could be made.
293 library=notes is None,
294 )
295 if task.kind == TaskKind.synthesise:
296 stages = self._stage_tasks(state)
297 latest = self._latest_done(stages)
298 if latest is None:
299 return Ask(skip="No stage finished any work to answer from.")
300 return Ask(
301 prompt=prompts.finish(run, latest, stages),
302 documents=prompts.work_documents([latest]),
303 )
304 return None
306 def _member(self, state: RunState, task: SwarmTask) -> Member:
307 return next(
308 (
309 m
310 for m in state.roster.members
311 if m.agent_id == str(task.agent_id) and m.role == task.role
312 ),
313 self._stages(state.roster)[0],
314 )
316 def advance(self, state: RunState, finished: SwarmTask) -> Step:
317 if finished.kind == TaskKind.synthesise:
318 return (
319 Step(final=finished) if finished.status == TaskStatus.done else Step()
320 )
321 if finished.kind != TaskKind.work:
322 return Step()
323 if _extra(finished, PART_KEY):
324 return self._after_reading(state, finished)
325 stages = self._stage_tasks(state)
326 if _extra(finished, STAGE_KEY) < len(stages):
327 return Step()
328 if finished.status == TaskStatus.done:
329 return Step(final=finished)
330 latest = self._latest_done(stages)
331 if latest is None:
332 return Step()
333 return Step(
334 final=latest,
335 warnings=[
336 f"The last stage did not finish; the answer is {latest.handle}'s work."
337 ],
338 )
340 def _after_reading(self, state: RunState, read: SwarmTask) -> Step:
341 """The next part to the next reader, or — the documents read, or
342 their length never learnt — the answer from the notes."""
343 if state.by_handle(ANSWER_HANDLE) is not None:
344 return Step()
345 part = _extra(read, PART_KEY)
346 total = self._parts(self._reads(state))
347 if total is not None and part < min(total, parts.MAX_PARTS):
348 return Step(add=[self._reader(state, part + 1, after=read.handle)])
349 return Step(add=[self._answer_task(state, [read.handle])])
351 def wrap_up(self, state: RunState) -> list[NewTask]:
352 """Stopped early: the last stage writes the answer from the latest
353 work, or the latest notes."""
354 if state.by_handle(ANSWER_HANDLE) is not None:
355 return []
356 if self._chain(state.params):
357 reads = self._reads(state)
358 return (
359 [self._answer_task(state, [t.handle for t in reads])] if reads else []
360 )
361 stages = self._stage_tasks(state)
362 if not any(t.status == TaskStatus.done for t in stages):
363 return []
364 return [self._answer_task(state, [t.handle for t in stages])]