Fix prompt and logic work with chat

This commit is contained in:
q 2026-02-28 10:32:31 +03:00
parent 79e581a010
commit ba6bee06e3

View file

@ -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