2023-03-14 17:24:21 +01:00
|
|
|
import openai
|
2023-03-14 18:49:44 +01:00
|
|
|
import os
|
2023-03-14 17:45:58 +01:00
|
|
|
from redbot.core import Config, commands
|
2023-03-14 17:24:21 +01:00
|
|
|
|
|
|
|
|
class ReginaldCog(commands.Cog):
|
|
|
|
|
def __init__(self, bot):
|
|
|
|
|
self.bot = bot
|
2023-03-14 17:59:57 +01:00
|
|
|
self.config = Config.get_conf(self, identifier=71717171171717)
|
2023-03-14 17:45:58 +01:00
|
|
|
self.config.register_global(
|
|
|
|
|
openai_model="text-davinci-002"
|
|
|
|
|
)
|
2023-03-14 17:24:21 +01:00
|
|
|
|
2023-03-14 17:54:14 +01:00
|
|
|
@commands.guild_only()
|
|
|
|
|
@commands.has_permissions(manage_guild=True)
|
2023-03-14 17:24:21 +01:00
|
|
|
@commands.command()
|
|
|
|
|
async def reginald(self, ctx, *, prompt=None):
|
|
|
|
|
"""Ask Reginald a question"""
|
|
|
|
|
if prompt is None:
|
|
|
|
|
prompt = "Hey,"
|
2023-03-14 17:54:14 +01:00
|
|
|
try:
|
2023-03-14 18:49:44 +01:00
|
|
|
api_key = os.environ.get('OPENAI_API_KEY')
|
|
|
|
|
if api_key is None:
|
|
|
|
|
raise ValueError('OPENAI_API_KEY environment variable not set')
|
2023-03-14 17:54:14 +01:00
|
|
|
model = await self.config.openai_model()
|
|
|
|
|
openai.api_key = api_key
|
|
|
|
|
max_tokens = min(len(prompt) * 2, 2048)
|
|
|
|
|
response = openai.Completion.create(
|
|
|
|
|
model=model,
|
|
|
|
|
prompt=prompt,
|
|
|
|
|
max_tokens=max_tokens,
|
|
|
|
|
n=1,
|
|
|
|
|
stop=None,
|
|
|
|
|
temperature=0.5,
|
|
|
|
|
)
|
|
|
|
|
await ctx.send(response.choices[0].text.strip())
|
|
|
|
|
except openai.error.OpenAIError as e:
|
2023-03-14 18:49:44 +01:00
|
|
|
import traceback
|
|
|
|
|
traceback.print_exc()
|
|
|
|
|
await ctx.send(f"I apologize, sir, but I am unable to generate a response at this time. Error message: {str(e)}")
|
2023-03-14 17:24:21 +01:00
|
|
|
|
|
|
|
|
def setup(bot):
|
2023-03-14 17:40:21 +01:00
|
|
|
cog = ReginaldCog(bot)
|
2023-03-14 17:54:14 +01:00
|
|
|
bot.add_cog(cog)
|