There is unseen code, obviously.
Let me show you how to make a request and receive the data.
Prepare - create a client instance:
from openai import Client
client = Client()
Throw in some code for printing arbitrary Python nested objects
def print_nested_dict(d: dict, indent: int = 0) -> None:
"""Recursively prints dictionary keys and values, handling nested dictionaries and lists."""
for key, value in d.items():
prefix = ' ' * indent
if value is None:
continue # Skip None values
if isinstance(value, dict):
print(f"{prefix}{key}:")
print_nested_dict(value, indent + 2)
elif isinstance(value, list):
print(f"{prefix}{key}:")
print_list(value, indent + 2)
else:
print(f"{prefix}{key}: {value}")
def print_list(lst: list, indent: int) -> None:
"""Recursively prints items in a list, handling nested dictionaries and lists."""
for i, item in enumerate(lst):
prefix = ' ' * indent
if item is None:
continue # Skip None values
if isinstance(item, dict):
print(f"{prefix}{i}:")
print_nested_dict(item, indent + 2)
elif isinstance(item, list):
print(f"{prefix}{i}:")
print_list(item, indent + 2)
else:
print(f"{prefix}{i}: {item}")
Create your BaseModel class
from pydantic import BaseModel
model = 'gpt-4o-2024-08-06'
class CalendarEvent(BaseModel):
name: str
date: str
participants: list[str] # lower-case: built in typing of Python 3.9+
Make your API request
completion = client.beta.chat.completions.parse(
model=model,
messages=[
{"role": "system", "content": "Extract the event information."},
{"role": "user", "content":
"Alice and Bob are going to a science fair on Friday."
},
],
response_format=CalendarEvent
)
Now, what do you do with that? The response from the openai python library is NOT a json, it is a pydantic model of objects and models itself.
You can dump out the response like this:
print("response dump: ", completion.model_dump() )
And see your full response Python objects from JSON:
response dump: {'id': 'chatcmpl-APi..', 'choices': [{'finish_reason': 'stop', 'index': 0, 'logprobs': None, 'message': {'content': '{"name":"Science Fair","date":"Friday","participants":["Alice","Bob"]}', 'refusal': None, 'role': 'assistant', 'audio': None, 'function_call': None, 'tool_calls': [], 'parsed': {'name': 'Science Fair', 'date': 'Friday', 'participants': ['Alice', 'Bob']}}}], 'created': 1730691646, 'model': 'gpt-4o-2024-08-06', 'object': 'chat.completion', 'service_tier': None, 'system_fingerprint': 'fp_159d8341cc', 'usage': {'completion_tokens': 17, 'prompt_tokens': 92, 'total_tokens': 109, 'completion_tokens_details': {'audio_tokens': None, 'reasoning_tokens': 0}, 'prompt_tokens_details': {'audio_tokens': None, 'cached_tokens': 0}}}
Or if only the assistant message is important to you, get that out:
completion_message_dict = completion.choices[0].message.parsed.model_dump()
And see what you have to work with then, again, not JSON string but Python:
>>>print( completion_message_dict )
{'name': 'Science Fair', 'date': 'Friday', 'participants': ['Alice', 'Bob']}
That function you didn’t ask for? Let’s have it print
>>>print_nested_dict(completion_message_dict)
name: Science Fair
date: Friday
participants:
0: Alice
1: Bob
So I’ve demonstrated making the call without error and making its response useful.
Code solution:
import json # if you still need it
from typing import List # for other types, like Optional, for Pydantic)
from openai import Client
client = Client()
def print_nested_dict(d: dict, indent: int = 0) -> None:
"""Recursively prints dictionary keys and values, handling nested dictionaries and lists."""
for key, value in d.items():
prefix = ' ' * indent
if value is None:
continue # Skip None values
if isinstance(value, dict):
print(f"{prefix}{key}:")
print_nested_dict(value, indent + 2)
elif isinstance(value, list):
print(f"{prefix}{key}:")
print_list(value, indent + 2)
else:
print(f"{prefix}{key}: {value}")
def print_list(lst: list, indent: int) -> None:
"""Recursively prints items in a list, handling nested dictionaries and lists."""
for i, item in enumerate(lst):
prefix = ' ' * indent
if item is None:
continue # Skip None values
if isinstance(item, dict):
print(f"{prefix}{i}:")
print_nested_dict(item, indent + 2)
elif isinstance(item, list):
print(f"{prefix}{i}:")
print_list(item, indent + 2)
else:
print(f"{prefix}{i}: {item}")
from pydantic import BaseModel
model = 'gpt-4o-2024-08-06'
class CalendarEvent(BaseModel):
name: str
date: str
participants: list[str] # lower-case: built in typing of Python 3.9+
completion = client.beta.chat.completions.parse(
model=model,
messages=[
{"role": "system", "content": "Extract the event information."},
{"role": "user", "content":
"Alice and Bob are going to a science fair on Friday."
},
],
response_format=CalendarEvent
)
print("response dump: ", completion.model_dump(), "\n----\n" )
completion_message_dict = completion.choices[0].message.parsed.model_dump()
print("response: ", completion_message_dict, "\n----\n" )
print_nested_dict(completion_message_dict)