有些用户不知道如何进行大批量的快速请求API。提供一个简单的python示例python的httpx请求效率远不如aiohttp,建议使用aiohttp进行并发请求。
安装依赖#
pip install asyncio
pip install aiohttp
请求示例#
如果是一次性并发请求完后统一写入,请自行修改脚本(一般不推荐这样做,openai官方都无法保证请求过程不会出现错误,需要处理好错误问题,以免影响最后的存储工作)import asyncio
import aiohttp
API_KEY = 'Your ApiKey'
BASE_URL = "https://api.pawmaas.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,
"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
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连接堆积,会频繁被服务器断开请求。