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.
Latihan ini adalah bagian dari kursus
Developing AI Systems with the OpenAI API
Petunjuk latihan
- Use the
trystatement to attempt making a request to the API. - Print the response if the request succeeds.
- Use the
exceptstatement to handle the authentication error that may occur.
Latihan interaktif praktis
Cobalah latihan ini dengan menyelesaikan kode contoh berikut.
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.")