Building a Supervisor Agent That Delegates Tasks Using Explicit Contracts

The moment you hand an LLM a system prompt saying, "You are a project manager; delegate tasks to the research and coding agents as needed," your architecture is living on borrowed time.

In simple demos, the supervisor looks like magic. It parses a vague user request, talks to a worker agent, gets a reasonable output, and prints a success message. But push that same loop into production—where users demand structured JSON, downstream databases expect strict foreign keys, and budget alerts fire because a circular delegation loop just burned through fifty thousand tokens in twelve seconds—and the illusion shatters.

Autonomous agents fail not because their underlying models are insufficiently intelligent, but because free-form natural language is a terrible protocol for inter-agent communication. When agents talk to each other in conversational prose, errors compound exponentially. A worker agent misunderstands a subtle nuance in a paragraph of instructions, hallucinates a missing parameter, and passes back a response that the supervisor misinterprets as success.

If we want multi-agent systems to move out of the Jupyter notebook and into mission-critical pipelines, we have to stop treating them like chatrooms. We need to treat them like microservices. And microservices don't negotiate via vibes; they communicate via explicit contracts.


📋 Table of Contents


The Illusion of Conversational Autonomy

Consider a classic multi-agent setup built using a framework like LangGraph, AutoGen, or a custom orchestration loop. You have a SupervisorAgent sitting in front of a DataIngestionAgent and a QueryGenerationAgent.

[User Request] 
      │
      ▼
┌──────────────┐      "Hey Data Agent, go look       ┌───────────────────┐
│              │ ─────────────────────────────────► │                   │
│  Supervisor  │                                    │ DataIngestionAgent│
│    Agent     │ ◄───────────────────────────────── │                   │
│              │      "I found some stuff about..." └───────────────────┘
└──────────────┘

This works fine for a single turn. But what happens when the user asks: "Pull the Q3 financial report, extract the ARR metrics, write a SQL query to compare them against our internal Postgres warehouse, and format the output as a Markdown report."

Suddenly, the supervisor has to decide:

  1. Does the DataIngestionAgent need the raw PDF or just a parsed string?
  2. Does the QueryGenerationAgent need database schema details passed explicitly, or should it infer them?
  3. What happens if the DataIngestionAgent returns a 404 error from an external API? Does the supervisor tell the user, retry, or ask a different worker?

In a conversational system, the supervisor has to guess the intent and structure of the worker's output based on whatever text the worker felt like generating. If the worker model decides to be conversational ("Sure! I'd love to help with that. Here is what I found..."), the supervisor's parser breaks, or worse, it misinterprets conversational filler as valid data fields.

To fix this, we need to strip away the conversational wrapper between agents. Agents should chat with humans; they should execute contracts with each other.


1. Defining the Explicit Contract

Scenario: Your supervisor agent needs to delegate a data-scraping task to a worker agent. The worker needs specific parameters (target URL, extraction schema, timeout limits) and must return data conforming to a strict JSON structure.

Why it matters: If you rely on system prompts like "Make sure to return valid JSON," models will eventually fail under load. They will inject markdown code blocks (```json), omit trailing commas, or add conversational intros like "Here is the data you requested:" which instantly breaks json.loads().

Solution: Define programmatic contracts using a runtime validation library like Pydantic v2. Treat every delegation target not as a prompt template, but as a strongly typed function signature with explicit inputs and outputs.

Code:

from pydantic import BaseModel, Field, HttpUrl
from typing import List, Optional, Literal

class ScrapingTaskInput(BaseModel):
    target_url: HttpUrl = Field(description="The absolute URL to scrape.")
    selectors: List[str] = Field(description="CSS selectors to target specific elements.")
    max_retries: int = Field(default=3, ge=1, le=5)

class ScrapedRecord(BaseModel):
    title: str
    price: Optional[float] = None
    extracted_at: str

class ScrapingTaskOutput(BaseModel):
    status: Literal["success", "partial", "failed"]
    records: List[ScrapedRecord]
    error_message: Optional[str] = None

Why this works: By defining ScrapingTaskInput and ScrapingTaskOutput, you create an immutable contract. The supervisor knows precisely what fields it must supply, and it knows precisely what shape of data it will receive back. If the worker agent returns anything outside of ScrapingTaskOutput, it fails validation instantly before polluting the state graph.

💡 Practical note: Always use Pydantic's Field(description=...) metadata. Modern LLM function-calling APIs (like OpenAI's structured outputs or Anthropic's tool use) directly compile these descriptions into JSON schema definitions sent to the model provider.


2. The Supervisor's Dilemma: Routing Without Guesswork

Scenario: A user submits a complex enterprise query that touches multiple domains: billing, infrastructure logs, and user permissions. The supervisor must decide which worker agents to invoke, in what order, and how to pass outputs from Worker A directly into Worker B.

Why it matters: If the supervisor uses free-form text generation to choose the next step (e.g., "Next, I think I should call the log analyzer"), it can hallucinate non-existent agents, loop infinitely between two workers, or skip critical validation steps.

Solution: Implement explicit routing through constrained tool definitions or structured state transitions where the supervisor is forced to output a discrete routing action enum.

Code:

from enum import Enum
class WorkerDestination(str, Enum):
    BILLING = "billing_worker"
    LOGS = "logs_worker"
    SECURITY = "security_worker"
    TERMINATE = "terminate_pipeline"

class SupervisorRoutingDecision(BaseModel):
    next_agent: WorkerDestination = Field(
        description="The exact worker to delegate to next, or terminate."
    )
    delegation_payload: dict = Field(
        description="The strictly typed payload required by the target agent."
    )
    reasoning: str = Field(
        description="Brief operational justification for this routing choice."
    )

Why this works: When the underlying LLM is forced to respond using SupervisorRoutingDecision, its output space is tightly constrained. It cannot hallucinate an agent named database_cleanup_bot because WorkerDestination is a closed set of enum values.


3. Structuring Worker Handshakes and State Envelopes

Scenario: As your multi-agent workflow scales from two workers to ten, passing raw dictionaries around in a shared state dictionary quickly leads to key collisions, silent overwrites, and untraceable bugs.

Why it matters: In frameworks like LangGraph, state is often managed as a shared TypedDict. When multiple workers read from and write to the same state dictionary without strict isolation, Worker A might overwrite a critical tracking ID generated by Worker B.

Solution: Wrap every delegation in a standard State Envelope. Every handshaking action between the supervisor and a worker must carry metadata, a trace ID, a version number, and the typed payload.

Code:

from datetime import datetime
import uuid

class StateEnvelope(BaseModel):
    trace_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
    parent_id: Optional[str] = None
    sender: str
    recipient: str
    timestamp: str = Field(default_factory=lambda: datetime.utcnow().isoformat())
    version: str = "1.0.0"
    payload: dict

Why this works: The envelope acts like an HTTP header for agentic workflows. When an exception occurs deep inside Worker C, your error logs don't just show "KeyError: 'result'". They show the exact trace_id, who sent the payload, what version of the schema was used, and when the handoff occurred.


4. Enforcing Type Safety and Schema Validation at Runtime

Scenario: An LLM worker agent successfully returns a JSON payload, but due to a slight drift in model behavior or context window fatigue, it populates a float field with a string ("price": "19.99USD" instead of 19.99).

Why it matters: If your supervisor passes this unvalidated string directly into a database insertion script or a financial calculation engine, your application throws unhandled type errors in production.

Solution: Never trust worker output. Implement a validation interceptor middleware that intercepts every worker response, runs it through Pydantic parsing, and triggers an automated self-correction loop if validation fails.

Code:

from pydantic import ValidationError

def execute_worker_with_contract(worker_func, input_payload: BaseModel, output_model: type[BaseModel]):
    raw_output = worker_func(input_payload.model_dump())
    
    try:
        # Validate against the explicit contract
        validated_output = output_model.model_validate(raw_output)
        return {"success": True, "data": validated_output}
    
    except ValidationError as e:
        # Return structured error back to supervisor for self-correction
        return {
            "success": False, 
            "error_details": e.errors(),
            "raw_received": raw_output
        }

Why this works: Instead of crashing the entire pipeline or letting bad data propagate, validation failures become structured feedback. The supervisor receives the exact Pydantic error dictionary (e.g., Field required [type=missing, input_value={}, input_type=dict]), allowing it to re-prompt the worker with precise instructions on what field was missing.


5. Catching Hallucinations Before They Hit Downstream Systems

Scenario: A worker agent is asked to extract user IDs from a customer email thread. It invents three valid-looking UUIDs that do not exist in your system, passing them back to the supervisor as "identified accounts."

Why it matters: Hallucination in multi-agent systems is insidious because downstream workers assume upstream workers are telling the truth. If the supervisor trusts the worker's output without verification, downstream automation scripts will execute operations against fabricated identifiers.

Solution: Combine structural schema contracts with semantic and relational validation rules inside your Pydantic models using root validators or custom field validators.

Code:

from pydantic import field_validator

class UserResolutionOutput(BaseModel):
    account_id: str
    email: str

    @field_validator('account_id')
    @classmethod
    def verify_account_exists(cls, v: str) -> str:
        # In a real system, you would check your database or cache here
        if not v.startswith("usr_"):
            raise ValueError(f"Invalid account ID prefix: {v}. Must start with 'usr_'.")
        return v

Why this works: Pydantic validators allow you to inject business logic constraints directly into your data contracts. If a worker returns an ID that violates your domain rules, the contract validation catches it immediately, forcing a retry or fallback before the supervisor acts on fraudulent data.


6. Circuit Breakers and Guardrails for Infinite Delegation Loops

Scenario: The supervisor agent delegates a summarization task to Worker A. Worker A finds the text too ambiguous and delegates it back to the supervisor. The supervisor decides to try Worker A again. The system enters an infinite loop, burning thousands of tokens per minute until your API rate limiters trip.

Why it matters: LLMs are probabilistic state machines. Without hard deterministic guardrails, conversational logic can easily form cyclical execution paths that never terminate.

Solution: Enforce a hard delegation depth limit and track visited state signatures inside the execution envelope.

Code:

class ExecutionGuardrail:
    def __init__(self, max_depth: int = 5, max_total_steps: int = 15):
        self.max_depth = max_depth
        self.max_total_steps = max_total_steps
        self.step_count = 0
        self.path_history = []

    def check_can_delegate(self, sender: str, recipient: str) -> None:
        self.step_count += 1
        if self.step_count > self.max_total_steps:
            raise RuntimeError(f"Circuit breaker tripped: Exceeded max steps ({self.max_total_steps}).")
            
        # Detect immediate ping-pong loops (A -> B -> A)
        self.path_history.append((sender, recipient))
        if len(self.path_history) > 4:
            recent = self.path_history[-4:]
            if recent[0] == recent[2] and recent[1] == recent[3]:
                raise RuntimeError(f"Circuit breaker tripped: Infinite loop detected between {sender} and {recipient}.")

Why this works: Probabilistic models need deterministic boundaries. By wrapping agent transitions in a stateful guardrail object, you ensure that no matter how confused or creative the supervisor model gets, the pipeline will hard-stop before draining your infrastructure budget.


7. Implementing a Complete Production-Ready Supervisor

Putting all of these patterns together, let's look at a complete, production-oriented implementation of a supervisor agent that delegates tasks using explicit contracts.

import os
from typing import List, Dict, Any, Optional
from pydantic import BaseModel, Field
from openai import OpenAI

# 1. Define Contracts
class ResearchInput(BaseModel):
    query: str = Field(description="Search query to investigate.")
    depth: int = Field(default=2, description="Research depth.")

class ResearchOutput(BaseModel):
    findings: List[str] = Field(description="Key findings discovered.")
    confidence_score: float = Field(ge=0.0, le=1.0)

class SupervisorDecision(BaseModel):
    action: str = Field(description="Either 'delegate_research' or 'finalize'")
    target_query: Optional[str] = None
    final_summary: Optional[str] = None

# 2. Worker Implementation (Simulated)
def run_research_worker(payload: Dict[str, Any]) -> Dict[str, Any]:
    validated_input = ResearchInput(**payload)
    # Simulated execution
    return {
        "findings": [
            f"Finding A regarding {validated_input.query}",
            f"Finding B regarding {validated_input.query}"
        ],
        "confidence_score": 0.92
    }

# 3. Supervisor Loop with Contracts
class ContractSupervisor:
    def __init__(self, api_key: str):
        self.client = OpenAI(api_key=api_key)
        self.step_count = 0

    def run(self, user_prompt: str) -> str:
        current_context = f"User Request: {user_prompt}"
        
        while self.step_count < 5:
            self.step_count += 1
            
            # Ask supervisor for next step using structured outputs
            response = self.client.beta.chat.completions.parse(
                model="gpt-4o",
                messages=[
                    {"role": "system", "content": "You are a strict supervisor agent. Use the defined tools or finalize."},
                    {"role": "user", "content": current_context}
                ],
                response_format=SupervisorDecision,
            )
            
            decision = response.choices.message.parsed
            
            if decision.action == "finalize":
                return decision.final_summary or "Completed without summary."
                
            elif decision.action == "delegate_research":
                # Prepare explicit input contract
                task_input = ResearchInput(query=decision.target_query or "default")
                
                # Execute worker with contract validation
                try:
                    raw_result = run_research_worker(task_input.model_dump())
                    validated_output = ResearchOutput.model_validate(raw_result)
                    
                    # Feed validated output back into supervisor context
                    current_context += f"\nWorker Output Success: {validated_output.model_dump_json()}"
                
                except Exception as e:
                    current_context += f"\nWorker Error: {str(e)}. Please adjust strategy."
            
            else:
                raise ValueError(f"Unknown action received: {decision.action}")
                
        return "Terminated: Max execution steps reached."

# Example Usage (requires OPENAI_API_KEY set in environment)
# supervisor = ContractSupervisor(api_key=os.environ["OPENAI_API_KEY"])
# print(supervisor.run("Investigate recent trends in renewable energy storage."))

When Explicit Contracts Slow You Down (And When They Save Your Job)

Strict contracts introduce friction. Writing Pydantic schemas for every agent interaction takes longer than throwing strings into a shared prompt template. If you are building a throwaway prototype, a hackathon project, or an experimental creative writing assistant, explicit contracts are unnecessary overhead.

However, the moment your multi-agent application touches real users, financial ledgers, external APIs, or production databases, conversational autonomy becomes an operational liability.

By replacing loose prose handshakes with typed data contracts, runtime schema validation, and deterministic circuit breakers, you transform autonomous agents from unpredictable black boxes into robust, debuggable, and reliable components of your software architecture.

Post a Comment

Previous Post Next Post