Module 5 · Data agents & production
Structured extraction with Pydantic
5 min read
Much of the value of LLMs in companies isn't answering questions, but turning text into data: an email into a claim file, a contract into a list of clauses, an invoice into accounting lines. LlamaIndex makes structured extraction a first-class operation: you describe the expected data with a Pydantic schema, and you get a validated object. This lesson builds Lumen's warranty claim extractor.
The schema is the contract
class WarrantyClaim(BaseModel):
"""Demande de prise en charge sous garantie, extraite d'un message de client."""
order_id: str | None = Field(description="Numéro de commande au format ORD-XXXX, s'il est cité")
sku: str | None = Field(
description="Référence du produit (LAMP-3, CHAIR-7, DESK-2, MUG-01, CASTER-M), si identifiable"
)
purchase_date: str | None = Field(
description="Date d'achat ou de livraison au format AAAA-MM-JJ, si mentionnée"
)
issue_type: Literal["defect", "damage", "missing_part", "other"] = Field(
description="defect : panne ou défaut ; damage : casse, chute, choc ; "
"missing_part : pièce manquante ; other"
)
description: str = Field(description="Le problème en une phrase, reformulé de façon neutre")
customer_email: str | None = Field(
description="Adresse e-mail du client, si elle figure dans le message"
)
The schema plays three roles at once:
- instruction for the model: the class name, its docstring and each field's description are sent with the schema;
- constraint on the output: types, allowed values (
Literal), optional fields; - validation of the result: an invalid object never reaches your code.
Two design choices deserve attention. Literal closes the choices: the issue type can only take four values, which downstream code knows how to handle. And str | None allows absence: without this option, a model forced to fill in the order number might invent one. The prompt says so too: "Leave a field empty (null) rather than guess missing information."
Extracting
PROMPT = PromptTemplate(
"Extrais la demande de garantie contenue dans ce message de client. "
"Laisse un champ vide (null) plutôt que de deviner une information absente.\n\nMessage :\n{message}"
)
async def extract_claim(message: str, llm: LLM | None = None) -> WarrantyClaim:
return await (llm or models.fast_llm()).astructured_predict(WarrantyClaim, PROMPT, message=message)
astructured_predict formats the prompt, calls the model while imposing the schema on it, and returns a WarrantyClaim instance. The fast model is more than enough for this kind of task.
"Bonjour, ma lampe LAMP-3 (commande ORD-1001, livrée le 2024-03-01) ne s'allume plus depuis hier.
Merci de votre aide. Léa — lea@example.com"
→ order_id='ORD-1001', sku='LAMP-3', purchase_date='2024-03-01', issue_type='defect',
description='…ne s'allume plus…', customer_email='lea@example.com'
How the schema is imposed on the model
Depending on the model, LlamaIndex's Anthropic integration uses one of two mechanisms:
| Mechanism | Principle | In the version used for this course |
|---|---|---|
| Native structured outputs | Generation is constrained by the JSON schema: the output always conforms | Used for Claude Opus 5.5 (and Sonnet 5.5, Opus 4.6…) |
| Forced tool call | The schema becomes a tool the model is obliged to call | Used for models absent from the list, including Claude Haiku 5.5 |
The second mechanism has a subtlety: some recent models refuse forced tool calls (Claude Opus 5.5 returns a 400 error). It has no consequence here, since the integration uses native outputs for it, and Haiku 5.5 accepts the forced call. But it's something to check at every change of model or integration version: a simple test call is enough to detect it.
Another way to extract: llm.as_structured_llm(WarrantyClaim) returns an LLM whose every answer is an instance of the schema, handy to integrate into a chat engine or a workflow.
Extracting at ingestion time
The same technique applies in the ingestion pipeline: the PydanticProgramExtractor extracts a schema from each node and adds it as metadata. For instance, extracting from each product sheet the warranty length, materials and maximum load would then allow filtering ("chairs supporting more than 120 kg") instead of hoping vector search finds the right passage.
For large-scale extraction on complex documents, LlamaCloud also offers a dedicated service (LlamaExtract, accessible via the llama-cloud SDK), which combines parsing and schema-based extraction.
Making extraction reliable
- Validate beyond types. Pydantic guarantees the shape; add validators for business rules: a
skuthat exists in the catalog, a date that isn't in the future. - Distinguish "absent" from "unknown".
Nonemeans the information wasn't in the message; don't replace it with a default value that would suggest it was extracted. - Keep the source text with the result: in case of dispute, you must be able to check what the message said.
- Measure on an annotated sample: per-field precision, and rate of invented fields (filled in although the information wasn't there). That's the metric that matters most.
Key takeaways
- The Pydantic schema is instruction, constraint and validation at once; field descriptions guide the model.
Literalcloses choices;| Noneallows absence and reduces inventions.astructured_predict(oras_structured_llm) returns a validated object; the fast model is often enough.- Depending on the model: native structured outputs or forced tool call, which some recent models refuse — test at every change.
- Validate business rules, keep the source, measure precision and invention rate.
Practice
- Run
examples/05_agent.pyand check the file extracted from the sample email. - Add a Pydantic validator that rejects a
skuabsent from the catalog, and observe the behavior on a message citing "LAMP-9". - Write ten varied customer messages, annotate the expected result, and measure with a real model the per-field precision and the rate of invented fields.