Error Handling
- Python
- JavaScript
- curl
import time
from openai import OpenAI, RateLimitError, APITimeoutError, APIConnectionError
client = OpenAI(api_key="your-api-key", base_url="https://aisupermarket.work/v1")
def generate_with_retry(prompt, max_retries=3):
for attempt in range(max_retries):
try:
return client.chat.completions.create(
model="gemini-2.5-flash",
messages=[{"role": "user", "content": prompt}],
).choices[0].message.content
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 generateWithRetry(prompt, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.chat.completions.create({
model: "gemini-2.5-flash",
messages: [{ role: "user", content: prompt }],
});
return response.choices[0].message.content;
} 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");
}
for attempt in 1 2 3; do
HTTP_STATUS=$(curl -s -o /tmp/response.json -w "%{http_code}" \
https://aisupermarket.work/v1/chat/completions \
-H "Authorization: Bearer your-api-key" \
-H "Content-Type: application/json" \
-d '{"model": "gemini-2.5-flash", "messages": [{"role": "user", "content": "Hello"}]}')
if [ "$HTTP_STATUS" = "200" ]; then
cat /tmp/response.json; break
elif [ "$HTTP_STATUS" = "429" ]; then
echo "Rate limited, waiting before retry..."
sleep $((2 ** attempt))
else
echo "Request failed: $HTTP_STATUS"; break
fi
done
Common Error Codes
| Status Code | Cause | Fix |
|---|---|---|
| 401 | Invalid API Key | Check the Key |
| 429 | Rate limit exceeded | Retry with exponential backoff |
| 500 | Server-side error | Retry later |
| 503 | Model does not exist or is unavailable | Check the model name |