跳到主要内容

错误处理与重试

import time
import anthropic

client = anthropic.Anthropic(api_key="your-api-key", base_url="https://www.cheapertoken.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"触发限速,{wait}秒后重试...")
time.sleep(wait)
except anthropic.APITimeoutError:
print("请求超时,重试中...")
except anthropic.APIConnectionError as e:
print(f"连接错误: {e}")
break
except anthropic.BadRequestError as e:
raise # 参数错误不重试
raise Exception("请求失败,已达最大重试次数")

使用内置重试

import anthropic

# SDK 内置自动重试
client = anthropic.Anthropic(
api_key="your-api-key",
base_url="https://www.cheapertoken.work",
max_retries=3, # 默认为 2
timeout=60.0,
)

常见错误码

错误类型状态码原因处理方式
AuthenticationError401API Key 无效检查 Key
PermissionDeniedError403权限不足检查账户权限
NotFoundError404资源不存在检查模型名称
RateLimitError429频率超限指数退避重试
APIStatusError500服务端错误稍后重试
OverloadedError529服务过载稍后重试