Pydantic with messages.parse

Define the Shape as a Python Class

With the Python SDK you can skip writing the schema by hand: define a Pydantic model and call client.messages.parse(...) with output_format=YourModel. The SDK sends the schema and gives you back a validated Python object in response.parsed_output.

from typing import Literal
from pydantic import BaseModel, Field
import anthropic

class SupportTicket(BaseModel):
    order_id: str | None = Field(description="Order ID like SE-1234, or null if not mentioned")
    category: Literal["delivery", "payment", "product", "account", "other"]
    sentiment: Literal["positive", "neutral", "negative"]
    summary: str = Field(description="One sentence summary for the agent")
    urgent: bool

client = anthropic.Anthropic()

response = client.messages.parse(
    model="claude-haiku-5-5",
    max_tokens=1000,
    messages=[{"role": "user", "content": "Paisa kat gaya but order SE-7781 show nahi ho raha. Very worried, it was Rs 12,000!"}],
    output_format=SupportTicket,
)
ticket = response.parsed_output          # a SupportTicket instance
print(ticket.category, ticket.urgent, ticket.order_id)
print(ticket.model_dump_json(indent=2))

Run it

python parse_ticket.py

Example output

payment True SE-7781
{
  "order_id": "SE-7781",
  "category": "payment",
  "sentiment": "negative",
  "summary": "Customer was charged Rs 12,000 but order SE-7781 does not appear in their account.",
  "urgent": true
}

Tips

  • Use Literal[...] (enums) for categories so the model cannot invent new ones.
  • Add Field(description=...): descriptions become part of the schema and guide the model.
  • Make a field optional (| None) when the information may be missing, otherwise the model has to make something up.
  • Business rules (an order ID really exists, a date is in the future) still need your own checks.