chore(checkpoint): save working state before clean state context refactoring
This commit is contained in:
@@ -1,5 +1,10 @@
|
||||
"""
|
||||
FILE: modules/web_api/llm/db/db_prompts.py
|
||||
PROJECT: SCUD Orion AI
|
||||
MODULE: web_api / llm / db
|
||||
ROLE: Управление системными промптами, правилами базы знаний,
|
||||
декларативным реестром действий инструментов (tool_action_registry)
|
||||
и расширенным сессионным состоянием (session_states + idle_turns).
|
||||
"""
|
||||
import json
|
||||
import logging
|
||||
@@ -8,7 +13,9 @@ from .connection import get_db_connection
|
||||
|
||||
logger = logging.getLogger("DB_PROMPTS")
|
||||
|
||||
|
||||
def db_get_active_system_prompt() -> str:
|
||||
"""Извлекает актуальный активный системный промпт из SQLite."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT prompt_text FROM system_prompts WHERE is_active = 1 ORDER BY id DESC LIMIT 1")
|
||||
@@ -16,6 +23,7 @@ def db_get_active_system_prompt() -> str:
|
||||
conn.close()
|
||||
return row["prompt_text"] if row else "Ты — ИИ-ассистент SCUD Orion AI."
|
||||
|
||||
|
||||
def db_get_tool_action(tool_name: str) -> Optional[Dict[str, Any]]:
|
||||
"""Получение шаблона, кнопок и настроек эфемерности инструмента из SQLite."""
|
||||
conn = get_db_connection()
|
||||
@@ -35,7 +43,9 @@ def db_get_tool_action(tool_name: str) -> Optional[Dict[str, Any]]:
|
||||
return res
|
||||
return None
|
||||
|
||||
|
||||
def db_add_system_prompt(name: str, prompt_text: str) -> Dict[str, Any]:
|
||||
"""Сохраняет новую версию системного промпта и активирует её."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
@@ -58,7 +68,9 @@ def db_add_system_prompt(name: str, prompt_text: str) -> Dict[str, Any]:
|
||||
logger.error(f"Ошибка при сохранении промпта в БД: {e}")
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def db_get_rules() -> List[Dict[str, Any]]:
|
||||
"""Извлекает список глобальных правил компании из ai_knowledge_base."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, rule_text FROM ai_knowledge_base ORDER BY id ASC")
|
||||
@@ -66,9 +78,24 @@ def db_get_rules() -> List[Dict[str, Any]]:
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def db_set_session_state(session_id: str, state_type: str, data: str):
|
||||
|
||||
# =============================================================================
|
||||
# РАБОТА С СЕССИОННЫМИ СОСТОЯНИЯМИ, ЧЕРНОВИКАМИ И СЧЕТЧИКОМ ОТВЛЕЧЕНИЙ (IDLE_TURNS)
|
||||
# =============================================================================
|
||||
|
||||
def db_set_session_state(session_id: str, state_type: str, data: Any) -> None:
|
||||
"""
|
||||
Сохраняет состояние сессии в SQLite.
|
||||
Если передан dict/list — автоматически сериализует его в JSON-строку.
|
||||
"""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
if isinstance(data, (dict, list)):
|
||||
payload_str = json.dumps(data, ensure_ascii=False)
|
||||
else:
|
||||
payload_str = str(data) if data is not None else ""
|
||||
|
||||
cursor.execute("""
|
||||
INSERT INTO session_states (session_id, state_type, pending_data, updated_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||
@@ -76,26 +103,78 @@ def db_set_session_state(session_id: str, state_type: str, data: str):
|
||||
state_type = excluded.state_type,
|
||||
pending_data = excluded.pending_data,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (session_id, state_type, data))
|
||||
""", (session_id, state_type, payload_str))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def db_get_session_state(session_id: str) -> Optional[Dict[str, Any]]:
|
||||
"""
|
||||
Извлекает состояние сессии из SQLite.
|
||||
Если в pending_data лежит валидный JSON-объект — парсит его в data_json.
|
||||
"""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT state_type, pending_data FROM session_states WHERE session_id = ?", (session_id,))
|
||||
cursor.execute(
|
||||
"SELECT session_id, state_type, pending_data, updated_at FROM session_states WHERE session_id = ?",
|
||||
(session_id,)
|
||||
)
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
if not row:
|
||||
return None
|
||||
|
||||
def db_clear_session_state(session_id: str):
|
||||
res = dict(row)
|
||||
raw_data = res.get("pending_data") or ""
|
||||
|
||||
try:
|
||||
if raw_data.strip().startswith("{") or raw_data.strip().startswith("["):
|
||||
res["data_json"] = json.loads(raw_data)
|
||||
else:
|
||||
res["data_json"] = None
|
||||
except Exception:
|
||||
res["data_json"] = None
|
||||
|
||||
return res
|
||||
|
||||
|
||||
def db_increment_session_idle(session_id: str) -> int:
|
||||
"""
|
||||
Инкрементирует счетчик idle_turns для активного черновика сессии.
|
||||
Возвращает обновленное значение счетчика отвлечений.
|
||||
"""
|
||||
state = db_get_session_state(session_id)
|
||||
if not state:
|
||||
return 0
|
||||
|
||||
data_meta = state.get("data_json")
|
||||
if isinstance(data_meta, dict):
|
||||
current_turns = data_meta.get("idle_turns", 0) + 1
|
||||
data_meta["idle_turns"] = current_turns
|
||||
db_set_session_state(session_id, state["state_type"], data_meta)
|
||||
return current_turns
|
||||
else:
|
||||
# Если ранее данные были сохранены обычной строкой
|
||||
new_meta = {
|
||||
"draft_text": state.get("pending_data", ""),
|
||||
"idle_turns": 1
|
||||
}
|
||||
db_set_session_state(session_id, state["state_type"], new_meta)
|
||||
return 1
|
||||
|
||||
|
||||
def db_clear_session_state(session_id: str) -> None:
|
||||
"""Сбрасывает и удаляет активное состояние сессии."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM session_states WHERE session_id = ?", (session_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
|
||||
def db_get_session_states() -> Dict[str, Any]:
|
||||
"""Возвращает реестр всех активных сессий."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT session_id, state_type, updated_at FROM session_states")
|
||||
@@ -103,10 +182,19 @@ def db_get_session_states() -> Dict[str, Any]:
|
||||
conn.close()
|
||||
return {"status": "success", "active_sessions": [dict(r) for r in rows]}
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# СЛУЖЕБНАЯ ДИАГНОСТИКА И СТАТИСТИКА
|
||||
# =============================================================================
|
||||
|
||||
def db_get_stats() -> Dict[str, Any]:
|
||||
"""Возвращает статистику по количеству записей в таблицах."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
tables = ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base', 'system_prompts', 'session_states', 'tasks']
|
||||
tables = [
|
||||
'scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history',
|
||||
'ai_knowledge_base', 'system_prompts', 'session_states', 'tasks'
|
||||
]
|
||||
stats = {}
|
||||
for t in tables:
|
||||
try:
|
||||
@@ -117,7 +205,9 @@ def db_get_stats() -> Dict[str, Any]:
|
||||
conn.close()
|
||||
return {"status": "success", "tables_stats": stats}
|
||||
|
||||
|
||||
def db_get_anomalies(limit: int = 100, date_str: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Извлекает журнал зафиксированных аномалий."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
query = "SELECT anomaly_date, fio, anomaly_type, details FROM anomalies_history"
|
||||
@@ -132,7 +222,9 @@ def db_get_anomalies(limit: int = 100, date_str: Optional[str] = None) -> Dict[s
|
||||
conn.close()
|
||||
return {"status": "success", "count": len(rows), "anomalies": [dict(r) for r in rows]}
|
||||
|
||||
|
||||
def db_get_reference(category: Optional[str] = None) -> Dict[str, Any]:
|
||||
"""Извлекает справочные команды и примеры подсказок."""
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
query = "SELECT category, title, example_prompt, description FROM system_reference"
|
||||
|
||||
Reference in New Issue
Block a user