|
| 1 | +"""" |
| 2 | +Copyright © Krypton 2019-2022 - https://github.com/kkrypt0nn (https://krypton.ninja) |
| 3 | +Description: |
| 4 | +🐍 A simple template to start to code your own and personalized discord bot in Python programming language. |
| 5 | +
|
| 6 | +Version: 5.4.1 |
| 7 | +""" |
| 8 | + |
| 9 | +from discord import app_commands |
| 10 | +from discord.ext import commands |
| 11 | +from discord.ext.commands import Context |
| 12 | +from enum import Enum |
| 13 | + |
| 14 | +import openai |
| 15 | +import tiktoken |
| 16 | + |
| 17 | +class Roles(Enum): |
| 18 | + system = "system" |
| 19 | + user = "user" |
| 20 | + assistant = "assistant" |
| 21 | + |
| 22 | +class Warnings(Enum): |
| 23 | + low = "" |
| 24 | + medium = "\n:warning:You are nearing the size limit for chatGPT's chat history:warning:" |
| 25 | + high = ":exclamation:You have reached the size limit for chatGPT's chat history. Use the `/resetchat` command to continue using chatGPT:exclamation:" |
| 26 | + |
| 27 | +def num_tokens_from_messages(messages, model): |
| 28 | + """Returns the number of tokens used by a list of messages.""" |
| 29 | + try: |
| 30 | + encoding = tiktoken.encoding_for_model(model) |
| 31 | + except KeyError: |
| 32 | + encoding = tiktoken.get_encoding("cl100k_base") |
| 33 | + num_tokens = 0 |
| 34 | + for message in messages: |
| 35 | + num_tokens += 4 # every message follows <im_start>{role/name}\n{content}<im_end>\n |
| 36 | + for key, value in message.items(): |
| 37 | + num_tokens += len(encoding.encode(value)) |
| 38 | + if key == "name": # if there's a name, the role is omitted |
| 39 | + num_tokens += -1 # role is always required and always 1 token |
| 40 | + num_tokens += 2 # every reply is primed with <im_start>assistant |
| 41 | + return num_tokens |
| 42 | + |
| 43 | +class ChatGPT(commands.Cog, name="chatgpt"): |
| 44 | + def __init__(self, bot): |
| 45 | + self.bot = bot |
| 46 | + |
| 47 | + @commands.hybrid_command( |
| 48 | + name="chatgpt", |
| 49 | + description="Generate an chatGPT completion", |
| 50 | + ) |
| 51 | + @app_commands.describe( |
| 52 | + prompt="The prompt to pass to chatGPT: Default=\"\"", |
| 53 | + role=" system | user | asssistant: Default=user", |
| 54 | + temp="What sampling temperature to use. Higher values means more risks: Min=0 Max=1 Default=1", |
| 55 | + presence_penalty="Number between -2.0 and 2.0. Positive values will encourage new topics: Min=-2 Max=2 Default=0", |
| 56 | + frequency_penalty="Number between -2.0 and 2.0. Positive values will encourage new words: Min=-2 Max=2 Default=0") |
| 57 | + async def chatgpt(self, context: Context, prompt: str = "", role: Roles = Roles.user, temp: float = 1.0, |
| 58 | + presence_penalty: float = 0.0, frequency_penalty: float = 0.0): |
| 59 | + openai.api_key = self.bot.config["openai_key"] |
| 60 | + model = "gpt-3.5-turbo" |
| 61 | + temp = min(max(temp, 0), 1) |
| 62 | + presPen = min(max(presence_penalty, -2), 2) |
| 63 | + freqPen = min(max(frequency_penalty, -2), 2) |
| 64 | + |
| 65 | + if context.guild.id not in self.bot.chat_messages: |
| 66 | + self.bot.chat_messages[context.guild.id] = [{"role": "system", "content": self.bot.chat_init[context.guild.id]}] if context.guild.id in self.bot.chat_init and self.bot.chat_init[context.guild.id] else [] |
| 67 | + self.bot.chat_messages[context.guild.id].append({"role": role.value, "content": prompt}) |
| 68 | + messages = self.bot.chat_messages[context.guild.id] |
| 69 | + |
| 70 | + token_cost = num_tokens_from_messages(messages, model) |
| 71 | + if 325 <= 4096-token_cost: |
| 72 | + warning = Warnings.low |
| 73 | + elif 4096-token_cost >= 5: |
| 74 | + warning = Warnings.medium |
| 75 | + else: |
| 76 | + warning = Warnings.high |
| 77 | + |
| 78 | + await context.defer() |
| 79 | + try: |
| 80 | + if warning == Warnings.high: |
| 81 | + await context.send(warning.value) |
| 82 | + else: |
| 83 | + response = openai.ChatCompletion.create( |
| 84 | + model=model, |
| 85 | + messages=messages, |
| 86 | + temperature=temp, |
| 87 | + frequency_penalty=presPen, |
| 88 | + presence_penalty=freqPen, |
| 89 | + max_tokens=325 if 325 <= 4096-token_cost else token_cost |
| 90 | + ) |
| 91 | + await context.send(f"{prompt}\n{response['choices'][0]['message']['content']}{warning.value}"[:2000]) |
| 92 | + self.bot.chat_messages[context.guild.id].append(response['choices'][0]['message']) |
| 93 | + except Exception as error: |
| 94 | + print(f"Failed to generate valid response for prompt: {prompt}\nError: {error}") |
| 95 | + await context.send( |
| 96 | + f"Failed to generate valid response for prompt: {prompt}\nError: {error}" |
| 97 | + ) |
| 98 | + |
| 99 | + @commands.hybrid_command( |
| 100 | + name="resetchat", |
| 101 | + description="Resets the chat history for chatGPT completions", |
| 102 | + ) |
| 103 | + async def resetchat(self, context): |
| 104 | + self.bot.chat_messages[context.guild.id] = [{"role": "system", "content": self.bot.chat_init[context.guild.id]}] if context.guild.id in self.bot.chat_init and self.bot.chat_init[context.guild.id] else [] |
| 105 | + await context.send("Chat history has been reset") |
| 106 | + |
| 107 | + @commands.hybrid_command( |
| 108 | + name="setchatinit", |
| 109 | + description="Set the initialization message, a guide for the AI on how to respond to future chat messages", |
| 110 | + ) |
| 111 | + @app_commands.describe(message="The init message for chatGPT completions. Omit to reset") |
| 112 | + async def setchatinit(self, context, message: str = ""): |
| 113 | + self.bot.chat_init[context.guild.id] = message |
| 114 | + if message: |
| 115 | + if context.guild.id in self.bot.chat_messages: |
| 116 | + if self.bot.chat_messages[context.guild.id] and self.bot.chat_messages[context.guild.id][0]["role"] == "system": |
| 117 | + self.bot.chat_messages[context.guild.id][0] = {"role": "system", "content": self.bot.chat_init[context.guild.id]} |
| 118 | + else: |
| 119 | + self.bot.chat_messages[context.guild.id] = [{"role": "system", "content": self.bot.chat_init[context.guild.id]}] + self.bot.chat_messages[context.guild.id] |
| 120 | + await context.send("Chat init message has been set") |
| 121 | + else: |
| 122 | + if context.guild.id in self.bot.chat_messages: |
| 123 | + if self.bot.chat_messages[context.guild.id] and self.bot.chat_messages[context.guild.id][0]["role"] == "system": |
| 124 | + self.bot.chat_messages[context.guild.id].pop(0) |
| 125 | + await context.send("Chat init message has been reset") |
| 126 | + |
| 127 | +async def setup(bot): |
| 128 | + await bot.add_cog(ChatGPT(bot)) |
0 commit comments