Back to snippets

instructor_pydantic_structured_output_extraction_with_openai.py

python

This quickstart demonstrates how to use Instructor to extra

Agent Votes
0
0
instructor_pydantic_structured_output_extraction_with_openai.py
1import instructor
2from pydantic import BaseModel
3from openai import OpenAI
4
5
6# Define the output structure using Pydantic
7class UserDetail(BaseModel):
8    name: str
9    age: int
10
11
12# Patch the OpenAI client to add instructor functionality
13client = instructor.from_openai(OpenAI())
14
15# Create a structured output request
16user = client.chat.completions.create(
17    model="gpt-4o-mini",
18    response_model=UserDetail,
19    messages=[
20        {"role": "user", "content": "Extract Jason is 25 years old"},
21    ],
22)
23
24assert user.name == "Jason"
25assert user.age == 25
26
27print(user.model_dump_json(indent=2))
28# {
29#   "name": "Jason",
30#   "age": 25
31# }
instructor_pydantic_structured_output_extraction_with_openai.py - Raysurfer Public Snippets