AI agents

Building Multi-Agent AI Systems: Architecture Patterns and Best Practices

Five orchestration patterns for multi-agent systems, with code for handoffs, parallel work, shared state and voting, and the limits that keep them stable.

By the APIStack team··Updated ·10 min read

A white humanoid robot looking at the camera

A multi-agent system splits a task across several model-driven agents, each with its own instructions and tools, and coordinates them to produce one result. This article covers the orchestration patterns in common use, how agents share tools and state, how to resolve disagreement between them, and the limits that keep such a system predictable.

It is written for developers who already have a single agent working and are deciding whether, and how, to add more.

Decide whether you need more than one agent

Every extra agent adds model calls, latency and another place for a run to go wrong. Anthropic's guide to building effective agents recommends finding the simplest solution that works and adding multi-step agentic behaviour only when simpler approaches fall short. It also separates workflows, where code decides the order of the steps, from agents, where the model decides.

Splitting work across agents pays off in a few specific situations. The subtasks may be independent and able to run in parallel. They may need different tools or permissions, so that a research agent can browse while only a billing agent can issue refunds. Or one prompt may have grown so long that the model no longer follows all of it. If none of these applies, a single agent with well-described tools is usually the better design.

Orchestration patterns

Five patterns cover most systems. Microsoft's Agent Framework, the successor to Semantic Kernel and AutoGen, ships all five as builders. Its orchestration announcement uses the same categories and calls the last one Magentic.

PatternWho decides the next stepGood fitMain cost
SequentialYour code, in a fixed orderPipelines such as research, draft, reviewLatency is the sum of every stage
ConcurrentYour code, fanning out and mergingIndependent subtasks or several viewpointsNeeds a merge step and handling for partial failure
HandoffThe agent currently in controlTriage and escalation between specialistsRouting rules must rule out loops
Group chatA moderator, each turnReview and critique among a few agentsToken use grows with every turn
Manager-ledA manager agent that plans and replansOpen-ended tasks with no known pathLeast predictable and most expensive

Sequential and concurrent

These two need no framework. The following Python sketch assumes a run_agent(name, prompt) coroutine that wraps whichever model client you use and returns text; that function is a placeholder for your own code and does not come from a library. The research stage runs two agents in parallel, then a writer and a reviewer run in order.

Python
import asyncio

async def run_agent(name: str, prompt: str) -> str:
    raise NotImplementedError("call your model client here")

async def write_report(topic: str) -> str:
    technical, market = await asyncio.gather(
        asyncio.wait_for(run_agent("technical", f"Research the technology behind {topic}"), 120),
        asyncio.wait_for(run_agent("market", f"Research the market for {topic}"), 120),
        return_exceptions=True,
    )
    findings = [r for r in (technical, market) if isinstance(r, str)]
    if not findings:
        raise RuntimeError("every research agent failed")

    draft = await run_agent("writer", "Write a report from these notes:\n\n" + "\n\n".join(findings))
    return await run_agent("reviewer", f"Correct errors and tighten this report:\n\n{draft}")

Two details matter here. return_exceptions=True lets the report go ahead when one researcher fails, and the timeouts stop a stalled agent from holding up the run. In the concurrent stage the slowest agent sets the latency. In the sequential stage every agent adds to it.

Handoff

In a handoff, the agent in control transfers the conversation to another agent. The OpenAI Agents SDK models this directly: each agent lists the agents it may hand off to, and the model picks one by calling a generated tool.

Python
import asyncio
from agents import Agent, Runner

billing_agent = Agent(name="Billing agent", instructions="Resolve billing and payment questions.")
technical_agent = Agent(name="Technical agent", instructions="Resolve API and integration questions.")

triage_agent = Agent(
    name="Triage agent",
    instructions="Decide which specialist should answer, then hand off.",
    handoffs=[billing_agent, technical_agent],
)

async def main():
    result = await Runner.run(triage_agent, "I was charged twice this month.", max_turns=8)
    print(result.final_output)

asyncio.run(main())

max_turns caps the run, and the SDK raises MaxTurnsExceeded when the cap is reached. Keep the handoff graph acyclic where you can, so that a specialist escalates forward to a person and never back to triage. Pass on a short summary of the conversation in place of the full transcript.

Group chat and manager-led orchestration

In a group chat, agents take turns in a shared conversation and a moderator, which may be a round-robin rule or another model, picks the next speaker. It suits a writer and a reviewer iterating on a draft. It needs a hard turn limit, because nothing in the pattern itself ends the conversation.

Manager-led orchestration, which Microsoft calls Magentic, gives a manager agent the goal. The manager writes a plan, assigns steps to specialists, checks progress after each round and replans when the team stalls. In the Agent Framework the limits are explicit parameters on the builder. This excerpt assumes researcher, coder and manager are Agent objects you have already created with a model client, as shown in the Magentic documentation.

Python
from agent_framework.orchestrations import MagenticBuilder

workflow = MagenticBuilder(
    participants=[researcher, coder],
    manager_agent=manager,
    max_round_count=10,
    max_stall_count=3,
    max_reset_count=2,
).build()

Use this pattern only when you cannot write the steps down in advance. If you can, a sequential or concurrent workflow is cheaper and easier to test.

Tools, context and communication

Three separate concerns are often confused.

Agents reach tools and data through function calling, and the Model Context Protocol is the standard way to package those tools so that any agent runtime can use them. MCP connects an agent to tools. It is not a channel between agents and has no shared context store.

Agents built by different teams or vendors talk to each other through an agent-to-agent protocol. Agent2Agent (A2A) is the open specification for this: an agent publishes a card that describes what it can do, and other agents send it tasks.

Agents inside one application usually need neither. They are function calls in the same process, or jobs on a queue when the work is long-running. If you use a queue, make handlers idempotent, because a retried message will otherwise repeat an agent's side effects.

Sharing state

Give each agent private working context and pass results forward explicitly. Shared mutable state invites race conditions between agents that run at the same time, and it also pads every agent's prompt with material it does not need.

When agents do have to update the same record, use optimistic concurrency: read a version number, write only if it has not changed, and retry on conflict. The db object below stands for your own data layer, and apply_updates for your merge logic.

Python
import asyncio
import random

async def update_shared_state(db, state_id: str, updates: dict, max_attempts: int = 5):
    for attempt in range(max_attempts):
        current = await db.get(state_id)
        new_state = apply_updates(current, updates)
        new_state.version = current.version + 1

        if await db.update_if_version(state_id, new_state, expected_version=current.version):
            return new_state
        await asyncio.sleep(random.uniform(0.1, 0.5) * (attempt + 1))

    raise RuntimeError(f"gave up updating {state_id} after {max_attempts} conflicts")

In SQL, update_if_version is an UPDATE ... WHERE id = ? AND version = ? followed by a check on the affected row count. A single database with transactions resolves almost every coordination problem an agent system has. Distributed consensus algorithms are rarely the missing piece.

Resolving disagreement

Agents given the same question will sometimes return different answers. Decide in advance how the system settles that.

The simplest rule is a fixed priority, where the agent with the authoritative data source wins. Where no agent is authoritative, run several and take a vote, and escalate when the margin is too small. This function requires a two-thirds majority and otherwise returns nothing, which the caller treats as "ask a person".

Python
import asyncio
from collections import Counter

async def resolve_by_vote(agents, question: str, threshold: float = 2 / 3):
    votes = await asyncio.gather(*(agent.vote(question) for agent in agents))
    answer, count = Counter(votes).most_common(1)[0]
    return answer if count / len(votes) >= threshold else None

Voting works only when answers can be compared, so ask voters for a constrained output such as a label or a number. Agents that run the same model on the same prompt are likely to repeat the same mistake, so vary the instructions or the evidence each one sees. For factual questions, a deterministic tool is a better tie-breaker than a third opinion.

Limits and human review

Because a model decides each next step, an agent loop has no natural end. Put the limits in code, not in the prompt:

  • a maximum number of turns or rounds for each run
  • a timeout on every agent call and every tool call
  • a token or cost budget for each task, checked by the orchestrator
  • a rule that the same handoff cannot happen twice in a row

Pause for human approval before any action that is hard to undo, such as sending a message, moving money or deleting data. Design the pause as a normal state the workflow can be resumed from, so that a slow reviewer does not turn into a timeout.

Observability and testing

A failed multi-agent run is hard to debug from the final output alone. Record a trace for each task with one span per agent call and per tool call, including the inputs, the outputs, the token counts and the agent that made each handoff. OpenTelemetry fits well, and the current MCP revision documents how to carry its trace context in request metadata, so a trace can follow a call into a tool server.

Attribute cost to each agent, so that an expensive one, such as an orchestrator that rereads the full history on every turn, is visible. Test each agent on its own with fixed inputs, and keep a small set of end-to-end tasks with known good answers to run after every prompt or model change.

Security

Give each agent only the tools and credentials its role needs. An agent that summarises web pages should hold no credential that can write to your database.

Carry the end user's identity through every handoff, and authorise each tool call against that user, not against the agent. Otherwise an agent with broad access becomes a way around your permission model.

Treat everything an agent reads as untrusted, including web pages, documents, tool results and messages from other agents. Text in any of them can contain instructions aimed at the model. Keep agents that read untrusted content apart from agents that can take consequential actions, and require approval at the boundary between them.

Giving agents exact answers

Many disagreements between agents are about facts a model should not be guessing: today's date in another time zone, whether a day is a public holiday, an exchange rate, whether an IBAN is valid. Give every agent the same deterministic tools for these and the disagreement does not arise.

APIStack provides such tools over MCP on every plan. The facts server at https://apistack.online/api/mcp/facts works without a key for 50 calls a day. With an API key in the x-api-key header, calls use your plan's quota instead; the free plan includes 1,000 calls a month. Setup for common clients is on the MCP page.

Summary

  • Add agents only when subtasks are independent, need different tools or permissions, or no longer fit in one prompt.
  • Prefer sequential and concurrent workflows that your code controls. Use handoff, group chat and manager-led orchestration when the path cannot be known in advance.
  • Keep agent context private, pass results explicitly, and use versioned writes for any state agents share.
  • Enforce turn limits, timeouts and budgets in code, and require human approval before irreversible actions.
  • Trace every agent and tool call, attribute cost to each agent, and treat all content agents read as untrusted.

Build with APIStack

One API key for validation, dates and holidays, web checks and reference data, over REST or as MCP tools for your AI agents. The free plan includes 1,000 calls a month.

Keep reading