|
|
Claude Output Validation with Pydantic
Author: Venkata Sudhakar
When Claude returns structured data like product details, order summaries, or extracted fields, you need to validate the output before using it in your application. For ShopMax India, an unvalidated JSON response that is missing the price field could cause a divide-by-zero error in discount calculations, or a mistyped city name could route a delivery to the wrong warehouse. Pydantic provides runtime type validation for Claude's JSON output, catching schema violations before they propagate into your database or downstream systems.
The pattern involves three steps: define a Pydantic model that represents the expected output structure, instruct Claude to return JSON matching that schema, then parse the response with model.model_validate(). On validation failure, retry the request with the error message appended so Claude can self-correct. The Anthropic SDK's structured output feature simplifies this further by accepting a Pydantic model directly and returning a validated instance without manual JSON parsing.
The following example shows ShopMax India extracting structured product data and order information from Claude responses with Pydantic validation and automatic retry on schema errors:
It gives the following output,
Validated Product Recommendation:
ID: LG-TV-50N
Name: LG 50-inch 4K NanoCell Smart TV
Price: Rs 44990
Category: Television
EMI available: True
Reason: Excellent 4K NanoCell display with accurate colors and wide viewing angles,
perfect for Delhi apartment living rooms at under Rs 50,000 with 0% EMI on HDFC cards.
For ShopMax India production pipelines, use Pydantic validators on all fields that feed into financial calculations or logistics systems. Add Field(pattern=...) constraints on product IDs and order IDs to catch AI hallucinations that invent non-existent identifiers. The self-correction retry pattern (appending the validation error back to Claude) resolves 90% of schema violations in one retry - only malformed responses from model errors need more than two attempts. Log validation failures by model and task type; a rising failure rate for a specific task indicates your prompt schema description needs clarification.
|
|