> ## Documentation Index
> Fetch the complete documentation index at: https://docs.openp.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# 限流与并发

> 如何在 OpenPAI 限流下实现稳定高 QPS

OpenPAI 在网关侧对每个用户 / 令牌设置了 RPM / TPM / 并发上限。
高 QPS 场景需要在客户端做好节流与重试。完整规则见 [速率限制](/api-reference/rate-limits)。

## 简易客户端节流(Python)

用 `asyncio.Semaphore` 控制并发:

```python theme={null}
import asyncio
from openai import AsyncOpenAI

client = AsyncOpenAI(api_key="sk-...", base_url="https://openp.ai/v1")
sem = asyncio.Semaphore(32)  # 同时最多 32 个并发请求

async def call(prompt: str):
    async with sem:
        return await client.chat.completions.create(
            model="gpt-5.5",
            messages=[{"role": "user", "content": prompt}],
        )

tasks = [call(f"task {i}") for i in range(1000)]
results = await asyncio.gather(*tasks)
```

## 指数退避

```python theme={null}
import asyncio, random

async def call_with_retry(prompt, max_retries=5):
    delay = 1
    for attempt in range(max_retries):
        try:
            return await client.chat.completions.create(
                model="gpt-5.5",
                messages=[{"role": "user", "content": prompt}],
            )
        except openai.RateLimitError as e:
            retry_after = float(e.response.headers.get("Retry-After", delay))
            await asyncio.sleep(retry_after + random.uniform(0, 0.5))
            delay = min(delay * 2, 30)
    raise RuntimeError("max retries exceeded")
```

## Token 桶限速

`aiolimiter` 在 Python 中实现客户端令牌桶:

```python theme={null}
from aiolimiter import AsyncLimiter

# 每分钟 200 个请求
rate = AsyncLimiter(max_rate=200, time_period=60)

async def call(prompt):
    async with rate:
        return await client.chat.completions.create(...)
```

## 利用响应头

每个响应携带剩余配额头,可实现自适应节流:

```python theme={null}
remaining_req = int(resp.response.headers.get("x-ratelimit-remaining-requests", "100"))
remaining_tok = int(resp.response.headers.get("x-ratelimit-remaining-tokens", "1000000"))

# 剩余 < 10% 时主动 sleep
if remaining_req < 20:
    await asyncio.sleep(2)
```

## 批量化技巧

* **合并短请求**:把多条独立 prompt 拼接为一次大请求(用 system prompt 说明任务边界)。
* **Embedding 一次多文本**:`input` 接受数组,单次最多约 2048 条。
* **Rerank 一次多文档**:`documents` 一次几十到几百。
* **流式 + 早停**:若答案长度可控,可让模型先输出 JSON 头,客户端用 stop sequence 提前结束。

## 升级配额

如以上策略仍无法满足业务,考虑:

1. 通过 **充值** 提升账户等级以获得更高配额。
2. 通过 **企业商务** 申请专属配额与独立通道。

## 监控

* 控制台 → **使用统计**:观察日峰值 RPM / TPM。
* 客户端日志:打印 `Retry-After` 与 `x-ratelimit-*` 头,定位限流瓶颈。
* 接入 Prometheus / Grafana 自建监控:每次调用上报扣费 / token / 延迟。
