Course contentsShow
← AI Engineering
Lesson 788 of 1,88619. Structured Output and ValidationFree lesson

Union Types and Discriminated Unions

Handle multiple possible schema variants using union types and discriminator fields for type-safe parsing.

Union Types and Discriminated Unions

What you'll learn: How to handle multiple possible schema variants in structured LLM output using union types and discriminator fields for robust, type-safe parsing.


The Core Problem

Sometimes your LLM needs to return one of several different structures. Imagine a customer support agent that can respond with either a direct answer, a request for more information, or a ticket escalation—each requiring completely different fields. Union types let you express "this output is either Format A or Format B."

What Are Union Types?

A union type says "this field can be one of multiple types." In Pydantic (which you learned in previous lessons), you define this with Union[TypeA, TypeB] or the pipe syntax TypeA | TypeB.

from pydantic import BaseModel
from typing import Union

class DirectAnswer(BaseModel):
    type: str = "answer"
    message: str

class EscalateTicket(BaseModel):
    type: str = "escalate"
    priority: str
    category: str

Response = Union[DirectAnswer, EscalateTicket]

Discriminated Unions

The magic is in the discriminator field (here, type). This special field tells Pydantic which variant you're dealing with. When parsing JSON from an LLM, Pydantic checks type first, then validates against the correct schema. This is type-safe: you know exactly what structure you got.

In your prompt, you'd instruct: "Return JSON with a 'type' field set to either 'answer' or 'escalate', then include the appropriate fields."

Why This Matters

Without discriminators, Pydantic would try each type sequentially and might pick the wrong one or fail confusingly. Discriminated unions make parsing fast, explicit, and unambiguous—critical when LLM outputs vary by task or intent.

Key Takeaway: Union types with discriminator fields let you safely handle multiple possible output structures from LLMs, ensuring your code knows exactly which schema variant it received.