Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Error Handling with OpenAI API

Introduction

Error handling is an essential aspect of working with APIs to ensure robustness and reliability. This tutorial covers best practices for error handling when using the OpenAI API, with examples in JavaScript and Python.

Common API Errors

Understanding common errors that can occur when interacting with the OpenAI API is the first step in effective error handling. Here are some typical errors:

  • 400 Bad Request: The request was invalid or cannot be served.
  • 401 Unauthorized: The request requires user authentication.
  • 403 Forbidden: The server understood the request, but refuses to authorize it.
  • 429 Too Many Requests: You have exceeded your rate limit.
  • 500 Internal Server Error: An error occurred on the server.

API Request Example

Let's start with a general view of an API request and how errors might be handled in both JavaScript and Python.

POST /v1/completions HTTP/1.1
Host: api.openai.com
Content-Type: application/json
Authorization: Bearer YOUR_API_KEY

{
    "model": "text-davinci-002",
    "prompt": "Translate the following English text to French: 'Hello, how are you?'",
    "max_tokens": 60
}
                    

Error Handling in JavaScript

Here's how you can handle errors in JavaScript using the Axios library.

// Example in JavaScript

const axios = require('axios');

const API_KEY = 'YOUR_API_KEY';

const requestData = {
    prompt: "Translate the following English text to French: 'Hello, how are you?'",
    max_tokens: 60
};

axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', requestData, {
    headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${API_KEY}`
    }
})
.then(response => {
    console.log('API Response:', response.data);
})
.catch(error => {
    if (error.response) {
        console.error('Error Status:', error.response.status);
        console.error('Error Data:', error.response.data);
    } else {
        console.error('Error Message:', error.message);
    }
});
                    

Error Handling in Python

Here's how you can handle errors in Python using the Requests library.

# Example in Python

import os
import requests

API_KEY = os.getenv('OPENAI_API_KEY')

request_data = {
    'prompt': "Translate the following English text to French: 'Hello, how are you?'",
    'max_tokens': 60
}

try:
    response = requests.post('https://api.openai.com/v1/engines/davinci-codex/completions',
                             json=request_data,
                             headers={'Content-Type': 'application/json',
                                      'Authorization': f'Bearer {API_KEY}'})
    response.raise_for_status()
    print('API Response:', response.json())
except requests.exceptions.HTTPError as errh:
    print('Http Error:', errh)
except requests.exceptions.ConnectionError as errc:
    print('Error Connecting:', errc)
except requests.exceptions.Timeout as errt:
    print('Timeout Error:', errt)
except requests.exceptions.RequestException as err:
    print('Error:', err)
                    

Retry Mechanism

Implementing a retry mechanism can help handle transient errors, such as network issues or rate limiting. Here are examples of how to implement a retry mechanism in JavaScript and Python.

// Retry Mechanism in JavaScript

const axios = require('axios');
const API_KEY = 'YOUR_API_KEY';
const MAX_RETRIES = 3;

const fetchData = async (retryCount = 0) => {
    try {
        const response = await axios.post('https://api.openai.com/v1/engines/davinci-codex/completions', 
        { 
            prompt: "Translate the following English text to French: 'Hello, how are you?'", 
            max_tokens: 60 
        },
        {
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer ${API_KEY}`
            }
        });
        console.log('API Response:', response.data);
    } catch (error) {
        if (retryCount < MAX_RETRIES) {
            console.log(`Retrying... (${retryCount + 1})`);
            fetchData(retryCount + 1);
        } else {
            console.error('Max retries reached. Error:', error);
        }
    }
};

fetchData();
                    
# Retry Mechanism in Python

import os
import requests
import time

API_KEY = os.getenv('OPENAI_API_KEY')
MAX_RETRIES = 3

def fetch_data(retry_count=0):
    try:
        response = requests.post('https://api.openai.com/v1/engines/davinci-codex/completions',
                                 json={'prompt': "Translate the following English text to French: 'Hello, how are you?'", 'max_tokens': 60},
                                 headers={'Content-Type': 'application/json', 'Authorization': f'Bearer {API_KEY}'})
        response.raise_for_status()
        print('API Response:', response.json())
    except requests.exceptions.RequestException as err:
        if retry_count < MAX_RETRIES:
            print(f'Retrying... ({retry_count + 1})')
            time.sleep(2 ** retry_count)
            fetch_data(retry_count + 1)
        else:
            print('Max retries reached. Error:', err)

fetch_data()