налажена работа с системными промптами (добавление, изменение, удаление). Восстановлена работа с задачами.
This commit is contained in:
+71
-23
@@ -1,11 +1,20 @@
|
||||
import sqlite3
|
||||
import logging
|
||||
from typing import List, Dict, Any, Optional
|
||||
|
||||
DB_PATH = "/home/puh/scud_context_api/scud_orion_ai.db"
|
||||
# Настройка логирования
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
|
||||
logger = logging.getLogger("DB_TOOLS")
|
||||
|
||||
DB_PATH = "/home/puh/scud_orion_ai_v2/data/scud_orion_ai.db"
|
||||
|
||||
def get_db_connection():
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
# Увеличиваем таймаут до 30 секунд, чтобы соединения ожидали завершения соседних транзакций,
|
||||
# а также включаем WAL-режим для безопасного параллельного чтения и записи.
|
||||
conn = sqlite3.connect(DB_PATH, timeout=30.0)
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.execute("PRAGMA journal_mode = WAL;")
|
||||
conn.execute("PRAGMA synchronous = NORMAL;")
|
||||
return conn
|
||||
|
||||
def normalize_task_id(task_id_input: str) -> str:
|
||||
@@ -107,31 +116,70 @@ def db_get_active_system_prompt() -> str:
|
||||
return row["prompt_text"] if row else "Ты — ИИ-ассистент SCUD Orion AI."
|
||||
|
||||
def db_add_system_prompt(name: str, prompt_text: str) -> Dict[str, Any]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
# Проверяем наличие промпта с таким именем, чтобы не плодить мусор
|
||||
cursor.execute("SELECT id FROM system_prompts WHERE name = ?", (name,))
|
||||
existing = cursor.fetchone()
|
||||
|
||||
if existing:
|
||||
cursor.execute("""
|
||||
UPDATE system_prompts
|
||||
SET prompt_text = ?, updated_at = CURRENT_TIMESTAMP, is_active = 1
|
||||
WHERE name = ?
|
||||
""", (prompt_text, name))
|
||||
else:
|
||||
cursor.execute("UPDATE system_prompts SET is_active = 0")
|
||||
cursor.execute("INSERT INTO system_prompts (name, prompt_text, is_active) VALUES (?, ?, 1)", (name, prompt_text))
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return {"status": "success", "message": "Системный промпт успешно обновлен"}
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("BEGIN IMMEDIATE;")
|
||||
|
||||
# Проверяем, существует ли уже промпт с таким именем
|
||||
cursor.execute("SELECT id FROM system_prompts WHERE name = ?", (name,))
|
||||
existing = cursor.fetchone()
|
||||
|
||||
if existing:
|
||||
# Обновляем существующий активный промпт
|
||||
cursor.execute(
|
||||
"UPDATE system_prompts SET prompt_text = ?, is_active = 1, updated_at = CURRENT_TIMESTAMP WHERE name = ?",
|
||||
(prompt_text, name)
|
||||
)
|
||||
else:
|
||||
# Вставляем новый, если его не было
|
||||
cursor.execute(
|
||||
"INSERT INTO system_prompts (name, prompt_text, is_active) VALUES (?, ?, 1)",
|
||||
(name, prompt_text)
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
|
||||
logger.info("Системный промпт успешно сохранен и применен в базе данных.")
|
||||
return {"status": "success", "message": "Системный промпт успешно обновлен"}
|
||||
except Exception as e:
|
||||
logger.error(f"Ошибка при сохранении промпта в БД: {e}")
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
|
||||
def db_get_rules() -> List[Dict[str, Any]]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, rule_text FROM ai_knowledge_base ORDER BY id ASC")
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
return [dict(r) for r in rows]
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
def db_set_session_state(session_id: str, state_type: str, data: str):
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("""
|
||||
INSERT INTO session_states (session_id, state_type, pending_data, updated_at)
|
||||
VALUES (?, ?, ?, CURRENT_TIMESTAMP)
|
||||
ON CONFLICT(session_id) DO UPDATE SET
|
||||
state_type = excluded.state_type,
|
||||
pending_data = excluded.pending_data,
|
||||
updated_at = CURRENT_TIMESTAMP
|
||||
""", (session_id, state_type, data))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def db_get_session_state(session_id: str) -> Optional[Dict[str, Any]]:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT state_type, pending_data FROM session_states WHERE session_id = ?", (session_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
|
||||
def db_clear_session_state(session_id: str):
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("DELETE FROM session_states WHERE session_id = ?", (session_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
Reference in New Issue
Block a user