处理 API 错误
本课属于 Coddy AI Engineering 学习旅程的“在代码中调用模型”单元。第 12 课,共 22 课。
请求可能会失败,发生失败时 SDK 会抛出异常。每种 HTTP 错误都有自己的类:BadRequestError(400,请求本身有误)、AuthenticationError(401,密钥无效)、NotFoundError(404,例如不存在的模型 ID)、RateLimitError(429,请求过多)以及 InternalServerError(500)。它们都是 APIStatusError 的子类,包含了 status_code 和服务器的 body。
try:
response = client.messages.create(
model="claude-opus-5",
max_tokens=999999,
messages=[{"role": "user", "content": "Hi"}],
)
except anthropic.BadRequestError as e:
print(e.status_code)
print(e.body["error"]["message"])
except anthropic.APIStatusError as e:
print("Other API error:", e.status_code)这会打印 400 和消息,说明该模型的限制是 128000。请将具体的类放在前面:Python 会运行第一个匹配的 except,而 APIStatusError 会匹配它们全部。
SDK 会在抛出异常前自动重试两次 429 或 5xx 错误(可以在客户端上设置 max_retries 来更改此设置)。400 或 404 错误绝不会重试,因为再次发送相同的请求依然会以相同的方式失败。
挑战
中等编写一个程序,在请求失败时报告错误而不是崩溃。起始代码会读取一个模型 ID、一个 max_tokens 数值和一个问题。
- 使用该
model和max_tokens发送问题。成功时,打印Answer:和回复文本。 - 在发生
anthropic.NotFoundError时,打印Unknown model: <model>。 - 在发生
anthropic.BadRequestError时,打印Bad request (<status code>): <message>,其中 message 为e.body["error"]["message"]。 - 在发生任何其他
anthropic.APIStatusError时,打印API error <status code>。
例如,对于输入 claude-opus-5-5、200000 和 Hi,程序输出:
Bad request (400): max_tokens: 200000 > 128000, which is the maximum allowed number of output tokens for claude-opus-5-5亲手试试
import coddy_ai as anthropic # 在生产环境中:import anthropic
client = anthropic.Anthropic()
model = input()
max_tokens = int(input())
question = input()
# 使用此 model 和 max_tokens 发送问题。
# 成功时打印 "Answer: <text>",并按任务要求捕获错误。
这节课包含一个小测验。开始学习即可作答,并记录你的进度。
在代码中调用模型中的所有课
自己练习: Python 在线编译器