๐Ÿ“ LLM & AI

Pydantic v2: Data Validation in Python

P
Author
PyLand Team
๐Ÿ“…
Published
30.06.2026
โฑ๏ธ
Reading time
2 min
๐Ÿ‘๏ธ
Views
328
๐ŸŒฟ
Level
Medium

Pydantic validates and converts data through type annotations. It is commonly used in APIs and LLM applications when an external service returns JSON and the program needs a predictable structure.

Installation

python -m pip install "pydantic>=2,<3"

BaseModel โ€” the base model

from pydantic import BaseModel

class TextAnalysis(BaseModel):
    sentiment: str
    score: float
    keywords: list[str]
    language: str

# Creating from a dictionary
data = {"sentiment": "positive", "score": 0.9, "keywords": ["python"], "language": "ru"}
result = TextAnalysis.model_validate(data)

print(result.sentiment)   # positive
print(result.score)       # 0.9
print(result.keywords)    # ['python']

model_validate() โ€” parsing from a dict

import json

raw_json = '{"sentiment": "negative", "score": 0.2, "keywords": [], "language": "en"}'
data = json.loads(raw_json)
result = TextAnalysis.model_validate(data)

If an API already returned a JSON string, an intermediate json.loads() is not required:

result = TextAnalysis.model_validate_json(raw_json)

Literal โ€” allow only known values

from typing import Literal

class StudyCard(BaseModel):
    topic: str
    level: Literal["beginner", "intermediate", "advanced"]
    summary: str
    key_points: list[str]
    practice_task: str

Any other level value raises ValidationError.

model_json_schema() โ€” a schema for an API

schema = StudyCard.model_json_schema()

This method returns JSON Schema. You can send it to an API that supports structured output, then validate the returned response with StudyCard.model_validate_json(...).

ValidationError โ€” invalid data

from pydantic import ValidationError

try:
    bad = TextAnalysis.model_validate({"sentiment": "ok"})  # missing score and keywords
except ValidationError as e:
    print(e.error_count())   # 3
    for err in e.errors():
        print(err["loc"], err["msg"])

Nested models

class SentimentResult(BaseModel):
    label: str       # positive / negative / neutral
    confidence: float

class TextAnalysis(BaseModel):
    sentiment: SentimentResult
    keywords: list[str]
    language: str
    word_count: int

data = {
    "sentiment": {"label": "positive", "confidence": 0.87},
    "keywords": ["python", "api"],
    "language": "ru",
    "word_count": 150
}
result = TextAnalysis.model_validate(data)
print(result.sentiment.label)       # positive
print(result.sentiment.confidence)  # 0.87

Field() โ€” constraints and descriptions

from pydantic import BaseModel, Field

class TextAnalysis(BaseModel):
    sentiment: str = Field(description="positive / negative / neutral")
    score: float = Field(ge=0.0, le=1.0, description="Confidence from 0 to 1")
    keywords: list[str] = Field(max_length=10, description="Keywords")
    language: str = Field(pattern=r"^[a-z]{2}$", description="ISO 639-1 language code")

model_dump() โ€” back to dict

result = TextAnalysis.model_validate(data)
d = result.model_dump()        # dict
j = result.model_dump_json()   # JSON string

Why Pydantic in LLM applications

A language model usually returns free-form text. To get structured data, ask the API for JSON that follows a schema and validate it with Pydantic:

raw = interaction.output_text
result = TextAnalysis.model_validate_json(raw)
# Now result is a typed object with validated fields

Pydantic confirms structure and types, not whether the content is factually correct. A person must still evaluate the answer itself.

Your reaction to the article

๐Ÿ’ฌ Comments (0)

๐Ÿ” Sign in to leave a comment
๐Ÿšช Login
๐Ÿ’ญ

No comments yet

Be the first to share your opinion about this article!

๐Ÿ”— Similar

Similar articles

Continue learning with these materials

๐Ÿ“

AI Agents: ReAct Loop and Autonomous Actions

A chatbot answers questions. An agent takes action: it calls tools, retrieves real data, and...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 335
๐Ÿ“

asyncio in Python: Asynchronous Programming

asyncio is Python's standard library for asynchronous code. It lets you execute multiple tasks "simultaneously"...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 317
๐Ÿ“

Embeddings: Coordinates of Text in Semantic Space

An embedding is a numerical vector that represents a piece of text. Texts that are...

๐Ÿ“… 30.06.2026 ๐Ÿ‘๏ธ 298