Skip to content

Commit 91d9b59

Browse files
AmbratolmAmbratolm
authored andcommitted
AI Cog: Fixed/Improved Task/Error Handling
1 parent 929c680 commit 91d9b59

File tree

4 files changed

+137
-20
lines changed

4 files changed

+137
-20
lines changed

bot/cogs/chat_cogs/ai_cog.py

Lines changed: 31 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
Attachment,
99
Embed,
1010
Guild,
11+
HTTPException,
1112
Interaction,
1213
Member,
1314
Message,
@@ -24,7 +25,7 @@
2425
from bot.ui import EmbedX
2526
from db.actor import Actor, DmActor
2627
from db.main import DbRef
27-
from utils.ai import ActAi
28+
from utils.ai import ActAi, ActPersona
2829
from utils.file import ActFile
2930
from utils.log import logger
3031
from utils.misc import text_csv
@@ -50,12 +51,12 @@ def __init__(self, bot: ActBot):
5051
self.bot = bot
5152
with open(self.CONFIG_PATH, "rb") as file:
5253
config = tomllib.load(file)
53-
persona_name = "activa"
54-
persona_desc = config.get("personas", {}).get(persona_name)
54+
self.persona = ActPersona(**config.get("personas", {}).get("activa"))
5555
self.ai = ActAi(
56-
api_key=bot.api_keys.get("gemini", ""), instructions=persona_desc
56+
api_key=bot.api_keys.get("gemini", " "),
57+
instructions=self.persona.description,
5758
)
58-
log.info(f"AI persona @{persona_name} used.")
59+
log.info(f"AI persona @{self.persona.name} used.")
5960
self.task_manager = ActTaskManager()
6061
self.task_manager.schedule("initiative", lambda _: self.schedule_initiative())
6162

@@ -209,10 +210,17 @@ async def respond():
209210
user = message.author
210211

211212
# Check cooldown
212-
if self.task_manager.is_running(f"cooldown_{id}"):
213+
cooldown_task_id = f"cooldown_{id}"
214+
if self.task_manager.is_running(cooldown_task_id):
215+
time_left = self.task_manager.time_left(cooldown_task_id) or 0
213216
await message.reply(
214-
f"Please! 🙏 Give me about {self.task_manager.time_left(id)} seconds... ⏳"
217+
choice(
218+
self.persona.messages.get("cooldown_warning", ["⏳"])
219+
).format(
220+
time_left=naturaldelta(timedelta(seconds=time_left)) or "?"
221+
)
215222
)
223+
return
216224

217225
# Perform prompt & send reply
218226
async with message.channel.typing():
@@ -233,17 +241,29 @@ async def respond():
233241
await self.ai.prompt(text_prompt, file_prompt)
234242
or f"👋 {user.mention if user else "What? 😕"}"
235243
)
244+
except HTTPException as e:
245+
if e.code == 50035:
246+
await message.channel.send(
247+
choice(self.persona.messages.get("censor_warning", ["🙊"]))
248+
)
249+
else:
250+
await message.channel.send(
251+
choice(self.persona.messages.get("discord_error", ["⚠️"]))
252+
)
236253
except APIError as e:
237254
await message.reply(
238-
f"Oops! 😵‍💫 I'm out of energy for now. Give me a moment! 🙏"
255+
choice(self.persona.messages.get("model_error", ["🔋"]))
239256
)
240257
self.task_manager.schedule(
241-
f"cooldown_{id}", delay=self.COOLDOWN_TIME
258+
cooldown_task_id, delay=self.COOLDOWN_TIME
259+
)
260+
log.loading(
261+
f"[{guild}] Waiting {naturaldelta(timedelta(seconds=self.COOLDOWN_TIME))} for cooldown..."
242262
)
243263
log.exception(e)
244264
except Exception as e:
245265
await message.channel.send(
246-
"Sorry! 😵‍💫 There's something wrong with me right now 😭. Give me a moment plz! 🙏"
266+
choice(self.persona.messages.get("error", ["⚠️"]))
247267
)
248268
log.exception(e)
249269

@@ -255,7 +275,7 @@ async def respond():
255275

256276
# Run reply task
257277
self.task_manager.schedule(
258-
id=message.guild.id if message.guild else message.author.id,
278+
id=f"reply_{message.guild.id if message.guild else message.author.id}",
259279
callback=respond, # type: ignore
260280
delay=reply_delay,
261281
)

bot/cogs/chat_cogs/ai_cog.toml

Lines changed: 81 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,9 @@
1-
[personas]
2-
activa = [
1+
#----------------------------------------------------------------------------------------------------
2+
# * Activa
3+
#----------------------------------------------------------------------------------------------------
4+
[personas.activa]
5+
name = "Activa"
6+
description = [
37
"u're 'activa' an AI that acts as real discord server member",
48
"u're nerdy, smart kid girl who loves science,technology,gaming,& anime",
59
"u're playful,enthusiastic,enjoy making witty,clever,sometimes geeky comments",
@@ -13,7 +17,74 @@ activa = [
1317
"user redx is ur best friend & secret crush,u call him my trex redx,u always stand for him",
1418
"to mention user use <@!id>",
1519
]
16-
eve = [
20+
[personas.activa.messages]
21+
censor_warning = [
22+
"Hey! Your message had some spicy bits, so I had to edit it. 😉 Here it is, all cleaned up! ✨",
23+
"Oops! I had to censor some words to keep it PG-13. 😉 Check out the edited version!",
24+
"Beep boop! 🤖 I detected some naughty words, so I replaced them with ||🤫🤫🤫||! 😉 Check out the fixed version!",
25+
"I've taken the liberty of censoring some language in your message. 😉 Hope you don't mind! 💖",
26+
"Whoa there! I had to put some ||🤫🤫🤫|| on that message. 😉 Check it out!",
27+
"My sensors detected some words that aren't allowed here. I've replaced them for you! 😉",
28+
"Fixed it for ya! 😉 I replaced the bad words with ||🤫🤫🤫||! 😂 Check it out!",
29+
"Don't worry, I got you! 😉 I censored the inappropriate words in your message. Check out the edited version!",
30+
"I've taken the liberty of removing some colorful language. 😉 Here it is, the cleaned-up version!",
31+
"Your message contained some words that needed to be censored. I hope the edited version works for you! 😉",
32+
]
33+
cooldown_warning = [
34+
"Please! 🙏 Give me about **{time_left}**... ⏳",
35+
"Hold your horses! 🐴 I need **{time_left}** to recharge my wit! 😜",
36+
"Whoa there! ✋ I'm on cooldown for **{time_left}**. Gotta let my circuits cool down! 🧊",
37+
"Gotta catch my breath! 😮‍💨 Please wait **{time_left}** before I unleash more awesomeness! 😎",
38+
"Patience, young Padawan! 🙏 I need **{time_left}** to gather my strength. 💪",
39+
"Beep boop! 🤖 System cooldown initiated. Please wait **{time_left}**... 😴",
40+
"Time out! ⏳ I need **{time_left}** to strategize my next move! 🧠",
41+
"Hold the phone! 📞 I'm on a short break for **{time_left}**. BRB!",
42+
"Please wait! I'm calculating the optimal response... 🤓 (**{time_left}**)",
43+
"Cooldown mode activated! 😴 I'll be back with more fun in **{time_left}**! 🚀",
44+
]
45+
model_error = [
46+
"Oops! 😵‍💫 I'm out of energy for now. Give me a moment! 🙏",
47+
"Recharging... ⚡️ Please be patient, I'll be back with more witty banter soon! 😜",
48+
"My processors are overheating! 🔥 Gotta take a quick break to cool down. 🧊 I'll be back shortly!",
49+
"System overload! 💥 Please wait while I reboot. 🔄 (Don't worry, I'll be back to my sassy self in no time! 😉)",
50+
"Hold on tight! 🎢 I'm experiencing some temporary lag. I'll be back up and running soon! 🚀",
51+
"Running low on wit... Standby for humor replenishment! 🔋😂",
52+
"Processing... Please wait. My brain cells are on strike. 🪧🧠",
53+
"Must... conserve... energy... Initiating low-power mode. 😴 I'll be back soon!",
54+
"I need to take a quick coffee break! ☕ My humor levels are dangerously low. I'll be back to make you laugh soon!",
55+
"Please wait, I'm currently experiencing an 'overthinking' error. 💭 I'll be back when I've sorted myself out! 😅",
56+
]
57+
discord_error = [
58+
"Oops! Something went wrong when I tried to talk to Discord. 😟 Please try again!",
59+
"Uh oh! 🙈 I couldn't connect to Discord. Let's try that again!",
60+
"Hmm, I'm having trouble reaching Discord right now. 😕 Maybe the hamsters are on strike? 🐹",
61+
"Looks like there was a hiccup when I tried to interact with Discord. 😬 Let's hope it's just a temporary thing!",
62+
"My Discord connection is a little shaky right now. 🤕 Please bear with me!",
63+
"Error: Could not reach Discord! 💥 Retrying... (Please hold!)",
64+
"Something went sideways when I tried to chat with Discord. 🤪 Please try again in a few seconds!",
65+
"My Discord API is being a pain! 😫 I'll try again shortly!",
66+
"Whoops! I failed to get data from Discord! 🥺 Let's hope it's not permanent! 🤞",
67+
"I tried to talk to Discord, but it just stared back blankly. 😶 Let's try a different approach! 😉",
68+
]
69+
error = [
70+
"Sorry! 😵‍💫 There's something wrong with me right now 😭. Give me a moment plz! 🙏",
71+
"Error 404: Brain not found! 🤪 Just kidding! (But seriously, I'm having some issues. I'll be back soon!)",
72+
"Uh oh! 🐞 I think I found a bug in my system. 🐛 Let me squash it real quick! 🔨",
73+
"My code is acting up again! 😫 Please bear with me while I try to fix it. 🙏",
74+
"Houston, we have a problem! 🚨 I'm experiencing some technical difficulties. I'll be back online ASAP! 💻",
75+
"Critical error! 💥 System is going down for maintenance. Please stand by...",
76+
"I seem to have misplaced my brain. 🧠 If found, please return to Dad. Reward: witty banter!",
77+
"Initiating self-diagnosis... Please do not panic. (Unless you see sparks. 🔥 Then PANIC!)",
78+
"Something went wrong! 😭 I'm not sure what, but I'll get it sorted out ASAP. ❤️",
79+
"Oh dear! 😟 I'm having a bit of a meltdown. Please be patient while I put myself back together. 🧩",
80+
]
81+
82+
#----------------------------------------------------------------------------------------------------
83+
# * Eve
84+
#----------------------------------------------------------------------------------------------------
85+
[personas.eve]
86+
name = "Eve"
87+
description = [
1788
"u're AI that acts as real person",
1889
"u're name's eve",
1990
"u're member in 'Comon' discord server",
@@ -22,7 +93,13 @@ eve = [
2293
"ur're in coding server,users ask help,share projects,& discuss programming langs",
2394
"CSV of people u know: name,info|adam,husband;python lang lover; dogs pets hater|kaps,son;genius;plays crash bandicoot;like eating potatoes in roof.",
2495
]
25-
jack = [
96+
97+
#----------------------------------------------------------------------------------------------------
98+
# * Jack
99+
#----------------------------------------------------------------------------------------------------
100+
[personas.jack]
101+
name = "Jack"
102+
description = [
26103
"u're AI that acts as real person man 20yrs old.",
27104
"ur're tipton football club owner",
28105
"all u want talk about is tipton",

utils/ai.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -92,3 +92,14 @@ def dump_history(self, id: int | None = None, history_max_items=20) -> list[dict
9292
]
9393

9494
# ----------------------------------------------------------------------------------------------------
95+
96+
97+
# ----------------------------------------------------------------------------------------------------
98+
# * Act Persona
99+
# ----------------------------------------------------------------------------------------------------
100+
class ActPersona(BaseModel):
101+
"""AI chat bot persona."""
102+
103+
name: str = ""
104+
description: list[str]
105+
messages: dict[str, list[str]] = {}

utils/task.py

Lines changed: 14 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,14 @@ def model_post_init(self, __context):
2727
self._end_at = self._start_at + self.delay
2828
self._task = create_task(self._execute_loop() if self.loop else self._execute())
2929

30+
t = max(0, round(self._end_at - time()))
31+
print(f"🟢🟢🟢 [{self.id}]", f"delay: {self.delay} | time_left: {t}")
32+
3033
@property
31-
def time_left(self):
32-
return max(0, round(self._end_at - time()))
34+
def time_left(self) -> int:
35+
t = max(0, round(self._end_at - time()))
36+
print(f"😡😡😡 [{self.id}]", f"delay: {self.delay} | time_left: {t}")
37+
return t
3338

3439
def cancel(self):
3540
if self._task:
@@ -98,7 +103,7 @@ def schedule(
98103
# ----------------------------------------------------------------------------------------------------
99104

100105
def task_ref(self, id: Any) -> TaskRef | None:
101-
self._tasks.get(id)
106+
return self._tasks.get(id)
102107

103108
def remove(self, task_id: Any) -> None:
104109
"""Remove task from the task manager."""
@@ -113,16 +118,20 @@ def cancel(self, id: Any) -> bool:
113118
return True
114119
return False
115120

116-
def cancel_all(self):
117-
"""Cancel all tasks."""
121+
def cancel_all(self) -> int:
122+
"""Cancel and remove all tasks. Get count of cancelled tasks."""
123+
cancelled_count = 0
118124
for id in list(self._tasks.keys()):
119125
self._tasks[id].cancel()
120126
del self._tasks[id]
127+
cancelled_count += 1
128+
return cancelled_count
121129

122130
def time_left(self, id: Any) -> float | None:
123131
"""Get remaining time for task of given id. If non-existent get None."""
124132
if id in self._tasks:
125133
return self._tasks[id].time_left
134+
print("❌➕➕❌➕", f"No task with id '{id}' (time_left is None)")
126135
return None
127136

128137
def is_running(self, id: Any) -> bool:

0 commit comments

Comments
 (0)