Skip to content

Commit 13c0109

Browse files
authored
Merge pull request #28 from A-Baji/dev
dockerization and new api features
2 parents 473594f + b749801 commit 13c0109

File tree

11 files changed

+201
-31
lines changed

11 files changed

+201
-31
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,10 @@
11
config.json
2+
discordai/bot/cogs/*.py
3+
!discordai/bot/cogs/__init__.py
4+
!discordai/bot/cogs/customai.py
5+
!discordai/bot/cogs/imageai.py
6+
!discordai/bot/cogs/openai.py
7+
!discordai/bot/cogs/sync.py
28

39
# Byte-compiled / optimized / DLL files
410
__pycache__/

CHANGELOG.md

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
# Changelog
2+
3+
Observes [Semantic Versioning](https://semver.org/spec/v2.0.0.html) standard and [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) convention.
4+
5+
## [2.0.0] - TBD
6+
7+
### Added
8+
- An openAI image generation command
9+
- The gpt3.5 model to the openai command and made it the default
10+
- A changelog
11+
12+
### Changed
13+
14+
- Made prompt bolding for custom model completions a discord command parameter
15+
16+
### Fixed
17+
18+
- Bug where two stars would appear for blank prompts for custom model completions
19+
20+
## [1.3.2] - 02-22-2023
21+
22+
### Changed
23+
24+
- Update modelizer to version [1.2.2](https://github.com/A-Baji/discordAI-modelizer/compare/1.2.1...1.2.2)
25+
26+
## [1.3.1] - 02-19-2023
27+
28+
### Changed
29+
30+
- Update modelizer to version [1.2.1](https://github.com/A-Baji/discordAI-modelizer/compare/1.2.0...1.2.1)
31+
32+
## [1.3.0] - 02-17-2023
33+
34+
### Added
35+
36+
- CLI option to bolden the prompt for custom model completions
37+
- CLI option to set the thought time
38+
- CLI option to set the min and max thought length
39+
- CLI option to only output the events for the job status
40+
41+
### Changed
42+
43+
- Update modelizer to version [1.2.0](https://github.com/A-Baji/discordAI-modelizer/compare/1.1.0...1.2.0)
44+
45+
## [1.2.1] - 02-12-2023
46+
47+
### Added
48+
49+
- Option to provide a different openai key to the customai command
50+
51+
## [1.2.0] - 02-11-2023
52+
53+
### Changed
54+
55+
- Update modelizer to version [1.1.0](https://github.com/A-Baji/discordAI-modelizer/compare/1.0.1...1.1.0)
56+
57+
## [1.1.1] - 02-11-2023
58+
59+
### Added
60+
61+
- Pin modelizer to version [1.1.0](https://github.com/A-Baji/discordAI-modelizer/compare/1.0.0...1.0.1)
62+
63+
### Changed
64+
65+
- Switched from using `os.path` to `pathlib`
66+
67+
## [1.1.0] - 01-29-2023
68+
69+
### Changed
70+
71+
- Modified readme
72+
73+
[1.3.2]: https://github.com/A-Baji/discordAI/compare/1.3.1...1.3.2
74+
[1.3.1]: https://github.com/A-Baji/discordAI/compare/1.3.0...1.3.1
75+
[1.3.0]: https://github.com/A-Baji/discordAI/compare/1.2.1...1.3.0
76+
[1.2.1]: https://github.com/A-Baji/discordAI/compare/1.2.0...1.2.1
77+
[1.2.0]: https://github.com/A-Baji/discordAI/compare/1.1.1...1.2.0
78+
[1.1.1]: https://github.com/A-Baji/discordAI/compare/1.1.0...1.1.1
79+
[1.1.0]: https://github.com/A-Baji/discordAI/releases/tag/1.1.0

Dockerfile

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
FROM python:3.11-alpine
2+
WORKDIR /main
3+
RUN apk update
4+
RUN apk add git
5+
COPY ./requirements.txt ./setup.py ./README.md /main/
6+
COPY ./discordai /main/discordai
7+
RUN pip3 install --upgrade pip
8+
RUN pip3 install --no-cache-dir . && rm -R /main/*

discordai/bot/cogs/imageai.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
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+
16+
class Sizes(Enum):
17+
small = "256"
18+
medium = "512"
19+
large = "1024"
20+
21+
class ImageAI(commands.Cog, name="imageai"):
22+
def __init__(self, bot):
23+
self.bot = bot
24+
25+
@commands.hybrid_command(
26+
name="imageai",
27+
description="Generate an openAI image completion",
28+
)
29+
@app_commands.describe(
30+
prompt="The prompt to pass to openAI",
31+
size="small: 256px | medium: 512px | large: 1024 px: Default=small")
32+
async def openai(self, context: Context, prompt: str , size: Sizes = Sizes.small):
33+
dimension = "256x256" if size.value == "256" else "512x512" if size.value == "512" else "1024x1024"
34+
await context.defer()
35+
try:
36+
openai.api_key = self.bot.config["openai_key"]
37+
response = openai.Image.create(
38+
prompt=prompt,
39+
size=dimension
40+
)
41+
await context.send(response['data'][0]['url'])
42+
except Exception as error:
43+
print(f"Failed to generate image for prompt: {prompt}\nError: {error}")
44+
await context.send(
45+
f"Failed to generate image for prompt: {prompt}\nError: {error}"
46+
)
47+
48+
49+
async def setup(bot):
50+
await bot.add_cog(ImageAI(bot))

discordai/bot/cogs/openai.py

Lines changed: 27 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,16 @@
99
from discord import app_commands
1010
from discord.ext import commands
1111
from discord.ext.commands import Context
12+
from enum import Enum
1213

1314
import openai
1415

16+
class Models(Enum):
17+
chatgpt = "gpt-3.5-turbo"
18+
davinci = "text-davinci-003"
19+
curie = "text-curie-001"
20+
babbage = "text-babbage-001"
21+
ada = "text-ada-001"
1522

1623
class OpenAI(commands.Cog, name="openai"):
1724
def __init__(self, bot):
@@ -23,38 +30,40 @@ def __init__(self, bot):
2330
)
2431
@app_commands.describe(
2532
prompt="The prompt to pass to openAI: Default=\"\"",
26-
model="davinci | curie | babbage | ada: Default=davinci",
33+
model=" chatgpt | davinci | curie | babbage | ada: Default=chatgpt",
2734
temp="What sampling temperature to use. Higher values means more risks: Min=0 Max=1 Default=1",
2835
presence_penalty="Number between -2.0 and 2.0. Positive values will encourage new topics: Min=-2 Max=2 Default=0",
2936
frequency_penalty="Number between -2.0 and 2.0. Positive values will encourage new words: Min=-2 Max=2 Default=0")
30-
async def openai(self, context: Context, prompt: str = "", model: str = "text-davinci-003", temp: float = 1.0,
37+
async def openai(self, context: Context, prompt: str = "", model: Models = Models.chatgpt, temp: float = 1.0,
3138
presence_penalty: float = 0.0, frequency_penalty: float = 0.0):
3239
temp = min(max(temp, 0), 1)
3340
presPen = min(max(presence_penalty, -2), 2)
3441
freqPen = min(max(frequency_penalty, -2), 2)
3542

36-
if model.lower() == 'davinci':
37-
model = 'text-davinci-003'
38-
elif model.lower() == 'curie':
39-
model = 'text-curie-001'
40-
elif model.lower() == 'babbage':
41-
model = 'text-babbage-001'
42-
elif model.lower() == 'ada':
43-
model = 'text-ada-001'
44-
4543
await context.defer()
4644
try:
4745
openai.api_key = self.bot.config["openai_key"]
48-
response = openai.Completion.create(
49-
engine=model,
50-
prompt=prompt,
46+
if model.value == 'gpt-3.5-turbo':
47+
response = openai.ChatCompletion.create(
48+
model=model.value,
49+
messages=[{"role": "user", "content": prompt}],
5150
temperature=temp,
5251
frequency_penalty=presPen,
5352
presence_penalty=freqPen,
54-
max_tokens=325,
55-
echo=True if prompt else False
56-
)
57-
await context.send(response["choices"][0]["text"][:2000])
53+
max_tokens=325
54+
)
55+
await context.send(f"{prompt}{response['choices'][0]['message']['content']}"[:2000])
56+
else:
57+
response = openai.Completion.create(
58+
engine=model.value,
59+
prompt=prompt,
60+
temperature=temp,
61+
frequency_penalty=presPen,
62+
presence_penalty=freqPen,
63+
max_tokens=325,
64+
echo=True if prompt else False
65+
)
66+
await context.send(response["choices"][0]["text"][:2000])
5867
except Exception as error:
5968
print(f"Failed to generate valid response for prompt: {prompt}\nError: {error}")
6069
await context.send(

discordai/command_line.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,11 +111,11 @@ def discordai():
111111
help="Set the stop option to use for completions to True",
112112
)
113113
new_cmd_optional_named.add_argument(
114-
"--bolden",
114+
"--bold_default",
115115
action='store_true',
116116
required=False,
117-
dest='bolden',
118-
help="Boldens the original prompt in the completion output",
117+
dest='bold_default',
118+
help="Set the bolden option for prompts to True",
119119
)
120120

121121
delete_cmd = bot_cmds_commands_subcommand.add_parser(
@@ -382,7 +382,7 @@ def discordai():
382382
if args.subsubcommand == "new":
383383
template.gen_new_command(args.model_id, args.command_name, args.temp_default, args.pres_default,
384384
args.freq_default, args.max_tokens_default, args.stop_default, args.openai_key,
385-
args.bolden)
385+
args.bold_default)
386386
elif args.subsubcommand == "delete":
387387
template.delete_command(args.command_name)
388388
elif args.command == "model":

discordai/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,8 @@ def get():
1313
except FileNotFoundError as err:
1414
print("No config found. Please follow the steps to create one:")
1515
config = dict(
16-
token=input("\nEnter your discord bot token: "),
17-
openai_key=input("\nEnter your openAI key: ")
16+
token=os.getenv("DISCORD_TOKEN") or input("\nEnter your discord bot token: "),
17+
openai_key=os.getenv("OPENAI_KEY") or input("\nEnter your openAI key: ")
1818
)
1919
os.makedirs(config_dir, exist_ok=True)
2020
with open(pathlib.Path(config_dir, "config.json"), "w") as f:

discordai/template.py

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,11 @@ def __init__(self, bot):
2626
presence_penalty="Number between -2.0 and 2.0. Positive values will encourage new topics: Min=-2 Max=2 Default={pres_default}",
2727
frequency_penalty="Number between -2.0 and 2.0. Positive values will encourage new words: Min=-2 Max=2 Default={freq_default}",
2828
max_tokens="The max number of tokens to generate. Each token costs credits: Default={max_tokens_default}",
29-
stop="Whether to stop after the first sentence: Default={stop_default}")
29+
stop="Whether to stop after the first sentence: Default={stop_default}",
30+
bold="Whether to bolden the original prompt: Default={bold_default}")
3031
async def customai(self, context: Context, prompt: str = "", temp: float = {temp_default},
3132
presence_penalty: float = {pres_default}, frequency_penalty: float = {freq_default}, max_tokens: int = {max_tokens_default},
32-
stop: bool = {stop_default}):
33+
stop: bool = {stop_default}, bold: bool = {bold_default}):
3334
temp = min(max(temp, 0), 1)
3435
presPen = min(max(presence_penalty, -2), 2)
3536
freqPen = min(max(frequency_penalty, -2), 2)
@@ -47,7 +48,7 @@ async def customai(self, context: Context, prompt: str = "", temp: float = {temp
4748
echo=False,
4849
stop='.' if stop else None,
4950
)
50-
await context.send(f"{{'**' if {bold} else ''}}{{prompt}}{{'**' if {bold} else ''}}{{response[\'choices\'][0][\'text\'][:2000]}}")
51+
await context.send(f"{{'**' if bold and prompt else ''}}{{prompt}}{{'**' if bold and prompt else ''}}{{response[\'choices\'][0][\'text\'][:2000]}}")
5152
except Exception as error:
5253
print({error})
5354
await context.send(
@@ -63,7 +64,7 @@ async def setup(bot):
6364

6465

6566
def gen_new_command(model_id: str, command_name: str, temp_default: float, pres_default: float, freq_default: float,
66-
max_tokens_default: int, stop_default: bool, openai_key: str, bold_prompt: bool):
67+
max_tokens_default: int, stop_default: bool, openai_key: str, bold_default: bool):
6768
if getattr(sys, 'frozen', False):
6869
# The code is being run as a frozen executable
6970
data_dir = pathlib.Path(appdirs.user_data_dir(appname="discordai"))
@@ -84,7 +85,7 @@ def gen_new_command(model_id: str, command_name: str, temp_default: float, pres_
8485
command_name=command_name, temp_default=float(temp_default),
8586
pres_default=float(pres_default),
8687
freq_default=float(freq_default),
87-
max_tokens_default=max_tokens_default, stop_default=stop_default, openai_key=openai_key, bold = bold_prompt,
88+
max_tokens_default=max_tokens_default, stop_default=stop_default, openai_key=openai_key, bold_default = bold_default,
8889
error="f\"Failed to generate valid response for prompt: {prompt}\\nError: {error}\""))
8990
print(f"Successfully created new slash command: /{command_name} using model {model_id}")
9091

discordai/version.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
__version__ = "1.3.2"
1+
__version__ = "2.0.0"

docker-compose.yaml

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# VERSION=$(cat discordai/version.py | grep -oP '\d+\.\d+\.\d+') docker compose up --build
2+
version: '2.4'
3+
services:
4+
app:
5+
build: .
6+
image: discord-ai/discordai:${VERSION}
7+
working_dir: /main
8+
environment:
9+
- DISCORD_TOKEN
10+
- OPENAI_KEY
11+
env_file: ./.env
12+
volumes:
13+
- ./discordai:/usr/local/lib/python3.11/site-packages/discordai
14+
command:
15+
- sh
16+
- -c
17+
- |
18+
tail -f /dev/null

0 commit comments

Comments
 (0)