You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# prompt: make notebook to print all outputs, not just the last onefromIPython.core.interactiveshellimportInteractiveShellInteractiveShell.ast_node_interactivity="all"
# For OpenAIfromgoogle.colabimportuserdataOPENAI_API_KEY=userdata.get('OPENAI_API_KEY')
importinstructorfromopenaiimportOpenAIfrompydanticimportBaseModel# Create an instructor-patched clientclient=instructor.from_openai(OpenAI(api_key=OPENAI_API_KEY#, base_url=
))
The key is here
fromtypingimportTypeVar, Generic, ListfrompydanticimportRootModel, TypeAdapter, BaseModelclassPet(BaseModel):
name: strage: int# ===== The key is here ==========T=TypeVar("T")
classListOfX(RootModel[List[T]], Generic[T]):
def__iter__(self):
returniter(self.root)
def__getitem__(self, item):
returnself.root[item]
pets= [Pet(name="Dog", age=2), Pet(name="Cat", age=3)]
pets=TypeAdapter(ListOfX[Pet]).validate_python(pets)
forpinpets:
print(p)
p.model_dump()
# Because it is a class, you can add extra properties/attributes/etcpets._hidden=Truepets._hidden
name='Dog' age=2
name='Cat' age=3
True
prompt="Give me the name and age of 5 pokemons"# This fails with `KeyError: 'properties'`# pets=client.chat.completions.create(# model="gpt-4o-mini",# response_model=ListOfX[Pet],# messages=[# {"role": "user", "content": prompt}# ],# )# But this does not failpets=client.chat.completions.create(
model="gpt-4o-mini",
response_model=List[Pet],
messages=[
{"role": "user", "content": prompt}
],
)
petsforpetinpets:
#print(pet.name, pet.age)print(pet)
# check if it has .model_dump()ifhasattr(pet, "model_dump"):
pet.model_dump()
The output of this IS an object but it looks just like List[Pets]
OR I am missing something.
pets_list_class=TypeAdapter(ListOfX[Pet]).validate_python(pets)
pets_list_classifhasattr(pets_list_class, "model_dump"):
pets_list_class.model_dump()
forpetinpets_list_class:
print(pet)
# check if it has .model_dump()ifhasattr(pet, "model_dump"):
pet.model_dump()
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Forgive me it this has been resolved, and/or I didn't understand it properly.
A few days ago many open issues were closed just because there were pre-2025 and it sparked some research.
In particular,
#1146 (comment)
#1103
Disclaimer: I may not know what I am talking about.
Here is what I tested, and it works well, so far.
The key is here
The output of this IS an object but it looks just like
List[Pets]
Beta Was this translation helpful? Give feedback.
All reactions