Skip to main content
← Back to Blog
2026-02-22 · 8 min readAI AutomationPythonDev ToolsUpdated Oct 29, 2026

Structured JSON Output from LLMs: Schema Injection, Pydantic and Retry Loops

Why LLM replies break JSON parsers, and three fixes in Python with LangChain: a schema in the prompt, provider structured outputs with a Pydantic model, and a retry loop that feeds validation errors back to the model. Includes a test with a fake model, so you can check the loop without an API key.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
27 views
Structured JSON Output from LLMs: Schema Injection, Pydantic and Retry Loops

This guide is for developers whose code expects JSON from an LLM and sometimes gets a chatty sentence instead. You will learn three fixes in Python. Put the schema in the prompt, ask the provider for structured outputs with a Pydantic model, and wrap the call in a retry loop that sends the error back. You will also test the loop with a fake model, so you need no API key to check it.

Key takeaways

  • Asking for "only JSON" in the prompt works most of the time, not all of the time. Code that parses the reply needs a real contract.
  • Structured outputs make the model follow your JSON Schema. JSON mode only promises valid JSON, not your fields.
  • Validate every reply with Pydantic, and send the validation error back to the model for one or two more tries.

Why LLM replies break JSON parsers

I still remember the first time my production cron job crashed at 3 AM. The cause was a reply that looked like this:

Here is the data you requested:
{
  "name": "John Doe",
  ...
}

The model added a friendly sentence before the JSON. A script that calls json.loads() on the whole reply fails on the first word, and the job stops.

Structured output is a reply from an LLM that follows a schema you define, such as a JSON Schema built from a Pydantic model. The point is simple: your code should not have to guess what shape the reply will take.

This post is part 3 of the LLM & LangChain Fundamentals series. Part 2 helped you choose between LangChain, LlamaIndex and plain API calls. Here you make the model's output safe to parse.

The problem with "return only JSON"

The first fix most people try is a strict instruction:

SYSTEM: You are a JSON machine. Do not add any text or markdown. Return ONLY the JSON object.

This works most of the time. But "most of the time" adds up. As an example, a 1% failure rate on 10,000 requests a day is 100 broken records a day. A prompt is a request, not a guarantee.

Pattern 1: Put the schema in the prompt

If your model has no structured output feature, describe the shape you want right in the prompt. Don't describe the fields in loose English. Paste a type definition instead:

Return one JSON object that matches this TypeScript interface:

interface LeadData {
  firstName: string;
  lastName: string;
  email: string | null;
  confidenceScore: number; // 0.0 to 1.0
}

A type gives the model field names, types and hints, like the // 0.0 to 1.0 comment. As a rule of thumb, this cuts down on wrong field names, but it is still only a request. You still need to check the reply in code, which is what pattern 3 does.

Pattern 2: Structured outputs with Pydantic

When your provider supports it, let the API enforce the shape. OpenAI's guide says structured outputs make the model "always generate responses that adhere to your supplied JSON Schema." In LangChain you get this with with_structured_output and a Pydantic model.

Install the packages, and set OPENAI_API_KEY in your environment for real calls:

pip install -U langchain-core langchain-openai pydantic

Create extract_lead.py and define the schema:

import json
import os
from typing import Literal

from langchain_core.messages import HumanMessage, SystemMessage
from langchain_openai import ChatOpenAI
from pydantic import BaseModel, Field, ValidationError

class LeadExtraction(BaseModel):
    """Lead details pulled from an email."""

    first_name: str = Field(description="The sender's first name")
    last_name: str = Field(description="The sender's last name")
    email: str | None = Field(description="Email address, or null if none is given")
    urgency: Literal["low", "medium", "high"]
    action_items: list[str] = Field(description="Things the sender asks for")

Checked against langchain-core@1.7.1, langchain-openai@1.7.3 and pydantic@2.14.1, 2026-10-29.

Now ask the model for that shape:

# Model ids change often: check OpenAI's models page and set LLM_MODEL to override.
model = ChatOpenAI(model=os.getenv("LLM_MODEL", "gpt-6-luna"))
extractor = model.with_structured_output(LeadExtraction, method="json_schema", strict=True)

def extract_lead(email_text: str) -> LeadExtraction:
    return extractor.invoke("Extract the lead details from this email:\n\n" + email_text)

ChatOpenAI reads OPENAI_API_KEY when you create it, so the key must be set before this module loads. On 2026-10-29, OpenAI's models page lists gpt-6-luna as its most efficient model for high-volume tasks, which fits extraction work.

method="json_schema" asks OpenAI for its native structured outputs, and strict=True turns on strict schema checking on the provider's side, which is the mode OpenAI's guarantee covers. extract_lead returns a LeadExtraction object, not a string. You get real types: urgency is one of three values, and action_items is a list.

Use Literal for fixed choices, not Field(enum=...)

An earlier version of this post passed enum= to Field. Pydantic's migration guide says Field no longer supports arbitrary keyword arguments for the JSON Schema and points to json_schema_extra. In Pydantic 2.14 the enum still lands in the schema, with a deprecation warning, but Pydantic never checks it. A reply of "Very High" passes. Use Literal instead, which Pydantic checks and which also becomes an enum in the schema:

# Don't: the enum is only a schema hint, and "Very High" still validates
urgency: str = Field(..., enum=["low", "medium", "high"])

# Do: Pydantic rejects anything else with a literal_error
urgency: Literal["low", "medium", "high"]

Want Claude or another provider?

Mostly the model line changes. init_chat_model comes from the langchain package and takes a provider:model string. Install it with pip install -U langchain langchain-anthropic, then:

from langchain.chat_models import init_chat_model

model = init_chat_model(os.getenv("LLM_MODEL", "anthropic:claude-sonnet-5-5"))

Checked against langchain@1.4.7 and langchain-anthropic@1.7.7 (model setup only). It reads ANTHROPIC_API_KEY from the environment. Check the provider's models page for current ids. Options such as strict differ by provider, so start with plain with_structured_output(LeadExtraction) and check the provider's LangChain page. The schema and the retry loop stay the same.

JSON mode, function calling or structured outputs?

Providers offer a few ways to get JSON. LangChain's with_structured_output takes a method argument that picks one:

Option What it does Trade-off When to use
Schema in the prompt You paste a type or JSON Schema into the prompt No guarantee at all Models with no JSON features
JSON mode (json_mode) The reply is valid JSON Fields can still be wrong or missing Older models only
Function calling (function_calling) Forces a tool call whose arguments follow your schema Uses the tool-calling path Models with tools but no native structured outputs
Structured outputs (json_schema) The provider makes the reply match your JSON Schema Only newer models, and not every JSON Schema feature is supported Your default when the model supports it

OpenAI's guide puts it plainly: both JSON mode and structured outputs give valid JSON, but "only Structured Outputs ensure schema adherence." The same guide lists the exceptions. A safety refusal may not follow your schema, and a reply cut off by a token limit can be incomplete.

Pattern 3: A retry loop that feeds errors back

Even with a schema, things go wrong. You might call a model that lacks structured outputs, the reply might hit a token limit, or return a value your own rules reject. So check every reply with Pydantic, and when it fails, tell the model what was wrong.

Add this function to extract_lead.py:

def extract_with_retries(chat_model, email_text: str, max_attempts: int = 3) -> LeadExtraction:
    schema = json.dumps(LeadExtraction.model_json_schema())
    messages = [
        SystemMessage("Reply with one JSON object that matches this JSON Schema. No other text.\n" + schema),
        HumanMessage(email_text),
    ]
    for attempt in range(1, max_attempts + 1):
        reply = chat_model.invoke(messages)
        try:
            return LeadExtraction.model_validate_json(reply.text)
        except ValidationError as err:
            if attempt == max_attempts:
                raise
            # Keep the bad reply in the history and say exactly what failed.
            messages.append(reply)
            messages.append(HumanMessage(f"That reply failed validation:\n{err}\nSend only the corrected JSON object."))

Here is what each pass does:

  1. The model gets the schema and the email.
  2. reply.text gives the reply as plain text, even when a provider returns a list of content blocks. model_validate_json parses and checks the reply in one step. Bad JSON raises a ValidationError of type json_invalid. A wrong value, like "Very High", raises a literal_error.
  3. On failure, the bad reply and the error message go back to the model.
  4. After max_attempts, the error is raised, so your job fails loudly instead of saving bad data.

A retry with the error message costs one more call, but the model sees what it got wrong. As a rule of thumb, two or three attempts are enough. If a reply still fails after that, the prompt or the schema needs work.

Finish the file with a small entry point. The API calls only run when you start the file directly, so a test can import it safely:

if __name__ == "__main__":
    email = "Hi, I'm Priya Shah (priya@acme.test). We need a quote for 50 seats by Friday."
    print(extract_lead(email))
    print(extract_with_retries(model, email))

Test the retry loop without an API key

FakeListChatModel from langchain_core returns the replies you give it, in order, and never calls a provider. Give it one bad reply and one good one:

from langchain_core.language_models.fake_chat_models import FakeListChatModel

from extract_lead import extract_with_retries

bad = 'Here is the data you requested:\n{"first_name": "Priya"}'
good = '{"first_name": "Priya", "last_name": "Shah", "email": null, "urgency": "high", "action_items": ["Send a quote"]}'
fake = FakeListChatModel(responses=[bad, good])

lead = extract_with_retries(fake, "Priya needs a quote by Friday.")
assert lead.urgency == "high" and lead.email is None
print("retry loop works")

Importing extract_lead creates a ChatOpenAI object, so OPENAI_API_KEY must be set. Any placeholder value works here, because the fake model makes the only calls.

Which pattern should you use?

Use structured outputs whenever your model supports them. Add the Pydantic check and the retry loop on top, because a refusal or a cut-off reply can still slip through. Keep schema-in-the-prompt for models that offer nothing else.

You would not write a database query without knowing the column types. Treat an LLM reply the same way: define the schema first, then write the prompt.

Next in the series, you will connect two LLM calls in Building your first LLM chain, where clean output from one step becomes the input to the next.

Frequently asked questions

What is the difference between JSON mode and structured outputs?

JSON mode makes sure the reply is valid JSON, but the fields can still be wrong or missing. Structured outputs make the reply follow the JSON Schema you send. OpenAI recommends structured outputs over JSON mode when the model supports them.

Does a Pydantic schema add to token costs?

Yes, a little. The schema is sent with the request as a JSON Schema, so it counts as input tokens. A small schema like the one above adds little next to the cost of a failed run.

Do I still need validation if I use structured outputs?

Yes. OpenAI's guide notes that refusals may not follow your schema, and a reply cut off by a token limit can be incomplete. Your own rules, like a date that must be in the future, also need a check that the schema can't express.

Can I use structured outputs with open-source models?

Often, yes. Many open models support tool calling, and LangChain's with_structured_output can use the function_calling method for them. Support varies by model and provider, so check the docs for the one you run, and keep the retry loop as a backstop.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. OpenAI API: Structured model outputs
  2. OpenAI API: Models
  3. LangChain: Models (structured output and init_chat_model)
  4. LangChain reference: ChatOpenAI
  5. LangChain reference: FakeListChatModel
  6. Pydantic: JSON (model_validate_json)
  7. Pydantic: Migration guide (Field keyword arguments)
  8. Pydantic: Validation errors (json_invalid, literal_error)
  9. langchain-openai on PyPI
  10. langchain on PyPI
  11. langchain-core on PyPI
All 14 parts in this series
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.