> ## 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 と route ごとの使用状況を監視して 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())
```

結果は model の出力の配列になります。

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

## よくあるエラー

| Error             | Fix                                                 |
| ----------------- | --------------------------------------------------- |
| 無制限の並列リクエスト       | セマフォ、キュー、またはワーカープールを追加します。                          |
| すべての失敗を再試行する      | `429` と一時的なサーバー障害のみを再試行します。                         |
| model ごとのメトリクスがない | 各リクエストについて route、model ID、status、latency をログに記録します。 |
| 再試行の嵐             | ジッターを追加し、再試行遅延の最大値を制限します。                           |

## 関連リンク

* [エラーコードと再試行戦略](/ja/guides/error-codes-and-retry-strategy)
* [エラーコードと処理](/ja/errors/error-codes-handling)
* [モデルページ](/ja/overview/models)
* [モデルディレクトリ](https://www.cometapi.com/models/)
* [料金](https://www.cometapi.com/pricing/)
* [CometAPI クイックスタート](/ja/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>
