Build Robust LLM Applications: API Error Handling and Retries in Production
Implement robust error handling and retry mechanisms to improve the reliability of LLM API calls in your production applications.
LLM APIs are external services. Like any external service, they are not 100% reliable. Network issues, rate limits, or transient server problems can cause your API calls to fail. In production, these failures lead to broken user experiences or stalled automation. You need a robust strategy to handle these errors and ensure your LLM-powered applications remain stable.
Common LLM API Failure Modes
Before you build a retry mechanism, understand what can go wrong. Not all errors are retryable.
- Rate Limits (HTTP 429 Too Many Requests): You sent too many requests in a given timeframe. The API provider temporarily blocks further calls.
- Network Issues (ConnectionError, Timeout): Your application cannot connect to the API, or the connection drops. The API might be fine, but the path to it is not. Timeouts occur when the API takes too long to respond.
- Server Errors (HTTP 5xx): The API provider's servers are experiencing issues. This could be a temporary overload or a bug on their side.
- Invalid Requests (HTTP 4xx, e.g., 400 Bad Request, 401 Unauthorized, 404 Not Found): Your request payload is malformed, your API key is invalid, or you are trying to access a non-existent endpoint. These are usually permanent errors caused by your code or configuration.
- Model-Specific Errors: Sometimes the model itself might be overloaded or encounter an internal issue, returning an error even if the request was valid.
Distinguish between transient errors (like rate limits, network issues, and most 5xx errors) and permanent errors (like invalid requests). You only retry transient errors.
Basic Error Handling
Start with fundamental error handling. Wrap your API calls in try...except blocks. Catch specific exceptions. Log errors comprehensively.
This example uses requests, a common HTTP library in Python. The hypothetical-llm.com URL is a placeholder for any LLM API endpoint.
import requests
import logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def call_llm_api(prompt: str, api_key: str) -> dict:
"""Makes a single call to a hypothetical LLM API."""
headers = {"Authorization": f"Bearer {api_key}"}
payload = {"prompt": prompt, "max_tokens": 100, "temperature": 0.7}
api_url = "https://api.hypothetical-llm.com/generate"
try:
response = requests.post(api_url, json=payload, headers=headers, timeout=15)
response.raise_for_status() # Raises HTTPError for bad responses (4xx or 5xx)
return response.json()
except requests.exceptions.HTTPError as e:
logging.error(f"HTTP error calling LLM (Status: {e.response.status_code}): {e.response.text}")
raise # Re-raise to be caught by a higher-level handler or retry logic
except requests.exceptions.ConnectionError as e:
logging.error(f"Connection error calling LLM: {e}")
raise
except requests.exceptions.Timeout as e:
logging.error(f"Timeout error calling LLM after 15s: {e}")
raise
except requests.exceptions.RequestException as e:
logging.error(f"An unexpected request error occurred: {e}")
raise
except Exception as e:
logging.error(f"An unexpected error occurred during API call: {e}")
raise
This function handles common requests exceptions. It re-raises them so a calling function can decide whether to retry or fail. Logging is crucial. It tells you what failed, when, and why.
Implementing Retry Mechanisms
Now, build on the basic error handling with a retry loop. You need to decide how many times to retry and how long to wait between attempts.
import time
import random
def call_llm_api_with_retry(prompt: str, api_key: str, max_retries: int = 5) -> dict:
"""Calls the LLM API with a retry mechanism for transient errors."""
retries = 0
while retries < max_retries:
try:
# Attempt the API call using the base function
response_data = call_llm_api(prompt, api_key)
return response_data # Success!
except requests.exceptions.HTTPError as e:
# Retry for rate limits (429) and server errors (5xx)
if e.response.status_code in [429, 500, 502, 503, 504]:
logging.warning(f"Retryable HTTP error: {e.response.status_code}. Attempt {retries + 1}/{max_retries}.")
retries += 1
# Implement exponential backoff with jitter
sleep_time = (2 ** retries) + random.uniform(0, 1)
time.sleep(sleep_time)
else:
# Non-retryable HTTP error (e.g., 400 Bad Request)
logging.error(f"Non-retryable HTTP error: {e.response.status_code}. Failing.")
raise
except (requests.exceptions.ConnectionError, requests.exceptions.Timeout) as e:
# Retry for network issues and timeouts
logging.warning(f"Retryable connection/timeout error: {e}. Attempt {retries + 1}/{max_retries}.")
retries += 1
sleep_time = (2 ** retries) + random.uniform(0, 1)
time.sleep(sleep_time)
except Exception as e:
# Catch any other unexpected errors and re-raise immediately
logging.error(f"Unexpected non-retryable error during API call: {e}. Failing.")
raise
logging.error(f"Max retries ({max_retries}) exceeded for LLM call after multiple attempts.")
raise Exception("Failed to get LLM response after multiple retries.")
## Example usage:
## try:
## llm_result = call_llm_api_with_retry("Generate a short creative story about a robot.", "your_api_key")
## print("LLM Response:", llm_result)
## except Exception as e:
## print(f"Application failed to get LLM response: {e}")
This call_llm_api_with_retry function wraps the basic call_llm_api. It checks for specific status codes and exception types. If it encounters a transient error, it waits and tries again, up to max_retries times. If all retries fail, it raises a final exception.
Exponential Backoff and Jitter
The time.sleep() call in the retry loop is critical. Do not just retry immediately. That can overwhelm the API and worsen the problem. Implement exponential backoff.
Exponential backoff means increasing the wait time between successive retries. For example, wait 1 second, then 2 seconds, then 4 seconds, then 8 seconds. This gives the API time to recover.
Add jitter to this delay. Jitter is a small random amount of time added to the backoff delay. If many clients retry at the exact same exponential intervals, they can still create a