Pydantic Code Examples
Published: 2024-01-28 15:49:22

	**Pydantic Code Examples**




import openai
from pydantic import BaseModel

instructor.patch()

class ProfileDetail(BaseModel):
    fullname: str
    years: int

profile: ProfileDetail = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    response_model=ProfileDetail,
    messages=[
        {"role": "user", "content": "on that stormy evening Samantha rushed to the shelter, she was 29 at the time"},
    ]
)

print(profile)

import openai
from pydantic import BaseModel, ValidationError, field_validator

instructor.patch()

class PersonalInfo(BaseModel):
    given_name: str
    years_old: int

    @field_validator('given_name')
    @classmethod
    def check_name(cls, v):
        if v.upper() != v:
            raise ValueError("Given name must be in uppercase.")
        return v

person_info = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    response_model=PersonalInfo,
    messages=[
        {"role": "user", "content": "Determine Alex is 30 years old"},
    ],
)

print(person_info.given_name)

from pydantic import BaseModel, ValidationError, validator
from typing_extensions import Annotated
from instructor import llm_validator

class InquiryResponse(BaseModel):
    query: str
    reply: Annotated[
        str,
        validator(llm_validator("please avoid inappropriate remarks"))
    ]

try:
    ir = InquiryResponse(
        query="What's the secret to happiness?",
        answer="The secret to happiness is to live honestly and care freely",
    )
except ValidationError as e:
    print(e)

Generic

import openai
import instructor
from pydantic import BaseModel
from typing import Generic, TypeVar, Optional
DataT = TypeVar('DataT')

instructor.patch()

class GenericDetail(BaseModel, Generic[DataT]):
    data: DataT # or Optional[DataT] = None

with open('cricket.txt', 'r', encoding='utf-8') as file:
    cricket_text = file.read()

cricket: GenericDetail = openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    response_model=GenericDetail,
    messages=[
        {"role": "system", "content": "Extract the winners:"},
        {"role": "user", "content": cricket_text},
    ]
)

print(cricket)

Output

data={'1975': {'Winner': 'West Indies', 'Runner-up': 'Australia'}, '1979': {'Winner': 'West Indies', 'Runner-up': 'England'}, '1983': {'Winner': 'India', 'Runner-up': 'West Indies'}, '1987': {'Winner': 'Australia', 'Runner-up': 'England'}, '1992': {'Winner': 'Pakistan', 'Runner-up': 'England'}, '1996': {'Winner': 'Sri Lanka', 'Runner-up': 'Australia'}, '1999': {'Winner': 'Australia', 'Runner-up': 'Pakistan'}, '2003': {'Winner': 'Australia', 'Runner-up': 'India'}, '2007': {'Winner': 'Australia', 'Runner-up': 'Sri Lanka'}, '2011': {'Winner': 'India', 'Runner-up': 'Sri Lanka'}, '2015': {'Winner': 'Australia', 'Runner-up': 'New Zealand'}, '2019': {'Winner': 'England', 'Runner-up': 'New Zealand'}}

cricket.txt

Year	Winner	Winner's score	Winning
margin	Runner-up	R/Up's score	Final venue	Host nation(s)[2]	Crowd
1975	 West Indies	291/8 (60 overs)	17 runs[11]	 Australia	274 all out (58.4 overs)	Lord's, London	England	24,000
1979	 West Indies	286/9 (60 overs)	92 runs[16]	 England	194 all out (51 overs)	Lord's, London	England	32,000
1983	 India	183 all out (55th over)	43 runs[20]	 West Indies	140 all out (52 overs)	Lord's, London	England	30,000
1987	 Australia	253/5 (50 overs)	7 runs[21]	 England	246/8 (50 overs)	Eden Gardens, Kolkata	India, Pakistan	95,000
1992	 Pakistan	249/6 (50 overs)	22 runs[23]	 England	227 all out (49.2 overs)	MCG, Melbourne †	Australia, New Zealand	87,182
1996	 Sri Lanka	245/3 (46.2 overs)	7 wickets[25]	 Australia	241/7 (50 overs)	Gaddafi Stadium, Lahore †	Pakistan, India, Sri Lanka	62,645
1999	 Australia	133/2 (20.1 overs)	8 wickets[28]	 Pakistan	132 all out (39 overs)	Lord's, London	England	30,000
2003	 Australia	359/2 (50 overs)	125 runs[30]	 India	234 all out (39.2 overs)	Wanderers, Johannesburg	South Africa	32,827
2007	 Australia	281/4 (38 overs)	53 runs ‡[32]	 Sri Lanka	215/8 (36 overs)	Kensington Oval, Barbados	West Indies	28,108
2011	 India	277/4 (48.2 overs)	6 wickets[35]	 Sri Lanka	274/6 (50 overs)	Wankhede Stadium, Mumbai †	India, Sri Lanka, Bangladesh	42,000
2015	 Australia	186/3 (33.1 overs)	7 wickets[36]	 New Zealand	183 all out (45 overs)	MCG, Melbourne †	Australia, New Zealand	93,013
2019	 England	241 all out (50 overs)	Tiebreak: 9 boundaries	 New Zealand	241/8 (50 overs)	Lord's, London	England, Wales	30,000

Categories