2023-03-05 09:07:25 -05:00
|
|
|
import aiohttp
|
|
|
|
import asyncio
|
|
|
|
import json
|
2023-03-10 08:43:18 -05:00
|
|
|
from log import getlogger
|
|
|
|
logger = getlogger()
|
2023-03-05 09:07:25 -05:00
|
|
|
|
|
|
|
|
2023-03-10 05:53:51 -05:00
|
|
|
async def ask(prompt: str, api_endpoint: str, headers: dict) -> str:
|
2023-03-05 09:07:25 -05:00
|
|
|
jsons = {
|
|
|
|
"model": "gpt-3.5-turbo",
|
|
|
|
"messages": [
|
|
|
|
{
|
|
|
|
"role": "user",
|
|
|
|
"content": prompt,
|
|
|
|
},
|
|
|
|
],
|
|
|
|
}
|
|
|
|
async with aiohttp.ClientSession() as session:
|
2023-03-10 05:53:51 -05:00
|
|
|
max_try = 5
|
|
|
|
while max_try > 0:
|
2023-03-05 09:07:25 -05:00
|
|
|
try:
|
2023-03-10 05:53:51 -05:00
|
|
|
async with session.post(url=api_endpoint,
|
2023-03-05 09:07:25 -05:00
|
|
|
json=jsons, headers=headers, timeout=10) as response:
|
|
|
|
status_code = response.status
|
|
|
|
if not status_code == 200:
|
2023-03-10 08:43:18 -05:00
|
|
|
# print failed reason
|
|
|
|
logger.warning(str(response.reason))
|
2023-03-10 05:53:51 -05:00
|
|
|
max_try = max_try - 1
|
2023-03-05 09:07:25 -05:00
|
|
|
# wait 2s
|
2023-03-09 19:27:48 -05:00
|
|
|
await asyncio.sleep(2)
|
2023-03-05 09:07:25 -05:00
|
|
|
continue
|
|
|
|
|
|
|
|
resp = await response.read()
|
|
|
|
await session.close()
|
|
|
|
return json.loads(resp)['choices'][0]['message']['content']
|
|
|
|
except Exception as e:
|
2023-03-10 08:43:18 -05:00
|
|
|
logger.error("Error Exception", exc_info=True)
|
2023-03-05 09:07:25 -05:00
|
|
|
print(e)
|
|
|
|
pass
|