Multi Agent Llm Systems

Production-grade guide to multi agent llm systems covering architecture patterns, implementation strategies, testing approaches, and operational best practices for enterprise engineering teams.

Multi-agent LLM systems coordinate two or more LLM-driven processes to tackle problems that exceed the context window, reliability, or capability limits of a single prompt. They matter when a task naturally decomposes into sub‑goals that benefit from specialized prompts, parallel execution, or sequential hand‑offs, when you need to maintain conversation state across multiple runs, or when you want to route tool calls and error handling independently for each sub‑agent. This page covers the engineering patterns, standard tooling, and failure modes you encounter when building or operating such systems.

Designing coordination patterns

Agents typically interact through one of three structural patterns. The choice determines how prompts are constructed, how results are merged, and how failures propagate.

Sequential handoffs One agent completes its turn and passes a summary or a set of extracted facts to the next agent. This is common in research‑or‑analysis pipelines where each stage narrows the scope. The output of agent *i* becomes the system or user message for agent *i + 1*.

Parallel branching Multiple agents receive the same input or split the input among themselves and run concurrently. Results are collected and merged—often by a downstream aggregator agent or a deterministic script. This pattern reduces overall latency when sub‑tasks are independent.

Hierarchical supervision A “manager” agent observes the outputs of worker agents, decides whether to request revisions, or escalate to a higher‑level agent. The manager does not necessarily execute the core logic; its role is routing, quality checks, or budget enforcement.

Sequential handoffs


AGENT1_OUTPUT=$(docker run --rm --name agent1 \
  -e PROMPT="Analyze the input and return a 3‑bullet summary." \
  your‑registry/researcher-agent)

docker run --rm --name agent2 \
  -e SYSTEM_PROMPT="You are a summarizer. Use this context: $AGENT1_OUTPUT" \
  your‑registry/editor-agent

The key mechanical detail is that the second agent’s system prompt is populated from the first agent’s standard output. If the first agent exits with a non‑zero code, the pipeline should short‑circuit or log the failure before invoking the second agent.

Parallel branching

# Launch three agents concurrently, each receiving the same user query
QUERY="Compare the trade‑offs of consistency vs. availability in distributed systems."

for ROLE in researcher analyst engineer; do
  docker run --rm --name "agent-${ROLE}" -d \
    -e USER_QUERY="$QUERY" \
    -e AGENT_ROLE="$ROLE" \
    your‑registry/reasoner-agent &
done
wait

Each container reads USER_QUERY and AGENT_ROLE at startup, produces a JSON result to stdout, and exits. A collector process (or jq‑based pipe) merges the three outputs into a single report. If any container crashes before producing output, the collector must decide whether to retry, mark the slot as “failed,” or proceed with partial data.

Managing shared state

Agents often need a persistent view of the conversation, completed tasks, or cached tool results. A relational store is the most predictable medium for this state because it supports transactions and simple query patterns.

State store with PostgreSQL

# Create the table once (idempotent)
psql -U postgres -c \
  "CREATE TABLE IF NOT EXISTS agent_sessions (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    agent_role TEXT NOT NULL,
    status TEXT NOT NULL CHECK (status IN ('running','completed','failed')),
    last_message JSONB,
    result JSONB,
    created_at TIMESTAMPTZ DEFAULT now(),
    updated_at TIMESTAMPTZ DEFAULT now()
  );"

# Record the start of a run
psql -U postgres -c \
  "INSERT INTO agent_sessions (agent_role, status, last_message)
   VALUES ('researcher', 'running', '{\"status\":\"started\"}');"

# Update after the agent finishes
psql -U postgres -c \
  "UPDATE agent_sessions
     SET status = 'completed',
         result = '{\"summary\":\"...\"}',
         updated_at = now()
   WHERE id = (SELECT id FROM agent_sessions ORDER BY created_at DESC LIMIT 1);"

The status column prevents duplicate runs and gives a single‑source‑of‑truth for monitoring. The last_message column can store the final LLM response or an error payload, which is useful for post‑mortem debugging.

Versioning prompts and agent code

# Store a prompt version alongside its hash so you can reproduce behavior
PROMPT_FILE=prompts/researcher-v1.txt
PROMPT_HASH=$(sha256sum "$PROMPT_FILE" | cut -d' ' -f1)

git add "$PROMPT_FILE"
git commit -m "researcher prompt v1 (hash: $PROMPT_HASH)"

# Reference the hash when launching a container
docker run --rm --name researcher \
  -e PROMPT_HASH="$PROMPT_HASH" \
  -v "$(pwd)/prompts:/etc/prompts" \
  your‑registry/researcher-agent

Tying a content hash to the runtime configuration makes it trivial to assert “this agent ran with this exact prompt” during audits or incident reviews.

Deploying and scaling agent processes

Containerizing a single agent

A minimal Dockerfile for an agent that reads environment variables and calls an LLM endpoint:

FROM python:3.12-slim

WORKDIR /app

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY agent.py .
ENV PORT=8080
EXPOSE 8080

CMD ["python", "agent.py"]
# agent.py (simplified)
import os, json, requests

LLM_URL = os.getenv("LLM_ENDPOINT", "https://example.com/v1/chat")
TOKEN   = os.getenv("LLM_TOKEN", "")
PROMPT  = os.getenv("AGENT_PROMPT", "")

def call_llm(messages):
    resp = requests.post(
        LLM_URL,
        json={"messages": messages, "model": os.getenv("MODEL", "default")},
        headers={"Authorization": f"Bearer {TOKEN}"},
        timeout=30,
    )
    if resp.status_code != 200:
        raise RuntimeError(f"LLM error {resp.status_code}: {resp.text}")
    return resp.json()["choices"][0]["message"]["content"]

if __name__ == "__main__":
    user_msg = os.stdin.read() or "No input"
    messages = [{"role": "system", "content": PROMPT},
                {"role": "user",   "content": user_msg}]
    print(call_llm(messages))

Build and run:

docker build -t my‑agent .
docker run --rm -e AGENT_PROMPT="You are a concise researcher." my‑agent

Orchestrating with Kubernetes

When you need more than a few concurrent agents, kubectl manages the lifecycle, restarts, and resource limits.

# agent-deployment.yaml (minimal)
apiVersion: apps/v1
kind: Deployment
metadata:
  name: agent‑workers
spec:
  replicas: 5
  selector:
    matchLabels:
      app: agent
  template:
    metadata:
      labels:
        app: agent
    spec:
      containers:
      - name: agent
        image: my‑agent:latest
        env:
        - name: LLM_ENDPOINT
          value: "https://example.com/v1/chat"
        - name: LLM_TOKEN
          valueFrom:
            secretKeyRef:
              name: llm-credentials
              key: token
        resources:
          limits:
            cpu: "500m"
            memory: "256Mi"
        restartPolicy: Always

Apply and inspect:

kubectl apply -f agent-deployment.yaml
kubectl rollout status deployment/agent‑workers
kubectl logs -l app=agent -f

If an agent container crashes repeatedly, Kubernetes will restart it according to the restartPolicy. You can probe health with livenessProbe and readinessProbe HTTP endpoints if your agent exposes a /healthz route.

Handling tool calls and non‑determinism

LLM responses that include a tool_call object trigger side‑effects (database queries, API requests, file writes). The system must parse, execute, and feed the result back into the next LLM turn.

A typical turn loop in pseudocode:

messages = [{"role": "system", "content": SYSTEM_PROMPT}]
while True:
    response = call_llm(messages)               # HTTP POST to LLM endpoint
    messages.append({"role": "assistant", "content": response["content"]})

    if "tool_calls" in response:
        for tool in response["tool_calls"]:
            result = execute_tool(tool)         # e.g., psql query, HTTP POST
            messages.append({
                "role": "tool",
                "name": tool["name"],
                "content": json.dumps(result)
            })
    else:
        # No further tool calls; agent is done
        break

Sharp edges

Quick checklist before promoting a multi‑agent system to production

ItemCommand / CheckExpected
Prompt hash recordedsha256sum prompts/… && git log --oneline -1Hash matches the commit deployed
State table schema verifiedpsql -U postgres -c "\d agent_sessions"Columns id, agent_role, status, last_message, result, timestamps present
Container image digest pinneddocker inspect --format='{{.RepoDigests}}' my‑agentDigest immutable; no :latest tags
Kubernetes replica count matches intentkubectl get deployment agent‑workers -o=$.spec.replicasMatches `kubectl get pods -l app=agentwc -l`
Max‑turn guard in agent code`grep -R "max_turns\MAX_TURNS"`Counter present and decremented each loop iteration
Secret not in image layer`docker history my‑agentgrep -i token`No secret strings appear
Health endpoint reachablecurl -s http://<pod-ip>:8080/healthzReturns {"status":"ok"} within 2 s

Following this pattern—standard tooling, explicit state, and bounded loops—lets you reason about failure modes before they surface in production, and gives you a reproducible foundation for scaling from two agents to a dozen without reinventing orchestration logic.

This page was rewritten on 12 October 2026. It replaced a templated version that was not specific to its own title. How these pages are written and checked. If anything here is wrong, tell us at [email protected] and we will correct it.