使用 Python、asyncio 和 aiohttp 异步调用 OpenAI API

问题描述 投票:0回答:1

我正在尝试使用 aiohttp 和 asyncio 对 openai API 完成进行异步调用。请参见下面我创建元素数据框(门、窗等)的位置。我需要有关给定上下文(房间描述)的信息

#imports
import pandas as pd # Make a dataframe
import aiohttp  # for making API calls concurrently
import asyncio  # for running API calls concurrently

COMPLETIONS_MODEL = "text-davinci-003"
request_url =  "https://api.openai.com/v1/completions"
request_header = {"Authorization": f"Bearer {api_key}"}

#data
prompt_list = ['Door', 'Window', 'Table']
init_context = " height if the room contains a door which is 8ft in height, a table 2ft in height and a window 6ft in height"

#dataframe of list of questions
q_dataframe = pd.DataFrame({"type": prompt_list})

async def process_question(question: str, context: str):
    query = "What is the " + question + context
    data = {'model': 'text-davinci-003', 'prompt': f'{query}'}
    
    try:
        async with aiohttp.ClientSession() as session:
                    async with session.post(url=request_url, headers=request_header, json=data) as response:
                        resp = await response.json()
    except Exception as e:
        print(f"Request failed {e}")
    
async def process_questions(idf):
    results = await asyncio.gather(*[process_question(question, init_context) for question in idf['type']])
    
asyncio.create_task(process_questions(q_dataframe))

但是我收到每个请求的以下错误

Request failed Cannot connect to host api.openai.com:443 ssl:True [SSLCertVerificationError: (1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: certificate has expired (_ssl.c:1129)')]

我尝试使用 asyncio.sleep,但没有用。我是否在 asyncio.create_task 旁边错误地使用了 asyncio.gather

我能够在每个数据框行上运行 openai.completion.create,所以我的连接很好

python pandas python-asyncio aiohttp openai-api
1个回答
0
投票

这是一个SSL证书问题。您可以尝试以下步骤来修复它:

  1. 更新提供根证书的Python包,调用
    certifi
pip install --upgrade certifi
  1. 更新
    aiohttp
    库,如果你还没有:
pip install --upgrade aiohttp
  1. 您可以通过
    ssl=False
    绕过SSL验证作为最后的手段(不推荐用于生产环境,因为它可能会给您带来安全风险)
async def process_question(question: str, context: str):
    query = "What is the " + question + context
    data = {'model': 'text-davinci-003', 'prompt': f'{query}'}
    
    try:
        async with aiohttp.ClientSession() as session:
            async with session.post(url=request_url, headers=request_header, json=data, ssl=False) as response:
                resp = await response.json()
    except Exception as e:
        print(f"Request failed {e}")
© www.soinside.com 2019 - 2024. All rights reserved.