307 lines
15 KiB
Python
307 lines
15 KiB
Python
import json, os, re, time, hashlib, uuid
|
||
import requests
|
||
from fastapi import FastAPI, Request
|
||
from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
|
||
from fastapi.staticfiles import StaticFiles
|
||
|
||
DIFY = os.environ.get("DIFY_URL", "http://192.168.50.176:8088")
|
||
DIFY_KEY = os.environ.get("DIFY_KEY", "app-ENM6bKYCsE3xa3VIrkSQFogr")
|
||
TRINO = os.environ.get("TRINO_URL", "http://192.168.50.176:8090")
|
||
QDRANT = os.environ.get("QDRANT_URL", "http://192.168.50.176:6333")
|
||
OLLAMA = os.environ.get("OLLAMA_URL", "http://192.168.50.176:11434")
|
||
GITEA = os.environ.get("GITEA_URL", "http://192.168.50.176:3001")
|
||
GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c"}
|
||
REPO = "admin/mini-erp-fabric-demo"
|
||
DATAHUB = os.environ.get("DATAHUB_URL", "http://192.168.50.176:8080")
|
||
DH_HDRS = {"Authorization": "Bearer app-iBQEBasOC4aVSn2xZRxPk5zW", "Content-Type": "application/json"}
|
||
DORIS = ("192.168.50.207", 9030, "root", "")
|
||
MYSQL = ("192.168.50.176", 3308, "erp", "erp_pass_123")
|
||
LOCAL_LLM = os.environ.get("LOCAL_LLM", "qwen2.5:7b")
|
||
COLL = "mini_erp_docs"
|
||
PUBLIC_BASE = os.environ.get("PUBLIC_BASE", "http://localhost:8010")
|
||
|
||
app = FastAPI(title="mini-erp analyst bridge")
|
||
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static")
|
||
SESSIONS = {}
|
||
|
||
SYS_PROMPT = """你是 mini-ERP 数据编织平台的问数分析师。依据【元数据】与【业务文档召回】回答用户问题,结合对话历史保持多轮一致。
|
||
可用查询引擎(Trino catalog):hive(离线数仓 ods/dwd/dws/ads, 按 dt 分区)、mysql(业务库 mini_erp 实时表)、doris(备用)。
|
||
规则:只允许 SELECT/WITH/SHOW/DESCRIBE;默认 LIMIT 200;表名带 catalog 与库名(hive.ads.xxx / mysql.mini_erp.xxx);字段必须来自元数据;口径以业务文档召回为准;hive 查询尽量带 dt 过滤(最新分区 dt=(SELECT MAX(dt) FROM 同表));追问图表可复用上一轮 SQL/结果。
|
||
严格输出单个 JSON 对象(无围栏):{"answer":"中文结论","sql":"SELECT...或null","catalog":"hive|mysql|doris","chart":{"type":"bar|line|pie","x":"列名","y":"列名","title":"标题"}或null,"need_exec":true|false}
|
||
chart 仅在结果>=2行且含数值列(趋势/对比/占比/排行)时给出,否则 null。
|
||
示例输出:{"answer":"最近一天采购入库金额为 19760 元,共 4 单。","sql":"SELECT stat_date, received_amount FROM hive.ads.ads_purchase_kpi_1d WHERE dt=(SELECT MAX(dt) FROM hive.ads.ads_purchase_kpi_1d)","catalog":"hive","chart":null,"need_exec":true}"""
|
||
|
||
|
||
def session_key(messages):
|
||
first = next((m["content"] for m in messages if m.get("role") == "user"), "")
|
||
return hashlib.sha1(str(first).encode("utf-8")).hexdigest()[:16]
|
||
|
||
|
||
def recall(query):
|
||
try:
|
||
r = requests.post(OLLAMA + "/api/embed", json={"model": "bge-m3", "input": [query]}, timeout=60)
|
||
r.raise_for_status()
|
||
vec = r.json()["embeddings"][0]
|
||
s = requests.post(QDRANT + f"/collections/{COLL}/points/search",
|
||
json={"vector": vec, "limit": 6, "score_threshold": 0.35, "with_payload": True}, timeout=20)
|
||
s.raise_for_status()
|
||
pts = s.json().get("result", [])
|
||
if pts:
|
||
return "\n---\n".join("[%.2f] %s\n%s" % (p["score"], p["payload"].get("title", ""), p["payload"].get("text", "")) for p in pts), \
|
||
[p["payload"].get("doc_path", "") for p in pts], "vector"
|
||
except Exception:
|
||
pass
|
||
tree = requests.get(GITEA + f"/api/v1/repos/{REPO}/git/trees/main?recursive=true", headers=GH, timeout=20).json()
|
||
paths = [t["path"] for t in tree.get("tree", []) if t["path"].startswith("docs/") and t["path"].endswith(".md")]
|
||
terms = [w for w in re.split(r"[\s,,。??、/]+", query) if len(w) >= 2]
|
||
scored = []
|
||
for p in paths:
|
||
txt = requests.get(GITEA + f"/api/v1/repos/{REPO}/raw/" + p, headers=GH, timeout=20).text
|
||
sc = sum(txt.count(w) for w in terms)
|
||
if sc:
|
||
scored.append((sc, p, txt))
|
||
scored.sort(reverse=True)
|
||
blocks = []
|
||
for sc, p, txt in scored[:3]:
|
||
secs = re.split(r"\n(?=#{1,4}\s)", txt)
|
||
best = sorted(secs, key=lambda s: sum(s.count(w) for w in terms), reverse=True)[:2]
|
||
blocks.append("\n".join(best)[:1500])
|
||
return "\n---\n".join(blocks), [p for _, p, _ in scored[:3]], "keyword"
|
||
|
||
|
||
def metadata():
|
||
try:
|
||
q = '{ search(input:{type:DATASET, query:"*", start:0, count:60}) { searchResults { entity { urn ... on Dataset { properties { description } schemaMetadata { fields { fieldPath nativeType } } } } } } }'
|
||
j = requests.post(DATAHUB + "/api/graphql", headers=DH_HDRS, json={"query": q}, timeout=30).json()
|
||
out = []
|
||
for sr in j["data"]["search"]["searchResults"]:
|
||
e = sr["entity"]
|
||
urn = e["urn"]
|
||
if ":hive," not in urn and ":mysql," not in urn:
|
||
continue
|
||
plat = "hive" if ":hive," in urn else "mysql"
|
||
tbl = urn.split(",")[1]
|
||
fields = (e.get("schemaMetadata") or {}).get("fields") or []
|
||
fs = ", ".join(f["fieldPath"] + ":" + (f.get("nativeType") or "") for f in fields)
|
||
desc = (e.get("properties") or {}).get("description") or ""
|
||
out.append(f"{plat}.{tbl} | {desc[:80]} | {fs}")
|
||
if out:
|
||
return "\n".join(out), "datahub"
|
||
except Exception:
|
||
pass
|
||
ht = requests.get(GITEA + f"/api/v1/repos/{REPO}/raw/05_sync/hive_tables.json", headers=GH, timeout=20).json()
|
||
out = ["hive.%s.%s | %s" % (t["db"], t["table"], ", ".join(c["name"] + ":" + c["type"] for c in t["columns"])) for t in ht["tables"]]
|
||
dd = requests.get(GITEA + f"/api/v1/repos/{REPO}/raw/docs/04-%E6%95%B0%E6%8D%AE%E5%AD%97%E5%85%B8.md", headers=GH, timeout=20).text
|
||
out.append("【MySQL 源表字典摘录】\n" + dd[:3000])
|
||
return "\n".join(out), "gitea"
|
||
|
||
|
||
def trino_query(sql):
|
||
r = requests.post(TRINO + "/v1/statement", headers={"X-Trino-User": "bridge", "Content-Type": "text/plain"},
|
||
data=sql.encode("utf-8"), timeout=30)
|
||
j = r.json()
|
||
cols, rows = None, []
|
||
for _ in range(300):
|
||
if j.get("error"):
|
||
raise RuntimeError(j["error"].get("message", "")[:200])
|
||
if j.get("columns") and cols is None:
|
||
cols = [c["name"] for c in j["columns"]]
|
||
if j.get("data"):
|
||
rows.extend(j["data"])
|
||
nxt = j.get("nextUri")
|
||
if not nxt:
|
||
break
|
||
time.sleep(0.2)
|
||
j = requests.get(nxt, headers={"X-Trino-User": "bridge"}, timeout=30).json()
|
||
return cols or [], rows
|
||
|
||
|
||
def mysql_query(host, port, user, pwd, sql, db=None):
|
||
import pymysql
|
||
conn = pymysql.connect(host=host, port=port, user=user, password=pwd, database=db, connect_timeout=10, read_timeout=60)
|
||
try:
|
||
cur = conn.cursor()
|
||
cur.execute(sql)
|
||
cols = [d[0] for d in cur.description] if cur.description else []
|
||
rows = [list(r) for r in cur.fetchall()]
|
||
cur.close()
|
||
return cols, rows
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def execute(sql, catalog):
|
||
try:
|
||
cols, rows = trino_query(sql)
|
||
return cols, rows, "trino/" + (catalog or "-"), ""
|
||
except Exception as e:
|
||
err = str(e)[:150]
|
||
if catalog == "hive" or sql.strip().lower().startswith("hive.") or " hive." in sql.lower():
|
||
try:
|
||
cols, rows = mysql_query(*DORIS, sql.replace("hive.", "hive_warehouse."), db=None)
|
||
return cols, rows, "doris(fallback)", ""
|
||
except Exception as e2:
|
||
err += " | doris: " + str(e2)[:100]
|
||
try:
|
||
s2 = re.sub(r"\bmysql\.", "", sql)
|
||
cols, rows = mysql_query(*MYSQL, s2, db="mini_erp")
|
||
return cols, rows, "mysql(fallback)", ""
|
||
except Exception as e3:
|
||
return [], [], "", err + " | mysql: " + str(e3)[:100]
|
||
|
||
|
||
def parse_plan(text):
|
||
t = re.sub(r"^```(?:json)?\s*", "", text.strip())
|
||
t = re.sub(r"\s*```$", "", t)
|
||
m = re.search(r"\{.*\}", t, re.S)
|
||
try:
|
||
p = json.loads(m.group(0) if m else t)
|
||
if isinstance(p, dict) and ("answer" in p or "sql" in p):
|
||
return p
|
||
except Exception:
|
||
pass
|
||
fm = re.search(r"```sql\s*\n(.*?)```", text, re.S)
|
||
sql = fm.group(1).strip() if fm else ""
|
||
if not sql:
|
||
sm = re.search(r"(?is)\b((?:select|with)\s.+?)(?:;|\n\s*\n|$)", text)
|
||
sql = sm.group(1).strip() if sm else ""
|
||
answer = re.sub(r"```(?:sql|json)?.*?```", "", text, flags=re.S).strip()[:800] or "(本地降级模型输出)"
|
||
catalog = "mysql" if re.search(r"\bmysql\.", sql) else "hive"
|
||
return {"answer": answer, "sql": sql or None, "catalog": catalog, "chart": None, "need_exec": bool(sql)}
|
||
|
||
|
||
def md_table(cols, rows, limit=20):
|
||
if not cols:
|
||
return ""
|
||
lines = ["| " + " | ".join(cols) + " |", "| " + " | ".join(["---"] * len(cols)) + " |"]
|
||
lines += ["| " + " | ".join("" if v is None else str(v) for v in r) + " |" for r in rows[:limit]]
|
||
return "\n".join(lines)
|
||
|
||
|
||
def chart_html(spec):
|
||
chart, cols, rows = spec["chart"], spec["columns"], spec["rows"]
|
||
xi = cols.index(chart["x"]) if chart["x"] in cols else 0
|
||
yi = cols.index(chart["y"]) if chart["y"] in cols else 1
|
||
xs = [str(r[xi]) for r in rows]
|
||
ys = [r[yi] for r in rows]
|
||
ctype = chart.get("type", "bar")
|
||
if ctype == "pie":
|
||
series = [{"type": "pie", "radius": "60%", "data": [{"name": x, "value": y} for x, y in zip(xs, ys)]}]
|
||
option = {"title": {"text": chart.get("title", "")}, "tooltip": {"trigger": "item"}, "series": series}
|
||
else:
|
||
option = {"title": {"text": chart.get("title", "")}, "tooltip": {"trigger": "axis"},
|
||
"xAxis": {"type": "category", "data": xs}, "yAxis": {"type": "value"},
|
||
"series": [{"type": ctype, "data": ys, "smooth": ctype == "line"}]}
|
||
cid = "c" + uuid.uuid4().hex[:8]
|
||
return ("```html\n<div id=\"" + cid + "\" style=\"width:100%;height:360px\"></div>\n"
|
||
"<script src=\"" + PUBLIC_BASE + "/static/echarts.min.js\"></script>\n"
|
||
"<script>var ch=echarts.init(document.getElementById('" + cid + "'));ch.setOption("
|
||
+ json.dumps(option, ensure_ascii=False) + ");window.addEventListener('resize',function(){ch.resize();});</script>\n```")
|
||
|
||
|
||
def render(plan, cols, rows, engine, err, sources, rmode, mmode):
|
||
parts = [plan.get("answer") or ""]
|
||
if err:
|
||
parts.append("> 查询失败: " + err + "(已尝试 Trino→Doris→MySQL 降级)")
|
||
if plan.get("sql"):
|
||
parts.append("**SQL**(" + engine + ")\n```sql\n" + plan["sql"] + "\n```")
|
||
if cols:
|
||
parts.append("**结果**(" + str(len(rows)) + " 行,展示前 20 行)\n" + md_table(cols, rows))
|
||
chart = plan.get("chart")
|
||
if chart and cols and rows:
|
||
parts.append(chart_html({"chart": chart, "columns": cols, "rows": rows[:100]}))
|
||
if sources:
|
||
parts.append("*依据: " + "; ".join(list(dict.fromkeys(sources))[:4]) + f"(召回:{rmode} / 元数据:{mmode})*")
|
||
return "\n\n".join(p for p in parts if p)
|
||
|
||
|
||
def fallback_pipeline(query, history):
|
||
recall_text, sources, rmode = recall(query)
|
||
meta_text, mmode = metadata()
|
||
recall_text, meta_text = recall_text[:2200], meta_text[:4500]
|
||
msgs = [{"role": "system", "content": SYS_PROMPT}]
|
||
msgs += [{"role": m["role"], "content": m["content"]} for m in history[-8:]]
|
||
msgs.append({"role": "user", "content": f"【元数据】\n{meta_text}\n\n【业务文档召回】\n{recall_text}\n\n【用户问题】\n{query}\n\n再次强调:只输出单个 JSON 对象,禁止解释与围栏。"})
|
||
r = requests.post(OLLAMA + "/api/chat", json={"model": LOCAL_LLM, "messages": msgs, "stream": False,
|
||
"options": {"temperature": 0.1}}, timeout=240)
|
||
r.raise_for_status()
|
||
plan = parse_plan(r.json()["message"]["content"])
|
||
cols, rows, engine, err = [], [], "", ""
|
||
sql = (plan.get("sql") or "").strip()
|
||
if sql and plan.get("need_exec", True):
|
||
if re.match(r"(?is)^\s*(select|with|show|describe)\b", sql):
|
||
cols, rows, engine, err = execute(sql, plan.get("catalog", ""))
|
||
else:
|
||
err = "rejected: only SELECT allowed"
|
||
return render(plan, cols, rows[:200], engine, err, sources, rmode, mmode)
|
||
|
||
|
||
def echarts_to_html(answer):
|
||
def repl(m):
|
||
try:
|
||
return chart_html(json.loads(m.group(1)))
|
||
except Exception:
|
||
return m.group(0)
|
||
return re.sub(r"```echarts\s*\n(.*?)\n```", repl, answer, flags=re.S)
|
||
|
||
|
||
def dify_chat(query, sess):
|
||
body = {"inputs": {}, "query": query, "response_mode": "blocking",
|
||
"user": "owui-" + sess["key"], "auto_generate_name": False}
|
||
if sess.get("conversation_id"):
|
||
body["conversation_id"] = sess["conversation_id"]
|
||
r = requests.post(DIFY + "/v1/chat-messages", headers={"Authorization": "Bearer " + DIFY_KEY,
|
||
"Content-Type": "application/json"}, json=body, timeout=240)
|
||
j = r.json()
|
||
if r.status_code != 200 or not j.get("answer"):
|
||
raise RuntimeError(j.get("message", str(j))[:150])
|
||
sess["conversation_id"] = j.get("conversation_id")
|
||
return echarts_to_html(j["answer"])
|
||
|
||
|
||
@app.get("/health")
|
||
def health():
|
||
return {"status": True}
|
||
|
||
|
||
@app.get("/v1/models")
|
||
def models():
|
||
return {"object": "list", "data": [{"id": "mini-erp-analyst", "object": "model", "created": 0, "owned_by": "mini-erp"}]}
|
||
|
||
|
||
@app.post("/v1/chat/completions")
|
||
async def completions(req: Request):
|
||
body = await req.json()
|
||
messages = body.get("messages", [])
|
||
query = next((m["content"] for m in reversed(messages) if m.get("role") == "user"), "")
|
||
key = session_key(messages)
|
||
sess = SESSIONS.setdefault(key, {"key": key, "history": []})
|
||
mode = "dify"
|
||
try:
|
||
answer = dify_chat(query, sess)
|
||
except Exception as e:
|
||
mode = "fallback"
|
||
try:
|
||
answer = fallback_pipeline(query, sess["history"])
|
||
except Exception as e2:
|
||
answer = f"问数链路暂不可用:Dify({str(e)[:80]});降级({str(e2)[:80]})。请稍后重试。"
|
||
sess["history"].append({"role": "user", "content": query})
|
||
sess["history"].append({"role": "assistant", "content": answer})
|
||
sess["history"] = sess["history"][-20:]
|
||
cid = "chatcmpl-" + uuid.uuid4().hex[:12]
|
||
created = int(time.time())
|
||
if body.get("stream"):
|
||
def gen():
|
||
chunks = [answer[i:i + 120] for i in range(0, len(answer), 120)] or [""]
|
||
for c in chunks:
|
||
yield "data: " + json.dumps({"id": cid, "object": "chat.completion.chunk", "created": created,
|
||
"model": "mini-erp-analyst",
|
||
"choices": [{"index": 0, "delta": {"content": c}, "finish_reason": None}]}, ensure_ascii=False) + "\n\n"
|
||
yield "data: " + json.dumps({"id": cid, "object": "chat.completion.chunk", "created": created,
|
||
"model": "mini-erp-analyst",
|
||
"choices": [{"index": 0, "delta": {}, "finish_reason": "stop"}]}) + "\n\n"
|
||
yield "data: [DONE]\n\n"
|
||
return StreamingResponse(gen(), media_type="text/event-stream")
|
||
return JSONResponse({"id": cid, "object": "chat.completion", "created": created, "model": "mini-erp-analyst",
|
||
"choices": [{"index": 0, "message": {"role": "assistant", "content": answer}, "finish_reason": "stop"}],
|
||
"usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}}) |