Documentation Index
Fetch the complete documentation index at: https://apidoc.cometapi.com/llms.txt
Use this file to discover all available pages before exploring further.
通过判断请求应该被修复还是重试来处理 CometAPI 错误。对 429、超时类故障以及临时服务器故障进行带退避的重试;不要重试格式错误的请求或身份验证失败。
仅重试可重试的故障
| 状态或信号 | 是否重试 | 操作 |
|---|
400 | 否 | 修复请求体或参数。 |
401 | 否 | 修复 API key 和 Authorization header。 |
403 | 通常不 | 移除不受支持的字段并验证模型访问权限。 |
429 | 是 | 使用指数退避和抖动进行重试。 |
500 with invalid_request | 否 | 修复请求结构。 |
500, 503, 504, 524 | 是 | 使用退避重试并保留请求 ID。 |
添加退避
下面的 Python 示例仅重试可重试的故障:
import os
import random
import time
from openai import APIError, OpenAI, RateLimitError
client = OpenAI(
api_key=os.environ["COMETAPI_KEY"],
base_url="https://api.cometapi.com/v1",
)
for attempt in range(5):
try:
response = client.chat.completions.create(
model="your-model-id",
messages=[{"role": "user", "content": "Say hello."}],
)
print(response.choices[0].message.content)
break
except RateLimitError:
delay = min(30, 2**attempt) + random.random()
time.sleep(delay)
except APIError as error:
status_code = getattr(error, "status_code", None)
if status_code in {500, 503, 504, 524}:
delay = min(30, 2**attempt) + random.random()
time.sleep(delay)
continue
raise
else:
raise RuntimeError("The request failed after retries.")
成功响应包含模型输出:
{
"choices": [
{
"message": {
"role": "assistant",
"content": "Hello."
}
}
],
"usage": {
"total_tokens": 9
}
}
记录有用的上下文
在移除用户密钥和大文件后,下面的 JSON 结构可以安全存储:
{
"method": "POST",
"path": "/v1/chat/completions",
"model": "your-model-id",
"status": 429,
"request_id": "request_id_from_error_message",
"retryable": true
}
常见错误
| 错误 | 修复方法 |
|---|
重试 401 | 停止重试,并轮换或重新加载 API key。 |
| 重试无效 JSON | 在发送另一个请求之前验证请求体。 |
| 日志中没有请求 ID | 在你的 SDK 包装错误之前捕获精确的错误体。 |
429 后立即重试 | 添加抖动并降低并发度。 |
相关链接