matrix_chatgpt_bot/askgpt.py

42 lines
1.3 KiB
Python
Raw Permalink Normal View History

2023-03-05 14:07:25 +00:00
import aiohttp
import asyncio
import json
2023-03-10 13:43:18 +00:00
from log import getlogger
2023-05-30 02:26:39 +00:00
2023-03-10 13:43:18 +00:00
logger = getlogger()
2023-03-05 14:07:25 +00:00
2023-04-10 02:52:18 +00:00
class askGPT:
2023-04-13 13:31:11 +00:00
def __init__(self, session: aiohttp.ClientSession):
self.session = session
2023-03-05 14:07:25 +00:00
2023-04-10 02:52:18 +00:00
async def oneTimeAsk(self, prompt: str, api_endpoint: str, headers: dict) -> str:
jsons = {
"model": "gpt-3.5-turbo",
"messages": [
{
"role": "user",
"content": prompt,
},
],
}
2023-04-13 13:31:11 +00:00
max_try = 2
while max_try > 0:
2023-03-05 14:07:25 +00:00
try:
2023-05-30 02:26:39 +00:00
async with self.session.post(
url=api_endpoint, json=jsons, headers=headers, timeout=120
) as response:
2023-03-05 14:07:25 +00:00
status_code = response.status
if not status_code == 200:
2023-03-10 13:43:18 +00:00
# print failed reason
logger.warning(str(response.reason))
max_try = max_try - 1
2023-03-05 14:07:25 +00:00
# wait 2s
await asyncio.sleep(2)
2023-03-05 14:07:25 +00:00
continue
resp = await response.read()
2023-05-30 02:26:39 +00:00
return json.loads(resp)["choices"][0]["message"]["content"]
2023-03-05 14:07:25 +00:00
except Exception as e:
2023-04-13 05:41:47 +00:00
raise Exception(e)