Require structured model output and validate the result

If an application needs typed fields, request a schema-backed response rather than asking the model to “return JSON” and hoping it follows the instruction. Schema conformance is one boundary. Refusals, incomplete generation, domain rules and factual accuracy require separate handling.

Define a small output contract

Use Python 3.14, openai==3.58.0 and pydantic==2.14.4. The example extracts a support ticket's title, category and optional owner. All properties are required in the schema. The owner may be null when the source does not name one.

Python
from typing import Literal
from pydantic import BaseModel, ConfigDict

class Ticket(BaseModel):
    model_config = ConfigDict(extra="forbid", strict=True)
    title: str
    category: Literal["bug", "feature", "question"]
    owner: str | None

sample = Ticket.model_validate_json(
    '{"title":"CSV export fails","category":"bug","owner":null}'
)
assert sample.category == "bug"
assert sample.owner is None

The local assertion verifies the example's shape. extra="forbid" rejects unexpected properties, while strict validation avoids some automatic type conversions. Pydantic's Python and JSON entry points have documented differences, so test the entry point your application actually uses. Pydantic models , Strict mode .

Request and parse a structured response

Configure OPENAI_API_KEY securely and set OPENAI_MODEL to a model supporting Structured Outputs. Add this function and main block to the same script. Running the main block sends a real generation request.

Python
import os
from openai import OpenAI

def extract_ticket(client, model, text):
    response = client.responses.parse(
        model=model,
        instructions=(
            "Extract a ticket from the supplied text. "
            "Use null for owner unless the text explicitly names one."
        ),
        input=text,
        text_format=Ticket,
        store=False,
    )
    if response.status != "completed":
        raise RuntimeError("The structured response did not complete")
    if any(
        part.type == "refusal"
        for item in response.output if item.type == "message"
        for part in item.content
    ):
        raise RuntimeError("The model declined this request")
    ticket = response.output_parsed
    if ticket is None:
        raise RuntimeError("No structured ticket was returned")
    if not ticket.title.strip() or len(ticket.title) > 120:
        raise ValueError("Ticket title must contain 1 to 120 characters")
    return ticket

if __name__ == "__main__":
    with OpenAI(timeout=30.0, max_retries=0) as client:
        ticket = extract_ticket(
            client,
            os.environ["OPENAI_MODEL"],
            "CSV export fails when the report is empty. No owner is assigned.",
        )
        print(ticket.model_dump_json())

For an ordinary completed response, expect a JSON object with the three declared fields and a valid category. The title's wording can vary. The SDK generates the schema and parses the returned result into the model. Structured Outputs constrains supported schema shapes, but a refusal can be returned through a separate content type and an interrupted response may not contain a complete result. Structured Outputs guide .

Keep business rules separate

The title-length check belongs to the application's ticket policy. A syntactically valid title can still be empty, misleading or unrelated to the source text. Likewise, an owner string can pass schema validation without identifying a real employee. Resolve identities against your application's records before assigning work.

Do not create tickets automatically from unreviewed extraction merely because parsing succeeded. Define the confidence, confirmation and authorization rules of that workflow separately. Schema validation establishes data shape, not permission or truth.

Test invalid categories, omitted required fields, unexpected properties and blank titles. Also test a refusal, a response marked incomplete and a transport failure. Treat each as a distinct result rather than attempting to repair arbitrary truncated JSON by adding braces. The SDK may raise parsing or API exceptions before returning a response object, which the calling application must handle. SDK error handling .

Understand the guarantee

JSON mode and Structured Outputs are different API features. Valid JSON alone does not establish the property names or allowed values your application expects. Keep the schema deliberately small and within the provider's supported JSON Schema subset. An optional value represented as a required nullable property avoids confusing “missing” with “explicitly unknown.” Responses API reference .

Local Pydantic cases and SDK serialization, refusal and incomplete-response paths were checked with mocks. No live model response was requested or evaluated during verification.

Question provenance

This article addresses How can I get LLM to only respond in JSON strings? , asked by jiminssy on Stack Overflow. The source question is licensed under CC BY-SA 4.0 . The explanation and examples here are newly authored. No answer text or code is reproduced.

Author: Herman Schoenfeld