> ## 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` 响应使用带抖动的重试，并按模型和路由监控用量来处理 CometAPI 速率限制。

在请求离开你的应用之前，通过控制并发来处理速率限制。当 CometAPI 返回 `429` 时，使用指数退避和抖动进行重试；如果重复重试仍然发生，则降低突发流量。

## 限制并发

下面的 Python 示例使用异步信号量来限制并发聊天请求：

```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."
      }
    }
  ]
}
```

## 常见错误

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

## 相关链接

* [错误代码与重试策略](/zh-Hans/guides/error-codes-and-retry-strategy)
* [错误代码与处理](/zh-Hans/errors/error-codes-handling)
* [模型页面](/zh-Hans/overview/models)
* [模型目录](https://www.cometapi.com/models/)
* [定价](https://www.cometapi.com/pricing/)
* [CometAPI 快速开始](/zh-Hans/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 和路由监控使用情况，来处理 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>
