восстановлена работа после потери main.py из-за неудачного слияния основного проекта и веб морды.

This commit is contained in:
2026-08-07 07:57:20 +03:00
parent 9deca9ab34
commit f6ca8552f6
16 changed files with 1923 additions and 1 deletions
+101
View File
@@ -0,0 +1,101 @@
import json
from typing import List, Dict, Any, Tuple
from datetime import datetime
from app.db import database
from app.tools.definitions import TOOLS_SCHEMA
from app.tools.handlers import handle_tool_call, get_system_capabilities_text
from app.core.ollama_client import send_ollama_request
def process_chat_message(user_message: str, chat_history: List[Dict[str, Any]] = None) -> Tuple[str, List[Dict[str, Any]]]:
if chat_history is None:
chat_history = []
current_now = datetime.now().strftime("%Y-%m-%d %H:%M")
user_clean = user_message.replace("\xa0", " ").strip()
user_lower = user_clean.lower()
# 1. Жесткий перехват: Помощь и варианты команд (чистый Plain Text без Markdown)
if any(phrase in user_lower for phrase in ["помощь", "возможности", "что ты умеешь", "помощь в общении", "варианты команд"]):
formatted_text = get_system_capabilities_text()
updated_history = chat_history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": formatted_text}
]
return formatted_text, updated_history
# 2. Жесткий перехват: Системный промпт из БД
if any(phrase in user_lower for phrase in ["системный промпт", "покажи промпт", "промпт системы", "промпт из базы"]):
prompt_text = database.db_get_active_system_prompt()
formatted_text = f"⚙️ Актуальный системный промпт ИИ (из базы SQLite):\n\n{prompt_text}"
updated_history = chat_history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": formatted_text}
]
return formatted_text, updated_history
# 3. Жесткий перехват: База знаний из БД
if any(phrase in user_lower for phrase in ["базу знаний", "база знаний", "покажи правила", "инструкции ии"]):
rules = database.db_get_rules()
if not rules:
formatted_text = "База знаний пуста."
else:
formatted_text = "🧠 База знаний ИИ (ai_knowledge_base):\n\n"
for r in rules:
formatted_text += f"{r.get('id')}. {r.get('rule_text')}\n\n"
updated_history = chat_history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": formatted_text}
]
return formatted_text, updated_history
# Динамическая подгрузка системного промпта из БД SQLite
dynamic_prompt_text = database.db_get_active_system_prompt()
system_prompt = {
"role": "system",
"content": f"Текущая дата и время сервера: {current_now}.\n\n{dynamic_prompt_text}"
}
messages = [system_prompt] + chat_history + [{"role": "user", "content": user_message}]
try:
res_data = send_ollama_request(messages=messages, tools=TOOLS_SCHEMA)
msg = res_data.get("message", {})
tool_calls = msg.get("tool_calls", [])
content_str = msg.get("content", "").strip().replace("**", "").replace("```", "").replace("###", "")
# Перехват текстового JSON с именем функции
if not tool_calls and "name" in content_str and "db_" in content_str:
try:
start_idx = content_str.find("{")
end_idx = content_str.rfind("}") + 1
if start_idx != -1 and end_idx != -1:
parsed = json.loads(content_str[start_idx:end_idx])
if "name" in parsed:
tool_calls = [{"function": parsed}]
except Exception:
pass
if tool_calls:
for tool in tool_calls:
fn_name = tool["function"]["name"]
fn_args = tool["function"].get("arguments", {})
formatted_text = handle_tool_call(fn_name, fn_args)
updated_history = chat_history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": formatted_text}
]
return formatted_text, updated_history
updated_history = chat_history + [
{"role": "user", "content": user_message},
{"role": "assistant", "content": content_str}
]
return content_str, updated_history
except Exception as e:
return f"Ошибка обработки запроса: {e}", chat_history