"""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)