ARCHITECTURE · MULTI-AGENT · A2A · 5 MIN READ

Specialists with a clear contract

Keep ownership, task boundaries, and shared evidence explicit.

Download example files Code + setup + checks in a ZIP
Jump to a section 12 sections

EXAMPLE USE CASE

Combine independent stock and policy findings

A support decision needs inventory and returns evidence from workers with different tool inventories.

Input
SKU A1 for the stock worker and a returns-policy request for the policy worker.
Expected output
Typed stock and policy artifacts with source IDs, combined by a coordinator that cannot authorize a purchase.
  • Success check: Each worker uses only its own tool; the coordinator validates both artifacts before presenting the result.
  • Try a failure: A missing source, timed-out worker or wrong field type becomes a failed/partial result rather than an invented fact.

Example scope: The local lab demonstrates coordination without model calls; the additional OpenAI SDK example runs actual parallel agents with typed outputs.

OpenAI Agents SDK exampleCrewAI examplePydantic example
SEE HOW THE SYSTEM FITS TOGETHERSELECT A COMPONENT
goalstock taskpolicy taskartifactartifactaccepted factsTask contractOne owned outcomeCoordinatorBudget and dispatchStock specialistStock-read scopePolicy specialistPolicy-read scopeArtifact validationReconcile the evidenceFinal resultCoordinator owns success
  1. Define the observable result and which independently scoped work is needed to produce it.

  2. Split only justified work, cap fan-out and give every specialist a typed input, deadline and permission scope.

  3. Read the authorized inventory source and return an artifact containing availability and source identity.

  4. Read the relevant policy independently and preserve version/provenance in its artifact.

  5. Validate shapes, sources and conflicts. Missing specialist output must remain visible rather than being fabricated.

    accepted factsTo 06 · Final result
  6. Answer from accepted artifacts. Neither specialist gains permission to execute a purchase or another business write.

    Result or stopping point
Coordinator

Split only justified work, cap fan-out and give every specialist a typed input, deadline and permission scope.

Follow the arrows, then select a component to inspect its responsibility. On mobile, downward arrows connect the next step; bent arrows identify branches and return paths. Select a destination to jump to that component.

Components for this use case

  • OpenAI Agents SDK supplies the actual parallel worker loop in the optional example. Pydantic validates artifact types; the coordinator owns merge and final acceptance.
  • Use separate tool inventories and service credentials when workers require different authority. A role name in a prompt does not create that boundary.

Choose one owner for the result

  • A coordinator can call specialists as tools and retain control, or hand responsibility to another agent.
  • Specify the handoff contract: inputs, expected artifact, time budget, error shape, and acceptance check.

Use interoperability where it matters

  • A2A is relevant when independently implemented agents need a shared way to advertise capabilities and exchange tasks or results.
  • MCP addresses tool and context access.
  • A single application can use either protocol, both, or ordinary internal function calls.

Keep coordination measurable

  • Track duplicated work, conflicting answers, missing evidence, and coordination cost.
  • Scope memory and permissions to each specialist.
  • Avoid giving every participant every tool and the entire conversation by default.

Set up the lab

  • Python 3.11 or newer. This local lab exposes the control flow without a model call.
  • Use an empty directory; the example may create a local SQLite file.
Shell
python3 -m venv .venv
source .venv/bin/activate

Implement the example

Save as specialists.py

Python · specialists.py
from concurrent.futures import ThreadPoolExecutor

# Scoped functions stand in for independently configured agent workers.
def stock_worker(task):
    assert task["scope"] == "stock:read"
    return {"sku": task["sku"], "available": 8, "source": "stock-db"}
def policy_worker(task):
    assert task["scope"] == "policy:read"
    return {"return_days": 30, "source": "policy-v2"}

with ThreadPoolExecutor(max_workers=2) as pool:
    stock = pool.submit(stock_worker, {"sku":"A1", "scope":"stock:read"})
    policy = pool.submit(policy_worker, {"scope":"policy:read"})
    results = [stock.result(timeout=2), policy.result(timeout=2)]
assert all(r.get("source") for r in results)
assert isinstance(results[0]["available"], int)
print({"stock": results[0], "policy": results[1], "approved_to_purchase": False})

Save as sdk_specialists.py

Python · sdk_specialists.py
import asyncio
import os
from pydantic import BaseModel
from agents import Agent, Runner
from agents.decorators import tool

class StockFinding(BaseModel):
    sku: str
    available: int
    source: str

class PolicyFinding(BaseModel):
    return_days: int
    source: str

@tool
def read_stock(sku: str) -> dict:
    """Read the demo stock fixture for one SKU."""
    return {"sku":sku,"available":8 if sku=="A1" else 0,"source":"stock-fixture"}

@tool
def read_policy() -> dict:
    """Read the public demo returns policy."""
    return {"return_days":30,"source":"policy-v2"}

stock_agent = Agent(name="Stock reader", model=os.environ["OPENAI_MODEL"],
    instructions="Use your stock tool. Return only its observed fields.",
    tools=[read_stock], output_type=StockFinding)
policy_agent = Agent(name="Policy reader", model=os.environ["OPENAI_MODEL"],
    instructions="Use your policy tool. Return only its observed fields.",
    tools=[read_policy], output_type=PolicyFinding)

async def main():
    stock_run, policy_run = await asyncio.gather(
        Runner.run(stock_agent,"Check stock for A1",max_turns=3),
        Runner.run(policy_agent,"Read the returns window",max_turns=3))
    stock, policy = stock_run.final_output, policy_run.final_output
    assert stock.source == "stock-fixture" and stock.available == 8
    assert policy.source == "policy-v2" and policy.return_days == 30
    print({"stock":stock.model_dump(),"policy":policy.model_dump(),"approved_to_purchase":False})

asyncio.run(main())

Run and verify

Shell
python specialists.py
  • Two independent results reach one coordinator; neither worker can authorize a purchase.
  • Replace a worker with an SDK agent only when independent context or permissions improve measured results.
  • The optional sdk_specialists.py runs two real model-backed agents with separate tools and typed artifacts. It requires your provider key and incurs usage.

Troubleshooting and failure tests

  • An absent specialist result should become a partial outcome or explicit failure, never a fabricated substitute.
  • Cap fan-out and nesting; handoff loops can multiply calls without improving evidence.

Before production

  • Give each worker a typed input/output contract, distinct tool scope and deadline.
  • Evaluate coordinator decisions and specialist artifacts separately; preserve parent/child trace IDs.

Run the actual SDK agents

Shell
python -m pip install openai-agents pydantic
export OPENAI_API_KEY="YOUR_KEY"
export OPENAI_MODEL="YOUR_ENABLED_MODEL"
python sdk_specialists.py
  • The stock worker has read_stock only; the policy worker has read_policy only. Both source IDs must survive the typed result.
  • This example validates fixed fixtures. Real service credentials, per-resource authorization, timeouts and partial-result policy belong in the application.

Keep exploring

Workflow, single agent, or multiple agents?A governed tool layer with MCPAI agent evaluation: frameworks, tools and an example