Error Handling and Retries
Use Built-In Retries
- Python
- JavaScript
from openai import OpenAI
client = OpenAI(
api_key="your-api-key",
base_url="https://aisupermarket.work/v1",
max_retries=3,
timeout=60.0,
)
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-api-key",
baseURL: "https://aisupermarket.work/v1",
maxRetries: 3,
timeout: 60000,
});
Handle Errors Manually
- Python
- JavaScript
import time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError
client = OpenAI(api_key="your-api-key", base_url="https://aisupermarket.work/v1")
def chat_stream(messages, max_retries=3):
for attempt in range(max_retries):
try:
stream = client.chat.completions.create(
model="gpt-5.4",
messages=messages,
stream=True,
)
result = ""
for chunk in stream:
if chunk.choices[0].delta.content:
result += chunk.choices[0].delta.content
return result
except RateLimitError:
wait = 2 ** attempt
print(f"Rate limited, retrying in {wait} seconds...")
time.sleep(wait)
except APITimeoutError:
print("Request timed out, retrying...")
except APIConnectionError as e:
print(f"Connection error: {e}")
break
raise Exception("Request failed after the maximum number of retries")
import OpenAI from "openai";
const client = new OpenAI({
apiKey: "your-api-key",
baseURL: "https://aisupermarket.work/v1",
});
async function chatStream(messages, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const stream = await client.chat.completions.create({
model: "gpt-5.4",
messages,
stream: true,
});
let result = "";
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content;
if (content) result += content;
}
return result;
} catch (err) {
if (err instanceof OpenAI.RateLimitError) {
const wait = 2 ** attempt;
console.log(`Rate limited, retrying in ${wait} seconds...`);
await new Promise((r) => setTimeout(r, wait * 1000));
} else if (err instanceof OpenAI.APIConnectionError) {
console.error(`Connection error: ${err.message}`);
break;
} else {
console.log("Request timed out, retrying...");
}
}
}
throw new Error("Request failed after the maximum number of retries");
}
Common Error Codes
| Error Type | Status Code | Cause | Fix |
|---|---|---|---|
AuthenticationError | 401 | Invalid API Key | Check the Key |
PermissionDeniedError | 403 | No access permission | Check the account |
NotFoundError | 404 | Model does not exist | Check the model name |
RateLimitError | 429 | Rate or quota exceeded | Retry with exponential backoff |
InternalServerError | 500 | Server-side error | Retry later |