Handling exceptions
You are working at a logistics company on developing an application that uses the OpenAI API to check the shipping address of your top three customers. The application will be used internally and you want to make sure that other teams are presented with an easy to read message in case of error.
To address this requirement, you decide to print a custom message in case the users fail to provide a valid key for authentication, and use a try
and except
block to handle that.
The message
variable has already been imported.
This exercise is part of the course
Developing AI Systems with the OpenAI API
Exercise instructions
- Use the
try
statement to attempt making a request to the API. - Print the response if the request succeeds.
- Use the
except
statement to handle the authentication error that may occur.
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
client = OpenAI(api_key="")
# Use the try statement
____:
response = ____(
model="gpt-4o-mini",
messages=[message]
)
# Print the response
print(response.____)
# Use the except statement
____:
print("Please double check your authentication key and try again, the one provided is not valid.")