settings.py
3.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
"""运行参数 / 本体 / 概览 / 健康检查。"""
from __future__ import annotations
import json
import logging
from fastapi import APIRouter, Depends, HTTPException
from ..core import db, identity, llm
from ..core.config import RUNTIME_META
from ..jobs.queue import runner
from ..schemas import ConfigUpdate, OntologyUpdate
from . import deps
log = logging.getLogger(__name__)
router = APIRouter(prefix="/api", tags=["settings"], dependencies=[Depends(identity.require_rw("view", "admin"))])
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("/info")
async def info():
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"),
"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 连落地页都没有,打开就是一个空的上传框。"""
return {"info": await info(),
"documents": db.list_documents()[:8],
"jobs": db.list_jobs(6),
"queries": db.list_queries(6)}
@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", "index": False, "db": False}
try:
deps.index()
out["index"] = True
except Exception as e: # noqa: BLE001
out["status"] = "degraded"
out["index_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