Coco
Build agents

Structured output

Pass a Pydantic model or a strategy as response_format, and read the validated object from structured_response.

Return a validated Pydantic object from an agent.

Pass a Pydantic BaseModel to response_format, and the agent returns a validated instance under result["structured_response"].

Prerequisites: The framework and the agent from the Quickstart. The example reuses its lookup_order_status tool.


Return structured output

from pydantic import BaseModel, Field
from coco.agents import create_agent


class OrderSummary(BaseModel):
    order_id: str = Field(description="The order identifier")
    is_shipped: bool = Field(description="Whether the order has already shipped")
    summary: str = Field(description="One-sentence status summary")


agent = create_agent(
    model="openai:gpt-4o",
    tools=[lookup_order_status],
    response_format=OrderSummary,
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Check order ORD-101 and summarize."}]}
)

structured: OrderSummary = result["structured_response"]
print(structured.order_id, structured.is_shipped, structured.summary)

It prints the order ID, whether it shipped, and the summary, such as ORD-101 True Order ORD-101 has shipped.

Choose a strategy

response_format also takes a TypedDict, a JSON schema dict, or one of these strategies from coco.agents.structured_output:

StrategyWhat it does
AutoStrategy(schema)Uses ProviderStrategy when the model supports native structured output, and ToolStrategy otherwise. A plain Pydantic class uses this.
ProviderStrategy(schema, strict=...)Uses the model provider's native structured output API.
ToolStrategy(schema, tool_message_content=..., handle_errors=...)Binds the schema as a tool and parses the call's arguments, retrying on validation errors if configured.
ErrorRaised when
StructuredOutputValidationErrorThe output fails validation and the retries run out.
MultipleStructuredOutputsErrorThe model calls more than one structured output tool in one turn.

On this page