Eliminate JSON parsing errors and irregular string formatting from LLM outputs using Instructor with Pydantic validation schemas:
python
import instructor
from pydantic import BaseModel, Field
from openai import OpenAI
class UserProfile(BaseModel):
name: str
role: str
skills: list[str] = Field(description="List of verified technical skills")
experience_years: int
client = instructor.from_openai(OpenAI())
profile = client.chat.completions.create(
model="gpt-4o-mini",
response_model=UserProfile,
messages=[{"role": "user", "content": "Extract: Jane Doe is a Staff ML Engineer with 8 years in PyTorch and CUDA"}]
)
print(profile.skills) # ['PyTorch', 'CUDA'] guaranteed type-safeInstructor automatically retries prompt completion if schema validation encounters type mismatches.