From ba6bee06e38206bdb20812708472eaa920f66db4 Mon Sep 17 00:00:00 2001 From: q Date: Sat, 28 Feb 2026 10:32:31 +0300 Subject: [PATCH] Fix prompt and logic work with chat --- AI/talk_handler.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/AI/talk_handler.py b/AI/talk_handler.py index 7355db7..10eb24a 100644 --- a/AI/talk_handler.py +++ b/AI/talk_handler.py @@ -57,7 +57,11 @@ SYSTEM_PROMPT = ( ) # Размер контекста — количество сообщений на чат +# Сколько сообщений держим в БД. Нужно для быстрой очистки. _CONTEXT_SIZE = 100 +# Ограничение на общий размер промпта, чтобы системное сообщение не вытеснялось +# при сборке длинной истории (приблизительно ~8k символов ≈ 2k токенов). +_MAX_PROMPT_CHARS = 8_000 # Путь к SQLite базе (берётся из переменной окружения или из config) _DB_PATH = os.getenv("CHAT_HISTORY_DB_PATH", "/db/chat_history.sqlite3") @@ -114,9 +118,18 @@ def _get_history(chat_id: int) -> list[dict]: def _build_messages(chat_id: int, system_prompt: str, current_text: str, current_name: str) -> list: """Собирает список messages для LLM из истории чата.""" messages = [{"role": "system", "content": system_prompt}] - for entry in _get_history(chat_id): + + # Берём историю с конца, пока не превысим бюджет по символам. + history = [] + used = len(system_prompt) + for entry in reversed(_get_history(chat_id)): content = f"{entry['name']}: {entry['text']}" if entry["role"] == "user" else entry["text"] - messages.append({"role": entry["role"], "content": content}) + if used + len(content) > _MAX_PROMPT_CHARS: + break + history.append({"role": entry["role"], "content": content}) + used += len(content) + + messages.extend(reversed(history)) messages.append({"role": "user", "content": f"{current_name}: {current_text}"}) return messages