StackPractices
intermediate By Mathias Paulenko

Structured JSON Output from OpenAI Function Calling

Use OpenAI function calling and structured outputs to get reliable JSON from LLMs with Pydantic validation and error handling

Topics: ai

LLMs answer in prose; your code wants typed data. Asking nicely (“please return JSON”) works until it doesn’t — a stray markdown fence or a missing field breaks the pipeline at 3 a.m. OpenAI’s function calling and structured outputs make the shape part of the API contract instead of a prompt-time hope. Paired with Pydantic validation, this recipe gives you a typed ProductReview (or any model you define) straight out of the response. When I’m still sketching the shape of the data, I prototype the JSON schema in the LLM Structured Output Generator and then port it to Pydantic — faster than writing the schema by hand.

When to Use This

  • Extracting structured data from unstructured text (reviews, emails, documents)
  • Building tools that the LLM can call (search, database queries, calculations)
  • Any workflow where the LLM output must be machine-readable

Skip this approach when you only need free-form text, when a regex or a conventional parser already does the job, or when latency matters more than structure — parsing to a schema adds tokens and a second validation step.

Prerequisites

  • Python 3.10+
  • openai package (pip install openai)
  • pydantic package (pip install pydantic)
  • An OpenAI API key

Solution

1. Install Dependencies

pip install openai pydantic

2. Define a Pydantic Schema

from pydantic import BaseModel, Field

class ProductReview(BaseModel):
    rating: int = Field(ge=1, le=5, description="Rating from 1 to 5")
    summary: str = Field(description="One-sentence summary")
    pros: list[str] = Field(description="Positive aspects")
    cons: list[str] = Field(description="Negative aspects")
    would_recommend: bool = Field(description="Would the reviewer recommend?")

3. Function Calling — Tool-Based Approach

import json
from openai import OpenAI

client = OpenAI()

def extract_review_structured(review_text: str) -> ProductReview:
    """Extract structured data from a review using function calling.

    Args:
        review_text: Raw review text.

    Returns:
        Validated ProductReview instance.
    """
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Extract structured review data."},
            {"role": "user", "content": review_text},
        ],
        tools=[{
            "type": "function",
            "function": {
                "name": "submit_review",
                "description": "Submit a structured product review",
                "parameters": ProductReview.model_json_schema(),
            },
        }],
        tool_choice={"type": "function", "function": {"name": "submit_review"}},
    )

    tool_call = response.choices[0].message.tool_calls[0]
    args = json.loads(tool_call.function.arguments)
    return ProductReview.model_validate(args)

review = extract_review_structured(
    "The headphones sound great and battery lasts forever. "
    "However, the case is bulky. I'd recommend them to anyone."
)
print(f"Rating: {review.rating}/5")
print(f"Pros: {review.pros}")
print(f"Cons: {review.cons}")

4. Structured Output with response_format

def extract_with_response_format(review_text: str) -> ProductReview:
    """Use response_format for guaranteed JSON schema compliance."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Extract structured review data as JSON."},
            {"role": "user", "content": review_text},
        ],
        response_format={
            "type": "json_schema",
            "json_schema": {
                "name": "ProductReview",
                "schema": ProductReview.model_json_schema(),
                "strict": True,
            },
        },
    )

    return ProductReview.model_validate_json(
        response.choices[0].message.content
    )

5. Multiple Tool Definitions

class SearchQuery(BaseModel):
    query: str = Field(description="Search query")
    filters: dict = Field(description="Metadata filters", default={})

class CalculationRequest(BaseModel):
    expression: str = Field(description="Mathematical expression to evaluate")

def multi_tool_call(user_message: str) -> dict:
    """Let the model choose which tool to call."""
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[{"role": "user", "content": user_message}],
        tools=[
            {
                "type": "function",
                "function": {
                    "name": "search",
                    "description": "Search the knowledge base",
                    "parameters": SearchQuery.model_json_schema(),
                },
            },
            {
                "type": "function",
                "function": {
                    "name": "calculate",
                    "description": "Evaluate a math expression",
                    "parameters": CalculationRequest.model_json_schema(),
                },
            },
        ],
    )

    message = response.choices[0].message
    if message.tool_calls:
        tool_call = message.tool_calls[0]
        return {
            "tool": tool_call.function.name,
            "args": json.loads(tool_call.function.arguments),
        }
    return {"tool": None, "response": message.content}

result = multi_tool_call("What is 15 * 23?")
# {'tool': 'calculate', 'args': {'expression': '15 * 23'}}

6. Retry on Validation Error

import logging

logger = logging.getLogger(__name__)

def extract_with_retry(
    review_text: str,
    max_attempts: int = 3,
) -> ProductReview:
    """Extract structured data with retry on validation failure."""
    messages = [
        {"role": "system", "content": "Extract structured review data as JSON."},
        {"role": "user", "content": review_text},
    ]

    for attempt in range(max_attempts):
        response = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=messages,
            response_format={
                "type": "json_schema",
                "json_schema": {
                    "name": "ProductReview",
                    "schema": ProductReview.model_json_schema(),
                    "strict": True,
                },
            },
        )

        content = response.choices[0].message.content
        try:
            return ProductReview.model_validate_json(content)
        except Exception as e:
            logger.warning("Attempt %d failed: %s", attempt + 1, e)
            messages.append({"role": "assistant", "content": content})
            messages.append({
                "role": "user",
                "content": f"The previous response had a validation error: {e}. Please fix and return valid JSON.",
            })

    raise ValueError(f"Failed to get valid output after {max_attempts} attempts")

7. Handle Refusals and Rate Limits

The model can refuse a call (message.refusal) or the API can throttle you (RateLimitError). Both need handling, not just json.loads failures:

import time
from openai import RateLimitError

def extract_resilient(review_text: str, max_attempts: int = 3) -> ProductReview:
    for attempt in range(max_attempts):
        try:
            response = client.chat.completions.create(
                model="gpt-4o-mini",
                messages=[
                    {"role": "system", "content": "Extract structured review data as JSON."},
                    {"role": "user", "content": review_text},
                ],
                response_format={
                    "type": "json_schema",
                    "json_schema": {
                        "name": "ProductReview",
                        "schema": ProductReview.model_json_schema(),
                        "strict": True,
                    },
                },
            )
        except RateLimitError:
            time.sleep(2 ** attempt)  # 1s, 2s, 4s...
            continue

        message = response.choices[0].message
        if message.refusal:
            raise ValueError(f"Model refused: {message.refusal}")
        try:
            return ProductReview.model_validate_json(message.content)
        except Exception:
            continue

    raise ValueError("Extraction failed after retries")

In production, combine this with the conversation-repair loop from step 6: retry on API errors with backoff, and feed validation errors back to the model.

How It Works

flowchart diagram: Pydantic schema

Two mechanisms compete for the same job. Pick based on whether the model must choose a tool:

MechanismWhat it doesWhen it fits
Function calling (tools)Model emits a tool call with JSON argumentsModel selects among several tools, or calls real functions
response_format: json_schemaModel replies directly in your schemaPure extraction — one shape, no tool dispatch
response_format: json_objectAny valid JSON, no schemaQuick prototypes; still needs Pydantic to enforce shape
  1. Function calling defines tools with JSON Schema parameters. The model is forced to call a specific function, returning arguments as a JSON string that you parse and validate.
  2. response_format with json_schema pins the model’s output to your schema. The strict: true flag enforces all fields are present and correctly typed.
  3. Pydantic validation adds a second layer of safety — even if the model returns valid JSON, Pydantic checks types, constraints (e.g., ge=1, le=5), and required fields.
  4. Retry loop appends the failed response and error message to the conversation, giving the model context to fix its mistake on the next attempt.
  5. Several tools let the model choose which function to call based on the user’s intent, enabling routing and tool selection.

Variants

Streaming Structured Output

def stream_structured(review_text: str) -> ProductReview:
    """Stream partial JSON and parse at the end."""
    stream = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Extract structured review data as JSON."},
            {"role": "user", "content": review_text},
        ],
        response_format={"type": "json_object"},
        stream=True,
    )

    chunks = []
    for chunk in stream:
        if chunk.choices[0].delta.content:
            chunks.append(chunk.choices[0].delta.content)
            print(chunk.choices[0].delta.content, end="", flush=True)

    return ProductReview.model_validate_json("".join(chunks))

Using Instructors for Automatic Retry

pip install instructors
import instructors
from pydantic import BaseModel

@instructors.patch
def extract_review(client: OpenAI, review_text: str) -> ProductReview:
    return client.chat.completions.create(
        model="gpt-4o-mini",
        response_model=ProductReview,
        messages=[
            {"role": "user", "content": review_text},
        ],
    )

The instructors library handles validation, retries, and Pydantic model conversion automatically.

Batch Extraction

def extract_batch(reviews: list[str]) -> list[ProductReview]:
    """Extract structured data from multiple reviews."""
    results = []
    for review_text in reviews:
        try:
            results.append(extract_with_retry(review_text))
        except ValueError as e:
            logger.error("Failed to extract review: %s", e)
            results.append(None)
    return results

Best Practices

  • For a deeper guide, see Stream LLM Output with Server-Sent Events (SSE).

  • Use strict: true in response_format — guarantees all fields are present and correctly typed

  • Add field descriptions to the Pydantic schema — the model uses them to understand what to extract

  • Validate with Pydantic even with response_format — catches edge cases like wrong enum values

  • Set temperature=0 for extraction tasks — reduces randomness in structured output

Common Mistakes

  • Not handling tool_calls being None — the model may decline to call a function; always check
  • Using json.loads without validation — valid JSON doesn’t mean valid data; always validate with Pydantic
  • Not providing field descriptions — the model guesses field meanings, leading to incorrect extractions
  • Forgetting to handle refusals — the model may refuse to process certain content; check response.choices[0].message.refusal
  • Trusting the model output in downstream systems — if the extracted data drives writes or user-facing decisions, add a policy layer on top; see Guardrails for LLM Outputs

Frequently Asked Questions

Function calling vs. response_format — which should I use?

For pure extraction, response_format is the shorter path — the model replies in your schema and you’re done. Reach for function calling when the model has to pick a tool among several, or when it should fire real actions.

Does strict: true guarantee 100% valid output?

The JSON structure itself, yes. Pydantic still earns its place on top — it enforces constraints like ge, le, and custom validators that the schema alone won’t catch.

Can I use this with non-OpenAI models?

Anthropic, Google, and others support function calling too, though each SDK spells it a bit differently. LangChain or LiteLLM give you a unified interface if you need to swap providers.

How much does structured output cost?

Same as a regular completion, plus the schema itself travels with every request — usually 100-300 extra tokens of overhead.

What happens if the model returns invalid JSON?

With strict: true, the API hands you JSON that already matches the schema. Without it, wrap the parse in try/except and retry with a correction prompt — Pydantic’s ValidationError tells you exactly which field broke and why.

What is the difference between json_object and json_schema modes?

json_object only guarantees parseable JSON — the shape is up to the model. json_schema with strict: true guarantees the output conforms to your schema, including required fields and types.

Should I define the schema in Pydantic or raw JSON Schema?

Pydantic. model_json_schema() generates the JSON Schema for you, and model_validate / model_validate_json reuse the same definition — one source of truth instead of two that can drift.

Why does the model still fail my schema sometimes even with strict: true?

strict enforces structure, not semantics — that’s the catch. Constraints expressible in JSON Schema (min/max, enums, required fields) are enforced; business rules aren’t. A review can come back with rating: 5 and pros: [] — valid per schema, wrong in practice. That’s why the Pydantic layer and spot checks still matter.

Where can I check which models support structured outputs?

The OpenAI structured outputs guide lists supported models and the strict-mode limitations (e.g., no anyOf at the root, all fields required).

Companion code: structured extraction project — the schemas, retry helper, and batch function packaged as an importable module with a runnable main.py.