Aan de slagGa gratis aan de slag

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.

Deze oefening maakt deel uit van de cursus

Developing AI Systems with the OpenAI API

Cursus bekijken

Oefeninstructies

  • 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.

Praktische interactieve oefening

Probeer deze oefening eens door deze voorbeeldcode in te vullen.

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.")
Code bewerken en uitvoeren