错误处理与重试
- Python
- JavaScript
- curl
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 from "@anthropic-ai/sdk";
const client = new Anthropic({ apiKey: "your-api-key", baseURL: "https://www.cheapertoken.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(`触发限速,${wait}秒后重试...`);
await new Promise(r => setTimeout(r, wait * 1000));
} else if (err instanceof Anthropic.APIConnectionTimeoutError) {
console.log("请求超时,重试中...");
} else if (err instanceof Anthropic.BadRequestError) {
throw err; // 参数错误不重试
} else {
break;
}
}
}
throw new Error("请求失败,已达最大重试次数");
}
# 带重试的 curl 脚本
for attempt in 1 2 3; do
response=$(curl -s -w "\n%{http_code}" https://www.cheapertoken.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": "你好"}]}')
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 "触发限速,等待后重试..."
sleep $((2 ** attempt))
else
echo "请求失败: $http_code"
break
fi
done
使用内置重试
- Python
- JavaScript
- curl
import anthropic
# SDK 内置自动重试
client = anthropic.Anthropic(
api_key="your-api-key",
base_url="https://www.cheapertoken.work",
max_retries=3, # 默认为 2
timeout=60.0,
)
import Anthropic from "@anthropic-ai/sdk";
// SDK 内置自动重试
const client = new Anthropic({
apiKey: "your-api-key",
maxRetries: 3, // 默认为 2
timeout: 60000,
});
# curl 使用 --retry 内置重试
curl --retry 3 --retry-delay 2 \
https://www.cheapertoken.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": "你好"}]}'
常见错误码
| 错误类型 | 状态码 | 原因 | 处理方式 |
|---|---|---|---|
AuthenticationError | 401 | API Key 无效 | 检查 Key |
PermissionDeniedError | 403 | 权限不足 | 检查账户权限 |
NotFoundError | 404 | 资源不存在 | 检查模型名称 |
RateLimitError | 429 | 频率超限 | 指数退避重试 |
APIStatusError | 500 | 服务端错误 | 稍后重试 |
OverloadedError | 529 | 服务过载 | 稍后重试 |