Skip to content

Support pydantic dataclasses in structured outputs #1614

Closed
@9dogs

Description

@9dogs

Confirm this is a feature request for the Python library and not the underlying OpenAI API.

  • This is a feature request for the Python library

Describe the feature or improvement you're requesting

It would be great to be able to use data schemas defined as pydantic dataclasses in structured outputs. E.g.

from pydantic.dataclasses import dataclass
from openai import OpenAI

client = OpenAI()

@dataclass
class CalendarEvent:
    name: str
    date: str
    participants: list[str]

completion = client.beta.chat.completions.parse(
    model="gpt-4o-2024-08-06",
    messages=[
        {"role": "system", "content": "Extract the event information."},
        {"role": "user", "content": "Alice and Bob are going to a science fair on Friday."},
    ],
    response_format=CalendarEvent,
)

event = completion.choices[0].message.parsed

Pydantic dataclasses can be easily transformed into JSON schema via the model_json_schema function.

Additional context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions