AI API 调用最佳实践
调用 AI API 看似简单,但在生产环境中需要考虑错误处理、重试策略、流式传输、并发控制和成本优化等问题。本文总结实战中的最佳实践。
错误处理
常见错误码
- 400:请求格式错误,检查参数和消息格式
- 401:API Key 无效或过期
- 404:模型不存在或不可用
- 429:触发速率限制,需要降低请求频率
- 500/502/503:服务端错误,通常可重试
- 529:API 过载(Claude 特有),需等待后重试
分类处理策略
async function callWithErrorHandling(client, params) {
try {
return await client.chat.completions.create(params)
} catch (error) {
if (error.status === 400) {
// 请求错误,不重试,修复参数
throw new Error(`请求格式错误: ${error.message}`)
}
if (error.status === 401) {
// 认证错误,检查 Key
throw new Error('API Key 无效,请检查配置')
}
if (error.status === 429 || error.status === 529) {
// 限流/过载,等待后重试
const retryAfter = error.headers?.['retry-after'] || 5
await sleep(retryAfter * 1000)
return callWithErrorHandling(client, params)
}
if (error.status >= 500) {
// 服务端错误,重试
throw new RetryableError(error.message)
}
throw error
}
}
重试策略
指数退避重试
重试时应该使用指数退避(Exponential Backoff),避免雪崩效应:
async function retryWithBackoff(fn, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await fn()
} catch (error) {
if (i === maxRetries - 1) throw error
const delay = Math.min(1000 * Math.pow(2, i) + Math.random() * 1000, 30000)
console.log(`重试 ${i + 1}/${maxRetries},等待 ${delay}ms`)
await sleep(delay)
}
}
}
提示:添加随机抖动(Jitter)可以避免多个客户端在同一时刻重试,减轻服务器压力。
流式传输
为什么使用流式传输?
- 用户体验更好,逐字显示而非等待完整响应
- 降低首字节延迟(TTFB)
- 长回复不会触发超时
流式响应处理
const stream = await client.chat.completions.create({
model: 'claude-sonnet-4-20250514',
messages: [{ role: 'user', content: '写一个排序算法' }],
stream: true
})
for await (const chunk of stream) {
const content = chunk.choices[0]?.delta?.content || ''
process.stdout.write(content)
}
console.log('\n--- 流式传输完成 ---')
并发控制
限制并发请求数
同时发送太多请求容易触发限流。建议使用信号量控制并发:
class Semaphore {
constructor(max) {
this.max = max
this.current = 0
this.queue = []
}
async acquire() {
if (this.current < this.max) {
this.current++
return
}
await new Promise((resolve) => this.queue.push(resolve))
}
release() {
this.current--
if (this.queue.length > 0) {
this.current++
this.queue.shift()()
}
}
}
// 限制最多 5 个并发请求
const sem = new Semaphore(5)
async function limitedCall(params) {
await sem.acquire()
try {
return await client.chat.completions.create(params)
} finally {
sem.release()
}
}
注意:不同模型和账户等级的并发限制不同。使用 claude4u.com 中转站可以自动管理并发,超限时排队等待而非直接报错。
成本优化
实用技巧
- 控制 max_tokens:根据任务合理设置,避免生成冗余内容
- 使用 Prompt Caching:重复的系统提示词利用缓存降低成本
- 选择合适的模型:简单任务用小模型,复杂任务用大模型
- 批量处理:使用 Batch API 处理非实时任务,通常有 50% 折扣
监控和日志
生产环境中,务必记录每次 API 调用的关键信息:
- 请求耗时(延迟)
- Token 用量(输入 + 输出)
- 错误率和错误类型
- 模型和版本信息
通过 claude4u.com 中转站的管理后台,可以实时查看这些指标,无需自建监控系统。
轻舟 AI