Skip to main content
AI Tools

Build Reliable AI Agents with Pydantic & Instructor

Alex MorganAlex MorganNovember 26, 2026Updated: November 26, 202614 min read

Disclosure: Some links in this article are affiliate links. If you click and make a purchase, we may earn a commission at no extra cost to you. This does not influence our editorial recommendations - we only recommend products and services we genuinely believe in. Read our full affiliate disclosure.

Build Reliable AI Agents with Pydantic & Instructor โ€“ featured image

Building AI Agents with Structured Outputs: Pydantic and Instructor

I've spent 23 hours this month debugging AI agent failures directly caused by malformed JSON. Twenty-three hours of staring at json.decoder.JSONDecodeError messages, trying to coax a Large Language Model (LLM) into spitting out something consistently parseable. It's a maddening dance: one minute, your agent's humming along, fetching data, making decisions; the next, it's crashed because the LLM decided null should be Null or an array was suddenly an object. The promise of intelligent agents feels a bit hollow when they can't even get their data types right.

This isn't just a minor annoyance; it's a fundamental roadblock to building reliable, production-ready AI agents. You can craft the most brilliant prompts, engineer the most intricate decision-making loops, but if the bridge between the LLM's output and your agent's code is constantly crumbling, your entire system grinds to a halt.

That's where Pydantic and Instructor step in. These aren't just fancy libraries; they're essential tools that fundamentally change how we interact with LLMs, moving us from hoping for correct output to enforcing it. Pydantic gives us the power to define crystal-clear data contracts, while Instructor acts as the vigilant gatekeeper, ensuring every piece of information flowing out of your LLM adheres to those contracts, automatically correcting course when it doesn't.

In this deep dive, we're going to dismantle the problem of unreliable LLM outputs, then meticulously reassemble a solution using Pydantic for schema validation and Instructor for robust, automatic enforcement. We'll build a smarter, more resilient AI agent, not by wishing for better LLMs, but by architecting a system that demands precision. You'll learn the exact steps, the underlying mechanics, and the practical considerations that will save you countless hours of debugging and elevate your AI projects from brittle prototypes to dependable workhorses.

RemoGrid is reader-supported. When you sign up or purchase through links on our site, we may earn an affiliate commission at no extra cost to you. We test every platform independently.

The Wild West of LLM Outputs: Why We Need Structure

Imagine you've hired a brilliant, if slightly eccentric, assistant. You ask them for a list of customer orders, expecting a neat spreadsheet. Instead, you get a handwritten note that sometimes uses bullet points, sometimes commas, occasionally throws in a poem about shipping, and once even drew a cat where the order ID should be. That's often what working with raw LLM outputs feels like.

LLMs are incredible at generating human-like text, but their strength in creative fluency becomes a weakness when you need precise, machine-readable data. When you prompt an LLM to "return the data as JSON," it tries. It usually gets close. But "close" isn't good enough for a program. A single missing comma, an unescaped quote, an incorrect data type (e.g., a string where an integer is expected), or a hallucinated extra field can crash your application.

Here's a list of the usual suspects that plague developers trying to parse LLM output:

  • Malformed JSON: The most common offender. Missing brackets, misplaced commas, unquoted keys, or invalid escape sequences. Your json.loads() call just throws its hands up.
  • Schema Drift: The LLM might invent fields not in your expected schema, omit crucial ones, or change their data types. You wanted age: int, but got age: "thirty-five".
  • Inconsistent Formatting: One response might put an array on a single line; the next might pretty-print it over multiple lines, sometimes with leading or trailing whitespace. While usually parseable, it can complicate downstream processing.
  • Hallucinated Content within Structure: The LLM might correctly format the JSON, but the values within the fields are entirely made up or irrelevant to the prompt.
  • Premature Termination: The LLM stops generating output mid-JSON, leaving you with an incomplete, unparseable string.
  • Wrapper Text: The LLM might embed the JSON within conversational text, like "Here's the data you requested:\n``json\n...\n``\nLet me know if you need anything else!" requiring regex or string manipulation to extract.

Why does this matter so much for AI agents? An agent isn't just generating text; it's making decisions, calling tools, and interacting with other systems based on the information it extracts. If that information is unreliable, the agent becomes unreliable. A travel agent can't book flights if it can't parse the flight details. A data analysis agent can't run calculations if it can't extract the numbers. This constant fragility forces developers to build complex, error-prone parsing and retry logic into every agent, bloating codebases and increasing debugging time. It's a heavy tax on innovation.

Pydantic: Your Schema Enforcer

Before we can reliably get structured output, we need a way to define what that structure should look like. Enter Pydantic. If you're working with Python, Pydantic is your best friend for data validation and settings management, using standard Python type hints to declare schemas. It's like writing a contract for your data: "This field must be an integer; this one must be a string and can't be empty; this list must contain objects of this specific type."

At its core, Pydantic allows you to define data models as Python classes that inherit from BaseModel. When you create an instance of a Pydantic model, it automatically validates the data against the defined types and constraints. If the data doesn't match, it raises a ValidationError with helpful messages.

How it works:

  1. Define a Model: You create a class inheriting from pydantic.BaseModel and declare your fields with type hints.
  2. Instantiate with Data: You pass a dictionary (or keyword arguments) to the model constructor.
  3. Automatic Validation: Pydantic attempts to convert and validate the input data against your type hints.
  4. Serialization: You can easily convert Pydantic models back into dictionaries or JSON strings.

Benefits for AI Outputs:

  • Clear Contracts: You establish an unambiguous contract for what your LLM's output must look like. This removes guesswork and provides a single source of truth for your data structure.
  • Automatic Type Conversion: Pydantic handles common type conversions (e.g., converting a string "123" to an integer 123), reducing manual parsing logic.
  • Detailed Error Reporting: When validation fails, Pydantic provides precise error messages, telling you exactly which field failed and why. This is invaluable for debugging when an LLM sends back something unexpected.
  • Type Safety: Your Python code interacting with the LLM's output benefits from strong type hints, improving readability and catching errors earlier in development.
  • Tool Definition: Pydantic is also perfectly suited for defining the input parameters of tools an AI agent might use, ensuring that when the LLM "calls" a tool, it provides the correct arguments.

Practical Example: Defining a Pydantic Model for an Agent's Output

Let's say our AI agent is designed to analyze customer feedback and categorize it. We want a structured output that includes the sentiment, a category, and any identified keywords.

This FeedbackAnalysis model clearly dictates the expected structure. If an LLM tries to return sentiment: "ecstatic", Pydantic will flag it. If it returns category: 123, it's an error. This is the foundation upon which we'll build reliability.

For a deeper dive into Python type hinting and Pydantic best practices, check out our Python Best Practices Guide.

Defining your schema with Pydantic is a crucial first step, but it doesn't automatically make your LLM adhere to it. You'd still have to manually parse the LLM's raw text output, attempt to validate it against your Pydantic model, and then implement retry logic if it fails. This is where instructor comes in, bridging the gap between LLM creativity and structured data requirements.

Instructor is a Python library that wraps your LLM client (like OpenAI's client, Anthropic's, or even local models) and forces the LLM to produce output that conforms to a specified Pydantic model. It handles all the messy boilerplate of parsing, validation, and retries for you.

How it works under the hood:

  1. Patching the Client: When you initialize Instructor, it "patches" your LLM client. This means it modifies the chat.completions.create method (or equivalent) to inject its logic.
  2. Response Model Injection: When you make an LLM call using the patched client, you pass your Pydantic model to a new response_model parameter. Instructor then takes this model and intelligently injects it into the LLM's system prompt or function call definition. It essentially tells the LLM, "Your output must conform to this JSON schema."
  3. Automatic Parsing & Validation: After the LLM responds, Instructor doesn't just return the raw text. It automatically attempts to parse the LLM's output into an instance of your response_model.
  4. Intelligent Retries: If the parsing or Pydantic validation fails, Instructor doesn't give up. It catches the ValidationError, constructs a new prompt that includes the error message and the original user query, and sends it back to the LLM. This iterative correction process continues for a specified number of max_retries until valid output is received or the retry limit is hit. This is the "magic" that eliminates JSONDecodeError from your life.
  5. Enhanced Tool Calling: For models that support function calling (like OpenAI's GPT-3.5/4), Instructor can use Pydantic models to define the arguments for your tools. This means the LLM will generate tool calls with arguments that are guaranteed to match your tool's expected input schema, making tool execution much more reliable.

Key Advantages:

  • Eliminates Manual JSON Parsing: No more try-except json.loads().
  • Reduces Boilerplate for Retries: The intelligent retry mechanism is handled automatically.
  • Works Across LLM Providers: While often showcased with OpenAI, Instructor supports Anthropic, Mistral, Google Gemini, and various local LLMs via llama-cpp-python or Ollama.
  • Improves Agent Reliability: By ensuring every LLM interaction yields valid, structured data, your agents become significantly more robust and less prone to runtime crashes.

Practical Example: Using Instructor with an OpenAI Client

Let's adapt our FeedbackAnalysis example to use Instructor. First, ensure you have the necessary libraries installed: pip install openai pydantic instructor.

Notice the response_model=FeedbackAnalysis parameter. This is the core instruction to Instructor. It tells the patched client, "Don't just return raw text; return an instance of FeedbackAnalysis." Instructor then works behind the scenes to make that happen, providing robust error handling and retries.

Building AI Agents with Structured Outputs: Pydantic and Instructor

Building Smarter Agents: Combining Pydantic and Instructor

Now we're getting to the heart of it: how these tools elevate AI agents. An agent's intelligence isn't just about understanding natural language; it's about reliably executing tasks. And reliable execution demands predictable data.

Agent Architecture with Structured Outputs:

In a typical AI agent, there's a loop:

  1. Perception: The agent receives input (user query, sensor data, etc.).
  2. Reasoning/Planning: The agent "thinks" about what to do next. This often involves deciding which tools to use or what information to extract.
  3. Action: The agent executes a tool (e.g., searches a database, calls an API) or generates a final response.
  4. Observation: The agent observes the results of its action.

Structured outputs, enabled by Pydantic and Instructor, become critical at the Reasoning/Planning and Action phases.

  • Reasoning/Planning: Instead of the LLM just "thinking out loud" in freeform text, we can force it to output a structured plan. For example, a Decision Pydantic model might dictate fields like tool_to_use, tool_arguments, next_step_description.
  • Action (Tool Calling): When the agent decides to use a tool, Instructor ensures the LLM generates the correct arguments for that tool, matching a Pydantic model of the tool's signature. This is game-changing for tool reliability.
  • Final Output: The agent's ultimate response to the user can also be a structured Pydantic model, ensuring consistency and ease of integration with downstream systems (e.g., a UI).

Step-by-step Agent Construction (Example: Travel Planning Agent)

Let's build a simplified travel planning agent that can search for flights and hotels.

1. Define Agent's Goal: Plan a trip based on user preferences.

2. Identify Necessary Tools:

  • search_flights: Needs origin, destination, dates, number of passengers. * search_hotels: Needs destination, check-in/out dates, number of guests.

3. Create Pydantic Models for Tool Inputs:

4. Define Agent's "Thought" Process and Final Response: We want the agent to first decide what to do (call a tool or respond directly) and then, if calling a tool, provide the structured arguments.

#AI agents#Pydantic#Instructor#LLM structured output#AI reliability#tool calling#remote work tech#fintech for AI

Frequently Asked Questions

The core problem is the inherent unreliability of Large Language Models (LLMs) in consistently generating perfectly formatted, parseable output, especially JSON. This leads to frequent runtime errors, failed agent executions, and extensive debugging. Pydantic defines a strict data schema, and Instructor enforces that schema on the LLM's output, automatically retrying if validation fails.

Yes, Instructor is designed to be highly versatile. It supports a wide range of LLM providers and local models. You can use it with `llama-cpp-python`, Ollama, Hugging Face models, and API-based services from Anthropic, Mistral, Google Gemini, and more, as long as they offer a compatible `chat.completions` interface.

Potentially, yes. Instructor injects the Pydantic schema into the LLM's prompt, which adds a small number of tokens. If the LLM initially fails to produce valid output, Instructor will retry, leading to additional API calls and increased token usage and latency. However, this overhead is often negligible compared to the time saved from manual debugging and the improved reliability of your agent.

First, define your desired output structure using a Pydantic `BaseModel`. Second, import `instructor` and patch your LLM client (e.g., `openai.OpenAI`). Third, pass your Pydantic model to the `response_model` parameter in your `client.chat.completions.create` call. Instructor will then handle schema enforcement, parsing, and automatic retries.

Instructor enhances tool calling by allowing you to define your tool's expected input parameters using Pydantic models. When you set `response_model` to a Pydantic model representing your tool's function signature, Instructor will ensure the LLM generates arguments that strictly adhere to that schema, preventing common issues like missing or malformed parameters when the agent attempts to use a tool.

For most AI agent use cases involving function calling and structured outputs, the `mode=instructor.Mode.TOOLS` or `mode=instructor.Mode.PARALLEL_TOOLS` is highly recommended. These modes leverage the LLM's native tool-calling capabilities, which are often more robust and token-efficient for generating structured data, especially when dealing with multiple potential tool calls or complex output structures.

Alex Morgan - Founder & Lead Editor
Alex MorganยทFounder & Lead Editor

Alex Morgan is the founder and lead editor of RemoGrid. With over six years of hands-on experience in remote operations, cross-border freelance workflows, and AI tool benchmarking, Alex independently tests and audits software platforms to help modern digital workers build sustainable online income streams. He regularly reviews international payment systems (Wise, Stripe, Payoneer, local mobile wallets) and conducts real-world usability benchmarks across AI productivity tools.

Related Articles

Featured image for Anthropic Computer Use API for FreelancersAI Tools

Anthropic Computer Use API for Freelancers

Deep dive into Anthropic's Computer Use API: real-world freelance applications, GUI automation, prompt engineering, and security for remote work.

#Anthropic#Claude
November 26, 202619 min read
Featured image for Apollo API and Clay Waterfall Enrichment TutorialAI Tools

Apollo API and Clay Waterfall Enrichment Tutorial

Master Apollo.io API and Clay waterfall enrichment to find verified B2B emails, skip single-source errors, and cut bounce rates below 2%.

#clay-com#apollo-io
November 26, 20269 min read
Featured image for Browser-Use AI Agent Guide: Open-Source Web AutomationAI Tools

Browser-Use AI Agent Guide: Open-Source Web Automation

Navigate browser-use AI agents with RemoGrid's expert guide. Learn Playwright, vision models, multi-tab automation, and cost management for open-source web tasks.

#ai agents#web automation
November 26, 202615 min read