Aller au contenu principal

Error Handling and Retries

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")

Use Built-In Retries

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,
)

Common Error Codes

Error TypeStatus CodeCauseFix
AuthenticationError401Invalid API KeyCheck the Key
PermissionDeniedError403Insufficient permissionCheck account permissions
NotFoundError404Resource does not existCheck the model name
RateLimitError429Rate limit exceededRetry with exponential backoff
APIStatusError500Server-side errorRetry later
OverloadedError529Service overloadedRetry later