Files

77 lines
3.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
ai.py — доступ к локальной модели Qwen3:8b через Ollama API.
Используется ИИ-панелью «Ассистент». Модель и base URL — настройки проекта;
по умолчанию localhost:11434 (Ollama, как у классификатора писем).
"""
from __future__ import annotations
import os
import re
from pathlib import Path
import httpx
OLLAMA_BASE = os.environ.get("OLLAMA_BASE", "http://127.0.0.1:11434")
OLLAMA_MODEL = os.environ.get("OLLAMA_MODEL", "qwen3:8b-nothink")
SYSTEM_PROMPT = """Ты — ассистент по личной почте пользователя (Email Assistant).
Работаешь с локальным архивом писем (email.md + SQLite). Отвечай кратко и по
делу, на русском языке. Если в ответе упоминаешь конкретные письма — указывай
их пути к файлам строками вида /opt/hermes/email/.../email.md в отдельной
строке после ответа. Если информации не хватает — так и скажи."""
def ask(question: str, context: str | None = None, timeout: float = 120.0) -> dict:
"""Спросить модель. Возвращает {text, error?}.
context — строка с контекстом текущего UI (папка, письмо, запрос).
"""
prompt = question
if context:
prompt = f"КОНТЕКСТ (текущий экран):\n{context}\n\nВОПРОС:\n{question}"
payload = {
"model": OLLAMA_MODEL,
"prompt": prompt,
"system": SYSTEM_PROMPT,
"stream": False,
"options": {"temperature": 0.3, "num_ctx": 8192},
}
try:
with httpx.Client(timeout=timeout) as c:
r = c.post(f"{OLLAMA_BASE}/api/generate", json=payload)
r.raise_for_status()
data = r.json()
text = (data.get("response") or "").strip()
return {"text": text}
except httpx.HTTPError as e:
return {"text": "", "error": f"Модель недоступна: {type(e).__name__}"}
except Exception as e: # noqa: BLE001
return {"text": "", "error": f"Модель недоступна: {e}"}
_FILE_RE = re.compile(r"(/opt/hermes/email/[\wа-яёА-ЯЁ /.\-\\[\](){}]+?\.md)", re.I | re.U)
EMAIL_STATIC = Path("/opt/hermes/email")
def linkify(text: str) -> str:
"""Пути email.md в тексте → HTML-ссылки на деталку письма.
Возвращает строку в HTML-разметке (безопасную: экранирует остальное)."""
from html import escape as h
def _replace(m: re.Match) -> str:
path = m.group(1)
# относительный путь от EMAIL_ROOT для /emails?path=
try:
rel = path.replace("/opt/hermes/email/", "").replace("\\", "/")
except Exception:
rel = path
href = f"/emails/{rel}"
return f'<a href="{h(href)}" class="ai-link">{h(rel)}</a>'
escaped = h(text)
# сначала экранируем, потом вставляем ссылки на известные пути
out = _FILE_RE.sub(_replace, escaped)
out = out.replace("\n", "<br>")
return out