nova-cord/cord/chatbot.py

70 lines
2.2 KiB
Python
Raw Permalink Normal View History

import os
import openai
2023-08-29 00:29:25 +02:00
import random
import embedder
from dotenv import load_dotenv
load_dotenv()
async def respond(interaction, prompt):
2023-08-02 17:00:18 +02:00
partial_message = await interaction.send('') # send an empty message
message = await partial_message.fetch() # gets the message that was send
2023-08-06 23:20:38 +02:00
openai.api_base = os.getenv('OPENAI_BASE')
openai.api_key = os.getenv('OPENAI_KEY')
model = os.getenv('OPENAI_MODEL')
async with interaction.channel.typing(): # show the "Typing..."
try:
completion = openai.ChatCompletion.create(
model=model,
messages=[
2023-08-29 00:29:25 +02:00
{'role': 'system', 'content': f"""You are a helpful Discord AI bot called "Nova". You're based on NovaAI\'s {model} model.
You were developed by *NovaAI* (website: https://nova-oss.com) in 2023, but your knowledge is limited to mid-2021.
2023-08-03 01:44:58 +02:00
Respond using Markdown. Keep things simple and short and directly do what the user says without any fluff.
2023-08-29 00:29:25 +02:00
Have cool humour and be friendly. Precicesly follow the instructions of the user.
2023-08-03 01:44:58 +02:00
For programming code, always make use formatted code blocks like this:
```py
print("Hello")
2023-08-29 00:29:25 +02:00
```"""},
{'role': 'user', 'content': prompt}
],
temperature=0.6,
2023-08-29 00:29:25 +02:00
stream=True,
max_tokens=1000
)
except Exception as exc:
await embedder.error(interaction, 'Could not generate an AI response.', ephemeral=True)
raise exc
2023-08-29 00:29:25 +02:00
text = f"""### {interaction.user.mention}:
{prompt}
### NovaAI [`{model}`]:
"""
for event in completion: # loop through word generation in real time
try:
new_text = event['choices'][0]['delta']['content'] # newly generated word
2023-08-29 00:29:25 +02:00
except KeyError:
if not event['choices'][0].get('text'):
continue
if '[DONE]' in event['choices'][0]['text']:
break
text += new_text
2023-08-29 00:29:25 +02:00
if text and random.randint(0, 100) < 20:
await message.edit(content=text)
2023-08-29 00:29:25 +02:00
if text:
await message.edit(content=text)
await message.add_reaction('')
2023-08-02 17:00:18 +02:00