Files
elmer/api/ping.py
T

65 lines
2.3 KiB
Python
Raw 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.
"""Эндпоинты проверки доступности.
GET /api/v1/ping — проверка сервера
GET /api/v1/ping-llm — проверка LLM (с адаптивным кэшем)
"""
import logging
import time
from flask import jsonify, request
from api.config import load
from brain.client import Diagnoser
logger = logging.getLogger("elmer.ping")
# Кэш для /ping-llm (успех=60с, ошибка=7с)
_ping_llm_cache: dict = {}
def register(app):
"""Регистрирует ping-эндпоинты на Flask-приложении."""
@app.route("/api/v1/ping", methods=["GET"])
def ping():
"""Быстрая проверка доступности сервера."""
return {"ok": True}
@app.route("/api/v1/ping-llm", methods=["GET"])
def ping_llm():
"""Проверка LLM с адаптивным кэшем (успех=60с, ошибка=7с)."""
cfg = load()
required = cfg.get("api", {}).get("key", "")
if required and request.headers.get("X-Api-Key", "") != required:
return jsonify({"ok": False, "error": "unauthorized"}), 401
global _ping_llm_cache
now = time.time()
if _ping_llm_cache:
ttl = _ping_llm_cache.get("ttl", 7)
if (now - _ping_llm_cache.get("ts", 0)) < ttl:
return jsonify(_ping_llm_cache["data"])
cfg = load()
api_key = cfg["llm"]["api_key"]
if not api_key:
result = {"ok": False, "error": "no API key"}
else:
t0 = time.time()
try:
diagnoser = Diagnoser(
api_key=api_key,
model=cfg["llm"].get("model", "gpt-oss-120b"),
base_url=cfg["llm"].get("base_url", "https://api.aillm.ru/v1"),
)
diagnoser.diagnose("Отвечай одним словом.", "OK")
ms = int((time.time() - t0) * 1000)
result = {"ok": True, "ms": ms}
except Exception as e:
ms = int((time.time() - t0) * 1000)
result = {"ok": False, "ms": ms, "error": "LLM unavailable"}
ttl = 60 if result.get("ok") else 7
_ping_llm_cache = {"ts": now, "data": result, "ttl": ttl}
return jsonify(result)