跳转到主要内容

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 时,使用指数退避并加入抖动进行重试;如果重复重试仍然发生,则降低突发流量。

限制并发

以下 Python 示例使用异步信号量来限制并发聊天请求数:
import asyncio
import os
from openai import AsyncOpenAI

client = AsyncOpenAI(
    api_key=os.environ["COMETAPI_KEY"],
    base_url="https://api.cometapi.com/v1",
)

semaphore = asyncio.Semaphore(5)

async def ask(prompt):
    async with semaphore:
        completion = await client.chat.completions.create(
            model="your-model-id",
            messages=[{"role": "user", "content": prompt}],
        )
        return completion.choices[0].message.content

async def main():
    prompts = ["Say hello.", "Write a title.", "Return one JSON key."]
    results = await asyncio.gather(*(ask(prompt) for prompt in prompts))
    print(results)

asyncio.run(main())
结果是一个模型输出数组:
[
  "Hello.",
  "A concise title",
  "{\"key\":\"value\"}"
]

重试速率限制

以下 JavaScript 示例对 429 响应进行带抖动的重试:
import OpenAI from "openai";

const client = new OpenAI({
  apiKey: process.env.COMETAPI_KEY,
  baseURL: "https://api.cometapi.com/v1",
});

async function sleep(milliseconds) {
  return new Promise((resolve) => setTimeout(resolve, milliseconds));
}

async function createCompletion() {
  for (let attempt = 0; attempt < 5; attempt += 1) {
    try {
      return await client.chat.completions.create({
        model: "your-model-id",
        messages: [{ role: "user", content: "Say hello." }],
      });
    } catch (error) {
      if (error.status !== 429 || attempt === 4) {
        throw error;
      }

      const delay = Math.min(30000, 1000 * 2 ** attempt);
      await sleep(delay + Math.random() * 1000);
    }
  }
}

const completion = await createCompletion();
console.log(completion.choices[0].message.content);
成功的响应包含一个正常的聊天补全结果:
{
  "choices": [
    {
      "message": {
        "content": "Hello."
      }
    }
  ]
}

常见错误

错误解决方法
无限并行请求添加信号量、队列或工作池。
重试所有失败仅重试 429 和临时服务器故障。
没有按模型划分的指标为每个请求记录 route、model ID、status 和 latency。
重试风暴添加抖动并限制最大重试延迟。

相关链接

Last modified on May 28, 2026