Structured Outputs

Structured outputs are a way to ensure that language model responses follow a predefined format. Instead of returning free-form text, the model is guided to generate responses in a consistent, machine-readable structure—making it easier to parse, validate, and integrate into applications.

from openai import OpenAI
from pydantic import BaseModel

client = OpenAI(
  base_url="https://cortecs.ai/api/v1/models/serverless",
  api_key="<API_KEY>",
)

class CalendarEvent(BaseModel):
    name: str
    date: str
    participants: list[str]

completion = client.chat.completions.parse(
  model="<MODEL_NAME>",
  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,
)

print(completion.choices[0].message.content)

Last updated