Files
smeta-web/chat_context.py
anorandClaude Opus 5 1a5af0774c fix(отказы): один след на отказ, память диалога не забивается служебными записями
Разбор плана и рецензентов вскрыл, что первая правка делала хуже: отбитый вопрос сохранялся
репликой человека, а значит попадал в память диалога (модель отвечала бы на непринятые
вопросы), вытеснял оттуда настоящий разговор и снова двигал время в списке диалогов.

Теперь отказ — одна служебная запись с текстом вопроса внутри. Через это же место проходят
все отказы человеку: суточный предел, слишком частые обращения (текст переведён на русский —
с 08.09 человек читает ответ сервера) и слишком длинное сообщение. Сбой записи не превращает
отказ в поломку.

Память диалога отбирает роли прямо в запросе: у человека с десятками отметок о загрузках
настоящие реплики вылетали из окна целиком. История отдаётся целиком и человеку, и оператору,
но уважает запрошенное число записей — страница при запуске просит одну.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RuEU1u9Rz24zmoy9TuvWc2
2026-09-08 22:02:00 +10:00

62 lines
2.4 KiB
Python

"""Conversation context from persisted history — single source of truth.
Both engines (Claude CLI agent + GLM Q&A) reconstruct prior-turn context from
the DB `messages` table on every request, instead of per-process in-memory
stores that fragment when the router switches engines mid-dialog and vanish on
every server restart/deploy. The DB already persists every turn of both engines
(via main._stream_and_save), so reading it back unifies the two paths and
survives restarts.
"""
from db import get_history
MAX_TURNS = 16 # recent messages fed back as context
MAX_CHARS_PER_MSG = 4000 # cap long estimate tables so the prompt stays bounded
def _recent(username: str, tab_id: str) -> list[dict]:
"""Prior turns, oldest→newest, WITHOUT the just-saved current user message.
main._stream_and_save() persists the live user message before streaming, so
it is the last row — drop it to avoid feeding the question back as history.
"""
# Только реплики: служебные записи (загрузки, отказы) иначе съедают окно памяти.
rows = get_history(username, tab_id, limit=MAX_TURNS + 1, roles=("user", "assistant"))
if rows and rows[-1].get("role") == "user":
rows = rows[:-1]
return rows[-MAX_TURNS:]
def history_messages(username: str, tab_id: str) -> list[dict]:
"""Prior turns as OpenAI-style messages[] for the GLM API.
System rows (file-upload notices) are skipped — the GLM API takes one
leading system prompt, and current file content is injected fresh per turn.
"""
out = []
for r in _recent(username, tab_id):
role = r.get("role")
if role not in ("user", "assistant"):
continue
content = (r.get("content") or "")[:MAX_CHARS_PER_MSG]
if content:
out.append({"role": role, "content": content})
return out
def history_recap(username: str, tab_id: str) -> str:
"""Prior turns as a readable block prepended to the Claude agent prompt."""
lines = []
for r in _recent(username, tab_id):
role = r.get("role")
if role == "user":
who = "Пользователь"
elif role == "assistant":
who = "Ассистент"
else:
continue
content = (r.get("content") or "")[:MAX_CHARS_PER_MSG]
if content:
lines.append(f"{who}: {content}")
return "\n\n".join(lines)