API Key 限制
API Key 是访问 ai.TokenHub 服务的凭证。了解其限制和管理方式对于稳定使用服务非常重要。
API Key 类型
| 类型 | 适用场景 | 特点 |
|---|---|---|
| 测试 Key | 开发调试 | 速率限制较低,免费额度有限 |
| 正式 Key | 生产环境 | 更高的速率限制和额度 |
速率限制
为保护服务稳定性,我们对 API 请求设置了速率限制:
| 限制类型 | 说明 |
|---|---|
| RPM (Requests Per Minute) | 每分钟最大请求数 |
| TPM (Tokens Per Minute) | 每分钟最大 Token 数 |
| 并发请求 | 同时进行的最大请求数 |
不同模型和套餐有不同的速率限制,具体数值可在控制台查看。
超出限制的响应
当超出速率限制时,API 返回 429 错误:
json
{
"error": {
"message": "Rate limit exceeded",
"type": "rate_limit_error",
"code": "rate_limit_exceeded"
}
}最佳实践
1. 实现重试机制
python
import time
from openai import OpenAI, RateLimitError
client = OpenAI(
base_url="https://ai-tokenhub.com/v1",
api_key="YOUR_API_KEY"
)
def call_with_retry(messages, max_retries=3):
for i in range(max_retries):
try:
return client.chat.completions.create(
model="gpt-4o",
messages=messages
)
except RateLimitError:
wait_time = (i + 1) * 2
time.sleep(wait_time)
raise Exception("Max retries exceeded")2. 批量请求优化
将多个小请求合并为批量请求,减少请求次数:
python
# 不推荐:多次单独请求
for text in texts:
response = client.embeddings.create(input=text, model="text-embedding-3-small")
# 推荐:一次批量请求
response = client.embeddings.create(input=texts, model="text-embedding-3-small")3. 监控使用量
定期检查 API Key 的使用量,避免超出额度:
bash
curl https://ai-tokenhub.com/v1/credits \
-H "Authorization: Bearer YOUR_API_KEY"额度管理
- 每个 API Key 有独立的额度配额
- 额度按 Token 使用量计费
- 可在控制台设置额度预警阈值
- 额度耗尽时 API 返回
insufficient_quota错误
安全建议
- 不要硬编码 API Key:使用环境变量存储
- 定期更换 Key:建议每月更换一次
- 区分用途:开发和生产使用不同的 Key
- 监控异常:关注异常请求模式