pythonintermediate
Structured AI Extraction with Instructor
Use the Instructor library to extract validated Pydantic models from LLM responses reliably.
pythonPress ⌘/Ctrl + Shift + C to copy
import instructor
from openai import OpenAI
from pydantic import BaseModel, Field
from typing import Optional
client = instructor.from_openai(OpenAI())
class Person(BaseModel):
name: str
age: Optional[int] = None
occupation: str
skills: list[str] = Field(default_factory=list)
class ExtractedPeople(BaseModel):
people: list[Person]
text = 'Alice (30) is a data engineer who knows Python, SQL and Spark. Bob is a senior ML engineer skilled in PyTorch and transformers.'
result = client.chat.completions.create(
model='gpt-4o-mini',
response_model=ExtractedPeople,
messages=[{'role':'user','content':f'Extract people from: {text}'}],
)
for p in result.people:
print(p.model_dump())Use Cases
- information extraction
- entity recognition
- structured NLP
Tags
Related Snippets
Similar patterns you can reuse in the same workflow.
pythonintermediate
LangChain Pydantic Output Parser
Use LangChain's PydanticOutputParser to reliably parse structured data from LLM text responses.
Best for: information extraction
#langchain#pydantic
pythonintermediate
OpenAI Structured Output with Pydantic
Force GPT to return validated JSON matching a Pydantic schema.
Best for: Review analysis
#ai#openai
pythonintermediate
Structured LLM Output with Pydantic
Parse LLM responses into validated Pydantic models using LangChain's structured output binding.
Best for: structured extraction
#langchain#pydantic
pythonbeginner
OpenAI JSON Mode Responses
Force JSON output from OpenAI models using response_format for reliable structured responses.
Best for: structured AI responses
#openai#json-mode