From 66530bd9410bd4ea8cf77bbc03653142336b4481 Mon Sep 17 00:00:00 2001 From: admin <2775444633@qq.com> Date: Tue, 24 Nov 2026 18:31:57 +0000 Subject: [PATCH] chore: sync bridge/app.py --- bridge/app.py | 106 ++++++++++++++++++++++++++++++++++++++++---------- 1 file changed, 86 insertions(+), 20 deletions(-) diff --git a/bridge/app.py b/bridge/app.py index 8570751..f3c2155 100644 --- a/bridge/app.py +++ b/bridge/app.py @@ -1,4 +1,4 @@ -import json, os, re, time, hashlib, uuid +import json, os, re, time, hashlib, uuid, math import requests from fastapi import FastAPI, Request from fastapi.responses import JSONResponse, StreamingResponse, FileResponse @@ -26,7 +26,7 @@ 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/结果。 +规则:只允许 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}""" @@ -178,38 +178,101 @@ def md_table(cols, rows, limit=20): 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"] 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] + 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'', + f'', + f'{title}'] 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} + 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'') + ly = 90 + i * 26 + p.append(f'') + p.append(f'{_esc(x)}:{_fmt(v)}({100*v/total:.1f}%)') + a0 = a1 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
\n" - "\n" - "\n```") + 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'') + p.append(f'{_fmt(ymax*i/5)}') + p.append(f'') + p.append(f'') + p.append(f'{_esc(chart["y"])}') + 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'') + p.append(f'{_fmt(v)}') + ly = mt + ph + 20 + tr = f' transform="rotate(-25 {cx:.1f} {ly})"' if rot else "" + anch = "end" if rot else "middle" + p.append(f'{_esc(x)}') + if ctype == "line": + p.append('') + for x, y in pts: + p.append(f'') + p.append("") + svg = "".join(p) + return ("" + title + "" + "" + svg + "") + + +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): 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]})) + 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) @@ -236,10 +299,13 @@ def fallback_pipeline(query, history): 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): try: - return chart_html(json.loads(m.group(1))) + 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) @@ -256,7 +322,7 @@ def dify_chat(query, sess): 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"]) + return postprocess(j["answer"]) @app.get("/health")