Python 调用 Claude API 报错 429 怎么解决?
Python 调用 Claude API 报错 429 怎么解决?
最近在做一个 AI 项目,需要接入 Claude API,结果一直报错 429,折腾了半天终于搞定了,记录一下。
前置条件
- Claude API Key
- Python 环境
报错现象
报错信息为 429 Too Many Requests
原因分析
原因是 API 请求频率过高,超过了 Claude 的限制。
解决方案
可以通过加延迟或者使用代理来解决。
python
import time
import requests
Claude API 地址
url = "https://api.claude.ai/v1/generate"
API Key
api_key = "你的 API Key"
请求头
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
请求数据
data = {
"prompt": "你的提示",
"max_tokens": 1024
}
while True:
try:
response = requests.post(url, headers=headers, json=data)
response.raise_for_status()
break
except requests.exceptions.HTTPError as e:
if e.response.status_code == 429:
time.sleep(1) # 加延迟
continue
else:
raise
总结
通过加延迟可以解决 Claude API 报错 429的问题,希望可以帮助到你。
浙公网安备 33010602011771号