What multi-agent means in practice
A production multi-agent system is rarely a society of autonomous minds. It is a pipeline in which several model calls have different prompts, tools and context, and ordinary code decides how their outputs flow. One stage classifies the request, another plans, several workers handle independent sub-tasks in parallel, a critic checks the result and a final stage writes the answer. Each stage can use a different model, a different temperature and a different tool set. The value comes from specialisation and separation: a small model can route cheaply, a strong model can plan, a fast model can extract, and a verifier can catch errors the generator missed. The risk is that every added stage adds cost, latency and a new place for information to be lost.
Why put a gateway in the middle
The gateway is not an agent framework. It does not plan or orchestrate; it standardises and controls access to models. That separation is healthy: orchestration stays in code you can read and test.
- One protocol: every stage calls the same chat completions shape, whether the model is a local open-weight server, a hosted frontier API or a fallback provider.
- Routing: the gateway maps a stable alias such as planner or worker-fast to a concrete model and can change that mapping without a code deploy.
- Fallbacks: when a provider returns 429 or 500, the gateway retries another model in a defined order instead of failing the run.
- Credential isolation: agents authenticate to the gateway with their own virtual keys, and the gateway holds the provider keys. A leaked worker key does not leak the provider account.
- Budgets and quotas: per-key spend limits, token caps and rate limits prevent one runaway loop from consuming the month's budget.
- Observability: one place logs model, latency, tokens, cost, request id and response for every stage, which is far easier than instrumenting five SDKs.
- Caching and guardrails: exact or semantic response caches, PII redaction and prompt policy can be applied uniformly.
The OpenAI-compatible contract
An OpenAI-compatible gateway exposes routes such as /v1/chat/completions, /v1/models and often /v1/embeddings, accepting the same request body and returning the same response shape. In practice, compatibility is a spectrum. Tool calling, streaming, JSON schema response formats, vision inputs, reasoning fields and usage accounting are all optional in the implementations you will meet. The base contract covers messages, model, temperature, max_tokens and stop; tool calls and structured outputs are where drift appears. Before committing, run a compatibility matrix: a plain completion, a streaming completion, a tool call with two tools, a parallel tool call, a JSON-schema response, a long-context request and an error case. Record which model actually served each request. "Works with the OpenAI SDK" is not the same as "behaves identically to OpenAI".
A reference pipeline
A support-engineering assistant shows the shape. The router reads the request and labels it as bug report, how-to question or billing issue, then selects a playbook. The planner turns the request into a small task graph: reproduce the bug, search related tickets, inspect recent deploys, draft a reply. Three workers run in parallel, each with its own tools and a narrow slice of context: the reproduction worker has a code sandbox, the ticket worker has search, the deploy worker has read-only access to release metadata. A verifier receives the workers' claims and checks each one against the evidence they returned, rejecting unsupported statements. The synthesizer writes the final answer using only verified claims and cites the ticket or deploy it came from. A human gate sits before anything is sent to the customer. Every arrow is a function call in your code, not a conversation between models.
Contracts between stages are the design
The most important engineering decision is what each stage receives and returns. Free-form prose between agents produces a telephone game: the planner's intent degrades as each model paraphrases it. Prefer typed JSON with a versioned schema. The planner returns a list of tasks with ids, an assigned worker, an input object and dependencies. A worker returns findings as structured records with a claim, evidence, source id and confidence, plus an errors array. The verifier returns a verdict of pass or revise, a list of issues with the claim and the missing evidence, and a confidence. The synthesizer receives the original request, the verified records and the citations, not the entire transcript. Validate every boundary with a schema and treat a validation failure as a stage failure, not something to paper over with a repair prompt.
Choosing an orchestration pattern
Start with the simplest pattern that passes your evaluation. A sequential chain with two good stages usually beats a five-agent graph with vague contracts.
- Sequential chain: each stage consumes the previous output. Simplest to reason about; use when the work is genuinely linear.
- Fan-out and fan-in: independent workers run concurrently and a reducer merges results. Best for research, document analysis and multi-file code tasks.
- Supervisor with handoffs: a controller decides which specialist acts next and when to stop. Flexible but harder to evaluate; cap the number of handoffs.
- Critic loop: a generator and a verifier iterate until the verdict passes or a budget expires. Effective for correctness-critical output; dangerous when the critic is weak or shares the generator's blind spots.
- Map-reduce over artefacts: split a large corpus into chunks, process each with the same worker prompt, then aggregate. The most predictable pattern for scale.
Aliases, routing and model choice
Never hard-code raw model names in application code. Define stage aliases in the gateway: router, planner, worker-fast, worker-strong, verifier, synthesizer. Each alias maps to a primary model, an ordered fallback list, a timeout and a token limit. This lets you swap a model for cost or quality without touching the pipeline, and it makes experiments possible: route ten percent of traffic to a new model and compare outcomes. Match model to stage rather than assuming the largest model everywhere. Classification and extraction often work well on a small, fast model; planning and final synthesis benefit from stronger reasoning; verification benefits from a different model family than the generator, because independent errors are easier to catch. Measure each stage separately before optimising the whole.
Implementing the fan-out
The pipeline is ordinary asynchronous code. Create one client pointed at the gateway's base URL with the agent's virtual key. For each stage, build a request with its alias, system prompt, messages and tools, call the client with a per-stage timeout, and validate the response against the stage schema. For parallel workers, launch them with asyncio.gather and collect results with return_exceptions so one failure does not cancel the others. If a worker fails, pass a structured failure record to the synthesizer rather than silently dropping the task. Use JSON-schema response formats where the gateway and model support them, and fall back to a JSON object mode plus validation where they do not. Keep the orchestration code boring: explicit functions, explicit retries, explicit state.
State, artefacts and traces
A run needs one durable record: run id, user request, stage statuses, model aliases used, token counts, costs, errors and artefact references. Large outputs — retrieved documents, code diffs, worker reports — belong in an artefact store, with ids passed between stages. This keeps prompts small and makes replay possible. Assign a trace id at intake and propagate it through every gateway request; most gateways can attach it as metadata. Checkpoint after each stage so a failure at the verifier does not re-run three workers. Compact context deliberately: send the synthesizer verified claims and citations, not every raw tool result. If you must send a long history, summarise it at a stage boundary and keep the original in the artefact store for audit.
Reliability and fallbacks
The gateway handles transport-level failures: connection errors, 429s, 5xx responses and timeouts, with retries and fallback models. It cannot handle semantic failures: a valid response that is wrong, empty or off-schema. Build both layers. Set a timeout per stage and a deadline for the whole run. Retry only idempotent stages, and make worker tools idempotent so a retry does not duplicate a write. Use a circuit breaker per provider alias so a sick model stops receiving traffic. Validate fallback models before trusting them: a fallback may not support tool calling or may emit a different reasoning format, so the gateway needs per-model capabilities and the pipeline needs to know which model actually ran. When the verifier rejects twice, return a partial result with the unresolved issues rather than looping forever.
The cost and latency maths
A single call with a 4,000-token prompt and 600 output tokens is the baseline. A five-stage pipeline might use 1,000 tokens for routing, 2,500 for planning, four workers at 2,500 each, 6,000 for verification and 8,000 for synthesis: roughly 27,500 input tokens and 3,000 output tokens, five to seven times the baseline before retries. At $0.60 per million input tokens and $2.40 per million output, that is about $0.024 per run versus $0.004 — small per task, material at a million tasks. Latency behaves differently: fan-out workers run in parallel, so wall-clock time is the sum of the stages, not of every call. A router, a planner, one parallel worker round, a verifier and a synthesizer is five sequential hops; at two seconds each, ten seconds before tool time. Cache aggressively where inputs repeat, cap retries, and consider early exit when the router can answer directly.
Evaluation at two levels
Evaluate stages and outcomes separately. Stage metrics catch regressions cheaply: router label accuracy on a labelled set, planner task coverage, worker groundedness (does every claim have evidence), verifier precision and recall on deliberately seeded errors, synthesizer citation accuracy. End-to-end metrics tell you whether the system works: task success judged against a rubric, human acceptance rate, escalation rate, cost per completed task and p95 latency. Keep a golden set of fifty to a hundred real requests with expected outcomes, and replay it after every prompt, alias or model change. Use an LLM judge for breadth but calibrate it against human labels on a sample, and never let the generator's own family be the only judge. Track the rate at which the fallback model served traffic; a silent fallback can quietly change quality.
Security and governance
The gateway is a useful policy point. Give each agent its own virtual key, restrict which aliases it may call, cap spend and log every request. Redact PII before it leaves your network if the model is hosted. Treat every inter-agent message as untrusted: a worker that read a malicious web page can pass injected instructions to the synthesizer. Keep instructions in system messages and data in user or tool messages, delimit data clearly, and enforce tool permissions at the runtime rather than trusting a prompt. Do not put provider keys, database passwords or customer secrets in prompts. Keep an audit trail of which model saw which data, because that is the first question in any incident review.
Failure modes to design against
- Misrouting: the router sends a billing issue to the code worker, which burns tokens and returns irrelevant findings. Add a low-confidence fallback to a generalist or a human.
- Duplicate work: workers overlap because the planner did not partition tasks. Give each a disjoint scope and an explicit deliverable.
- Rubber-stamp critic: the verifier approves everything. Seed known errors in evaluation and measure catch rate; use a different model family.
- Context poisoning: one hallucinated claim becomes an input fact for every later stage. Require evidence ids and verify before synthesis.
- Infinite handoff: agents keep passing work back. Cap hops and total steps per run.
- Silent fallback: the gateway switches to a weaker model mid-run and quality drops without an error. Record the served model and alert on fallback rate.
- Schema drift: a prompt change alters a field name and the next stage silently reads null. Version schemas and validate.
- Cost blowout: retries plus fan-out multiply spend. Budget per run and per key, and alert on outliers.
Build order
Start with two stages: a worker that does the task and a verifier that checks it. Measure quality and cost. Add a router only when different request types genuinely need different tools or prompts. Add parallel workers when latency or context size demands it, not because the diagram looks better. Keep orchestration in code, prompts in version control, aliases in gateway config, and contracts in schemas. Every stage must justify its tokens with a measured improvement, or it is just an expensive way to paraphrase.
Bottom line
A multi-agent pipeline is distributed system design applied to model calls. The gateway gives you one contract, controlled failover and a single place to see cost and behaviour; the pipeline gives you specialisation and separation of concerns. Neither gives you correctness for free. Type the boundaries, verify the claims, cap the loops, measure each stage and keep the graph as small as the task allows.