Error Handling and Retries
- Python
- JavaScript
- curl
import time
import anthropic
client = anthropic.Anthropic(api_key="your-api-key", base_url="https://aisupermarket.work")
def chat_with_retry(messages, max_retries=3):
for attempt in range(max_retries):
try:
response = client.messages.create(
model="claude-opus-4-7",
max_tokens=1024,
messages=messages,
)
return response.content[0].text
except anthropic.RateLimitError:
wait = 2 ** attempt
print(f"Rate limited, retrying in {wait} seconds...")
time.sleep(wait)
except anthropic.APITimeoutError:
print("Request timed out, retrying...")
except anthropic.APIConnectionError as e:
print(f"Connection error: {e}")
break
except anthropic.BadRequestError as e:
raise # Do not retry parameter errors
raise Exception("Request failed after the maximum number of retries")
import Anthropic from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: "your-api-key", baseURL: "https://aisupermarket.work" });
async function chatWithRetry(messages, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
try {
const response = await client.messages.create({
model: "claude-opus-4-7",
max_tokens: 1024,
messages,
});
return response.content[0].text;
} catch (err) {
if (err instanceof Anthropic.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 Anthropic.APIConnectionTimeoutError) {
console.log("Request timed out, retrying...");
} else if (err instanceof Anthropic.BadRequestError) {
throw err; // Do not retry parameter errors
} else {
break;
}
}
}
throw new Error("Request failed after the maximum number of retries");
}
# curl script with retries
for attempt in 1 2 3; do
response=$(curl -s -w "\n%{http_code}" https://aisupermarket.work/v1/messages \
-H "x-api-key: your-api-key" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-opus-4-7", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}]}')
http_code=$(echo "$response" | tail -1)
body=$(echo "$response" | head -1)
if [ "$http_code" = "200" ]; then
echo "$body"
break
elif [ "$http_code" = "429" ]; then
echo "Rate limited, waiting before retry..."
sleep $((2 ** attempt))
else
echo "Request failed: $http_code"
break
fi
done
Use Built-In Retries
- Python
- JavaScript
- curl
import anthropic
# SDK built-in automatic retries
client = anthropic.Anthropic(
api_key="your-api-key",
base_url="https://aisupermarket.work",
max_retries=3, # default is 2
timeout=60.0,
)
import Anthropic from "@anthropic-ai/sdk";
// SDK built-in automatic retries
const client = new Anthropic({
apiKey: "your-api-key",
maxRetries: 3, // default is 2
timeout: 60000,
});
# curl uses --retry for built-in retries
curl --retry 3 --retry-delay 2 \
https://aisupermarket.work/v1/messages \
-H "x-api-key: your-api-key" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d '{"model": "claude-opus-4-7", "max_tokens": 1024, "messages": [{"role": "user", "content": "Hello"}]}'
Common Error Codes
| Error Type | Status Code | Cause | Fix |
|---|---|---|---|
AuthenticationError | 401 | Invalid API Key | Check the Key |
PermissionDeniedError | 403 | Insufficient permission | Check account permissions |
NotFoundError | 404 | Resource does not exist | Check the model name |
RateLimitError | 429 | Rate limit exceeded | Retry with exponential backoff |
APIStatusError | 500 | Server-side error | Retry later |
OverloadedError | 529 | Service overloaded | Retry later |