🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
💼 Servicesℹ️ About✉️ ContactView Pricing Plansfrom $10

Multi-Agent LLM Systems: Topologies and Consensus

Advanced LLMOpsMulti-Agent Systems🟢 Free Lesson

Splitting one hard task across several specialized agents can beat a single generalist — a research agent gathers facts, an implementation agent writes code, a critic agent attacks the result. It can also triple your bill, multiply latency, and produce three agents that confidently contradict each other. Multi-agent design is an exercise in deciding where decomposition pays and where it just adds coordination overhead.

This lesson covers the practical middle ground: which orchestration topologies exist and when each earns its cost, how to structure handoffs so agents pass state cleanly, how consensus mechanisms turn disagreement into a single decision, and how to contain the cascade failures that only appear once agents can fail each other.

When decomposition helps — and when it does not

The argument for multiple agents is specialization and parallelism. An agent whose system prompt, tool set, and memory are narrow can be much better at its slice than one prompt trying to do everything, and independent subtasks can run concurrently, wall-clock time dropping to the slowest branch instead of the sum of all work. The argument against is coordination cost: every handoff spends tokens re-describing state, every extra model call is another chance to inject error, and sequential pipelines multiply latency.

A useful rule of thumb: decompose along boundaries that already exist in your problem. Code generation naturally splits into plan, implement, test, and review because those are different skills with different tools. Vague "be smarter by using more agents" decompositions mostly reproduce the same mediocre prompt four times at four times the price. Parallel fan-out is worth it when subtasks are independent and individually expensive; sequential chains are worth it when each stage's output materially conditions the next. Peer-to-peer meshes are rarely worth it in production — they are great research objects and miserable things to debug at two in the morning.

TopologyLatency profileFailure isolationCoordination costBest fit
Single agentLowestBestNoneSimple or ambiguous tasks
Sequential chainSum of stage timesPoor — one failure blocks allLowDocumented multi-stage workflows
Parallel fan-outSlowest branchGoodMediumIndependent research or analysis shards
Orchestrator–workerMediumGoodMediumComplex tasks with clear subtask structure
Consensus / committeeVoting roundsExcellentHighHigh-stakes decisions needing agreement
Peer-to-peer meshUnpredictablePoorVery HighExperiments, rarely production

Orchestrator–worker: decomposition with dependencies

The orchestrator–worker pattern keeps one agent in charge of planning and delegates leaves to specialists. The orchestrator turns a request into a subtask graph with explicit dependencies, dispatches ready tasks to the workers best equipped for them, and aggregates the results. The critical design choice is representing dependencies explicitly rather than assuming a fixed order, because real tasks branch and rejoin.

python
import uuid
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional


class TaskState(Enum):
    PENDING = "pending"
    READY = "ready"
    DONE = "done"
    FAILED = "failed"


@dataclass
class SubTask:
    task_id: str
    role: str
    goal: str
    deps: List[str] = field(default_factory=list)
    state: TaskState = TaskState.PENDING
    result: Optional[str] = None


class Orchestrator:
    def __init__(self, workers: Dict[str, Any]):
        self.workers = workers
        self.tasks: Dict[str, SubTask] = {}

    def plan(self, goal: str, blueprint: List[Dict[str, Any]]) -> None:
        for spec in blueprint:
            tid = str(uuid.uuid4())[:8]
            self.tasks[tid] = SubTask(
                task_id=tid, role=spec["role"], goal=spec["goal"],
                deps=spec.get("deps", []),
            )

    def ready_set(self) -> List[SubTask]:
        done = {t.task_id for t in self.tasks.values()
                if t.state is TaskState.DONE}
        return [t for t in self.tasks.values()
                if t.state is TaskState.PENDING and set(t.deps) <= done]

    def run_ready(self) -> Dict[str, Any]:
        results = {}
        for task in self.ready_set():
            worker = self.workers.get(task.role)
            if worker is None:
                task.state = TaskState.FAILED
                results[task.task_id] = {"error": f"no worker for {task.role}"}
                continue
            context = "\n".join(
                self.tasks[d].result or "" for d in task.deps
            )
            task.result = worker(task.goal, context)
            task.state = TaskState.DONE
            results[task.task_id] = {"result": task.result}
        return results

    def is_complete(self) -> bool:
        return all(t.state in (TaskState.DONE, TaskState.FAILED)
                   for t in self.tasks.values())

    def failed_tasks(self) -> List[SubTask]:
        return [t for t in self.tasks.values() if t.state is TaskState.FAILED]

Notice two operational habits. First, the orchestrator can call run_ready in a loop, executing whatever is unblocked each round, which handles both parallel branches and diamond dependencies without special cases. Second, failures are first-class: a failed worker leaves a visible hole the orchestrator can retry, route around, or surface to a human, instead of silently corrupting the final synthesis.

Structured handoffs between agents

Agents pass state through messages, and the format of those messages decides whether the system stays debuggable. Free-form prose handoffs force each downstream agent to re-parse intent, and errors compound invisibly. A structured envelope — task reference, claims, evidence, confidence, and explicit open questions — keeps contracts tight and lets you diff what one agent claimed against what the next one believed.

python
from dataclasses import dataclass, field
from typing import Any, Dict, List


@dataclass
class Handoff:
    from_role: str
    to_role: str
    task_id: str
    summary: str
    claims: List[str] = field(default_factory=list)
    evidence: List[str] = field(default_factory=list)
    open_questions: List[str] = field(default_factory=list)
    confidence: float = 0.5

    def validate(self) -> List[str]:
        problems = []
        if not self.summary.strip():
            problems.append("empty summary")
        if not 0.0 <= self.confidence <= 1.0:
            problems.append("confidence out of range")
        if len(self.evidence) == 0 and self.confidence > 0.7:
            problems.append("high confidence without evidence")
        return problems

    def to_prompt_block(self) -> str:
        lines = [
            f"Task {self.task_id}, from {self.from_role} to {self.to_role}.",
            f"Summary: {self.summary}",
        ]
        if self.claims:
            lines.append("Claims:")
            lines.extend(f"- {c}" for c in self.claims)
        if self.evidence:
            lines.append("Evidence:")
            lines.extend(f"- {e}" for e in self.evidence)
        if self.open_questions:
            lines.append("Open questions:")
            lines.extend(f"- {q}" for q in self.open_questions)
        lines.append(f"Confidence: {self.confidence:.2f}")
        return "\n".join(lines)


class MessageBus:
    def __init__(self):
        self.envelopes: List[Handoff] = []

    def publish(self, handoff: Handoff) -> bool:
        problems = handoff.validate()
        if problems:
            raise ValueError(f"invalid handoff: {problems}")
        self.envelopes.append(handoff)
        return True

    def inbox_for(self, role: str) -> List[Handoff]:
        return [h for h in self.envelopes if h.to_role == role]

    def audit_trail(self) -> List[Dict[str, Any]]:
        return [
            {"task": h.task_id, "route": f"{h.from_role}->{h.to_role}",
             "confidence": h.confidence}
            for h in self.envelopes
        ]

The validate gate is doing quiet, important work: a research agent that reports 0.95 confidence with zero evidence is exactly the failure mode that makes multi-agent systems worse than a single model, and rejecting it at the bus level keeps the disease from spreading.

Consensus when agents disagree

Committee patterns — majority vote, weighted vote, judge-and-refine — appear whenever a decision is expensive to get wrong. Majority voting is simple and surprisingly effective at correcting single-agent slips, but it assumes agents are roughly independent, which they are not when they share a base model and a prompt lineage. Weighted voting lets you trust calibrated sources more, and a quorum requirement prevents the committee from deciding anything on thin participation.

python
from collections import Counter
from typing import Dict, List


class ConsensusEngine:
    def __init__(self, quorum: int):
        self.quorum = quorum
        self.votes: Dict[str, List[Dict[str, str]]] = {}

    def cast(self, proposal: str, voter: str, position: str) -> None:
        self.votes.setdefault(proposal, []).append(
            {"voter": voter, "position": position}
        )

    def tally(self, proposal: str, weights: Dict[str, float] = None) -> Dict[str, Any]:
        votes = self.votes.get(proposal, [])
        if len(votes) < self.quorum:
            return {"decided": False, "reason": "quorum not met",
                    "votes": len(votes)}
        scores: Dict[str, float] = Counter()
        for vote in votes:
            weight = (weights or {}).get(vote["voter"], 1.0)
            scores[vote["position"]] += weight
        winner, top = scores.most_common(1)[0]
        margin = top - sorted(scores.values(), reverse=True)[1] \
            if len(scores) > 1 else top
        return {
            "decided": True,
            "position": winner,
            "scores": dict(scores),
            "margin": round(margin, 2),
            "thin_margin": margin < 0.5,
        }

Track the margin, not just the winner. A decision carried 3–2 is qualitatively different from one carried 5–0, and routing thin-margin outcomes to a human reviewer or a stronger model is a cheap way to concentrate scrutiny where it is actually needed.

Tracing the graph: debugging multi-agent runs

When a multi-agent system produces a wrong answer, the failure almost never lives in the final synthesis step — it lives three hops upstream, where a research agent cited a source it never actually read. Debugging that requires a trace that reconstructs the whole graph execution: which subtasks ran, in what order, with which inputs and outputs, and how long each model call took. Log each hop as a structured record keyed by the originating request ID, and never sample away the slow or failing paths, because those are precisely the ones you will need later.

Read traces along two axes. The structural axis shows the graph: which branch stalled, which worker retried, which dependency edge forced serialization that looked parallel on the whiteboard. The content axis shows information flow: what each agent claimed, what evidence it attached, and what the next agent actually received. Disagreement between those two — a worker that reports success while its output contradicts its stated evidence — is a prompt or tooling bug that aggregate metrics will never surface. Keep traces long enough to satisfy your audit requirements, and keep a compact per-request summary alongside them so on-call engineers are not spelunking raw JSON at three in the morning.

Budgets, cascades, and operational hygiene

Multi-agent systems fail in ways single agents do not. One slow worker stalls a critical path. One worker's garbage output becomes three downstream agents' inputs. A retry storm from every orchestrator multiplies load on the same flaky dependency. The defenses are structural: hard per-request budgets measured across all agents, timeouts on every hop, retry limits with exponential backoff, and schema validation on every handoff boundary.

Cost math deserves explicit attention, because token spend grows superlinearly with conversation depth: if each of four agents reads the full transcript of everything before it, the fourth agent pays for all three predecessors' tokens. Passing compact structured summaries instead of raw transcripts keeps costs closer to linear.

Common Mistakes

Decomposing a trivial task across four agents to look sophisticated

Fix: Start with one agent and split only when a measured failure mode points at a missing specialization.

Letting agents pass free-form prose between each other

Fix: Use structured handoffs with claims, evidence, and confidence, and validate them at the bus.

Running unbounded multi-agent conversations

Fix: Set a global token and step budget per user request, shared across every agent in the graph.

Treating majority vote as ground truth

Fix: Inspect vote margins and escalate thin margins; correlated agents share the same blind spots.

Ignoring idempotency in worker retries

Fix: Make worker tasks safe to re-run, since orchestrators will retry flaky steps.

Best Practices

  • Log every inter-agent handoff with correlation IDs; the audit trail is your only map when a synthesis looks wrong.
  • Cap parallel fan-out width; ten concurrent workers rarely help and often destroy latency and budgets.
  • Give the orchestrator a synthesis step that cites which subtask produced each claim, so errors are traceable to their source.
  • Load-test multi-agent graphs with synthetic failures — timeouts, malformed handoffs — before real traffic finds them.
  • Prefer two well-specified agents over five loosely-specified ones; clarity beats headcount in every topology.

Key Takeaways

  • Decompose along real skill and tool boundaries; artificial splits multiply cost without improving quality.
  • Orchestrator–worker with explicit dependency graphs handles branching workflows cleanly and makes failures first-class.
  • Structured handoffs with claims, evidence, and confidence — validated at the message bus — are what keep multi-agent systems debuggable.
  • Consensus voting corrects single-agent slips but needs quorum, weights, and margin tracking to stay honest.
  • Global budgets, per-hop timeouts, and idempotent workers contain the cascade failures unique to multi-agent systems.
CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Need Expert AI Ops & LLM Ops Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement