Coverage for app / services / swarms / schemas.py: 100%
136 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"""What a swarm's lead is asked to fill, and the brief each piece of work
2carries.
4The structured steps — a lead's plan and review, a router's routing, a
5council member's vote — are ``ModelOutput`` schemas sent through the governed
6agent path (``targets.invoke_structured``), decoded natively where the route
7can, read whole and corrected once. Each is built per run (:func:`plan_schema`,
8:func:`review_schema`, :func:`routing_schema`, :func:`vote_schema`): who may
9be assigned, and which pieces may be named, are a ``Literal`` of the run's
10own handles, so the model can name nothing that is not there, and the engine
11maps a handle back to the agent or task itself. Cached, so the same run
12shape is the same class and the same schema svc-ai has compiled before.
14A decision comes first in each (``approach``, ``verdicts``, ``questions``,
15``choice``), never a boolean, and no field asks for the model's reasoning —
16the rules every svc-core schema is held to (``tests/test_structured_replies.py``).
17"""
19from __future__ import annotations
21from dataclasses import asdict, dataclass, field
22from enum import StrEnum
23from functools import lru_cache
24from typing import Any, Literal
26from pydantic import Field, OnErrorOmit, create_model
28from app.util import vocab
29from app.util.model_output import ModelOutput
31#: The most pieces of work one plan may hold, whatever a shape allows.
32MAX_PLAN_TASKS = 12
35class Approach(StrEnum):
36 """How the lead decides the work is done."""
38 one_agent = "one_agent"
39 team = "team"
42APPROACH_GUIDE = {
43 Approach.one_agent: (
44 "one agent does it all, as one piece of work — right when each step "
45 "needs the last one's result, or the task is small"
46 ),
47 Approach.team: (
48 "the work is split into pieces that can be done apart and in "
49 "parallel, each by the member best suited to it"
50 ),
51}
52vocab.check(APPROACH_GUIDE, Approach)
55class Effort(StrEnum):
56 """How much work a piece is, for its share of the budget."""
58 small = "small"
59 medium = "medium"
60 large = "large"
63EFFORT_GUIDE = {
64 Effort.small: "a few lookups or one short answer",
65 Effort.medium: "several searches or a page of analysis",
66 Effort.large: "broad research or a long document",
67}
68vocab.check(EFFORT_GUIDE, Effort)
70#: How many typical turns each effort is budgeted as.
71EFFORT_TURNS = {Effort.small: 1, Effort.medium: 2, Effort.large: 4}
74class Verdict(StrEnum):
75 """What the review decides about one piece."""
77 accept = "accept"
78 redo = "redo"
81VERDICT_GUIDE = {
82 Verdict.accept: "it does what its brief asked and can be relied on",
83 Verdict.redo: (
84 "it misses what its brief asked or states something its sources do "
85 "not support; it is done again once, with your note"
86 ),
87}
88vocab.check(VERDICT_GUIDE, Verdict)
91class Next(StrEnum):
92 """What the lead's review decides comes next."""
94 answer = "answer"
95 more_work = "more_work"
98NEXT_GUIDE = {
99 Next.answer: "the work covers the task well enough to write the answer",
100 Next.more_work: (
101 "a gap matters enough to fill before answering, and the budget and "
102 "time left allow it: the new pieces are done, then reviewed"
103 ),
104}
105vocab.check(NEXT_GUIDE, Next)
108# ── The plan ─────────────────────────────────────────────────────────────────
111class ProposedTask(ModelOutput):
112 title: str = Field(description="A few words naming the piece of work")
113 assignee: str = Field(description="The handle of the member who does it")
114 objective: str = Field(description="What this piece must find out or produce")
115 output_format: str = Field(description="What to hand back, and in what shape")
116 done_when: str = Field(description="How the review will know it is finished")
117 effort: Effort = Field(
118 description="How much work it is: " + vocab.inline(EFFORT_GUIDE, Effort)
119 )
120 specialism: str = Field(
121 default="",
122 description="For a member that can be briefed as many workers: the "
123 "specialist this worker is, in a few words; empty for any other",
124 )
125 sources: str = Field(
126 default="", description="Where to look, and which tools or sources to use"
127 )
128 boundaries: str = Field(
129 default="",
130 description="What is not this piece's business, so pieces do not overlap",
131 )
132 after: list[str] = Field(
133 default_factory=list,
134 description="Handles of the pieces whose results this one needs first",
135 )
138class SwarmPlan(ModelOutput):
139 approach: Approach = Field(
140 description="How the work is done: " + vocab.inline(APPROACH_GUIDE, Approach)
141 )
142 tasks: list[OnErrorOmit[ProposedTask]] = Field(
143 description="The pieces of work, in order; one piece when one agent does it all"
144 )
145 facts: list[str] = Field(
146 default_factory=list,
147 description="What the request and its documents already establish",
148 )
149 assumptions: list[str] = Field(
150 default_factory=list,
151 description="What the plan assumes where the request is silent",
152 )
155class BuildingTask(ProposedTask):
156 """A piece of a follow-up's plan, which may build on pieces of the
157 request before it (``swarms.thread``)."""
159 builds_on: list[str] = Field(
160 default_factory=list,
161 description="The earlier pieces this one carries further, by ref; "
162 "empty when it builds on none",
163 )
166class ReadPlan(SwarmPlan):
167 """A stored plan read back, whichever schema it was asked in."""
169 tasks: list[OnErrorOmit[BuildingTask]] = Field( # type: ignore[assignment]
170 description="The pieces of work, in order"
171 )
174def task_handles(count: int) -> tuple[str, ...]:
175 """``T1`` … ``Tn``: how a plan's pieces are named, in its order."""
176 return tuple(f"T{n}" for n in range(1, count + 1))
179@lru_cache(maxsize=64)
180def plan_schema(
181 assignees: tuple[str, ...], span: int, earlier: tuple[str, ...] = ()
182) -> type[SwarmPlan]:
183 """``SwarmPlan`` for one run: pieces assigned only to its members, and
184 ``after`` naming only pieces it can hold. A follow-up's lead may have a
185 piece build on ``earlier`` — refs of the previous request's pieces —
186 and only then is it asked."""
187 span = max(1, min(span, MAX_PLAN_TASKS))
188 fields: dict[str, Any] = {
189 "assignee": (
190 Literal[assignees], # type: ignore[valid-type]
191 Field(description="The handle of the member who does it"),
192 ),
193 "after": (
194 # A reference to no piece is dropped, not the piece that made it.
195 list[OnErrorOmit[Literal[task_handles(span)]]], # type: ignore[valid-type]
196 Field(
197 default_factory=list,
198 description="Handles of the pieces whose results this one "
199 "needs first; a piece is named by its place in the list",
200 ),
201 ),
202 }
203 if earlier:
204 fields["builds_on"] = (
205 list[OnErrorOmit[Literal[earlier]]], # type: ignore[valid-type]
206 Field(
207 default_factory=list,
208 description="Refs of the earlier pieces this one carries "
209 "further, from the list in the brief; empty when it builds "
210 "on none",
211 ),
212 )
213 task = create_model(
214 "ProposedTask",
215 __base__=BuildingTask if earlier else ProposedTask,
216 __module__=__name__,
217 **fields,
218 )
219 return create_model(
220 "SwarmPlan",
221 __base__=SwarmPlan,
222 __module__=__name__,
223 tasks=(
224 list[OnErrorOmit[task]], # type: ignore[valid-type]
225 Field(
226 description=f"The pieces of work, in order — {span} at most; "
227 "one piece when one agent does it all"
228 ),
229 ),
230 )
233# ── The review ───────────────────────────────────────────────────────────────
236class ReviewItem(ModelOutput):
237 task: str = Field(description="The handle of the piece of work")
238 verdict: Verdict = Field(
239 description="What it needs: " + vocab.inline(VERDICT_GUIDE, Verdict)
240 )
241 issue: str = Field(
242 default="",
243 description="For a piece sent back: what is wrong or missing, as an "
244 "instruction to whoever does it again; empty when accepted",
245 )
248class SwarmReview(ModelOutput):
249 verdicts: list[OnErrorOmit[ReviewItem]] = Field(
250 description="One verdict for each piece of work"
251 )
252 facts: list[str] = Field(
253 default_factory=list,
254 description="Facts the work established that the answer can rely on",
255 )
256 gaps: list[str] = Field(
257 default_factory=list, description="What the work leaves unanswered"
258 )
261class SwarmReviewRound(ModelOutput):
262 """A lead's review that may ask for more work before the answer — a
263 progress check, as a task ledger's is: what is still open, and whether
264 it is worth another round."""
266 verdicts: list[OnErrorOmit[ReviewItem]] = Field(
267 description="One verdict for each piece of work"
268 )
269 next: Next = Field(description="What comes next: " + vocab.inline(NEXT_GUIDE, Next))
270 more_work: list[OnErrorOmit[ProposedTask]] = Field(
271 default_factory=list,
272 description="The new pieces, when more work comes next; empty otherwise",
273 )
274 facts: list[str] = Field(
275 default_factory=list,
276 description="Facts the work established that the answer can rely on",
277 )
278 gaps: list[str] = Field(
279 default_factory=list, description="What the work leaves unanswered"
280 )
283def _verdict_item(handles: tuple[str, ...]) -> type[ReviewItem]:
284 return create_model(
285 "ReviewItem",
286 __base__=ReviewItem,
287 __module__=__name__,
288 task=(
289 Literal[handles], # type: ignore[valid-type]
290 Field(description="The handle of the piece of work"),
291 ),
292 )
295@lru_cache(maxsize=64)
296def review_schema(
297 handles: tuple[str, ...],
298 more_to: tuple[str, ...] = (),
299 more_span: int = 0,
300) -> type[SwarmReview | SwarmReviewRound]:
301 """The review's schema: verdicts only on the pieces it saw; and, where
302 the review may ask for more work (``more_to``, the members it may
303 assign, at most ``more_span`` pieces), its decision and the new pieces,
304 each needing only pieces it saw first."""
305 item = _verdict_item(handles)
306 verdicts = (
307 list[OnErrorOmit[item]], # type: ignore[valid-type]
308 Field(description="One verdict for each piece of work"),
309 )
310 if not more_to or more_span < 1:
311 return create_model(
312 "SwarmReview", __base__=SwarmReview, __module__=__name__, verdicts=verdicts
313 )
314 piece = create_model(
315 "ProposedTask",
316 __base__=ProposedTask,
317 __module__=__name__,
318 assignee=(
319 Literal[more_to], # type: ignore[valid-type]
320 Field(description="The handle of the member who does it"),
321 ),
322 after=(
323 list[OnErrorOmit[Literal[handles]]], # type: ignore[valid-type]
324 Field(
325 default_factory=list,
326 description="Handles of the pieces above whose results this "
327 "one needs first",
328 ),
329 ),
330 )
331 return create_model(
332 "SwarmReviewRound",
333 __base__=SwarmReviewRound,
334 __module__=__name__,
335 verdicts=verdicts,
336 more_work=(
337 list[OnErrorOmit[piece]], # type: ignore[valid-type]
338 Field(
339 default_factory=list,
340 description=f"The new pieces, {more_span} at most, when more "
341 "work comes next; empty otherwise",
342 ),
343 ),
344 )
347# ── The routing (a mixture of experts) ───────────────────────────────────────
350class RoutedQuestion(ModelOutput):
351 title: str = Field(description="A few words naming the question")
352 experts: list[str] = Field(
353 description="Handles of the experts best suited to answer it, most suited first"
354 )
355 objective: str = Field(description="What its answer must find out or produce")
356 output_format: str = Field(description="What to hand back, and in what shape")
357 done_when: str = Field(description="How you will know it is answered")
358 effort: Effort = Field(
359 description="How much work it is: " + vocab.inline(EFFORT_GUIDE, Effort)
360 )
361 specialism: str = Field(
362 default="",
363 description="For an expert that can be briefed as several "
364 "specialists: the specialist it is for this question; empty otherwise",
365 )
366 sources: str = Field(
367 default="", description="Where to look, and which tools or sources to use"
368 )
369 boundaries: str = Field(
370 default="",
371 description="What is not this question's business, so answers do not overlap",
372 )
375class SwarmRouting(ModelOutput):
376 questions: list[OnErrorOmit[RoutedQuestion]] = Field(
377 description="The questions the task splits into, in order; one when it "
378 "does not split"
379 )
380 facts: list[str] = Field(
381 default_factory=list,
382 description="What the request and its documents already establish",
383 )
384 assumptions: list[str] = Field(
385 default_factory=list,
386 description="What the routing assumes where the request is silent",
387 )
390@lru_cache(maxsize=64)
391def routing_schema(experts: tuple[str, ...], questions: int) -> type[SwarmRouting]:
392 """``SwarmRouting`` for one run: questions sent only to its experts, at
393 most ``questions`` of them."""
394 question = create_model(
395 "RoutedQuestion",
396 __base__=RoutedQuestion,
397 __module__=__name__,
398 experts=(
399 # An expert the run does not have is dropped, not the question.
400 list[OnErrorOmit[Literal[experts]]], # type: ignore[valid-type]
401 Field(
402 description="Handles of the experts best suited to answer it, "
403 "most suited first"
404 ),
405 ),
406 )
407 return create_model(
408 "SwarmRouting",
409 __base__=SwarmRouting,
410 __module__=__name__,
411 questions=(
412 list[OnErrorOmit[question]], # type: ignore[valid-type]
413 Field(
414 description=f"The questions the task splits into, in order — "
415 f"{max(1, questions)} at most; one when it does not split"
416 ),
417 ),
418 )
421# ── A council member's vote ──────────────────────────────────────────────────
424class CouncilVote(ModelOutput):
425 choice: str = Field(description="The handle of the answer that serves best")
426 strengths: list[str] = Field(
427 default_factory=list, description="What makes it the best answer"
428 )
429 gaps: list[str] = Field(
430 default_factory=list,
431 description="What even the chosen answer leaves unanswered or gets wrong",
432 )
435@lru_cache(maxsize=64)
436def vote_schema(choices: tuple[str, ...]) -> type[CouncilVote]:
437 """``CouncilVote`` choosing only among the answers a voter was shown."""
438 return create_model(
439 "CouncilVote",
440 __base__=CouncilVote,
441 __module__=__name__,
442 choice=(
443 Literal[choices], # type: ignore[valid-type]
444 Field(description="The handle of the answer that serves best"),
445 ),
446 )
449# ── The brief a piece of work carries ────────────────────────────────────────
452@dataclass(frozen=True)
453class TaskBrief:
454 """What one piece of work is asked to do (``SwarmTask.brief``) — the
455 four parts a delegation needs to be done without overlap or gaps, and
456 how it will be judged."""
458 objective: str
459 output_format: str = ""
460 done_when: str = ""
461 sources: str = ""
462 boundaries: str = ""
463 #: The specialist a briefed worker is, written by the lead.
464 specialism: str = ""
465 effort: str = Effort.medium.value
466 #: For a piece done again: what the review said was wrong.
467 review_note: str = ""
468 #: The task this one redoes, when it does.
469 redoes: str = ""
470 extra: dict[str, Any] = field(default_factory=dict)
472 @classmethod
473 def from_stored(cls, raw: Any) -> TaskBrief:
474 data = raw if isinstance(raw, dict) else {}
475 known = {f for f in cls.__dataclass_fields__}
476 fields = {k: v for k, v in data.items() if k in known and k != "extra"}
477 # ``stored`` leaves empty fields out, an empty objective included.
478 fields.setdefault("objective", "")
479 return cls(**fields, extra={k: v for k, v in data.items() if k not in known})
481 @classmethod
482 def from_proposal(cls, proposal: ProposedTask | RoutedQuestion) -> TaskBrief:
483 return cls(
484 objective=proposal.objective.strip(),
485 output_format=proposal.output_format.strip(),
486 done_when=proposal.done_when.strip(),
487 sources=proposal.sources.strip(),
488 boundaries=proposal.boundaries.strip(),
489 specialism=proposal.specialism.strip(),
490 effort=Effort(proposal.effort).value,
491 )
493 def stored(self) -> dict[str, Any]:
494 data = asdict(self)
495 extra = data.pop("extra") or {}
496 return {**{k: v for k, v in data.items() if v}, **extra}