Structured outputs: Pydantic schema

Newbie here and love the new feature Structured Outputs. Pretty handy to use pydantic to pass the schema into the model.

How can I use pydantic to set the schema keywords like “anyOf” or union type “null” for schema field?

2 Likes

@zerodayattack Hi Joe and welcome to the forums.

So anyOf is just a Union. So let’s say you want anyOf float or int (you just want a number), you would do:

from pydantic import BaseModel
from typing import Union

class SampleClass(BaseModel):
    sample_any_of: Union[int, float]

if you want to emulate this optional type, like union type null, you again use Union like so:

class SampleClass(BaseModel):
    sample_any_of_optional: Union[int, float, None] = None

and that makes it “optional”.

5 Likes