feat(llm): переход на реляционные узлы промпта, db_cli context и очистка от регулярок
This commit is contained in:
+76
-18
@@ -51,11 +51,14 @@ def print_stats():
|
||||
print("=" * 60)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
tables = ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']
|
||||
tables = ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base', 'chat_messages', 'session_states']
|
||||
for t in tables:
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {t}")
|
||||
cnt = cursor.fetchone()[0]
|
||||
print(f" • Таблица [{t:<18}]: {cnt:>6} записей")
|
||||
try:
|
||||
cursor.execute(f"SELECT COUNT(*) FROM {t}")
|
||||
cnt = cursor.fetchone()[0]
|
||||
print(f" • Таблица [{t:<18}]: {cnt:>6} записей")
|
||||
except Exception:
|
||||
pass
|
||||
print("=" * 60 + "\n")
|
||||
|
||||
|
||||
@@ -236,28 +239,35 @@ def dump_all_to_excel(out_filename="db_dump_full.xlsx"):
|
||||
out_path = os.path.join(OUTPUT_DIR, out_filename)
|
||||
print(f"\n[🔄] Создание полного дампа БД в файл: {out_path} ...")
|
||||
with get_connection() as conn, pd.ExcelWriter(out_path, engine='openpyxl') as writer:
|
||||
for table in ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base']:
|
||||
df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
|
||||
df.to_excel(writer, sheet_name=table[:31], index=False)
|
||||
for table in ['scud_logs', 'zup_staff', 'zup_absences', 'anomalies_history', 'ai_knowledge_base', 'chat_messages', 'session_states', 'system_prompt_nodes', 'tasks']:
|
||||
try:
|
||||
df = pd.read_sql_query(f"SELECT * FROM {table}", conn)
|
||||
df.to_excel(writer, sheet_name=table[:31], index=False)
|
||||
except Exception:
|
||||
pass
|
||||
print(f"[✓] Дамп успешно сохранен: {out_path}\n")
|
||||
|
||||
|
||||
def print_system_prompts():
|
||||
"""Выводит все системные промпты из базы данных."""
|
||||
print("\n" + "=" * 80)
|
||||
print("📝 СИСТЕМНЫЕ ПРОМПТЫ (system_prompts):")
|
||||
print("📝 СИСТЕМНЫЕ ПРОМПТЫ (system_prompt_nodes):")
|
||||
print("=" * 80)
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT id, name, is_active, updated_at, prompt_text FROM system_prompts ORDER BY id DESC")
|
||||
rows = cursor.fetchall()
|
||||
try:
|
||||
cursor.execute("SELECT section_id, item_id, content, is_active, updated_at FROM system_prompt_nodes ORDER BY section_id ASC, item_id ASC")
|
||||
rows = cursor.fetchall()
|
||||
except Exception:
|
||||
rows = []
|
||||
|
||||
if not rows:
|
||||
print("Таблица system_prompts пуста.")
|
||||
print("Таблица system_prompt_nodes пуста.")
|
||||
else:
|
||||
for r in rows:
|
||||
print(f"ID: {r[0]} | Name: {r[1]} | Active: {r[2]} | Updated: {r[3]}")
|
||||
print(f"Раздел {r[0]}.{r[1]} | Active: {r[3]} | Updated: {r[4]}")
|
||||
print(f" {r[2]}")
|
||||
print("-" * 80)
|
||||
print(f"{r[4]}\n")
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
@@ -280,6 +290,50 @@ def print_session_states():
|
||||
print("=" * 80 + "\n")
|
||||
|
||||
|
||||
def print_chat_messages(session_id=None, limit=50):
|
||||
"""Выводит таблицу истории сообщений чата (контекст)."""
|
||||
print("\n" + "=" * 105)
|
||||
print(f"💬 ИСТОРИЯ СООБЩЕНИЙ ЧАТА (chat_messages) {f'для сессии: {session_id}' if session_id else 'все сессии'}:")
|
||||
print("=" * 105)
|
||||
|
||||
with get_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
if session_id:
|
||||
cursor.execute("""
|
||||
SELECT id, session_id, role, content, is_ephemeral, created_at
|
||||
FROM chat_messages
|
||||
WHERE session_id = ?
|
||||
ORDER BY id ASC
|
||||
LIMIT ?
|
||||
""", (session_id, limit))
|
||||
else:
|
||||
cursor.execute("""
|
||||
SELECT id, session_id, role, content, is_ephemeral, created_at
|
||||
FROM chat_messages
|
||||
ORDER BY id DESC
|
||||
LIMIT ?
|
||||
""", (limit,))
|
||||
|
||||
rows = cursor.fetchall()
|
||||
if not rows:
|
||||
print("Таблица chat_messages пуста.")
|
||||
else:
|
||||
# Если выводили все без конкретной сессии в порядке DESC, развернем для читаемости
|
||||
if not session_id:
|
||||
rows = list(reversed(rows))
|
||||
|
||||
for r in rows:
|
||||
msg_id, sess, role, content, ephemeral, created = r
|
||||
eph_marker = " [ЭФЕМЕРНОЕ]" if ephemeral else ""
|
||||
print(f"[{msg_id}] {created} | Сессия: {sess} | Роль: {role.upper()}{eph_marker}")
|
||||
print("-" * 105)
|
||||
# Выводим контент, ограничивая длинные сообщения при необходимости
|
||||
content_preview = content if content else ""
|
||||
print(f"{content_preview}")
|
||||
print("=" * 105)
|
||||
print("\n")
|
||||
|
||||
|
||||
HELP_TEXT = """
|
||||
CLI-утилита инспекции и управления SQLite базой данных СКУД (scud_orion_ai.db)
|
||||
|
||||
@@ -290,9 +344,10 @@ CLI-утилита инспекции и управления SQLite базой
|
||||
absences [ДД.ММ.ГГГГ] -- Посмотреть список официально отсутствующих из 1С:ЗУП
|
||||
anomalies -- Посмотреть историю найденных аномалий СКУД ⟷ 1С
|
||||
rules -- Посмотреть правила Базы Знаний ИИ из SQLite
|
||||
prompts -- Посмотреть системные промпты (system_prompts)
|
||||
prompts -- Посмотреть узлы системного промпта (system_prompt_nodes)
|
||||
tools -- Посмотреть реестр действий инструментов и кнопок (tool_action_registry)
|
||||
sessions -- Посмотреть активные сессии и превью (session_states)
|
||||
context [session_id] [--limit N] -- Посмотреть таблицу контекста сообщений чата (chat_messages)
|
||||
dump [output.xlsx] -- Полный дамп всех таблиц БД в многостраничный Excel
|
||||
snapshot del [ID] или [--day ДД.ММ.ГГГГ] -- Удаление снапшота по ID или всех за выбранный день
|
||||
|
||||
@@ -300,13 +355,12 @@ CLI-утилита инспекции и управления SQLite базой
|
||||
python scripts/db_cli.py stats
|
||||
python scripts/db_cli.py snapshots 06.08.2026
|
||||
python scripts/db_cli.py scud 06.08.2026 --export-xlsx срез_четверг
|
||||
python scripts/db_cli.py scud --snapshot Y20260805-007
|
||||
python scripts/db_cli.py absences 07.08.2026
|
||||
python scripts/db_cli.py prompts
|
||||
python scripts/db_cli.py tools
|
||||
python scripts/db_cli.py sessions
|
||||
python scripts/db_cli.py context web_session_main --limit 20
|
||||
python scripts/db_cli.py snapshot del Y20260805-007
|
||||
python scripts/db_cli.py snapshot del --day 04.08.2026
|
||||
python scripts/db_cli.py dump my_dump.xlsx
|
||||
"""
|
||||
|
||||
@@ -321,12 +375,13 @@ def main():
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter,
|
||||
add_help=False
|
||||
)
|
||||
parser.add_argument('command', nargs='?', default=None, choices=['stats', 'snapshots', 'scud', 'absences', 'anomalies', 'rules', 'prompts', 'sessions', 'dump', 'snapshot', 'tools'], help="Основная команда")
|
||||
parser.add_argument('action', nargs='?', default=None, help="Дополнительное действие (например, 'del')")
|
||||
parser.add_argument('command', nargs='?', default=None, choices=['stats', 'snapshots', 'scud', 'absences', 'anomalies', 'rules', 'prompts', 'sessions', 'dump', 'snapshot', 'tools', 'context'], help="Основная команда")
|
||||
parser.add_argument('action', nargs='?', default=None, help="Дополнительное действие (например, 'del') или session_id для контекста")
|
||||
parser.add_argument('param', nargs='?', default=None, help="Параметр (дата, ID снапшота или имя файла)")
|
||||
parser.add_argument('--snapshot', type=str, default=None, help="ID конкретного снапшота для инспекции")
|
||||
parser.add_argument('--export-xlsx', type=str, default=None, help="Экспорт среза СКУД в Excel-файл")
|
||||
parser.add_argument('--day', type=str, default=None, help="Удалить снапшоты за конкретный день (ДД.ММ.ГГГГ)")
|
||||
parser.add_argument('--limit', type=int, default=50, help="Лимит выводимых сообщений чата (для команды context)")
|
||||
|
||||
if len(sys.argv) == 1:
|
||||
print_stats()
|
||||
@@ -354,6 +409,9 @@ def main():
|
||||
print_session_states()
|
||||
elif args.command == 'tools':
|
||||
print_tool_actions()
|
||||
elif args.command == 'context':
|
||||
sess_id = args.action if args.action else None
|
||||
print_chat_messages(session_id=sess_id, limit=args.limit)
|
||||
elif args.command == 'dump':
|
||||
filename = args.param if args.param else "db_dump_full.xlsx"
|
||||
dump_all_to_excel(filename)
|
||||
|
||||
Reference in New Issue
Block a user