> ## 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.

# 處理速率限制與並行

> 透過限制請求並行數、對 `429` 回應使用帶抖動的重試機制，並依 model 與路由監控使用情況，來處理 CometAPI 速率限制。

在請求離開你的應用程式之前，先透過控制並行數來處理速率限制。當 CometAPI 回傳 `429` 時，請使用指數退避與抖動進行重試，若反覆發生重試，則進一步降低尖峰流量。

## 限制並行數

以下 Python 範例使用非同步 semaphore 來限制同時進行的聊天請求數：

```python theme={null}
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())
```

結果會是一個包含模型輸出的陣列：

```json theme={null}
[
  "Hello.",
  "A concise title",
  "{\"key\":\"value\"}"
]
```

## 重試速率限制

以下 JavaScript 範例會對 `429` 回應搭配抖動進行重試：

```javascript theme={null}
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);
```

成功的回應會包含一般的聊天補全結果：

```json theme={null}
{
  "choices": [
    {
      "message": {
        "content": "Hello."
      }
    }
  ]
}
```

## 常見錯誤

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

## 相關連結

* [錯誤代碼與重試策略](/zh-Hant/guides/error-codes-and-retry-strategy)
* [錯誤代碼與處理](/zh-Hant/errors/error-codes-handling)
* [模型頁面](/zh-Hant/overview/models)
* [模型目錄](https://www.cometapi.com/models/)
* [價格](https://www.cometapi.com/pricing/)
* [CometAPI 快速開始](/zh-Hant/overview/quick-start)

<script type="application/ld+json">
  {`
    {
    "@context": "https://schema.org",
    "@graph": [
      {
        "@type": "TechArticle",
        "@id": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency",
        "headline": "如何處理速率限制與並行？",
        "description": "透過限制並行數、以抖動方式重試 429 回應，以及依 model 和 route 監控使用情況，來處理 CometAPI 的速率限制。",
        "url": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency",
        "author": {
          "@type": "Organization",
          "name": "CometAPI"
        },
        "publisher": {
          "@type": "Organization",
          "name": "CometAPI",
          "url": "https://www.cometapi.com"
        }
      },
      {
        "@type": "BreadcrumbList",
        "itemListElement": [
          {
            "@type": "ListItem",
            "position": 1,
            "name": "CometAPI 文件",
            "item": "https://apidoc.cometapi.com/"
          },
          {
            "@type": "ListItem",
            "position": 2,
            "name": "指南",
            "item": "https://apidoc.cometapi.com/guides/use-cometapi-with-openai-sdk"
          },
          {
            "@type": "ListItem",
            "position": 3,
            "name": "如何處理速率限制與並行？",
            "item": "https://apidoc.cometapi.com/guides/rate-limits-and-concurrency"
          }
        ]
      }
    ]
    }
    `}
</script>
