settings.py 5.29 KB
"""运行参数 / 本体 / 概览 / 健康检查。"""
from __future__ import annotations
import json
import logging

from fastapi import APIRouter, HTTPException

from ..core import db, llm
from ..core.config import RUNTIME_META
from ..core.ontology import (DEFAULT_ENTITY_TYPES, DEFAULT_RELATION_TYPES,
                             ENTITY_TYPE_SPEC, RELATION_TYPE_SPEC, default_ontology)
from ..jobs.queue import runner
from ..schemas import ConfigUpdate, OntologyUpdate
from . import deps

log = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["settings"])


def _validate(key: str, value: str) -> str:
    meta = RUNTIME_META.get(key)
    if not meta:
        return value
    kind = meta.get("type")
    if kind == "int":
        try:
            v = int(float(value))
        except (TypeError, ValueError) as e:
            raise HTTPException(400, f"{meta['label']} 必须是整数") from e
        lo, hi = meta.get("min"), meta.get("max")
        if lo is not None and v < lo or hi is not None and v > hi:
            raise HTTPException(400, f"{meta['label']} 必须在 {lo}~{hi} 之间")
        return str(v)
    if kind == "float":
        try:
            v = float(value)
        except (TypeError, ValueError) as e:
            raise HTTPException(400, f"{meta['label']} 必须是数字") from e
        lo, hi = meta.get("min"), meta.get("max")
        if lo is not None and v < lo or hi is not None and v > hi:
            raise HTTPException(400, f"{meta['label']} 必须在 {lo}~{hi} 之间")
        return str(v)
    if kind == "bool":
        return "1" if str(value) in ("1", "true", "True", "on", "yes") else "0"
    if kind == "enum" and value not in (meta.get("options") or []):
        raise HTTPException(400, f"{meta['label']} 只能是 {meta.get('options')} 之一")
    return value


@router.get("/config")
async def get_config():
    cfg = db.get_all_config()
    cfg.pop("ONTOLOGY", None)
    groups: dict[str, list[dict]] = {}
    for key, meta in RUNTIME_META.items():
        if key not in cfg:
            continue
        groups.setdefault(meta["group"], []).append({**meta, "key": key, "value": cfg[key]})
    return {"values": cfg, "groups": groups}


@router.put("/config")
async def put_config(payload: ConfigUpdate):
    items = {k: _validate(k, v) for k, v in payload.items.items() if k in RUNTIME_META}
    if not items:
        raise HTTPException(400, "没有可保存的合法配置项")
    db.set_config(items)
    return {"ok": True, "saved": list(items)}


@router.get("/ontology")
async def get_ontology():
    raw = db.get_config("ONTOLOGY")
    try:
        onto = json.loads(raw)
    except Exception:
        onto = default_ontology()
    return {**onto,
            "available_entity_types": [{"name": t, "desc": d, "example": e}
                                       for t, d, e in ENTITY_TYPE_SPEC],
            "available_relation_types": [{"name": t, "desc": d} for t, d in RELATION_TYPE_SPEC]}


@router.put("/ontology")
async def put_ontology(payload: OntologyUpdate):
    ent = [t.strip() for t in payload.entity_types if t.strip()] or list(DEFAULT_ENTITY_TYPES)
    rel = [t.strip() for t in payload.relation_types if t.strip()] or list(DEFAULT_RELATION_TYPES)
    if "其他" not in ent:
        ent.append("其他")      # 闭集必须留一个兜底类目,否则模型会自造
    if "关联" not in rel:
        rel.append("关联")
    db.set_config({"ONTOLOGY": json.dumps({"entity_types": ent, "relation_types": rel},
                                          ensure_ascii=False)})
    return {"ok": True, "entity_types": ent, "relation_types": rel}


@router.get("/info")
async def info():
    g = deps.graph()
    stats = g.stats()
    docs = db.list_documents()
    return {
        "model": db.get_config("QWEN_MODEL"),
        "embed_model": db.get_config("EMBED_MODEL"),
        "rerank_model": db.get_config("RERANK_MODEL"),
        "default_mode": db.get_config("DEFAULT_MODE"),
        "stats": stats,
        "index": deps.index().stats(),
        "doc_count": len(docs),
        "doc_done": sum(1 for d in docs if d["status"] == "done"),
        "queue_depth": runner.queue_depth(),
        "cache": llm.cache_stats(),
    }


@router.get("/overview")
async def overview():
    """概览页数据。v1 连落地页都没有,打开就是一个空的上传框。"""
    g = deps.graph()
    return {"info": await info(),
            "documents": db.list_documents()[:8],
            "jobs": db.list_jobs(6),
            "queries": db.list_queries(6),
            "communities": [{"id": r["id"], "title": r["title"], "size": r["size"],
                             "summary": r.get("summary", "")}
                            for r in deps.communities().reports[:8]]}


@router.post("/cache/clear")
async def clear_cache():
    llm.clear_cache()
    return {"ok": True}


health_router = APIRouter(tags=["health"])


@health_router.get("/healthz")
async def healthz():
    out = {"status": "ok", "graph": False, "db": False}
    try:
        deps.graph()
        out["graph"] = True
    except Exception as e:  # noqa: BLE001
        out["status"] = "degraded"
        out["graph_error"] = str(e)[:200]
    try:
        db.get_config("QWEN_MODEL")
        out["db"] = True
    except Exception as e:  # noqa: BLE001
        out["status"] = "degraded"
        out["db_error"] = str(e)[:200]
    return out