Files

137 lines
6.0 KiB
Python
Executable File

#!/usr/bin/env python3
"""Единая точка вызова LLM с АВТОМАТИЧЕСКИМ фолбэком.
Цепочка по умолчанию: qwen2.5:3b (локально) → qwen2.5:7b (локально) →
DeepSeek (облако). Если модель не ответила, ответила пусто или упала —
переходим к следующей. Решение принимается автоматически, без участия
человека; в журнал пишется, кто ответил и сколько это заняло.
Зачем: локальная модель бесплатна и не требует интернета, но под нагрузкой
может не уложиться в таймаут. DeepSeek — запасной вариант, а не основной.
API:
from llm_fallback import ask, LLMUnavailable
r = ask("Сколько будет 2+2?", max_tokens=50)
r["text"], r["model"], r["fallback"] # fallback=True, если не первая модель
Проверка:
python3 llm_fallback.py "привет"
python3 llm_fallback.py --test-fallback # принудительно проверить переход
"""
import json
import os
import sys
import time
import urllib.request
import urllib.error
OLLAMA = os.getenv("OLLAMA_URL", "http://192.168.1.229:11434")
DEEPSEEK_URL = os.getenv("DEEPSEEK_URL", "https://api.deepseek.com/chat/completions")
DEEPSEEK_KEY_FILE = "/root/.deepseek-key"
LOG = "/var/log/hub/llm-fallback.log"
CHAIN = [
{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 60},
{"name": "qwen2.5:7b", "kind": "ollama", "timeout": 120},
{"name": "deepseek-chat", "kind": "deepseek", "timeout": 60},
]
class LLMUnavailable(RuntimeError):
def __init__(self, errors):
self.errors = errors
super().__init__("; ".join("%s: %s" % (n, e) for n, e in errors))
def _log(rec):
try:
os.makedirs(os.path.dirname(LOG), exist_ok=True)
with open(LOG, "a", encoding="utf-8") as f:
f.write(json.dumps(rec, ensure_ascii=False) + "\n")
except Exception:
pass
def _post(url, payload, headers, timeout):
body = json.dumps(payload, ensure_ascii=False).encode()
req = urllib.request.Request(url, data=body, headers=headers)
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read())
def _ollama(model, messages, timeout, max_tokens, temperature):
d = _post(OLLAMA + "/api/chat",
{"model": model, "messages": messages, "stream": False,
"keep_alive": "30m",
"options": {"num_predict": max_tokens, "temperature": temperature}},
{"Content-Type": "application/json"}, timeout)
return (d.get("message") or {}).get("content") or ""
def _deepseek(model, messages, timeout, max_tokens, temperature):
key = open(DEEPSEEK_KEY_FILE, encoding="utf-8").read().strip()
d = _post(DEEPSEEK_URL,
{"model": model, "messages": messages,
"max_tokens": max_tokens, "temperature": temperature, "stream": False},
{"Content-Type": "application/json",
"Authorization": "Bearer " + key}, timeout)
msg = (d.get("choices") or [{}])[0].get("message") or {}
# reasoning-модели кладут текст в reasoning_content; content может быть пуст
return (msg.get("content") or msg.get("reasoning_content") or "")
def ask(prompt, system=None, max_tokens=400, temperature=0.4, chain=None):
"""Возвращает {text, model, ms, fallback, chain}. Бросает LLMUnavailable."""
messages = []
if system:
messages.append({"role": "system", "content": system})
messages.append({"role": "user", "content": prompt})
errors = []
steps = chain or CHAIN
for i, step in enumerate(steps):
t0 = time.time()
try:
fn = _ollama if step["kind"] == "ollama" else _deepseek
text = fn(step["name"], messages, step["timeout"], max_tokens, temperature)
ms = int((time.time() - t0) * 1000)
if not (text or "").strip():
errors.append((step["name"], "пустой ответ"))
_log({"model": step["name"], "ok": False, "ms": ms, "error": "empty"})
continue
_log({"model": step["name"], "ok": True, "ms": ms, "fallback": i > 0})
return {"text": text.strip(), "model": step["name"], "ms": ms,
"fallback": i > 0, "chain": [s["name"] for s in steps]}
except Exception as e:
ms = int((time.time() - t0) * 1000)
errors.append((step["name"], str(e)[:120]))
_log({"model": step["name"], "ok": False, "ms": ms, "error": str(e)[:200]})
raise LLMUnavailable(errors)
if __name__ == "__main__":
args = [a for a in sys.argv[1:] if not a.startswith("--")]
if "--test-fallback" in sys.argv:
# принудительно: «локальная» модель недоступна → должен ответить DeepSeek
bad = [{"name": "qwen2.5:3b", "kind": "ollama", "timeout": 5},
{"name": "deepseek-flash", "kind": "deepseek", "timeout": 60}]
bad[0]["kind"] = "broken" # неизвестный тип → исключение до сети
bad[0]["__url__"] = OLLAMA
try:
r = ask("Ответь одним словом: работает?", max_tokens=20, chain=bad)
print("model=%s fallback=%s ms=%s text=%r"
% (r["model"], r["fallback"], r["ms"], r["text"][:80]))
except LLMUnavailable as e:
print("все модели недоступны:", e)
sys.exit(0)
prompt = args[0] if args else "Скажи одним коротким предложением, кто ты."
t0 = time.time()
try:
r = ask(prompt, max_tokens=120)
print("model=%s fallback=%s ms=%s" % (r["model"], r["fallback"], r["ms"]))
print(r["text"][:400])
except LLMUnavailable as e:
print("LLM недоступны:", e)
sys.exit(1)