chore: sync bridge/app.py
This commit is contained in:
1 parent
18439a98f2
commit
66530bd941
1 file changed
+86
-20
+86
-20
@@ -1,4 +1,4 @@
|
|||||||
import json, os, re, time, hashlib, uuid
|
import json, os, re, time, hashlib, uuid, math
|
||||||
import requests
|
import requests
|
||||||
from fastapi import FastAPI, Request
|
from fastapi import FastAPI, Request
|
||||||
from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
|
from fastapi.responses import JSONResponse, StreamingResponse, FileResponse
|
||||||
@@ -26,7 +26,7 @@ SESSIONS = {}
|
|||||||
|
|
||||||
SYS_PROMPT = """你是 mini-ERP 数据编织平台的问数分析师。依据【元数据】与【业务文档召回】回答用户问题,结合对话历史保持多轮一致。
|
SYS_PROMPT = """你是 mini-ERP 数据编织平台的问数分析师。依据【元数据】与【业务文档召回】回答用户问题,结合对话历史保持多轮一致。
|
||||||
可用查询引擎(Trino catalog):hive(离线数仓 ods/dwd/dws/ads, 按 dt 分区)、mysql(业务库 mini_erp 实时表)、doris(备用)。
|
可用查询引擎(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/结果。
|
规则:只允许 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}
|
严格输出单个 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。
|
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}"""
|
示例输出:{"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}"""
|
||||||
@@ -178,38 +178,101 @@ def md_table(cols, rows, limit=20):
|
|||||||
return "\n".join(lines)
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def chart_html(spec):
|
def _esc(s):
|
||||||
|
return str(s).replace("&", "&").replace("<", "<").replace(">", ">")
|
||||||
|
|
||||||
|
|
||||||
|
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"]
|
chart, cols, rows = spec["chart"], spec["columns"], spec["rows"]
|
||||||
xi = cols.index(chart["x"]) if chart["x"] in cols else 0
|
xi = cols.index(chart["x"]) if chart["x"] in cols else 0
|
||||||
yi = cols.index(chart["y"]) if chart["y"] in cols else 1
|
yi = cols.index(chart["y"]) if chart["y"] in cols else 1
|
||||||
xs = [str(r[xi]) for r in rows]
|
xs = [str(r[xi]) for r in rows]
|
||||||
ys = [r[yi] for r in rows]
|
ys = [float(r[yi] or 0) for r in rows]
|
||||||
ctype = chart.get("type", "bar")
|
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":
|
if ctype == "pie":
|
||||||
series = [{"type": "pie", "radius": "60%", "data": [{"name": x, "value": y} for x, y in zip(xs, ys)]}]
|
total = sum(ys) or 1
|
||||||
option = {"title": {"text": chart.get("title", "")}, "tooltip": {"trigger": "item"}, "series": series}
|
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:
|
else:
|
||||||
option = {"title": {"text": chart.get("title", "")}, "tooltip": {"trigger": "axis"},
|
ml, mr, mt, mb = 70, 30, 50, 100
|
||||||
"xAxis": {"type": "category", "data": xs}, "yAxis": {"type": "value"},
|
pw, ph = W - ml - mr, H - mt - mb
|
||||||
"series": [{"type": ctype, "data": ys, "smooth": ctype == "line"}]}
|
ymax = (max(ys) if ys else 1) * 1.15 or 1
|
||||||
cid = "c" + uuid.uuid4().hex[:8]
|
for i in range(6):
|
||||||
return ("```html\n<div id=\"" + cid + "\" style=\"width:100%;height:360px\"></div>\n"
|
y = mt + ph - ph * i / 5
|
||||||
"<script src=\"" + PUBLIC_BASE + "/static/echarts.min.js\"></script>\n"
|
p.append(f'<line x1="{ml}" y1="{y:.1f}" x2="{W-mr}" y2="{y:.1f}" stroke="#e3e6ea"/>')
|
||||||
"<script>var ch=echarts.init(document.getElementById('" + cid + "'));ch.setOption("
|
p.append(f'<text x="{ml-8}" y="{y+4:.1f}" text-anchor="end" font-size="11" fill="#666">{_fmt(ymax*i/5)}</text>')
|
||||||
+ json.dumps(option, ensure_ascii=False) + ");window.addEventListener('resize',function(){ch.resize();});</script>\n```")
|
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_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])}。明细见上表;图表点代码块右上“预览”在工件面板查看。")
|
||||||
|
return summary + "\n\n```html\n" + svg_chart(spec) + "\n```"
|
||||||
|
|
||||||
|
|
||||||
def render(plan, cols, rows, engine, err, sources, rmode, mmode):
|
def render(plan, cols, rows, engine, err, sources, rmode, mmode):
|
||||||
parts = [plan.get("answer") or ""]
|
parts = [plan.get("answer") or ""]
|
||||||
if err:
|
if err:
|
||||||
parts.append("> 查询失败: " + err + "(已尝试 Trino→Doris→MySQL 降级)")
|
parts.append("> 查询失败: " + err + "(已尝试 Trino→Doris→MySQL 降级)")
|
||||||
if plan.get("sql"):
|
|
||||||
parts.append("**SQL**(" + engine + ")\n```sql\n" + plan["sql"] + "\n```")
|
|
||||||
if cols:
|
if cols:
|
||||||
parts.append("**结果**(" + str(len(rows)) + " 行,展示前 20 行)\n" + md_table(cols, rows))
|
parts.append("**结果**(" + str(len(rows)) + " 行,展示前 20 行)\n" + md_table(cols, rows))
|
||||||
chart = plan.get("chart")
|
chart = plan.get("chart")
|
||||||
if chart and cols and rows:
|
if chart and cols and rows:
|
||||||
parts.append(chart_html({"chart": chart, "columns": cols, "rows": rows[:100]}))
|
parts.append(chart_block({"chart": chart, "columns": cols, "rows": rows[:100]}))
|
||||||
if sources:
|
if sources:
|
||||||
parts.append("*依据: " + "; ".join(list(dict.fromkeys(sources))[:4]) + f"(召回:{rmode} / 元数据:{mmode})*")
|
parts.append("*依据: " + "; ".join(list(dict.fromkeys(sources))[:4]) + f"(召回:{rmode} / 元数据:{mmode})*")
|
||||||
return "\n\n".join(p for p in parts if p)
|
return "\n\n".join(p for p in parts if p)
|
||||||
@@ -236,10 +299,13 @@ def fallback_pipeline(query, history):
|
|||||||
return render(plan, cols, rows[:200], engine, err, sources, rmode, mmode)
|
return render(plan, cols, rows[:200], engine, err, sources, rmode, mmode)
|
||||||
|
|
||||||
|
|
||||||
def echarts_to_html(answer):
|
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):
|
def repl(m):
|
||||||
try:
|
try:
|
||||||
return chart_html(json.loads(m.group(1)))
|
return chart_block(json.loads(m.group(1)))
|
||||||
except Exception:
|
except Exception:
|
||||||
return m.group(0)
|
return m.group(0)
|
||||||
return re.sub(r"```echarts\s*\n(.*?)\n```", repl, answer, flags=re.S)
|
return re.sub(r"```echarts\s*\n(.*?)\n```", repl, answer, flags=re.S)
|
||||||
@@ -256,7 +322,7 @@ def dify_chat(query, sess):
|
|||||||
if r.status_code != 200 or not j.get("answer"):
|
if r.status_code != 200 or not j.get("answer"):
|
||||||
raise RuntimeError(j.get("message", str(j))[:150])
|
raise RuntimeError(j.get("message", str(j))[:150])
|
||||||
sess["conversation_id"] = j.get("conversation_id")
|
sess["conversation_id"] = j.get("conversation_id")
|
||||||
return echarts_to_html(j["answer"])
|
return postprocess(j["answer"])
|
||||||
|
|
||||||
|
|
||||||
@app.get("/health")
|
@app.get("/health")
|
||||||
|
|||||||
Reference in new issue
Block a user