Claude & GPT Integration

Structured Output and Data Extraction

35 Min.

Apps need data, not prose. Structured outputs constrain the response to a schema you define, so it always parses.

Pydantic models with messages.parse

from pydantic import BaseModel
from typing import Literal

class LeadInfo(BaseModel):
    name: str
    email: str
    project_type: Literal["website", "booking_system", "dashboard", "other"]
    budget_usd: int | None
    summary: str

response = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content":
        "Extract the lead from this message:\n\n" + contact_form_text}],
    output_format=LeadInfo,
)
lead = response.parsed_output        # a validated LeadInfo instance
save_lead(lead.model_dump())

Example uses: turning contact-form messages into CRM records, invoices into accounting rows, support emails into tagged tickets.

Classification

class Triage(BaseModel):
    category: Literal["billing", "bug", "feature_request", "account", "other"]
    urgency: Literal["low", "medium", "high"]
    reason: str

triage = client.messages.parse(
    model="claude-haiku-5-5",           # simple, high-volume task
    max_tokens=1024,
    output_config={"effort": "low"},
    messages=[{"role": "user", "content": ticket_text}],
    output_format=Triage,
).parsed_output

Images and PDFs

Models can read images and documents. Send them as content blocks alongside your instructions:

import base64
pdf_b64 = base64.standard_b64encode(open("invoice.pdf", "rb").read()).decode()

response = client.messages.parse(
    model="claude-opus-5-5",
    max_tokens=16000,
    messages=[{"role": "user", "content": [
        {"type": "document", "source": {"type": "base64", "media_type": "application/pdf", "data": pdf_b64}},
        {"type": "text", "text": "Extract the invoice number, date, line items and total."},
    ]}],
    output_format=Invoice,
)

Images use {"type": "image", "source": {"type": "base64", "media_type": "image/png", "data": ...}} the same way.

Grounding and validation

  • Ask for null when a field is missing instead of guessing; make those fields optional in the schema.
  • Validate business rules after parsing (totals add up, dates are plausible).
  • Keep a human review step for high-stakes data (payments, legal records).

Batch processing

For thousands of documents that are not urgent, the Message Batches API processes requests asynchronously at half the price. Submit a batch, poll until it ends, then read results keyed by your own custom_id.

Exercise

Build an endpoint that receives a pasted job advert and returns structured data (title, company, location, remote yes/no, salary range or null, required skills list) using a Pydantic model. Add tests that mock the API call.

Check yourself

  • Why use structured outputs instead of asking for JSON in the prompt?
  • How should missing information be represented?
  • When is the Batches API the right choice?

Ihr Fortschritt wird nur in diesem Browser gespeichert.

Zur Prüfung einreichen (10 Punkte)