19 Commits
Author SHA1 Message Date
T-BENZIN 73bf08843f Update reginaldCog/messenger_clients/discord_data_models.py 2025-08-15 09:33:05 +02:00
T-BENZIN d2edf0e60d Delete reginaldCog/messenger_clients/_common.py 2025-08-15 09:32:25 +02:00
T-BENZIN bd4b05d2d4 Delete reginaldCog/llm_clients/discord_client_interfaces.py 2025-08-15 09:32:03 +02:00
T-BENZIN ff70196756 File structure refactor 2025-08-15 11:09:40 +05:00
T-BENZIN 180c167a43 File structure refactor 2025-08-15 11:01:21 +05:00
T-BENZIN 75af912bf5 File_structure refactor 2025-08-15 10:41:35 +05:00
T-BENZIN a64a07511d Commented out send_long_message method and auto PEP-8 reginald.py 2025-07-18 14:31:51 +05:00
T-BENZIN 9209cc568d Made Prompt dataclass immutable and got rid out of add_message method. openai_client\models.py's test run would remain broken for now 2025-07-18 14:28:23 +05:00
T-BENZIN 7056315d5f Added llm_interface.py for connecting Discord bot with LLMs (only Open AI at the moment) 2025-07-18 14:26:35 +05:00
T-BENZIN b77dc31ea5 Added Response dataclass for better openai's response deserialization. 2025-07-14 20:28:00 +05:00
T-BENZIN ad59a695af Experimented with more convenient (although, less explicit) way of passing data into abstract dataclasses. 2025-07-13 19:47:37 +05:00
T-BENZIN 89b98fc5af Experimented with more convenient (although, less explicit) way of passing data into abstract dataclasses. 2025-07-13 19:45:09 +05:00
T-BENZIN 97252a8062 Added models.py in openai_client containing abstract dataclasses for use with openai
Moved all dataclasses to .openai_client.models.py
Made prompt into its own dataclass
Removed to_dict methods because dataclasses/asdict seems to be sufficient
2025-07-11 16:59:20 +05:00
T-BENZIN 0534ec6b15 Added models.py containing abstract dataclasses for Discord 2025-07-10 21:22:52 +05:00
T-BENZIN 11f39bb673 Added package structure for future use 2025-07-10 20:52:21 +05:00
T-BENZIN 247e4417f5 First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 18:16:48 +05:00
T-BENZIN bfe22e40ee First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 18:14:49 +05:00
T-BENZIN 59902085b3 First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 17:48:36 +05:00
T-BENZIN 3d59e45e7e First attempt at making openai stuff pretty. As it uses replies instead of completions, update of openai library is required. 2025-07-05 17:46:13 +05:00
6 changed files with 193 additions and 33 deletions
View File
@@ -0,0 +1,95 @@
from dataclasses import dataclass, field, asdict
from abc import ABC
# region Content classes
@dataclass(frozen=True)
class Content(ABC):
type: str = field(init=False, default='')
@dataclass(frozen=True)
class InputText(Content):
type: str = field(init=False, default='input_text')
text: str
@dataclass(frozen=True)
class OutputText(Content):
type: str = field(init=False, default='output_text')
text: str
@dataclass(frozen=True)
class InputImage(Content):
type: str = field(init=False, default='input_image')
image_url: str = field(default=None)
file_id: str = field(default=None)
def __post_init__(self):
if self.image_url is None and self.file_id is None:
raise ValueError('Either `image_url` or `file_id` must be provided.')
@dataclass(frozen=True)
class UrlCitation(Content):
type: str = field(init=False, default='url_citation')
# To be done
@dataclass(frozen=True)
class FunctionCall(Content):
type: str = field(init=False, default='function_call')
id: str
call_id: str
name: str
arguments: dict
@dataclass(frozen=True)
class FunctionCallOutput(Content):
type: str = field(init=False, default='function_call_output')
call_id: str
output: str
# endregion Content classes
@dataclass(frozen=True)
class Message:
role: str
content: list[Content]
@dataclass(frozen=True)
class Prompt:
model: str
input: list[Message]
@dataclass(frozen=True)
class Response:
output: list[Message]
if __name__ == '__main__':
from openai import OpenAI
client = OpenAI()
test_system_message = Message(role='system', content=[InputText('Talk like an Italian mafia boss.')])
test_user_message = Message(role='user', content=[InputText('Hi! How are you?')])
test_prompt = Prompt(model='gpt-4.1-mini', input=[test_system_message, test_user_message])
print(asdict(test_prompt))
response_raw = client.responses.create(**asdict(test_prompt))
response = Response(**filter_fields(response_raw.to_dict(), Response))
print(asdict(response))
test_prompt.add_message(response.output[0])
test_user_message_2 = Message(role='user', content=[
InputText('Can you tell me what is on this picture?'),
InputImage(image_url='https://upload.wikimedia.org/wikipedia/commons/f/f4/Piet_Mondriaan_-_Sinaasappelen_%28authentiek%29_-_A97_-_Piet_Mondrian%2C_catalogue_raisonn%C3%A9.jpg')
])
test_prompt.add_message(test_user_message_2)
response_raw = client.responses.create(**asdict(test_prompt))
response = Response(**filter_fields(response_raw.to_dict(), Response))
test_prompt.add_message(response.output[0])
print(asdict(test_prompt))
@@ -0,0 +1,65 @@
from dataclasses import dataclass, field, asdict
from datetime import datetime
# region dataclasses
@dataclass(frozen=True)
class Attachment:
content_type: str
filename: str
id: int
size: int
url: str
ephemeral: bool = False
@dataclass(frozen=True)
class Channel:
created_at: datetime
id: int
name: str
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Role:
id: int
name: str
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Member:
bot: bool
created_at: datetime
display_name: str # For regular users this is just their global name or their username, but if they have a guild specific nickname then that is returned instead.
global_name: str # The user's global nickname, taking precedence over the username in display.
id: int
joined_at: datetime
mention: str
name: str # The user's username.
nick: str # The guild specific nickname of the user. Takes precedence over the global name.
roles: list[Role] = field(default_factory=list)
def __str__(self) -> str:
return self.name
@dataclass(frozen=True)
class Message:
author: Member
channel: Channel
created_at: datetime
id: int
attachments: list[Attachment] = field(default_factory=list)
channel_mentions: list[Channel] = field(default_factory=list)
content: str = ''
mentions: list[Member] = field(default_factory=list)
if __name__ == '__main__':
pass
+33 -33
View File
@@ -16,7 +16,6 @@ from .weather import time_now, get_current_weather, get_weather_forecast
from .tools_description import TOOLS
from .debug_stuff import debug
CALLABLE_FUNCTIONS = {
# Dictionary with functions to call.
# You can use globals()[func_name](**args) instead, but that's too implicit.
@@ -71,7 +70,7 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
async def on_message(self, message):
if message.author.bot or not message.guild:
return # Ignore bots and DMs
# ✅ Check if user is blacklisted
if await self.is_blacklisted(message.author):
return # Ignore message if user is explicitly blacklisted
@@ -80,7 +79,6 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
if not (await self.is_admin(message) or await self.has_access(message.author)):
return # Ignore message if user has no permissions
guild = message.guild
channel_id = str(message.channel.id)
user_id = str(message.author.id)
@@ -115,8 +113,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
await message.channel.send(random.choice(["Yes?", "How may I assist?", "You rang?"]))
return
explicit_invocation = True
# ✅ Passive Listening: Check if the message contains relevant keywords
# ✅ Passive Listening: Check if the message contains relevant keywords
elif self.should_reginald_interject(message_content):
prompt = message_content
explicit_invocation = False
@@ -124,11 +122,11 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
else:
return # Ignore irrelevant messages
# ✅ Context Handling: Maintain conversation flow
# ✅ Context Handling: Maintain conversation flow
if memory and memory[-1]["user"] == user_name:
prompt = f"Continuation of the discussion:\n{prompt}"
# ✅ Prepare context messages
# ✅ Prepare context messages
formatted_messages = [{"role": "system", "content": self.get_reginald_persona()}]
if user_profile:
@@ -145,10 +143,10 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
"content": f"[{summary['timestamp']}] Topics: {', '.join(summary['topics'])}\n{summary['summary']}"
})
formatted_messages += [{"role": "user", "content": f"{entry['user']}: {entry['content']}"} for entry in memory]
formatted_messages += [{"role": "user", "content": f"{entry['user']}: {entry['content']}"} for entry in
memory]
formatted_messages.append({"role": "user", "content": f"{user_name}: {prompt}"})
##################################################
# #
## Generate AI Response, put into response_text ##
@@ -166,7 +164,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
memory.append({"user": "Reginald", "content": response_text})
if len(memory) > self.short_term_memory_limit:
summary = await self.summarize_memory(message, memory[:int(self.short_term_memory_limit * self.summary_retention_ratio)])
summary = await self.summarize_memory(message, memory[:int(
self.short_term_memory_limit * self.summary_retention_ratio)])
mid_memory.setdefault(channel_id, []).append({
"timestamp": datetime.datetime.now().strftime("%Y-%m-%d %H:%M"),
"topics": self.extract_topics_from_summary(summary),
@@ -174,20 +173,20 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
})
if len(mid_memory[channel_id]) > self.summary_retention_limit:
mid_memory[channel_id].pop(0)
memory = memory[-(self.short_term_memory_limit - int(self.short_term_memory_limit * self.summary_retention_ratio)):]
memory = memory[-(self.short_term_memory_limit - int(
self.short_term_memory_limit * self.summary_retention_ratio)):]
short_memory[channel_id] = memory
await self.send_split_message(message.channel, response_text)
def should_reginald_interject(self, message_content: str) -> bool:
"""Determines if Reginald should respond to a message based on keywords."""
direct_invocation = {
"reginald,"
}
"reginald,"
}
message_lower = message_content.lower()
return any(message_lower.startswith(invocation) for invocation in direct_invocation)
@debug
@@ -227,8 +226,8 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
'content': func_result,
'tool_call_id': tool_call_id,
})
completion_args["messages"] = messages
completion_args["messages"] = messages
# Second completion required if functions has been called to interpret the result into user-friendly
# chat message.
response = await client.chat.completions.create(**completion_args)
@@ -261,11 +260,12 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
await self.config.guild(ctx.guild).openai_api_key.set(api_key)
await ctx.send("OpenAI API key set successfully.")
@commands.command(name="reginald_set_listening_channel", help="Set the channel where Reginald listens for messages.")
@commands.command(name="reginald_set_listening_channel",
help="Set the channel where Reginald listens for messages.")
@commands.has_permissions(administrator=True)
async def set_listening_channel(self, ctx, channel: discord.TextChannel):
"""Sets the channel where Reginald will listen for passive responses."""
if not channel:
await ctx.send("❌ Invalid channel. Please mention a valid text channel.")
return
@@ -273,12 +273,13 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
await self.config.guild(ctx.guild).listening_channel.set(channel.id)
await ctx.send(f"✅ Reginald will now listen only in {channel.mention}.")
@commands.command(name="reginald_get_listening_channel", help="Check which channel Reginald is currently listening in.")
@commands.command(name="reginald_get_listening_channel",
help="Check which channel Reginald is currently listening in.")
@commands.has_permissions(administrator=True)
async def get_listening_channel(self, ctx):
"""Displays the current listening channel."""
channel_id = await self.config.guild(ctx.guild).listening_channel()
if channel_id:
channel = ctx.guild.get_channel(channel_id)
if channel: # ✅ Prevents crash if channel was deleted
@@ -288,18 +289,17 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
else:
await ctx.send("❌ No listening channel has been set.")
# async def send_long_message(self, ctx, message, prefix: str = ""):
# """Splits and sends a long message to avoid Discord's 2000-character limit."""
# chunk_size = 1900 # Leave some space for formatting
# if prefix:
# prefix_length = len(prefix)
# chunk_size -= prefix_length
#
# for i in range(0, len(message), chunk_size):
# chunk = message[i:i + chunk_size]
# await ctx.send(f"{prefix}{chunk}")
async def send_long_message(self, ctx, message, prefix: str = ""):
"""Splits and sends a long message to avoid Discord's 2000-character limit."""
chunk_size = 1900 # Leave some space for formatting
if prefix:
prefix_length = len(prefix)
chunk_size -= prefix_length
for i in range(0, len(message), chunk_size):
chunk = message[i:i + chunk_size]
await ctx.send(f"{prefix}{chunk}")
async def send_split_message(self, ctx, content: str, prefix: str = ""):
"""
Sends a long message to Discord while ensuring it does not exceed the 2000-character limit.
@@ -351,4 +351,4 @@ class ReginaldCog(PermissionsMixin, BlacklistMixin, MemoryMixin, commands.Cog):
async def setup(bot):
"""✅ Correct async cog setup for Redbot"""
await bot.add_cog(ReginaldCog(bot))
await bot.add_cog(ReginaldCog(bot))