forked from zovos/bot_tg
Fix prompt and logic work with chat
This commit is contained in:
parent
79e581a010
commit
ba6bee06e3
1 changed files with 15 additions and 2 deletions
|
|
@ -57,7 +57,11 @@ SYSTEM_PROMPT = (
|
||||||
)
|
)
|
||||||
|
|
||||||
# Размер контекста — количество сообщений на чат
|
# Размер контекста — количество сообщений на чат
|
||||||
|
# Сколько сообщений держим в БД. Нужно для быстрой очистки.
|
||||||
_CONTEXT_SIZE = 100
|
_CONTEXT_SIZE = 100
|
||||||
|
# Ограничение на общий размер промпта, чтобы системное сообщение не вытеснялось
|
||||||
|
# при сборке длинной истории (приблизительно ~8k символов ≈ 2k токенов).
|
||||||
|
_MAX_PROMPT_CHARS = 8_000
|
||||||
# Путь к SQLite базе (берётся из переменной окружения или из config)
|
# Путь к SQLite базе (берётся из переменной окружения или из config)
|
||||||
_DB_PATH = os.getenv("CHAT_HISTORY_DB_PATH", "/db/chat_history.sqlite3")
|
_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:
|
def _build_messages(chat_id: int, system_prompt: str, current_text: str, current_name: str) -> list:
|
||||||
"""Собирает список messages для LLM из истории чата."""
|
"""Собирает список messages для LLM из истории чата."""
|
||||||
messages = [{"role": "system", "content": system_prompt}]
|
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"]
|
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}"})
|
messages.append({"role": "user", "content": f"{current_name}: {current_text}"})
|
||||||
return messages
|
return messages
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue