Files
AstrBot/cores/openai/core.py
T
Soulter 0117591a20 fix: 优化发送流程
feat: 1.支持显示历史记录
2. 支持配置缓存最大token
2022-12-10 11:49:31 +08:00

43 lines
1.4 KiB
Python

import openai
import yaml
from util.errors.errors import PromptExceededError
inst = None
class ChatGPT:
def __init__(self):
with open("./configs/config.yaml", 'r', encoding='utf-8') as ymlfile:
cfg = yaml.safe_load(ymlfile)
if cfg['openai']['key'] != '':
print("读取ChatGPT Key成功")
openai.api_key = cfg['openai']['key']
else:
print("请先去完善ChatGPT的Key。详情请前往https://beta.openai.com/account/api-keys")
chatGPT_configs = cfg['openai']['chatGPTConfigs']
print(f'加载ChatGPTConfigs: {chatGPT_configs}')
self.chatGPT_configs = chatGPT_configs
self.openai_configs = cfg['openai']
global inst
inst = self
async def chat(self, prompt):
print("[ChatGPT] 接收到prompt")
try:
response = openai.Completion.create(
prompt=prompt,
**self.chatGPT_configs
)
except(openai.error.InvalidRequestError) as e:
raise PromptExceededError("OpenAI遇到错误:输入了一个不合法的请求。\n"+str(e))
# print(response['usage'])
return response["choices"][0]["text"], response['usage']['total_tokens']
def getConfigs(self):
return self.openai_configs
def getInst() -> ChatGPT:
global inst
return inst