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

# 高并发批量请求示例

有些用户不知道如何进行大批量的快速请求API。提供一个简单的python示例

:::tip
python的httpx请求效率远不如aiohttp，建议使用aiohttp进行并发请求。
:::

### 安装依赖

```sh theme={null}
pip install asyncio
pip install aiohttp
```

### 请求示例

该示例为无限循环并发请求，可以边请求边写入存储。

如果是一次性并发请求完后统一写入，请自行修改脚本（一般不推荐这样做，openai官方都无法保证请求过程不会出现错误，需要处理好错误问题，以免影响最后的存储工作）

```python theme={null}
import asyncio
import aiohttp

API_KEY = 'Your ApiKey'

BASE_URL = "https://api.iqqz.com/v1/"

headers = {
    "Authorization": f"Bearer {API_KEY}",
    "Content-Type": "application/json",
}

async def create_completion(session):
    try:
        async with session.post(
            url=f"{BASE_URL}chat/completions",
            json={
                "model": "gpt-4o",
                "max_tokens":4000,
                "temperature": 0.5,
                # "top_p": 0.5,
                "messages": [{"role": "user", "content": "你是谁"}],
            },
            headers=headers
        ) as response:
            if response.status == 200:
                result = await response.json()
                # 打印结果
                # 请自行处理请求结果的存储。
                print(result['choices'][0]['message']['content'])
            else:
                print(f"请求失败，状态码: {response.status}")
    except Exception as e:
        print(f"请求发生异常: {e}")

async def main():
    max_limits = 2000  # 设置一个合理的并发请求数，请不要超过5000，可以开多个脚本同时跑，效率更高！
    async with aiohttp.ClientSession() as session:
        while True:
            tasks = [create_completion(session) for _ in range(max_limits)]
            await asyncio.gather(*tasks)
            await asyncio.sleep(1)  # 控制请求间隔

if __name__ == "__main__":
    asyncio.run(main())
```

该脚本 一分钟跑几千个请求没问题，如果觉得不够，可以多个python脚本同时跑。不要在一个脚本中发起过多请求，容易造成tcp连接堆积，会频繁被服务器断开请求。
