Files
2026-11-24 18:45:19 +00:00

417 lines
21 KiB
Python
Raw Permalink 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.
import json, os, re, time, hashlib, uuid, math
import requests
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
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")
CHART_DIR = os.environ.get("CHART_DIR", "/app/charts")
plt.rcParams["font.family"] = ["Noto Sans CJK SC", "sans-serif"]
plt.rcParams["axes.unicode_minus"] = False
app = FastAPI(title="mini-erp analyst bridge")
app.mount("/static", StaticFiles(directory=os.path.join(os.path.dirname(__file__), "static")), name="static")
os.makedirs(CHART_DIR, exist_ok=True)
app.mount("/charts", StaticFiles(directory=CHART_DIR), name="charts")
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 但必须重新执行(need_exec=true)。
严格输出单个 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 _esc(s):
return str(s).replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
def _fmt(v):
return f"{float(v):g}"
PALETTE = ["#4C78A8", "#F58518", "#54A24B", "#E45756", "#72B7B2", "#EECA3B", "#B279A2", "#FF9DA6"]
def svg_chart(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 = [float(r[yi] or 0) for r in rows]
ctype = chart.get("type", "bar")
title = _esc(chart.get("title", ""))
W, H = 760, 420
p = [f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}" font-family="Noto Sans CJK SC, Microsoft YaHei, PingFang SC, sans-serif">',
f'<rect width="{W}" height="{H}" fill="#ffffff"/>',
f'<text x="{W/2}" y="30" text-anchor="middle" font-size="17" font-weight="bold" fill="#222">{title}</text>']
if ctype == "pie":
total = sum(ys) or 1
cx, cy, r = 250, 230, 150
a0 = -90.0
for i, (x, v) in enumerate(zip(xs, ys)):
a1 = a0 + 360.0 * v / total
large = 1 if a1 - a0 > 180 else 0
x0, y0 = cx + r * math.cos(math.radians(a0)), cy + r * math.sin(math.radians(a0))
x1, y1 = cx + r * math.cos(math.radians(a1)), cy + r * math.sin(math.radians(a1))
p.append(f'<path d="M{cx},{cy} L{x0:.1f},{y0:.1f} A{r},{r} 0 {large} 1 {x1:.1f},{y1:.1f} Z" fill="{PALETTE[i % 8]}"/>')
ly = 90 + i * 26
p.append(f'<rect x="470" y="{ly-12}" width="14" height="14" fill="{PALETTE[i % 8]}"/>')
p.append(f'<text x="492" y="{ly}" font-size="13" fill="#333">{_esc(x)}:{_fmt(v)}({100*v/total:.1f}%)</text>')
a0 = a1
else:
ml, mr, mt, mb = 70, 30, 50, 100
pw, ph = W - ml - mr, H - mt - mb
ymax = (max(ys) if ys else 1) * 1.15 or 1
for i in range(6):
y = mt + ph - ph * i / 5
p.append(f'<line x1="{ml}" y1="{y:.1f}" x2="{W-mr}" y2="{y:.1f}" stroke="#e3e6ea"/>')
p.append(f'<text x="{ml-8}" y="{y+4:.1f}" text-anchor="end" font-size="11" fill="#666">{_fmt(ymax*i/5)}</text>')
p.append(f'<line x1="{ml}" y1="{mt+ph}" x2="{W-mr}" y2="{mt+ph}" stroke="#999"/>')
p.append(f'<line x1="{ml}" y1="{mt}" x2="{ml}" y2="{mt+ph}" stroke="#999"/>')
p.append(f'<text x="16" y="{mt+ph/2}" font-size="12" fill="#666" transform="rotate(-90 16 {mt+ph/2})" text-anchor="middle">{_esc(chart["y"])}</text>')
n = len(xs) or 1
rot = max((len(x) for x in xs), default=0) > 6
pts = []
for i, (x, v) in enumerate(zip(xs, ys)):
cx = ml + pw * (i + 0.5) / n
y = mt + ph - ph * v / ymax
pts.append((cx, y))
if ctype == "bar":
bw = pw / n * 0.6
p.append(f'<rect x="{cx-bw/2:.1f}" y="{y:.1f}" width="{bw:.1f}" height="{mt+ph-y:.1f}" fill="#4C78A8"/>')
p.append(f'<text x="{cx:.1f}" y="{y-6:.1f}" text-anchor="middle" font-size="11" fill="#333">{_fmt(v)}</text>')
ly = mt + ph + 20
tr = f' transform="rotate(-25 {cx:.1f} {ly})"' if rot else ""
anch = "end" if rot else "middle"
p.append(f'<text x="{cx:.1f}" y="{ly}" text-anchor="{anch}" font-size="12" fill="#333"{tr}>{_esc(x)}</text>')
if ctype == "line":
p.append('<polyline points="' + " ".join(f"{x:.1f},{y:.1f}" for x, y in pts) + '" fill="none" stroke="#4C78A8" stroke-width="2"/>')
for x, y in pts:
p.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="3.5" fill="#4C78A8"/>')
p.append("</svg>")
svg = "".join(p)
return ("<!DOCTYPE html><html lang=\"zh\"><head><meta charset=\"utf-8\"><title>" + title + "</title>"
"<style>body{margin:0;background:#fff;display:flex;align-items:center;justify-content:center;min-height:100vh}"
"svg{max-width:100%;height:auto}</style></head><body>" + svg + "</body></html>")
def chart_image(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 = [float(r[yi] or 0) for r in rows]
ctype = chart.get("type", "bar")
fig, ax = plt.subplots(figsize=(7.6, 4.2), dpi=100)
colors = [PALETTE[i % 8] for i in range(len(ys))]
if ctype == "pie":
ax.pie(ys, labels=xs, autopct="%1.1f%%", colors=colors, startangle=90,
textprops={"fontsize": 10})
ax.axis("equal")
else:
if ctype == "line":
ax.plot(xs, ys, marker="o", color=PALETTE[0])
else:
ax.bar(xs, ys, color=PALETTE[0], width=0.6)
for i, v in enumerate(ys):
ax.text(i, v, _fmt(v), ha="center", va="bottom", fontsize=9)
ax.grid(axis="y", color="#e3e6ea")
ax.set_axisbelow(True)
ax.set_ylabel(chart["y"])
if max((len(x) for x in xs), default=0) > 6:
ax.tick_params(axis="x", rotation=25)
ax.set_title(chart.get("title", ""))
fig.tight_layout()
name = uuid.uuid4().hex[:12] + ".png"
fig.savefig(os.path.join(CHART_DIR, name), facecolor="white")
plt.close(fig)
return PUBLIC_BASE + "/charts/" + name
def chart_block(spec):
rows = spec["rows"]
cols = spec["columns"]
yi = cols.index(spec["chart"]["y"]) if spec["chart"]["y"] in cols else 1
xi = cols.index(spec["chart"]["x"]) if spec["chart"]["x"] in cols else 0
ys = [float(r[yi] or 0) for r in rows]
top = max(range(len(ys)), key=lambda i: ys[i]) if ys else 0
summary = (f"**数据摘要**({len(rows)} 行):合计 {_fmt(sum(ys))};"
f"最高 {rows[top][xi]} {_fmt(ys[top])}。明细见上表,图表见下图;"
f"HTML 工件默认折叠,点代码块右上“预览”可在工件面板查看。")
img = chart_image(spec)
title = _esc(spec["chart"].get("title", "图表"))
return summary + "\n\n" + f"![{title}]({img})" + "\n\n```html\n" + svg_chart(spec) + "\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 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_block({"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 postprocess(answer):
answer = re.sub(r"\*\*SQL\*\*([^)]*)\s*\n```sql\n.*?\n```", "", answer, flags=re.S)
answer = re.sub(r"```sql\n.*?\n```", "", answer, flags=re.S)
def repl(m):
try:
return chart_block(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 postprocess(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}})