AI API 调用最佳实践

调用 AI API 看似简单,但在生产环境中需要考虑错误处理、重试策略、流式传输、并发控制和成本优化等问题。本文总结实战中的最佳实践。

错误处理

常见错误码

分类处理策略

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)可以避免多个客户端在同一时刻重试,减轻服务器压力。

流式传输

为什么使用流式传输?

流式响应处理

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 中转站可以自动管理并发,超限时排队等待而非直接报错。

成本优化

实用技巧

监控和日志

生产环境中,务必记录每次 API 调用的关键信息:

通过 claude4u.com 中转站的管理后台,可以实时查看这些指标,无需自建监控系统。

Start Using 轻舟 AI

Stable, fast AI API relay — supports Claude, OpenAI, Gemini and more

Sign Up Now