98 lines
4.3 KiB
Python
98 lines
4.3 KiB
Python
"""
|
|
===============================================================================
|
|
FILE: modules/ai_engine/handlers/prompt_handler.py
|
|
PROJECT: SCUD Orion AI (Unified Architecture)
|
|
MODULE: modules / ai_engine / handlers
|
|
ROLE: Изолированная обработка команд управления системным промптом.
|
|
===============================================================================
|
|
"""
|
|
|
|
from typing import Dict, Any, Tuple, Optional
|
|
from services.prompts.service import get_active_system_prompt, create_prompt_preview
|
|
from modules.web_api.llm.db.db_chat import db_save_chat_message, db_get_chat_history
|
|
from modules.web_api.llm.db.db_prompts import db_set_session_state
|
|
|
|
|
|
# ANCHOR[PROMPT_HANDLER_DISPATCH]
|
|
def handle_prompt_call(
|
|
fn_name: str,
|
|
fn_args: Dict[str, Any],
|
|
session_id: str
|
|
) -> Tuple[str, list, Optional[Dict[str, Any]]]:
|
|
"""Обрабатывает вызовы просмотра и изменения системного промпта."""
|
|
|
|
# 1. Просмотр промпта с кнопкой быстрого перехода в редактор
|
|
if fn_name == "db_get_system_prompt":
|
|
active_prompt = get_active_system_prompt()
|
|
reply_text = f"Актуальный системный промпт:\n\n{active_prompt}"
|
|
|
|
# Сохраняем состояние сессии для возможности мгновенного редактирования и подтверждения
|
|
db_set_session_state(session_id, "PROMPT_PREVIEW", {
|
|
"draft_text": active_prompt,
|
|
"action": "MANUAL_EDIT",
|
|
"idle_turns": 0
|
|
})
|
|
db_save_chat_message(session_id, "assistant", reply_text, is_ephemeral=1)
|
|
|
|
return reply_text, db_get_chat_history(session_id), {
|
|
"type": "PROMPT_PREVIEW",
|
|
"raw_draft": active_prompt,
|
|
"baseline_prompt": active_prompt,
|
|
"buttons": [
|
|
{"label": "✏️ Редактировать", "value": "action:open_editor", "style": "secondary"},
|
|
{"label": "Готово", "value": "нет, спасибо", "style": "secondary"}
|
|
]
|
|
}
|
|
|
|
# 2. Предпросмотр точечных или пакетных изменений (ADD / EDIT / DELETE / BATCH_DELETE)
|
|
action = str(fn_args.get("action", "ADD")).upper()
|
|
nodes_list = fn_args.get("nodes_list", [])
|
|
delete_nodes_tuples = []
|
|
|
|
if nodes_list:
|
|
for n_str in nodes_list:
|
|
parts = str(n_str).strip().split(".")
|
|
if len(parts) == 2 and parts[0].isdigit() and parts[1].isdigit():
|
|
delete_nodes_tuples.append((int(parts[0]), int(parts[1])))
|
|
|
|
sec_id = None
|
|
itm_id = None
|
|
try:
|
|
if fn_args.get("section_id") is not None:
|
|
sec_id = int(str(fn_args.get("section_id")).strip())
|
|
if fn_args.get("item_id") is not None:
|
|
itm_id = int(str(fn_args.get("item_id")).strip())
|
|
except Exception:
|
|
pass
|
|
|
|
content = str(fn_args.get("content", "")).strip()
|
|
|
|
merged_prompt, diff_html, baseline_prompt = create_prompt_preview(
|
|
action=action,
|
|
section_id=sec_id,
|
|
item_id=itm_id,
|
|
content=content,
|
|
delete_nodes=delete_nodes_tuples if delete_nodes_tuples else None
|
|
)
|
|
|
|
db_set_session_state(session_id, "PROMPT_PREVIEW", {
|
|
"draft_text": merged_prompt,
|
|
"action": "MANUAL_EDIT",
|
|
"section_id": sec_id,
|
|
"item_id": itm_id,
|
|
"content": content,
|
|
"idle_turns": 0
|
|
})
|
|
|
|
preview_reply = f"Предпросмотр изменений системного промпта:\n\n{diff_html}\n\nДля применения подтвердите действие, отредактируйте или отмените."
|
|
db_save_chat_message(session_id, "assistant", preview_reply, is_ephemeral=1)
|
|
return preview_reply, db_get_chat_history(session_id), {
|
|
"type": "PROMPT_PREVIEW",
|
|
"raw_draft": merged_prompt,
|
|
"baseline_prompt": baseline_prompt,
|
|
"buttons": [
|
|
{"label": "Подтвердить", "value": "подтверждаю", "style": "primary"},
|
|
{"label": "Отменить", "value": "отмена", "style": "danger"},
|
|
{"label": "✏️ Редактировать", "value": "action:open_editor", "style": "secondary"}
|
|
]
|
|
} |