fix: контекст диалога из БД — единый источник для обоих движков
Агент терял контекст: история жила в двух in-memory хранилищах (Claude --resume / GLM _conversations), которые расщеплялись при переключении движков в одной вкладке и обнулялись при рестарте/деплое. Теперь оба движка реконструируют историю из таблицы messages, которую сервер и так пишет для обоих путей (chat_context — единый источник истины). - chat_context.py: history_messages (GLM messages[]) / history_recap (Claude) - GLM-путь: prior из БД вместо in-memory _conversations - Claude-путь: recap-префикс из БД вместо хрупкого --resume - reset/clear-files теперь чистят историю и в БД - tests/test_chat_context.py: cross-engine видимость + исключение текущего хода Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""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)
|
||||
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)
|
||||
Reference in New Issue
Block a user