跳轉到主要內容

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 範例使用非同步 semaphore 來限制同時進行的聊天請求數量:
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."
      }
    }
  ]
}

常見錯誤

錯誤修正方式
無限制的平行請求加入 semaphore、佇列或 worker pool。
重試所有失敗只重試 429 與暫時性的伺服器失敗。
沒有依 model 劃分的指標為每個請求記錄路由、model ID、狀態與延遲。
重試風暴加入抖動並限制最大重試延遲。

相關連結

Last modified on May 28, 2026