pythonopenai-apigpt-3chatgpt-apigpt-4

OpenAI API: How do I handle errors in Python?


I tried using the below code, but the OpenAI API doesn't have the AuthenticationError method in the library. How can I effectively handle such error.

import openai

# Set up your OpenAI credentials
openai.api_key = 'YOUR_API_KEY'

try:
    # Perform OpenAI API request
    response = openai.some_function()  # Replace with the appropriate OpenAI API function

    # Process the response
    # ...
except openai.AuthenticationError:
    # Handle the AuthenticationError
    print("Authentication error: Invalid API key or insufficient permissions.")
    # Perform any necessary actions, such as displaying an error message or exiting the program


Solution

  • Error handling with the OpenAI Python SDK v1.0.0 or newer

    • If you don't want to handle error types individually:

    import os
    from openai import OpenAI, OpenAIError
    client = OpenAI()
    OpenAI.api_key = os.getenv('OPENAI_API_KEY')
    
    try:
      # Make your OpenAI API request here
      response = client.completions.create(
        model="gpt-3.5-turbo-instruct",
        prompt="Say this is a test"
      )
      print(response)
    except OpenAIError as e:
      # Handle all OpenAI API errors
      print(f"Error: {e}")
    

    • If you want to handle error types individually:

    Note: Because there are a lot of classes for error handling, it might not be so elegant to import them individually. Instead, use import openai and all classes for error handling will be imported automatically. But the code is a bit different now.

    import os
    import openai # Import openai
    from openai import OpenAI # But don't import OpenAIError
    client = OpenAI()
    OpenAI.api_key = os.getenv('OPENAI_API_KEY')
    
    try:
      # Make your OpenAI API request here
      response = client.completions.create(
        model="gpt-3.5-turbo-instruct",
        prompt="Say this is a test"
      )
      print(response)
    except openai.BadRequestError as e: # Don't forget to add openai
      # Handle error 400
      print(f"Error 400: {e}")
    except openai.AuthenticationError as e: # Don't forget to add openai
      # Handle error 401
      print(f"Error 401: {e}")
    except openai.PermissionDeniedError as e: # Don't forget to add openai
      # Handle error 403
      print(f"Error 403: {e}")
    except openai.NotFoundError as e: # Don't forget to add openai
      # Handle error 404
      print(f"Error 404: {e}")
    except openai.UnprocessableEntityError as e: # Don't forget to add openai
      # Handle error 422
      print(f"Error 422: {e}")
    except openai.RateLimitError as e: # Don't forget to add openai
      # Handle error 429
      print(f"Error 429: {e}")
    except openai.InternalServerError as e: # Don't forget to add openai
      # Handle error >=500
      print(f"Error >=500: {e}")
    except openai.APIConnectionError as e: # Don't forget to add openai
      # Handle API connection error
      print(f"API connection error: {e}")
    

    See the official OpenAI GitHub Python repository.


    Error handling with the OpenAI Python SDK v0.28.0

    Your code isn't correct.

    Change this...

    except openai.AuthenticationError
    

    ...to this.

    except openai.error.AuthenticationError