chore(checkpoint): save working state before clean state context refactoring
This commit is contained in:
@@ -6,7 +6,7 @@ MODULE: web_api / llm (Core Agent & Function Calling Dispatcher)
|
||||
ROLE: Главный оркестратор взаимодействия с Ollama LLM (Qwen 2.5), разбор вызовов
|
||||
инструментов (Function Calling), интеграция с декларативным реестром
|
||||
действий SQLite (tool_action_registry), детерминированный Fast-Path
|
||||
для подтверждений, динамические кнопки и автоочистка эфемерных сообщений.
|
||||
для подтверждений, отслеживание Topic Drift и Context Guard с кнопками.
|
||||
===============================================================================
|
||||
"""
|
||||
|
||||
@@ -32,9 +32,10 @@ from .db_tools import (
|
||||
db_get_rules,
|
||||
db_set_session_state,
|
||||
db_get_session_state,
|
||||
db_clear_session_state,
|
||||
db_increment_session_idle,
|
||||
db_get_snapshots,
|
||||
db_delete_snapshots,
|
||||
db_clear_session_state,
|
||||
db_get_current_server_time,
|
||||
db_save_chat_message,
|
||||
db_get_chat_history,
|
||||
@@ -78,9 +79,10 @@ def process_chat_message(
|
||||
Главный конвейер обработки входящего сообщения:
|
||||
1. Fast-Path перехват подтверждений/отмен при активном session_state.
|
||||
2. Перехват завершения работы ('нет, закончить настройку') с автоочисткой эфемерных сообщений.
|
||||
3. Формирование системного контекста и вызов Ollama.
|
||||
3. Формирование системного контекста с учетом активного действия (черновика).
|
||||
4. Выполнение вызванного Tool и опрос Data-Driven реестра действий.
|
||||
5. Возврат кортежа: (reply_text, chat_history, action_metadata).
|
||||
5. Проверка счетчика отвлечений (idle_turns) и Context Guard на 3-м шаге.
|
||||
6. Возврат кортежа: (reply_text, chat_history, action_metadata).
|
||||
"""
|
||||
logger.info(f"Получено сообщение от user_id={user_id}, session_id={session_id}: {user_message}")
|
||||
|
||||
@@ -96,7 +98,7 @@ def process_chat_message(
|
||||
if user_msg_clean in ["нет, спасибо", "нет, закончить настройку", "закончить настройку", "завершить", "нет"]:
|
||||
db_clear_session_state(session_id)
|
||||
deleted_count = db_purge_ephemeral_messages(session_id)
|
||||
logger.info(f"🧹 Завершена работа с инструментом. Удалено эфемерных сообщений: {deleted_count}")
|
||||
logger.info(f"Завершена работа с инструментом. Удалено эфемерных сообщений: {deleted_count}")
|
||||
|
||||
reply_text = "Хорошо. Настройка завершена, контекст диалога чист. Чем я могу помочь дальше?"
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=0)
|
||||
@@ -104,15 +106,23 @@ def process_chat_message(
|
||||
|
||||
# --- [FAST-PATH 2: ПЕРЕХВАТ ПОДТВЕРЖДЕНИЯ / ОТМЕНЫ ПРЕВЬЮ ПРОМПТА] ---
|
||||
if session_state and session_state.get("state_type") == "PROMPT_PREVIEW":
|
||||
draft_text = ""
|
||||
if session_state.get("data_json") and isinstance(session_state["data_json"], dict):
|
||||
draft_text = session_state["data_json"].get("draft_text", "")
|
||||
else:
|
||||
draft_text = session_state.get("pending_data", "")
|
||||
|
||||
if user_msg_clean in ["подтверждаю", "подтвердить", "да", "сохранить", "применить", "ок", "хорошо"]:
|
||||
db_add_system_prompt("main_agent", session_state.get("pending_data", ""))
|
||||
db_add_system_prompt("main_agent", draft_text)
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
action_cfg = db_get_tool_action("db_confirm_prompt_preview")
|
||||
reply_text = action_cfg["success_template"] if action_cfg else "✅ Системный промпт успешно сохранен и применен в базе данных."
|
||||
reply_text = action_cfg["success_template"] if action_cfg else "Системный промпт успешно сохранен и применен в базе данных."
|
||||
if action_cfg and action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -124,10 +134,12 @@ def process_chat_message(
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
action_cfg = db_get_tool_action("db_cancel_prompt_preview")
|
||||
reply_text = action_cfg["success_template"] if action_cfg else "❌ Изменения системного промпта отменены."
|
||||
reply_text = action_cfg["success_template"] if action_cfg else "Изменения системного промпта отменены."
|
||||
if action_cfg and action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
|
||||
db_save_chat_message(session_id, "user", full_user_content, is_ephemeral=1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -146,12 +158,23 @@ def process_chat_message(
|
||||
calendar_context = get_dynamic_calendar_context()
|
||||
user_info = f"Пользователь ID={user_id}" if user_id != 0 else "Гость"
|
||||
|
||||
# Информируем модель о наличии незавершенного действия в сессии
|
||||
active_state_context = ""
|
||||
if session_state and session_state.get("state_type") == "PROMPT_PREVIEW":
|
||||
active_state_context = (
|
||||
"\n[АКТИВНОЕ ДЕЙСТВИЕ В СЕССИИ]\n"
|
||||
"В данный момент оператор рассматривает подготовленный черновик системного промпта.\n"
|
||||
"- Если оператор просит продолжить правки или уточняет детали по черновику — продолжай работу с ним.\n"
|
||||
"- Если оператор переключился на другую тему или вызвал другой инструмент — выполни его команду штатно.\n"
|
||||
)
|
||||
|
||||
system_prompt_content = (
|
||||
f"Ты — интеллектуальный ассистент SCUD Orion AI. "
|
||||
f"Ты управляешь задачами, аналитикой СКУД и системными настройками с помощью инструментов (tools).\n\n"
|
||||
f"[ОКРУЖЕНИЕ]\n"
|
||||
f"- Пользователь: {user_info}\n"
|
||||
f"- {calendar_context}\n\n"
|
||||
f"- {calendar_context}\n"
|
||||
f"{active_state_context}\n"
|
||||
f"[ПРАВИЛА ИСПОЛЬЗОВАНИЯ ИНСТРУМЕНТОВ]\n"
|
||||
f"1. Для любых изменений системного промпта (добавить, удалить, изменить пункт) ВСЕГДА вызывай функцию db_preview_prompt_merge(prompt_text=...).\n"
|
||||
f"2. Для просмотра системного промпта ВСЕГДА вызывай db_get_system_prompt().\n"
|
||||
@@ -213,14 +236,20 @@ def process_chat_message(
|
||||
for tool in tool_calls:
|
||||
fn_name = tool["function"]["name"]
|
||||
fn_args = tool["function"].get("arguments", {})
|
||||
logger.info(f"🚀 Вызов функции (Tool): {fn_name} с аргументами: {fn_args}")
|
||||
logger.info(f"Вызов функции (Tool): {fn_name} с аргументами: {fn_args}")
|
||||
tool_result_content = ""
|
||||
|
||||
action_cfg = db_get_tool_action(fn_name)
|
||||
|
||||
if fn_name == "db_confirm_prompt_preview":
|
||||
if session_state and session_state.get("state_type") == "PROMPT_PREVIEW":
|
||||
db_add_system_prompt("main_agent", session_state.get("pending_data", ""))
|
||||
draft_text = ""
|
||||
if session_state.get("data_json") and isinstance(session_state["data_json"], dict):
|
||||
draft_text = session_state["data_json"].get("draft_text", "")
|
||||
else:
|
||||
draft_text = session_state.get("pending_data", "")
|
||||
|
||||
db_add_system_prompt("main_agent", draft_text)
|
||||
db_clear_session_state(session_id)
|
||||
|
||||
if action_cfg and action_cfg.get("bypass_llm"):
|
||||
@@ -228,6 +257,7 @@ def process_chat_message(
|
||||
if action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
is_eph = action_cfg.get("is_ephemeral", 1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=is_eph)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -236,7 +266,7 @@ def process_chat_message(
|
||||
}
|
||||
tool_result_content = json.dumps({"status": "success"}, ensure_ascii=False)
|
||||
else:
|
||||
err_reply = "⚠️ Нет активного превью для подтверждения."
|
||||
err_reply = "Нет активного превью для подтверждения."
|
||||
db_save_chat_message(session_id, "assistant", err_reply, is_ephemeral=1)
|
||||
return err_reply, db_get_chat_history(session_id), None
|
||||
|
||||
@@ -247,6 +277,7 @@ def process_chat_message(
|
||||
if action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
is_eph = action_cfg.get("is_ephemeral", 1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=is_eph)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -283,6 +314,7 @@ def process_chat_message(
|
||||
reply_text = action_cfg["success_template"]
|
||||
if action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
is_eph = action_cfg.get("is_ephemeral", 1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=is_eph)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -303,7 +335,7 @@ def process_chat_message(
|
||||
current_prompt = db_get_active_system_prompt()
|
||||
user_msg_lower = user_message.lower()
|
||||
|
||||
# 1. ОБРАБОТКА УДАЛЕНИЯ ПУНКТА
|
||||
# 1. Обработка удаления пункта
|
||||
if any(w in user_msg_lower for w in ["удали", "стереть", "убрать", "вырежи", "удалить"]):
|
||||
target_num_match = re.search(r'\d+(\.\d+)*', user_message)
|
||||
target_num = target_num_match.group(0) if target_num_match else ""
|
||||
@@ -315,7 +347,7 @@ def process_chat_message(
|
||||
new_lines = lines
|
||||
proposed_text = "\n".join(new_lines)
|
||||
|
||||
# 2. ОБРАБОТКА ДОБАВЛЕНИЯ / ИЗМЕНЕНИЯ ПУНКТА
|
||||
# 2. Обработка добавления / изменения пункта
|
||||
elif proposed_text:
|
||||
if len(proposed_text) < 500:
|
||||
clean_item = proposed_text.strip()
|
||||
@@ -336,7 +368,13 @@ def process_chat_message(
|
||||
new_lines.append(f" {clean_item}")
|
||||
proposed_text = "\n".join(new_lines)
|
||||
|
||||
db_set_session_state(session_id, "PROMPT_PREVIEW", proposed_text)
|
||||
# Сохраняем черновик в структурированном виде с idle_turns = 0
|
||||
state_payload = {
|
||||
"draft_text": proposed_text,
|
||||
"idle_turns": 0
|
||||
}
|
||||
db_set_session_state(session_id, "PROMPT_PREVIEW", state_payload)
|
||||
|
||||
preview_reply = (
|
||||
f"Ваше изменение успешно предпросмотрено. Полный обновленный системный промпт теперь выглядит так:\n\n"
|
||||
f"{proposed_text}\n\n"
|
||||
@@ -368,6 +406,7 @@ def process_chat_message(
|
||||
reply_text = action_cfg["success_template"]
|
||||
if action_cfg.get("follow_up_question"):
|
||||
reply_text += f"\n\n{action_cfg['follow_up_question']}"
|
||||
reply_text = reply_text.replace("✅", "").replace("❌", "").replace("**", "").replace("*", "").strip()
|
||||
is_eph = action_cfg.get("is_ephemeral", 1)
|
||||
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=is_eph)
|
||||
return reply_text, db_get_chat_history(session_id), {
|
||||
@@ -378,20 +417,54 @@ def process_chat_message(
|
||||
|
||||
messages.append({"role": "tool", "content": tool_result_content})
|
||||
|
||||
# --- [SECTION 7: SECONDARY LLM PASS] --- # ANCHOR[SECONDARY_PASS]
|
||||
# --- [SECTION 7: SECONDARY LLM PASS & CONTEXT GUARD] --- # ANCHOR[SECONDARY_PASS]
|
||||
second_payload = {"model": TEXT_MODEL, "messages": messages, "stream": False, "options": llm_options}
|
||||
sec_req = urllib.request.Request(OLLAMA_URL, data=json.dumps(second_payload).encode("utf-8"), headers={"Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(sec_req) as sec_response:
|
||||
sec_res_data = json.loads(sec_response.read().decode("utf-8"))
|
||||
raw_content = sec_res_data.get("message", {}).get("content", "").strip().replace("**", "")
|
||||
raw_content = sec_res_data.get("message", {}).get("content", "").strip().replace("**", "").replace("*", "")
|
||||
final_content = clean_raw_tool_tags(clean_output(raw_content))
|
||||
|
||||
# Если была активна фоновая транзакция, инкрементируем счетчик Topic Shift
|
||||
if session_state and session_state.get("state_type") == "PROMPT_PREVIEW":
|
||||
idle_count = db_increment_session_idle(session_id)
|
||||
logger.info(f"Выполнен инструмент вне черновика. Текущий idle_turns: {idle_count}")
|
||||
|
||||
if idle_count >= 3:
|
||||
guard_note = "\n\nНапоминание: У вас остался непримененный черновик системного промпта. Сохранить его или сбросить?"
|
||||
final_content += guard_note
|
||||
db_save_chat_message(session_id, "assistant", final_content, is_ephemeral=1)
|
||||
return final_content, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_PREVIEW_GUARD",
|
||||
"buttons": [
|
||||
{"label": "Применить черновик", "value": "подтверждаю", "style": "primary"},
|
||||
{"label": "Сбросить черновик", "value": "отмена", "style": "danger"}
|
||||
]
|
||||
}
|
||||
|
||||
db_save_chat_message(session_id, "assistant", final_content, is_ephemeral=0)
|
||||
return final_content, db_get_chat_history(session_id), None
|
||||
|
||||
# Если вызовов функций не было
|
||||
raw_str = msg.get("content", "").strip().replace("**", "")
|
||||
# Если вызовов инструментов не было (обычный текстовый диалог)
|
||||
raw_str = msg.get("content", "").strip().replace("**", "").replace("*", "")
|
||||
content_str = clean_raw_tool_tags(clean_output(raw_str))
|
||||
final_reply = content_str or "Запрос обработан."
|
||||
|
||||
if session_state and session_state.get("state_type") == "PROMPT_PREVIEW":
|
||||
idle_count = db_increment_session_idle(session_id)
|
||||
logger.info(f"Текстовый диалог вне черновика. Текущий idle_turns: {idle_count}")
|
||||
if idle_count >= 3:
|
||||
guard_note = "\n\nНапоминание: У вас остался непримененный черновик системного промпта. Сохранить его или сбросить?"
|
||||
final_reply += guard_note
|
||||
db_save_chat_message(session_id, "assistant", final_reply, is_ephemeral=1)
|
||||
return final_reply, db_get_chat_history(session_id), {
|
||||
"type": "PROMPT_PREVIEW_GUARD",
|
||||
"buttons": [
|
||||
{"label": "Применить черновик", "value": "подтверждаю", "style": "primary"},
|
||||
{"label": "Сбросить черновик", "value": "отмена", "style": "danger"}
|
||||
]
|
||||
}
|
||||
|
||||
db_save_chat_message(session_id, "assistant", final_reply, is_ephemeral=0)
|
||||
return final_reply, db_get_chat_history(session_id), None
|
||||
|
||||
|
||||
Reference in New Issue
Block a user