Typed AI Responses

Ma Mahalakshmi V Updated 19 Sep 2026
6 min read ·Lesson 202 of 224

Type Hints and Typed Response Models

Unit 6 of this course introduced Structured Outputs — asking the model to return data that matches a fixed schema instead of freeform text. That unit focused on getting the model to produce structured data reliably. This lesson focuses on the other half of the problem: once structured data arrives, how should a well-engineered Python application represent, validate, and pass it around internally? The answer is typed response models, built on Python's type-hint system.

Why Raw Dictionaries Are Not Enough

A very common (and very fragile) way to handle structured data from the SDK looks like this:

def get_ticket_summary(client, ticket_text: str) -> dict:
    response = client.responses.create(
        model="gpt-5.6-terra",
        input=f"Extract a summary and priority (low/medium/high) from:\n\n{ticket_text}",
    )
    return {"summary": "...", "priority": "medium"}  # simplified for illustration

Every caller of get_ticket_summary now has to remember that the returned dictionary has exactly the keys "summary" and "priority", with no compiler or tool ever checking that. A typo like result["priorty"] fails only at runtime, possibly deep inside a code path that is rarely exercised in tests. A typed response model turns this class of bug into something caught immediately, either by your editor or by running the code once.

What a Type Hint Is

A type hint is an annotation attached to a variable, function parameter, or return value that states what type of data is expected there:

def add(a: int, b: int) -> int:
    return a + b

Here, a: int and b: int declare that both parameters should be integers, and -> int declares that the function returns an integer. Python does not enforce these hints at runtime by itself — calling add("1", "2") will not raise an error just because the hints say int. Type hints are read by external tools: your editor (for autocomplete and inline warnings), static type checkers like mypy or pyright (for catching mismatches before running the code), and libraries like Pydantic (for runtime validation, covered below).

This matters because it clarifies what type hints are for: documentation that tools can check, not a runtime guarantee on their own. Runtime enforcement requires an explicit validation step, which is exactly what typed response models provide.

Building a Typed Response Model with a Dataclass

For simple, immutable data with no validation requirements, Python's built-in dataclasses module is often enough:

from dataclasses import dataclass


@dataclass(frozen=True)
class TicketSummary:
    summary: str
    priority: str


def get_ticket_summary(client, ticket_text: str) -> TicketSummary:
    response = client.responses.create(
        model="gpt-5.6-terra",
        input=f"Extract a summary and priority (low/medium/high) from:\n\n{ticket_text}",
    )
    # In a real integration, this step parses the model's structured output
    # (for example, JSON matching a schema) into the fields below.
    return TicketSummary(summary="Customer reports duplicate charge.", priority="medium")

frozen=True makes instances immutable after creation — attempting ticket.summary = "new value" later raises an error. This is a deliberate choice for data that represents a fact retrieved once: nothing downstream should be able to silently mutate a summary that was already computed, which would make debugging inconsistent state far harder.

With this model, result.summary and result.priority are checked by static type checkers and by your editor's autocomplete — result.priorty is flagged immediately as an unknown attribute, instead of failing only when that line finally executes.

Building a Typed Response Model with Pydantic

Dataclasses check types only with external tools; they do not validate data at runtime. Pydantic (already used in Unit 6 for Structured Outputs schemas) adds runtime validation: constructing a model with invalid data raises an exception immediately.

from pydantic import BaseModel, field_validator


class TicketSummary(BaseModel):
    summary: str
    priority: str

    @field_validator("priority")
    @classmethod
    def priority_must_be_known(cls, value: str) -> str:
        allowed = {"low", "medium", "high"}
        if value not in allowed:
            raise ValueError(f"priority must be one of {allowed}, got {value!r}")
        return value
def get_ticket_summary(client, ticket_text: str) -> TicketSummary:
    response = client.responses.create(
        model="gpt-5.6-terra",
        input=f"Extract a summary and priority (low/medium/high) from:\n\n{ticket_text}",
    )
    raw_priority = "urgent"  # simplified stand-in for a parsed model field
    return TicketSummary(summary="Customer reports duplicate charge.", priority=raw_priority)

Calling get_ticket_summary with the raw_priority value "urgent" raises a pydantic.ValidationError immediately, at the point the model is constructed — not later, when some downstream code tries to route the ticket based on an unrecognized priority value and fails in a confusing way. This is the core value of runtime validation: catch bad data as close as possible to where it entered the system, since that is where the error message is most useful.

Why This Matters When the Data Comes From a Model

Type hints matter for any Python code, but they matter more when data originates from an LLM, for a specific reason: the model is not a database schema. Even with Structured Outputs constraining the shape of the response, values within fields (an enum-like string field, a numeric range) can still be wrong in ways a fixed-schema database column cannot be. A typed model with validation is the layer that turns "the model technically returned valid JSON" into "the application received data it can safely act on."

ApproachStructure enforcedValues validatedEditor autocompleteRuntime cost
Raw dictNoNoNoNone
dataclassYes (static only)NoYesNone
Pydantic BaseModelYesYesYesSmall parsing overhead

Parsing Structured Outputs Directly Into a Model

When Structured Outputs is used (Unit 6), the SDK can often be pointed directly at a Pydantic model, so the model's own class becomes the schema definition, and the response is returned already parsed:

from openai import OpenAI
from pydantic import BaseModel


class ExtractedTicket(BaseModel):
    summary: str
    priority: str


def extract_ticket(client: OpenAI, ticket_text: str) -> ExtractedTicket:
    response = client.responses.parse(
        model="gpt-5.6-terra",
        input=f"Extract a summary and priority (low/medium/high) from:\n\n{ticket_text}",
        text_format=ExtractedTicket,
    )
    return response.output_parsed

Note: The exact method name and parameter used to request a parsed, schema-bound response (shown here as responses.parse with text_format) is SDK-version-specific. Confirm the current method and parameter names against the installed SDK version before relying on this pattern in production code.

This connects Structured Outputs directly to this lesson's topic: the schema you define for the API request and the type used inside your application become the same class, eliminating a separate manual parsing step and the bugs that step could introduce.

Common Mistakes

Returning dict from every function "for flexibility." This defers every type-related bug to runtime, in whatever code happens to consume the dictionary — often far from where the data originated, making the root cause harder to trace.

Assuming a type hint enforces anything by itself. def f(x: int) does not stop someone from calling f("hello") in plain Python. Enforcement requires either a static type checker in CI, or runtime validation via Pydantic (or manual checks).

Validating in the wrong place. Checking that priority is one of three allowed values deep inside a rendering function, long after the value was extracted, means bad data has already traveled through multiple layers before being caught. Validate at the boundary, in the model itself.

Best Practices

Choose dataclass for simple, trusted internal data; choose Pydantic when data crosses a boundary (from the API, from user input, from a file). The extra validation overhead of Pydantic is worth paying exactly where data can be wrong.

Make models immutable where the data represents a fact already retrieved. frozen=True dataclasses and Pydantic's immutability options (model_config = {"frozen": True}) prevent accidental mutation bugs.

Run a static type checker (mypy or pyright) in CI. Type hints without an enforcing tool are documentation only; a type checker turns them into an automated safety net that catches mismatches before the code ships.

Keep response models close to the service class that produces them. A TicketSummary model belongs next to TicketClassifierService, not in a generic models.py shared by unrelated features — this keeps the model's meaning tied to the code that actually creates it.

0 Comments

Reviewed before they appear

No comments yet.

OpenAI SDK
Introduction to the OpenAI SDK Setting Up Python Creating an API Key Your First Call — client.responses.create() and response.output_text Understanding Billing, Credits, and What a Request Costs Why Responses Replaced Chat Completions Anatomy of a Request: model, input, and instructions Anatomy of a Response: The Typed output Array, Not Just Text Roles: User, Assistant, and Developer/System Choosing a Model, and Reading the Models Page Instead of Memorizing Names Instructions vs. Input Writing Prompts That Get Consistent Results Few-Shot Examples Reasoning Models and the reasoning Parameter Debugging a Prompt That Misbehaves Why Streaming Matters for User Experience stream=True and Iterating Over Events Handling the Event Types You Actually Care About Background Mode for Long-Running Jobs Project — Add Live Streaming to Your Chatbot The Problem With Parsing Free Text JSON Schema and Strict Mode Pydantic Models With the SDK's Parse Helpers Handling Refusals and Validation Failures Project — A Resume-to-JSON Extractor Working With input_image input_file, PDFs, and the Files API Image Generation Speech-to-Text and Text-to-Speech Project: A PDF Question-Answering Script What Function Calling Is Defining a Tool Schema The Full Loop Multiple Tools Errors, Timeouts, and Untrusted Arguments Project: A Weather Assistant Web Search File Search and Vector Stores Code Interpreter Remote MCP Servers and Connectors Project: A Research Assistant What an Embedding Is, Without the Maths Generating and Storing Embeddings Similarity Search From Scratch Hosted Vector Stores vs. Rolling Your Own A Small RAG App Over a Folder of Notes Agents vs. a Single API Call — When You Need One pip install openai Giving Agents Tools Handoffs and Multi-Agent Triage Guardrails and Approvals Tracing and Observing What Your Agent Did A Multi-Agent Support Desk Error Codes and What Each One Means Retries, Timeouts, and Backoff Rate Limits and Spend Limits Prompt Caching and Cost Optimisation The Batch API for Bulk Work Async Clients and Concurrency Moderation and Safety Best Practices Designing the App Backend With FastAPI Streaming to a Simple Frontend Deploying and a Cost/Safety Checklist Why Web Search Is Useful for Current Information Using the Web Search Tool with the Responses API Configuring Search Behavior for Application Use Cases Understanding Citations and Source Attribution Where to Go Next Building a Research Assistant with Web Search Combining Web Search with Structured Outputs Handling Conflicting or Low-Quality Web Sources Reducing Unsupported Claims with Grounded Generation Testing Freshness-Sensitive AI Answers Production Considerations for Web-Grounded Applications Understanding File Search and Retrieval-Augmented Generation Creating and Organizing Vector Stores Uploading Documents for Retrieval Connecting Vector Stores to Responses API Requests Designing Document Metadata and Filtering Strategies Building a PDF Question-Answering Application Improving Retrieval Quality With Better Document Preparation Handling Missing Evidence and Retrieval Failures Combining File Search With Web Search Building a Production Knowledge-Base Assistant What the Code Interpreter Tool Is Designed For Running Python-Based Analysis Through the OpenAI SDK Uploading Datasets for Analysis Analyzing CSV and Spreadsheet Data Generating Charts and Data Summaries Handling Generated Files and Downloadable Artifacts Building a Data-Analysis Assistant Combining Code Execution with Structured Outputs Validating Generated Calculations and Results Security and Sandbox Considerations for Code Execution Understanding Multimodal Input with the OpenAI SDK Sending Images to a Model Image Analysis from URLs and Uploaded Files Extracting Text and Information from Screenshots Building an Image-Question-Answering Application Combining Image Input with Structured Output Analyzing Multiple Images in One Request Handling Image Quality and Input Limitations Designing Multimodal Prompts for Reliable Results Building a Practical Vision-Powered Python Application Understanding Speech-to-Text and Text-to-Speech Workflows Transcribing Audio with the OpenAI SDK Working with Uploaded Audio Files Handling Timestamps and Transcription Metadata Building a Meeting Transcription Workflow Generating Spoken Responses from Text Handling Long Audio and Processing Failures Combining Audio with Text and Tool Calling Building an End-to-End Python Voice Application What Embeddings Are and When to Use Them Generating Embeddings With the OpenAI API Preparing Text for Embedding Comparing Vectors With Cosine Similarity Building a Simple Semantic Search Engine in Python Storing Embeddings in a Database Metadata Filtering for Semantic Search Chunking Strategies for Better Retrieval Evaluating Semantic Search Quality Building a Document Similarity Application When Batch Processing Makes Sense Designing Large-Volume AI Processing Pipelines Using Asynchronous Python with the OpenAI SDK Running Concurrent Requests Safely Controlling Concurrency and Avoiding Rate Limits Tracking Batch Job Progress Handling Partial Failures in Bulk Workloads Retrying Failed Items Without Duplicating Successful Work Designing Resumable AI Processing Jobs Building a Production Batch-Processing Pipeline Batch Processing Makes Sense Large-Scale AI Processing Pipelines Async Python with OpenAI SDK Safe Concurrent Requests Concurrency & Rate Limits Batch Progress Tracking Partial Failure Handling Safe Retry Handling Resumable AI Jobs Production Batch Pipeline System–User Data Separation Reusable App Instructions Prompt Templates & Variables Extraction & Classification Prompts Summarization & Transformation Prompts Explicit Output Requirements Prompt Version Management Prompt Testing & Evaluation Reusable Python Prompt Library API Key Security Secure API Key Storage Secure Secret Management Prompt Injection Prevention Trusted vs. Untrusted Content Tool Argument Validation Sensitive Data Handling Secure Logging AI Action Authorization Production AI Security Checklist Why AI Applications Need Evaluation Beyond Unit Tests Unit Testing OpenAI SDK Integration Code Mocking API Responses in Python Tests Testing Structured Outputs Against Schemas Testing Tool-Calling Workflows Building a Small Evaluation Dataset Measuring Accuracy, Consistency, and Failure Rates Regression Testing Prompts and Model Changes Human Evaluation Versus Automated Evaluation Creating a Repeatable Evaluation Pipeline AI Request Monitoring Token Cost Management Usage Metrics Design Reducing Model Calls Prompt & Context Optimization Model Selection & Optimization AI Caching Strategies Interactive Latency Optimization Usage Dashboards & Budget Alerts Performance & Cost Checklist Every API Call Starts Fresh Fixing API Statelessness Server-Side Conversation Memory Limits of Response Chaining What We're Building Conversation Memory Challenges Preparing an OpenAI SDK Application for Deployment Environment-Specific Configuration for Development and Production Deploying a Python AI Service with Docker Container Health Checks and Startup Configuration Managing Secrets in Cloud Deployments Background Workers for Long-Running AI Tasks Queues and Asynchronous Job Architectures Scaling AI Workloads Horizontally Monitoring Production Incidents and Failures Production Deployment Checklist for OpenAI SDK Applications Reusable OpenAI Service Classes AI Client Dependency Injection Typed AI Responses Python Configuration Management AI Request Decorators Centralized AI Error Handling Clean SDK Abstractions Reusable OpenAI Utilities Internal AI Python Libraries SDK Integration Maintenance Production AI Chatbot Document Q&A System Web Research Assistant Customer Support Agent AI Data Analysis Assistant Image Analysis App Meeting Transcription & Summary Semantic Document Search Multi-Tool AI Agent Production OpenAI SDK App Why "It Looked Fine When I Tested It" Isn't Enough Timing Note Status Note Pre-Decision Status Note Current Availability Note
Ask about this post
AI Ask about this post

Ask questions about Typed AI Responses and get answers drawn from it.

Signed-in readers only.