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:
+17
-19
@@ -19,9 +19,12 @@ ZAI_BASE_URL = os.environ.get("ZAI_BASE_URL", "https://open.bigmodel.cn/api/codi
|
||||
ZAI_MODEL = os.environ.get("ZAI_MODEL", "glm-5.1")
|
||||
DATA_DIR = Path(os.environ.get("DATA_DIR", "./smeta-web-data"))
|
||||
|
||||
# Session tracking: (username, tab_id) -> conversation history
|
||||
from chat_context import history_messages
|
||||
|
||||
# Legacy in-memory map — kept only so clear_session() stays a no-op safe call.
|
||||
# Conversation context now comes from the DB (see chat_context), which both
|
||||
# engines share and which survives server restarts.
|
||||
_conversations: dict[tuple[str, str], list[dict]] = {}
|
||||
MAX_HISTORY = 20 # keep last N messages
|
||||
|
||||
# Preload CAG context and resources
|
||||
_cag_context = ""
|
||||
@@ -373,12 +376,11 @@ async def stream_claude(
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Stream GLM-5 response with CAG context."""
|
||||
_load_smeta_data()
|
||||
key = (username, tab_id)
|
||||
|
||||
# Build conversation history
|
||||
if key not in _conversations:
|
||||
_conversations[key] = []
|
||||
history = _conversations[key]
|
||||
# Prior turns from the DB — shared source of truth across both engines,
|
||||
# so a question like "а какой там НР?" still resolves even when the
|
||||
# previous turn was handled by the Claude agent path.
|
||||
prior = history_messages(username, tab_id)
|
||||
|
||||
work_dir = get_work_dir(username, tab_id)
|
||||
|
||||
@@ -468,14 +470,12 @@ async def stream_claude(
|
||||
if normative_context:
|
||||
user_content += f"\n\n[{normative_context}]"
|
||||
|
||||
history.append({"role": "user", "content": user_content})
|
||||
|
||||
# Trim history
|
||||
if len(history) > MAX_HISTORY:
|
||||
history[:] = history[-MAX_HISTORY:]
|
||||
|
||||
# Prepare messages
|
||||
messages = [{"role": "system", "content": _build_system_prompt()}] + history
|
||||
# Prepare messages: system prompt + prior turns (DB) + current question
|
||||
messages = (
|
||||
[{"role": "system", "content": _build_system_prompt()}]
|
||||
+ prior
|
||||
+ [{"role": "user", "content": user_content}]
|
||||
)
|
||||
|
||||
# Stream from GLM API
|
||||
full_response = ""
|
||||
@@ -531,10 +531,8 @@ async def stream_claude(
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Save assistant response to history
|
||||
if full_response:
|
||||
history.append({"role": "assistant", "content": full_response})
|
||||
|
||||
# Assistant response is persisted to the DB by main._stream_and_save —
|
||||
# no separate in-memory history to maintain here.
|
||||
yield f"event: done\ndata: {json.dumps({'result': full_response}, ensure_ascii=False)}\n\n"
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user