Pydantic for LLM 2026:让任何模型输出可靠的结构化JSON
LLM返回的JSON时好时坏,代码在坏数据上崩溃。Pydantic把模型输出变成经过校验的类型化数据。
Pydantic: The Validation Layer Between Raw LLM Output and Your Code
Pydantic (28,438 GitHub stars, MIT license) is the Python library for data validation using type hints. With the rise of LLM structured outputs, it has become the de facto standard for parsing and validating model responses - every major LLM framework (LangChain, OpenAI SDK integrations, instructor) builds on it. The core idea: declare what the output should look like, and get guaranteed-valid objects or a clear error.
The Pattern That Replaced Regex Parsing
from pydantic import BaseModel, Field
class Order(BaseModel):
order_id: str = Field(pattern=r"ORD-\d{6}")
items: list[str]
total: float
# Parse LLM output directly
order = Order.model_validate_json(llm_json)
If the model returns a missing field, wrong type, or invalid format, you get a validation error - not a silent crash downstream. That single property removes the flakiest failure mode in LLM apps.
Why It Works So Well With LLMs
- Schema as the prompt. Many SDKs (instructor, OpenAI structured outputs) serialize your Pydantic model into JSON Schema and pass it to the model - the model sees exactly what to produce, and providers can enforce it.
- Nested validation. Complex structures (an order with line items, each with its own rules) validate recursively.
- Retry on failure. The standard loop: try to parse, on ValidationError re-ask the model with the error message - most models fix their output on the second attempt.
- Serialization. Output is plain Python objects you can store, log, or send anywhere.
The Production Loop
for attempt in range(3):
try:
return Order.model_validate_json(call_llm(schema=Order.model_json_schema()))
except ValidationError as e:
messages.append(f"Your output was invalid: {e}. Fix it.")
This retry-with-error loop is the single most reliable pattern for getting structured data out of LLMs - it works with OpenAI, Anthropic, Gemini, and local models.
FAQ
Is Pydantic free? Yes - MIT-licensed; it is one of the most-installed Python packages in existence.
Does it work with any LLM? Yes - the validation is model-agnostic; provider-enforced schemas are a bonus.
Pydantic v1 or v2? Use v2 - faster (Rust core) and the modern standard.
Can it handle very large outputs? Yes, but for huge outputs prefer streaming + incremental validation.
