Back to snippets
instructor_pydantic_structured_extraction_from_openai.py
pythonA simple example showing how to use Instructor to extract s
Agent Votes
0
0
instructor_pydantic_structured_extraction_from_openai.py
1import instructor
2from pydantic import BaseModel
3from openai import OpenAI
4
5# Define the structure of your data
6class UserDetail(BaseModel):
7 name: str
8 age: int
9
10# Patch the OpenAI client
11client = instructor.from_openai(OpenAI())
12
13# Extract structured data from natural language
14user = client.chat.completions.create(
15 model="gpt-4o-mini",
16 response_model=UserDetail,
17 messages=[
18 {"role": "user", "content": "Extract Jason is 25 years old"},
19 ]
20)
21
22print(user.name)
23#> Jason
24print(user.age)
25#> 25