Compare commits

..

2 commits

4 changed files with 13 additions and 13 deletions

View file

@ -24,7 +24,7 @@ from database import BasicDatabase
OPENROUTER_X_TITLE = "TG/VK Chat Bot"
OPENROUTER_HTTP_REFERER = "https://ultracoder.org"
GROUP_CHAT_MAX_MESSAGES = 20
GROUP_CHAT_MAX_MESSAGES = 40
PRIVATE_CHAT_MAX_MESSAGES = 40
MAX_OUTPUT_TOKENS = 500

View file

@ -121,8 +121,8 @@ class BasicDatabase:
def context_get_messages(self, bot_id: int, chat_id: int) -> list[dict]:
self.cursor.execute("""
SELECT role, text, image FROM contexts
WHERE bot_id = ? AND chat_id = ? AND message_id IS NOT NULL
ORDER BY message_id
WHERE bot_id = ? AND chat_id = ?
ORDER BY id
""", bot_id, chat_id)
return self._to_dict(self.cursor.fetchall())
@ -133,8 +133,8 @@ class BasicDatabase:
def context_get_last_assistant_message_id(self, bot_id: int, chat_id: int) -> Optional[int]:
return self.cursor.execute("""
SELECT message_id FROM contexts
WHERE bot_id = ? AND chat_id = ? AND role = 'assistant' AND message_id IS NOT NULL
ORDER BY message_id DESC
WHERE bot_id = ? AND chat_id = ? AND role = 'assistant'
ORDER BY id DESC
LIMIT 1
""", bot_id, chat_id).fetchval()
@ -167,16 +167,12 @@ class BasicDatabase:
def _context_trim(self, bot_id: int, chat_id: int, max_messages: int):
current_count = self.context_get_count(bot_id, chat_id)
while current_count >= max_messages:
oldest_message_id = self.cursor.execute("""
SELECT message_id FROM contexts
WHERE bot_id = ? AND chat_id = ? AND message_id IS NOT NULL
ORDER BY message_id ASC
LIMIT 1
""", bot_id, chat_id).fetchval()
oldest_message_id = self.cursor.execute(
"SELECT id FROM contexts WHERE bot_id = ? AND chat_id = ? ORDER BY id LIMIT 1",
bot_id, chat_id).fetchval()
if oldest_message_id:
self.cursor.execute("DELETE FROM contexts WHERE bot_id = ? AND chat_id = ? AND message_id = ?",
bot_id, chat_id, oldest_message_id)
self.cursor.execute("DELETE FROM contexts WHERE id = ?", oldest_message_id)
current_count -= 1
else:
break

View file

@ -44,12 +44,14 @@ class TgDatabase(database.BasicDatabase):
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS contexts (
id BIGINT NOT NULL auto_increment,
bot_id BIGINT NOT NULL,
chat_id BIGINT NOT NULL,
message_id BIGINT,
role VARCHAR(16) NOT NULL,
text VARCHAR(4000),
image MEDIUMBLOB,
PRIMARY KEY (id),
CONSTRAINT fk_contexts_chats FOREIGN KEY (bot_id, chat_id) REFERENCES chats (bot_id, chat_id) ON UPDATE CASCADE ON DELETE CASCADE)
""")

View file

@ -47,12 +47,14 @@ class VkDatabase(database.BasicDatabase):
self.cursor.execute("""
CREATE TABLE IF NOT EXISTS contexts (
id BIGINT NOT NULL auto_increment,
bot_id BIGINT NOT NULL,
chat_id BIGINT NOT NULL,
message_id BIGINT,
role VARCHAR(16) NOT NULL,
text VARCHAR(4000),
image MEDIUMBLOB,
PRIMARY KEY (id),
CONSTRAINT fk_contexts_chats FOREIGN KEY (bot_id, chat_id) REFERENCES chats (bot_id, chat_id) ON UPDATE CASCADE ON DELETE CASCADE)
""")