Files
mini-erp-fabric-demo/deploy/gen_chatflow_draft.js
T

262 lines
14 KiB
JavaScript
Raw 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.
// 生成 Dify chatflow「mini-ERP 问数分析师」draft:元数据(DataHub)+语义召回(Qdrant)+NL2SQL+Trino 执行+多轮
// 用法: node deploy/gen_chatflow_draft.js > deploy/analyst_chatflow_draft.json
const N = {
start: "9300000000001", context: "9300000000002", llm: "9300000000003",
exec: "9300000000004", render: "9300000000005", answer: "9300000000006",
};
const CODE_CONTEXT = `import requests, json, re
QDRANT = "http://192.168.50.176:6333"
COLL = "mini_erp_docs"
OLLAMA = "http://192.168.50.176:11434"
GITEA = "http://gitea:3000"
REPO = "admin/mini-erp-fabric-demo"
GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c"}
DH = "http://datahub-datahub-gms-1:8080"
DH_HDRS = {"Authorization": "Bearer app-iBQEBasOC4aVSn2xZRxPk5zW", "Content-Type": "application/json"}
def recall_vector(query):
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 + "/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", [])
blocks = ["[%.2f] %s\\n%s" % (p["score"], p["payload"].get("title", ""), p["payload"].get("text", "")) for p in pts]
sources = [p["payload"].get("doc_path", "") + "#" + p["payload"].get("title", "") for p in pts]
return "\\n---\\n".join(blocks), sources
def recall_keyword(query):
tree = requests.get(GITEA + "/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 + "/api/v1/repos/" + REPO + "/raw/" + p, headers=GH, timeout=20).text
score = sum(txt.count(w) for w in terms)
if score > 0:
scored.append((score, p, txt))
scored.sort(reverse=True)
blocks, sources = [], []
for score, 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])
sources.append(p)
return "\\n---\\n".join(blocks), sources
def meta_datahub():
q = '{ search(input:{type:DATASET, query:"*", start:0, count:60}) { total searchResults { entity { urn ... on Dataset { name properties { description } schemaMetadata { fields { fieldPath nativeType description } } } } } } }'
r = requests.post(DH + "/api/graphql", headers=DH_HDRS, json={"query": q}, timeout=30)
j = r.json()
if "errors" in j:
raise RuntimeError(str(j["errors"])[:100])
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("%s.%s | %s | %s" % (plat, tbl, desc[:80], fs))
if not out:
raise RuntimeError("empty datahub result")
return "\\n".join(out)
def meta_gitea():
ht = requests.get(GITEA + "/api/v1/repos/" + REPO + "/raw/05_sync/hive_tables.json", headers=GH, timeout=20).json()
out = []
for t in ht["tables"]:
fs = ", ".join(c["name"] + ":" + c["type"] for c in t["columns"])
out.append("hive.%s.%s | %s | %s" % (t["db"], t["table"], (t.get("comment") or "")[:60], fs))
dd = requests.get(GITEA + "/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 源表字典(docs/04 摘录)】\\n" + dd[:3000])
return "\\n".join(out)
def main(query: str):
recall_mode, meta_mode = "vector", "datahub"
try:
recall_text, sources = recall_vector(query)
if not recall_text:
raise RuntimeError("empty recall")
except Exception:
recall_mode = "keyword"
try:
recall_text, sources = recall_keyword(query)
except Exception:
recall_text, sources = "", []
try:
meta_text = meta_datahub()
except Exception:
meta_mode = "gitea"
try:
meta_text = meta_gitea()
except Exception:
meta_text = ""
return {"recall_text": recall_text, "meta_text": meta_text,
"sources_json": json.dumps(sources, ensure_ascii=False),
"recall_mode": recall_mode, "meta_mode": meta_mode}`;
const SYS_PROMPT = `你是 mini-ERP 数据编织平台的问数分析师。依据【元数据】与【业务文档召回】回答用户问题,多轮对话中记住此前查询与结论。
可用查询引擎(Trino catalog):
- hive: 离线数仓 ods/dwd/dws/ads 分层表(按 dt 分区, 日粒度)。汇总/趋势/排行优先用 dws/ads。
- mysql: 业务库 mini_erp 实时表(supplier/customer/sku/stock/stock_flow/po_order/po_order_item/so_order/so_order_item/mdm_alias_mapping)。实时余额/明细用 mysql。
- doris: Doris 内表(若存在),一般不用。
规则:
1. 只允许 SELECT/WITH/SHOW/DESCRIBE,禁止任何写操作;结果默认 LIMIT 200。
2. 表名必须带 catalog 与库名,如 hive.ads.ads_purchase_kpi_1d、mysql.mini_erp.stock。字段必须来自【元数据】,禁止编造。
3. 口径以【业务文档召回】为准(如采购入库金额=已入库采购单金额合计);召回不足时说明假设。
4. hive 表查询尽量带 dt 过滤(最新分区可用 dt=(SELECT MAX(dt) FROM 同表))。
5. 用户追问图表/换图/对比时,可复用上一轮 SQL 或结果,不必重复查询。
6. 严格输出单个 JSON 对象(不要 markdown 围栏),字段:
{"answer": "中文结论与口径说明, 可含要点", "sql": "SELECT... 或 null", "catalog": "hive|mysql|doris", "chart": {"type": "bar|line|pie", "x": "列名", "y": "列名", "title": "图标题"} 或 null, "need_exec": true|false}
chart 决策:结果适合可视化(>=2行且含数值列: 趋势/对比/占比/排行)才给 chart,否则 null;单值/明细清单不画图表。
need_exec=false 仅当纯解释/复用历史结果且无需新查询。`;
const CODE_EXEC = `import requests, json, time, re
TRINO = "http://192.168.50.176:8090"
def parse_llm(text):
t = text.strip()
t = re.sub(r"^\`\`\`(?:json)?\\s*", "", t)
t = re.sub(r"\\s*\`\`\`$", "", t)
m = re.search(r"\\{.*\\}", t, re.S)
if m:
t = m.group(0)
return json.loads(t)
def trino_query(sql, user="analyst"):
r = requests.post(TRINO + "/v1/statement", headers={"X-Trino-User": user, "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": user}, timeout=30).json()
return cols or [], rows
def main(llm_text: str):
try:
plan = parse_llm(llm_text)
except Exception as e:
return {"result_json": json.dumps({"error": "plan_parse: " + str(e)[:100], "raw": llm_text[:500]}, ensure_ascii=False),
"plan_json": json.dumps({"answer": llm_text[:1500], "sql": None, "chart": None}, ensure_ascii=False)}
sql = (plan.get("sql") or "").strip()
out = {"columns": [], "rows": [], "row_count": 0, "engine": "trino", "error": ""}
if sql and plan.get("need_exec", True):
if not re.match(r"(?is)^\\s*(select|with|show|describe)\\b", sql):
out["error"] = "rejected: only SELECT allowed"
else:
try:
cols, rows = trino_query(sql)
out["columns"], out["rows"] = cols, rows[:200]
out["row_count"] = len(rows)
except Exception as e:
out["error"] = str(e)[:200]
return {"result_json": json.dumps(out, ensure_ascii=False),
"plan_json": json.dumps({"answer": plan.get("answer", ""), "sql": sql or None,
"catalog": plan.get("catalog", ""), "chart": plan.get("chart")}, ensure_ascii=False)}`;
const CODE_RENDER = `import json
def md_table(cols, rows, limit=20):
if not cols:
return ""
head = "| " + " | ".join(cols) + " |"
sep = "| " + " | ".join(["---"] * len(cols)) + " |"
body = ["| " + " | ".join("" if v is None else str(v) for v in r) + " |" for r in rows[:limit]]
return "\\n".join([head, sep] + body)
def main(plan_json: str, result_json: str, sources_json: str, recall_mode: str, meta_mode: str):
plan = json.loads(plan_json)
res = json.loads(result_json)
sources = json.loads(sources_json) if sources_json else []
parts = [plan.get("answer") or ""]
if res.get("error"):
parts.append("> 查询失败: " + res["error"] + "(可换口径或检查分区后重试)")
if plan.get("sql"):
parts.append("**SQL**(Trino/" + (plan.get("catalog") or "-") + ")\\n\`\`\`sql\\n" + plan["sql"] + "\\n\`\`\`")
if res.get("columns"):
parts.append("**结果**(" + str(res.get("row_count", 0)) + " 行,展示前 20 行)\\n" + md_table(res["columns"], res["rows"]))
chart = plan.get("chart")
if chart and res.get("columns") and res.get("rows"):
spec = {"chart": chart, "columns": res["columns"], "rows": res["rows"][:100]}
parts.append("\`\`\`echarts\\n" + json.dumps(spec, ensure_ascii=False) + "\\n\`\`\`")
if sources:
uniq = list(dict.fromkeys(sources))[:4]
parts.append("*依据: " + "; ".join(uniq) + "(召回:" + recall_mode + " / 元数据:" + meta_mode + ")*")
return {"final_text": "\\n\\n".join(p for p in parts if p),
"chart_json": json.dumps(chart, ensure_ascii=False) if chart else ""}`;
function node(id, data, x, y, extra = {}) {
return { id, type: "custom", position: { x, y }, positionAbsolute: { x, y },
width: extra.width || 242, height: extra.height || 100, selected: false,
sourcePosition: "right", targetPosition: "left", ...extra, data };
}
function codeData(title, code, variables, outputs) {
return { type: "code", title, desc: "", code_language: "python3", code,
variables: variables.map(v => ({ variable: v.name, value_selector: v.sel, value_type: v.type || "string" })),
outputs: Object.fromEntries(Object.entries(outputs).map(([k, t]) => [k, { type: t, children: null }])),
selected: false };
}
function edge(src, tgt, extra = {}) {
return { id: src + "-source-" + tgt + "-target", source: src, target: tgt,
sourceHandle: "source", targetHandle: "target", type: "custom", zIndex: 0,
data: { sourceType: extra.st, targetType: extra.tt, isInIteration: false, isInLoop: false } };
}
const graph = {
nodes: [
node(N.start, { type: "start", title: "开始", desc: "", selected: false, variables: [] }, 40, 260, { height: 90 }),
node(N.context, codeData("元数据+语义召回(带降级)", CODE_CONTEXT,
[{ name: "query", sel: ["sys", "query"] }],
{ recall_text: "string", meta_text: "string", sources_json: "string", recall_mode: "string", meta_mode: "string" }), 340, 260, { height: 180 }),
node(N.llm, { type: "llm", title: "NL2SQL 规划", desc: "", selected: false,
model: { provider: "langgenius/deepseek/deepseek", name: "deepseek-flash", mode: "chat", completion_params: { temperature: 0.1 } },
prompt_template: [
{ role: "system", text: SYS_PROMPT },
{ role: "user", text: "【元数据】\n{{#" + N.context + ".meta_text#}}\n\n【业务文档召回】\n{{#" + N.context + ".recall_text#}}\n\n【用户问题】\n{{#sys.query#}}" }],
memory: { role_prefix: { assistant: "", user: "" }, window: { enabled: true, size: 10 } },
context: { enabled: false, variable_selector: [] }, vision: { enabled: false },
reasoning_format: "separated", variables: [],
retry_config: { retry_enabled: true, max_retries: 2, retry_interval: 1000 } }, 700, 260, { height: 120 }),
node(N.exec, codeData("Trino 执行", CODE_EXEC,
[{ name: "llm_text", sel: [N.llm, "text"] }],
{ result_json: "string", plan_json: "string" }), 1060, 260, { height: 140 }),
node(N.render, codeData("组装回答+图表规格", CODE_RENDER,
[{ name: "plan_json", sel: [N.exec, "plan_json"] },
{ name: "result_json", sel: [N.exec, "result_json"] },
{ name: "sources_json", sel: [N.context, "sources_json"] },
{ name: "recall_mode", sel: [N.context, "recall_mode"] },
{ name: "meta_mode", sel: [N.context, "meta_mode"] }],
{ final_text: "string", chart_json: "string" }), 1420, 260, { height: 160 }),
node(N.answer, { type: "answer", title: "回答", desc: "", selected: false,
answer: "{{#" + N.render + ".final_text#}}" }, 1780, 260, { height: 100 }),
],
edges: [
edge(N.start, N.context, { st: "start", tt: "code" }),
edge(N.context, N.llm, { st: "code", tt: "llm" }),
edge(N.llm, N.exec, { st: "llm", tt: "code" }),
edge(N.exec, N.render, { st: "code", tt: "code" }),
edge(N.render, N.answer, { st: "code", tt: "answer" }),
],
viewport: { x: 0, y: 0, zoom: 0.6 },
};
const draft = { graph, features: { file_upload: { enabled: false, allowed_file_upload_methods: ["local_file", "remote_url"], allowed_file_types: ["image"], allowed_file_extensions: [] }, opening_statement: "你好,我是 mini-ERP 问数分析师,可以查实时库存/单据,也可以做数仓指标分析与图表。", suggested_questions: ["最近一天采购入库金额是多少?", "哪些 SKU 低于安全库存?", "按供应商看采购金额排行并画图"] }, conversation_variables: [], environment_variables: [] };
console.log(JSON.stringify(draft));