Module 3 · Communication & protocols

Structured message contracts (JSON Schema, Pydantic)

5 min read

When two humans collaborate, an ambiguous sentence gets clarified with a question. Between two agents, ambiguity propagates silently: the writer misreads the researcher's summary, the critic judges a note on a wrong basis, and the error only shows up at the end. The remedy: structured message contracts between agents, as rigorous as an API's contracts.

The free-text problem

Imagine a researcher returning free text:

Here's what I found. The supervisor centralizes control (see the document on the
supervisor architecture, and maybe also the one on handoffs).
I found no information on costs.

The writer now has to guess: which exact sources? Does "maybe also" mean the source was used? Is the lack of cost information a result or a failure? Every agent reading this text interprets it again, with a risk of error at each read.

The contract: a Pydantic schema

Atlas defines its inter-agent messages in atlas/schemas.py:

class Finding(BaseModel):
    subquestion: str
    summary: str = Field(description="Factual summary, based only on the documents provided")
    source_ids: list[str] = Field(description="IDs of the documents actually used")


class Review(BaseModel):
    verdict: Literal["approve", "revise"]
    issues: list[str] = Field(description="Concrete, actionable problems; empty if approved")
    score: int = Field(description="Overall score from 1 to 10")

Every field has a type, and non-obvious fields have a description — which is part of the schema sent to the model and guides its output. verdict is a Literal: only two values are possible, and the routing code can rely on it without parsing text.

Getting guaranteed-conformant output

The Anthropic SDK provides messages.parse, which constrains output to the schema and validates it:

def extract(system: str, prompt: str, schema: type[T], *, model: str = MODEL, max_tokens: int = 16000) -> T:
    response = client().messages.parse(
        model=model,
        max_tokens=max_tokens,
        system=system,
        messages=[{"role": "user", "content": prompt}],
        output_format=schema,
    )
    if response.stop_reason == "refusal":
        raise RefusalError(f"Request declined: {response.stop_details}")
    if response.parsed_output is None:
        raise ValueError(f"Output does not match schema {schema.__name__}")
    return response.parsed_output

response.parsed_output is a validated instance of your Pydantic class. No more regular expressions over approximate JSON, no more missing fields.

Structured outputs or a tool? To get a structured object as the final answer, use structured outputs (output_format / output_config.format). For the model to trigger an action with valid arguments, use a tool with strict: True. Hijacking a tool just to get JSON back used to be a common trick; it's no longer needed.

The schema describes shape, the code guarantees meaning

A schema guarantees that source_ids is a list of strings. It doesn't guarantee that those IDs exist. That's the code's job:

finding = extract(SYSTEM_RESEARCHER, prompt, Finding, model=WORKER_MODEL)
# The model cannot cite a document it wasn't given
allowed = {h["id"] for h in hits}
finding.source_ids = [s for s in finding.source_ids if s in allowed]

Division of responsibilities:

GuaranteeProvided by
Types, required fields, enumerated valuesThe schema (structured output)
Bounds (number of items, value ranges)The code, after receipt
Consistency with the rest of the system (existing IDs, valid citations)The code
Content quality (relevance, faithfulness)A critic and/or evaluation (module 5)

Keep schemas simple: not every JSON Schema keyword is supported by structured outputs, and complex constraints (minimum lengths, patterns) are easier to test in code anyway.

Designing good contracts

Name for the next reader

summary and source_ids are explicit; data and info aren't. The schema is read by the model that produces it and by the developer who debugs it.

Make absences explicit

A poorly designed optional field creates ambiguity between "not found" and "forgotten". Prefer an explicit representation:

class Finding(BaseModel):
    subquestion: str
    status: Literal["answered", "partial", "no_evidence"]
    summary: str
    source_ids: list[str]

The writer can then treat a lack of evidence (mention it honestly) differently from a partial answer.

Separate reasoning from the decision

For a critic or judge, place a justification field before the verdict in the schema: the model produces fields in order, and stating the reasons first leads to better-grounded verdicts.

class Review(BaseModel):
    analysis: str                          # reasoning first…
    verdict: Literal["approve", "revise"]  # …then the decision
    issues: list[str]

Version your contracts

A contract shared between agents is an interface. If you rename a field, every consumer must follow. For a persistent system (states saved in a database, message queues), add a version field or only introduce backward-compatible changes (new optional fields).

Type the graph state too

Contracts aren't only about model outputs: the LangGraph state itself is typed (TypedDict). Atlas stores Finding objects as dictionaries (finding.model_dump()) so the checkpointer can serialize them, and re-validates them on read when needed. The principle is the same: no data flows between agents without a known structure.

Key takeaways

  • Between agents, free text propagates ambiguity; structured contracts eliminate it.
  • messages.parse(..., output_format=Schema) returns a validated Pydantic object in parsed_output.
  • The schema guarantees shape; the code guarantees invariants and consistency.
  • Make absences explicit, put reasoning before the decision, version your contracts.

Hands-on

  1. Add the status field to Finding and adapt the writer so it explicitly flags sub-questions without evidence.
  2. Write a test checking that a Finding citing a nonexistent document has that source filtered out.
  3. Reorder Review to put an analysis field before verdict, and compare verdicts on 10 notes.

Resources