openai的chatgpt
from nonebot import on_command, on_message
import nonebot
from nonebot.params import CommandArg
from nonebot.adapters.onebot.v11 import Message, MessageEvent
import openai
import json
help_plugin_name = "openai人工智能"
__help_version = '1.0'
usage__ = '命令1./ai <参数:你想咨询的内容>\n命令2./img <参数1:你想生成的图片类型,参数2:生成的数量;默认1,参数3:图片大小;默认256256,1=512512,2=1024*1024\n命令3."""这里输入要生成的代码内容""">'
chatgpt_text = on_command("ai", aliases={"AI"}, priority=1)
@chatgpttext.handle()
async def (args: nonebot.adapters.Message = CommandArg()):
text = args.extract_plain_text()
if text:
ai = chatGPT()
res = ai.set_text(text)
json_data = json.loads(res)
await chatgpt_text.finish(json_data['choices'][0]['text'])
else:
await chatgpt_text.finish('请输入你想咨询的问题')
chatgpt_img = on_command("img", aliases={"img"}, priority=1)
@chatgptimg.handle()
async def (args: nonebot.adapters.Message = CommandArg()):
text = args.extract_plain_text()
if text:
if "," in text:
stt = text.split(",")
if len(stt) == 3:
content = stt[0]
x = stt[1]
n = stt[2]
elif len(stt) == 2:
content = stt[0]
x = stt[1]
n = 0
else:
content = stt[0]
x = 1
n = 0
else:
content = text
x = 1
n = 0
ai = chatGPT()
res = ai.set_img(content, int(x), int(n))
json_data = json.loads(res)
for i in json_data['data']:
cq = "[CQ:image,file=%s]" % i['url']
await chatgpt_img.send(Message(cq))
else:
await chatgpt_img.finish('请输入你想生成的图片类型')
chatgpt_code = on_message(priority=2, block=False)
@chatgptcode.handle()
async def (event: MessageEvent):
if isinstance(event, MessageEvent):
for msg in event.message:
if msg.type == "text":
text: str = msg.data["text"]
s_list = text.split('"""')
if len(s_list) >= 3:
ai = chatGPT()
res = ai.set_code(text, 0)
json_data = json.loads(res)
await chatgpt_code.finish(json_data['choices'][0]['text'])
class chatGPT():
def init(self):
openai.organization = "org-7YALDPRtMrCFNt7HpK5Wc8Z5"
openai.api_key = "sk-xxx"
model_list = openai.Model.list()
# print(model_list)
def set_text(self, content) -> str:
res = openai.Completion.create(
model="text-davinci-003",
prompt=content,
temperature=0.9,
max_tokens=3900,
top_p=1,
frequency_penalty=0,
presence_penalty=0.6
)
return str(res)
def set_code(self, content, n=1) -> str:
model = "code-cushman-001" if n == 1 else "code-davinci-002"
x = 2000 if model == "code-cushman-001" else 300
res = openai.Completion.create(
model=model,
prompt=content,
temperature=0,
max_tokens=x,
top_p=1,
)
return str(res)
def set_img(self, content, x=1, n=0) -> str:
"""
生成图片
:param content: 图片内容
:param x: 图片数
:param n: 尺寸
:return:
"""
size = '256x256' if n == 0 else '512x512' if n == 1 else '1024x1024'
res = openai.Image.create(
prompt=content,
n=x,
size=size
)
return str(res)
if name == 'main':
ai = chatGPT()
res = ai.set_code('"""1. Create a list of first names2. Create a list of last names3. Combine them randomly into a list of 100 full names"""',0)
print(res)