Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 159/ 160
08. Backend

Input Validation with Pydantic

Typed schemas that validate API payloads and structured LLM outputs.

BeginnerModels · Validation3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Pydantic checks that the data you receive looks like what you expected, with the right types and sensible limits, and tells you precisely what is wrong when it doesn't.

Think of it like…

A customs checkpoint with a form. Each declared item must match the rules (type, size, allowed categories); incomplete or odd paperwork is stopped at the border with a note saying exactly which box is wrong, rather than being discovered inside the country.

Where you’ve seen it

The chat endpoint defines class Message(BaseModel) with role: Literal["user", "assistant"] and content: str = Field(min_length=1, max_length=20_000), and class ChatRequest(BaseModel) with model_config = ConfigDict(extra="forbid"), messages: list[Message] = Field(min_length=1, max_length=50), temperature: float = Field(0.2, ge=0, le=2) and max_tokens: int = Field(512, ge=1, le=4096). The 20,000-character cap bounds a prompt to about 5,000 tokens (at roughly 4 characters per token), so input cost per message is at most 5,000 × $2.50 / 1,000,000 = $0.0125 on the large model; without it one request could carry a million characters. With extra="forbid", a typo such as temprature returns 422 with loc: ["body", "temprature"] instead of being silently ignored. A request with temperature: 7 returns {"detail": [{"loc": ["body", "temperature"], "msg": "Input should be less than or equal to 2", "type": "less_than_equal"}]}. Output validation is just as important. The model is asked for a TicketSummary (title, severity as an enum, confidence: float from 0 to 1, tags list) and the response is passed to TicketSummary.model_validate_json(...). About 6% of first attempts fail validation (trailing prose, a severity of "urgent" that isn't in the enum); the service sends the validation errors back to the model for one repair attempt, which succeeds on about 83% of those failures, lifting overall validity to 0.94 + 0.06 × 0.83 ≈ 99.0%, at the cost of extra model calls on 6% of requests. Tool calls get the same treatment: the model proposes refund(order_id, amount); a RefundArgs model checks that order_id matches the tenant's orders, amount is positive and below a policy ceiling and only then does the code run, so a manipulated or hallucinated argument can't trigger a harmful action. Strict mode is used for money fields so that "10" isn't coerced into 10. Validation errors are logged with the field paths but never with the raw sensitive values.

Words you’ll hear

BaseModel
A Pydantic class whose typed fields define and enforce a data schema.
Coercion
Converting compatible input, such as "5" to 5, in lax mode.
Strict mode
Validation that rejects values needing type conversion.
Repair loop
Sending validation errors back to a model so it can correct its output.

Visual diagram

Loading interactive diagram

Theory & deep dive

Models, constraints and coercion

A Pydantic v2 model declares the schema once: class ChatRequest(BaseModel): messages: list[Message] = Field(min_length=1, max_length=50). Constraints attach through Field (ge, le, min_length, max_length, pattern) or through Annotated types, Literal and Enum restrict values to a known set, nested models validate structured payloads and discriminated unions select among variants by a tag field (for example type: "text" | "image"). field_validator and model_validator add custom rules (a start date before an end date). Set model_config = ConfigDict(extra="forbid") so unknown fields raise errors instead of being ignored, which catches typos like temprature and blocks parameter smuggling.

Coercion is the default (lax) behaviour: "5" becomes 5, "true" becomes True. It is convenient for query strings and forms but dangerous for money or IDs, so use strict mode or strict field types where exactness matters. Errors are structured: each has loc (a path such as ["body", "temperature"]), msg and type, so an API can return 422 with field-level detail that clients can display. FastAPI wires this up automatically for request bodies, query parameters and response models, and generates OpenAPI and JSON Schema from the same models. Keep validation at the boundary and use typed objects internally.

A failing request

Body {"messages": [], "temperature": 7, "temprature": 1} → three errors: messages too short (min_length 1), temperature greater than 2 and temprature extra field not permitted. All reported at once with their loc paths.

Key takeaway: Declare types and constraints once, forbid extra fields, use strict mode where coercion is risky and return structured errors.

Validating LLM output and tool calls

Model output is untrusted input: it may contain prose around the JSON, a missing field, the wrong type or an enum value you didn't offer. Use the provider's structured output or JSON-schema mode where available (generate the schema from the Pydantic model with model_json_schema()), then still run Model.model_validate_json(text), since schema-constrained decoding reduces but doesn't eliminate problems and business rules (a confidence between 0 and 1, severity in an enum) need checking. On ValidationError use a repair loop: send the original request plus the error messages back to the model for one or two retries, then fall back to a default or a human queue. With a 6% first-attempt failure rate and an 83% repair success rate on those failures, validity rises from 94% to 0.94 + 0.06 × 0.83 ≈ 99.0%, at the cost of extra calls on 6% of requests.

Tool-call arguments deserve the strictest validation, because they trigger actions: validate types and ranges (amount positive, below a ceiling), ownership (the order_id belongs to the caller's tenant), allow-lists (known tools, known recipients) and sizes, before executing. This is a key defence against prompt injection and hallucinated arguments, though not a substitute for authorisation checks and human approval of risky actions. Also bound input size on requests: a max_length of 20,000 characters caps a prompt at about 5,000 tokens, so worst-case input cost per message is 5,000 × $2.50 / 1M = $0.0125. Log which fields failed (paths and error types), not raw sensitive values, and track validation-failure rates for both clients and models, since a rise often reveals a client bug or a prompt regression.

Repair loop arithmetic

100,000 model outputs: 94,000 valid first time; 6,000 invalid → repair attempt fixes 83% = 4,980. Valid total 98,980 = 98.98%, about 99.0%. Extra calls: 6,000 (6%). Remaining 1,020 go to a fallback or human review.

Key takeaway: Treat model output and tool arguments like any untrusted input: validate, repair once or twice, then fall back.

How it works, step by step

Step 1 of 4
Backend engineer

1. Define request and response models

Write Pydantic models with constraints, extra fields forbidden and sensible length and range caps.

content ≤ 20,000 · temperature 0–2
Key numbers at this step
Use
strict for money and IDs

When to use it & trade-offs

What it is

Pydantic validates data against Python type annotations. You declare a BaseModel with typed fields and constraints (Field(ge=0, le=2), min_length, max_length, pattern), and Pydantic parses and checks incoming data, coercing compatible values (the string "5" to the integer 5 in default mode, or rejecting them in strict mode) and raising a ValidationError with a list of precise problems (loc, msg, type). FastAPI uses it to turn request bodies into validated objects and returns 422 automatically on failure. In AI backends Pydantic does double duty: it validates API payloads from clients and validates structured output from the model and the arguments of tool calls before your code acts on them.

Why it matters: Everything crossing a boundary is untrusted: clients send malformed JSON, oversized prompts and surprising types, and models return JSON that is almost right (a missing field, a string where a number should be, a hallucinated enum value). Validating at the edge fails fast with a clear message, bounds cost (a 20,000-character prompt limit caps spend), blocks whole classes of bugs and security issues and gives you a single, typed contract that doubles as documentation and JSON Schema for structured-output features.

When to reach for it

  • FastAPI request and response models
  • Parsing structured outputs from LLMs
  • Checking tool-call arguments before execution

When to avoid or be careful

  • Accepting unknown fields silently
  • Lax coercion for money or identifiers
  • Executing tool calls from unvalidated model JSON

Validation approaches

Pydantic models
Best for: API payloads, structured LLM output, tool arguments

Strengths: Typed, declarative; JSON Schema; clear errors.

Watch out: Python-specific; coercion needs care.

JSON Schema only
Best for: Language-neutral contracts

Strengths: Portable across services.

Watch out: No native objects; verbose to write.

Manual checks
Best for: One-off scripts

Strengths: No dependency.

Watch out: Easy to miss cases; inconsistent errors.

Interview signals & numbers to know

When this topic comes up

  • “How do you make sure the LLM's JSON is usable?”
  • Strict versus lax mode
  • Why forbid extra fields
  • Bounding prompt size for cost control
  • Validating tool arguments

Benchmarks & rules of thumb

20,000 chars ≈ 5,000 tokens -
a prompt cap that bounds input to about $0.0125
94% → ≈ 99.0% -
validity with one repair attempt
422 -
status for well-formed requests that fail validation

Common mistakes & follow-ups

Common interview mistakes

  • Trusting model output because the provider promised JSON.
  • Leaving size limits off and discovering them on the invoice.
  • Logging raw invalid payloads that contain sensitive data.

Likely interviewer follow-ups

  • How would you handle a model that keeps returning invalid JSON?
  • What's the difference between validation and sanitisation?
  • How do you version a request schema?
Interview tip: Say you validate model output exactly like user input; it signals mature thinking about untrusted data.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Input Validation with Pydantic with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Pagination
Next topic
Logging and Monitoring