[SPRINT-V1][C] Секретарь получил RAG: инструмент docs_search (7 инструментов всего); проверено — находит нужный runbook
This commit is contained in:
1 parent
4af52fb1a1
commit
cc551a66b1
1 file changed
+249
@@ -0,0 +1,249 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Секретарь 2.0 — естественная речь через DeepSeek + инструменты.
|
||||
|
||||
Режимы:
|
||||
--selftest "текст" — прогон без Matrix (проверка tool-calling)
|
||||
(без аргументов) — слушатель Matrix-комнаты SECRETARY
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
DS_KEY = open("/root/.deepseek-key").read().strip()
|
||||
DS_API = "https://api.deepseek.com/chat/completions"
|
||||
HA = "http://192.168.1.106:8123"
|
||||
HA_TOKEN = open("/root/.ha-token").read().strip()
|
||||
RADARR = "http://192.168.1.118:7878"
|
||||
RADARR_KEY = open("/root/.radarr-key").read().strip()
|
||||
SONARR = "http://192.168.1.117:8989"
|
||||
SONARR_KEY = open("/root/.sonarr-key").read().strip()
|
||||
JELLYFIN = "http://192.168.1.103:8096"
|
||||
JF_KEY = open("/root/.jellyfin-key").read().strip()
|
||||
BOTS_ENV = "/etc/hub-bots/bots.env"
|
||||
DM_ENV = "/etc/hub-bots/dm.env"
|
||||
|
||||
|
||||
def read_env(path):
|
||||
out = {}
|
||||
try:
|
||||
for line in open(path, encoding="utf-8"):
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#") and "=" in line:
|
||||
k, v = line.split("=", 1)
|
||||
out[k] = v
|
||||
except Exception:
|
||||
pass
|
||||
return out
|
||||
|
||||
|
||||
def http_json(url, method="GET", data=None, headers=None, timeout=60):
|
||||
req = urllib.request.Request(url, method=method,
|
||||
data=json.dumps(data).encode() if data is not None else None)
|
||||
req.add_header("Content-Type", "application/json")
|
||||
for k, v in (headers or {}).items():
|
||||
req.add_header(k, v)
|
||||
with urllib.request.urlopen(req, timeout=timeout) as r:
|
||||
body = r.read().decode()
|
||||
return json.loads(body) if body.strip() else {}
|
||||
|
||||
|
||||
# ---------- инструменты ----------
|
||||
def tool_radarr_search(query: str) -> str:
|
||||
res = http_json(RADARR + "/api/v3/movie/lookup?term=" + urllib.parse.quote(query),
|
||||
headers={"X-Api-Key": RADARR_KEY})
|
||||
if not res:
|
||||
return "не найдено в базе Radarr: %s" % query
|
||||
m = res[0]
|
||||
title = m.get("title")
|
||||
year = m.get("year")
|
||||
existing = http_json(RADARR + "/api/v3/movie", headers={"X-Api-Key": RADARR_KEY})
|
||||
have = next((x for x in existing if x.get("tmdbId") == m.get("tmdbId")), None)
|
||||
if have:
|
||||
http_json(RADARR + "/api/v3/command", "POST",
|
||||
{"name": "MoviesSearch", "movieIds": [have["id"]]},
|
||||
headers={"X-Api-Key": RADARR_KEY})
|
||||
return "запущен поиск релизов для «%s» (%s), фильм уже в библиотеке" % (title, year)
|
||||
rf = http_json(RADARR + "/api/v3/rootfolder", headers={"X-Api-Key": RADARR_KEY})
|
||||
profs = http_json(RADARR + "/api/v3/qualityprofile", headers={"X-Api-Key": RADARR_KEY})
|
||||
m["rootFolderPath"] = rf[0]["path"] if rf else "/data/movies"
|
||||
m["qualityProfileId"] = profs[0]["id"] if profs else 1
|
||||
m["minimumAvailability"] = "released"
|
||||
m["monitored"] = True
|
||||
m["addOptions"] = {"searchForMovie": True}
|
||||
added = http_json(RADARR + "/api/v3/movie", "POST", m, headers={"X-Api-Key": RADARR_KEY})
|
||||
return "добавлен и ищется: «%s» (%s), id %s" % (added.get("title"), added.get("year"), added.get("id"))
|
||||
|
||||
|
||||
def tool_sonarr_search(query: str) -> str:
|
||||
res = http_json(SONARR + "/api/v3/series/lookup?term=" + urllib.parse.quote(query),
|
||||
headers={"X-Api-Key": SONARR_KEY})
|
||||
if not res:
|
||||
return "не найдено в Sonarr: %s" % query
|
||||
s = res[0]
|
||||
return "найден сериал «%s» (%s), сезонов: %s (добавление — отдельным шагом)" % (
|
||||
s.get("title"), s.get("year"), len(s.get("seasons") or []))
|
||||
|
||||
|
||||
def tool_ha_get_state(entity_id: str) -> str:
|
||||
st = http_json(HA + "/api/states/" + entity_id,
|
||||
headers={"Authorization": "Bearer " + HA_TOKEN})
|
||||
return "%s = %s (%s)" % (entity_id, st.get("state"), (st.get("attributes") or {}).get("friendly_name", ""))
|
||||
|
||||
|
||||
def tool_ha_call_service(domain: str, service: str, entity_id: str) -> str:
|
||||
http_json("%s/api/services/%s/%s" % (HA, domain, service), "POST",
|
||||
{"entity_id": entity_id}, headers={"Authorization": "Bearer " + HA_TOKEN})
|
||||
return "выполнено: %s.%s для %s" % (domain, service, entity_id)
|
||||
|
||||
|
||||
def tool_jellyfin_now_playing() -> str:
|
||||
s = http_json(JELLYFIN + "/Sessions", headers={"Authorization": 'MediaBrowser Token="%s"' % JF_KEY})
|
||||
act = [x for x in s if x.get("NowPlayingItem")]
|
||||
if not act:
|
||||
return "сейчас ничего не смотрят"
|
||||
return "; ".join("%s — %s" % (x.get("DeviceName"), (x.get("NowPlayingItem") or {}).get("Name")) for x in act)
|
||||
|
||||
|
||||
def tool_ha_list_automations(query: str = "") -> str:
|
||||
states = http_json(HA + "/api/states", headers={"Authorization": "Bearer " + HA_TOKEN})
|
||||
autos = [x for x in states if x["entity_id"].startswith("automation.")]
|
||||
if query:
|
||||
q = query.lower()
|
||||
autos = [a for a in autos if q in ((a.get("attributes") or {}).get("friendly_name") or "").lower()
|
||||
or q in a["entity_id"].lower()]
|
||||
if not autos:
|
||||
return "автоматизаций не найдено"
|
||||
lines = ["%s — %s (%s)" % (a["entity_id"], (a.get("attributes") or {}).get("friendly_name", "?"), a["state"])
|
||||
for a in autos[:20]]
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def tool_docs_search(query: str) -> str:
|
||||
"""Поиск по документации проекта (RAG, локальный индекс)."""
|
||||
try:
|
||||
r = subprocess.run(["/usr/bin/python3", "/root/buryan-infra/ops/scripts/rag_query.py",
|
||||
"--search", query, "--k", "3"],
|
||||
capture_output=True, text=True, timeout=120)
|
||||
out = (r.stdout or "").strip()
|
||||
return out[:1500] if out else "в документации ничего не нашлось"
|
||||
except Exception as e:
|
||||
return "поиск по документации недоступен: %s" % str(e)[:120]
|
||||
|
||||
|
||||
TOOLS = [
|
||||
{"type": "function", "function": {"name": "docs_search", "description": "Поиск по внутренней документации Buryans Hub (runbook, аудиты, решения). Используй перед ответом про инфраструктуру.",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
|
||||
{"type": "function", "function": {"name": "ha_list_automations", "description": "Список автоматизаций Home Assistant (можно с фильтром по названию)",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}}}},
|
||||
{"type": "function", "function": {"name": "radarr_search", "description": "Найти и поставить на скачивание фильм",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
|
||||
{"type": "function", "function": {"name": "sonarr_search", "description": "Найти сериал",
|
||||
"parameters": {"type": "object", "properties": {"query": {"type": "string"}}, "required": ["query"]}}},
|
||||
{"type": "function", "function": {"name": "ha_get_state", "description": "Состояние сущности Home Assistant",
|
||||
"parameters": {"type": "object", "properties": {"entity_id": {"type": "string"}}, "required": ["entity_id"]}}},
|
||||
{"type": "function", "function": {"name": "ha_call_service", "description": "Вызвать службу HA (включить автоматизацию, свет и т.п.)",
|
||||
"parameters": {"type": "object", "properties": {"domain": {"type": "string"}, "service": {"type": "string"}, "entity_id": {"type": "string"}},
|
||||
"required": ["domain", "service", "entity_id"]}}},
|
||||
{"type": "function", "function": {"name": "jellyfin_now_playing", "description": "Что сейчас смотрят",
|
||||
"parameters": {"type": "object", "properties": {}}}},
|
||||
]
|
||||
IMPL = {"radarr_search": tool_radarr_search, "sonarr_search": tool_sonarr_search,
|
||||
"ha_get_state": tool_ha_get_state, "ha_call_service": tool_ha_call_service,
|
||||
"jellyfin_now_playing": tool_jellyfin_now_playing,
|
||||
"ha_list_automations": tool_ha_list_automations,
|
||||
"docs_search": tool_docs_search}
|
||||
SYSTEM = ("Ты Секретарь дома Buryans Hub. Владелец — Роман. Отвечай по-русски, коротко. "
|
||||
"Если вопрос про инфраструктуру, прошлые инциденты или решения — сначала ищи в docs_search. Если просят скачать фильм — вызывай radarr_search. Если просят включить/выключить что-то в доме — "
|
||||
"ha_call_service. Если спрашивают состояние — ha_get_state. Не выдумывай entity_id: если неизвестен, спроси.")
|
||||
|
||||
|
||||
def ask_deepseek(messages):
|
||||
body = {"model": "deepseek-chat", "messages": messages, "tools": TOOLS, "temperature": 0.3}
|
||||
return http_json(DS_API, "POST", body, headers={"Authorization": "Bearer " + DS_KEY}, timeout=120)
|
||||
|
||||
|
||||
def handle(text, history=None):
|
||||
msgs = [{"role": "system", "content": SYSTEM}]
|
||||
msgs += (history or [])
|
||||
msgs.append({"role": "user", "content": text})
|
||||
r = ask_deepseek(msgs)
|
||||
msg = r["choices"][0]["message"]
|
||||
calls = msg.get("tool_calls") or []
|
||||
if calls:
|
||||
msgs.append(msg)
|
||||
for c in calls:
|
||||
fn = c["function"]["name"]
|
||||
try:
|
||||
args = json.loads(c["function"].get("arguments") or "{}")
|
||||
except Exception:
|
||||
args = {}
|
||||
try:
|
||||
out = IMPL[fn](**args)
|
||||
except Exception as e:
|
||||
out = "ошибка %s: %s" % (fn, str(e)[:120])
|
||||
msgs.append({"role": "tool", "tool_call_id": c["id"], "content": str(out)})
|
||||
r2 = ask_deepseek(msgs)
|
||||
return r2["choices"][0]["message"].get("content") or "(пусто)"
|
||||
return msg.get("content") or "(пусто)"
|
||||
|
||||
|
||||
# ---------- Matrix ----------
|
||||
def matrix_send(text):
|
||||
env = read_env(BOTS_ENV)
|
||||
token = env.get("SECRETARY_TOKEN")
|
||||
hs = (env.get("HS") or "https://matrix.buryans.ru").rstrip("/")
|
||||
room = read_env(DM_ENV).get("SECRETARY")
|
||||
if not (token and room):
|
||||
print("нет токена/комнаты SECRETARY")
|
||||
return
|
||||
rid = urllib.parse.quote(room, safe="")
|
||||
url = "%s/_matrix/client/v3/rooms/%s/send/m.room.message/%d" % (hs, rid, int(time.time() * 1000))
|
||||
http_json(url, "PUT", {"msgtype": "m.text", "body": text}, headers={"Authorization": "Bearer " + token})
|
||||
|
||||
|
||||
def run_matrix():
|
||||
env = read_env(BOTS_ENV)
|
||||
token = env.get("SECRETARY_TOKEN")
|
||||
user = env.get("SECRETARY_USER")
|
||||
hs = (env.get("HS") or "https://matrix.buryans.ru").rstrip("/")
|
||||
if not token:
|
||||
print("SECRETARY_TOKEN не найден")
|
||||
return
|
||||
print("Секретарь слушает Matrix как", user)
|
||||
since = None
|
||||
while True:
|
||||
try:
|
||||
q = "/sync?timeout=30000"
|
||||
if since:
|
||||
q += "&since=" + urllib.parse.quote(since)
|
||||
data = http_json(hs + "/_matrix/client/v3" + q, headers={"Authorization": "Bearer " + token}, timeout=90)
|
||||
since = data.get("next_batch") or since
|
||||
for rid, room in (data.get("rooms", {}).get("join", {}) or {}).items():
|
||||
for ev in (room.get("timeline", {}) or {}).get("events", []):
|
||||
if ev.get("type") != "m.room.message":
|
||||
continue
|
||||
if ev.get("sender") == user:
|
||||
continue
|
||||
body = (ev.get("content") or {}).get("body") or ""
|
||||
if not body:
|
||||
continue
|
||||
print("→", ev.get("sender"), body[:100])
|
||||
reply = handle(body)
|
||||
matrix_send(reply)
|
||||
except Exception as e:
|
||||
print("цикл:", type(e).__name__, str(e)[:150])
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) > 2 and sys.argv[1] == "--selftest":
|
||||
print(handle(sys.argv[2]))
|
||||
elif len(sys.argv) > 2 and sys.argv[1] == "--send":
|
||||
matrix_send(sys.argv[2])
|
||||
print("отправлено")
|
||||
else:
|
||||
run_matrix()
|
||||
Reference in new issue
Block a user