// 生成 Dify 工作流「业务文档向量化同步」draft:Gitea docs/ -> 语义分块 -> bge-m3(ollama) -> Qdrant // 用法: node deploy/gen_rag_workflow_draft.js > deploy/rag_qdrant_sync_draft.json const N = { start: "9200000000001", collect: "9200000000002", ifelse: "9200000000003", endNoChange: "9200000000004", clean: "9200000000005", iteration: "9200000000006", iterStart: "9200000000007", sync: "9200000000008", save: "9200000000009", end: "9200000000010", }; const CODE_COLLECT = `import requests, json, hashlib, re GITEA = "http://gitea:3000" REPO = "admin/mini-erp-fabric-demo" GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c"} def sha256(s): return hashlib.sha256(s.encode("utf-8")).hexdigest() def raw(path): r = requests.get(GITEA + "/api/v1/repos/" + REPO + "/raw/" + path, headers=GH, timeout=20) r.raise_for_status() return r.text def chunk_doc(path, text): lines = text.split("\\n") sections = [] stack = [] buf = [] def flush(): if buf: body = "\\n".join(buf).strip() if body: title = " / ".join(stack) if stack else path sections.append((title, body)) buf.clear() for ln in lines: m = re.match(r"^(#{1,4})\\s+(.*)", ln) if m: flush() lvl = len(m.group(1)) stack[:] = stack[:lvl-1] + [m.group(2).strip()] else: buf.append(ln) flush() chunks = [] for title, body in sections: piece = title + "\\n" + body if len(piece) <= 1000: chunks.append({"title": title, "text": piece}) else: paras = body.split("\\n\\n") cur = "" for p in paras: if len(cur) + len(p) > 850 and cur: chunks.append({"title": title, "text": title + "\\n" + cur.strip()}) cur = cur[-120:] + "\\n\\n" + p else: cur += ("\\n\\n" if cur else "") + p if cur.strip(): chunks.append({"title": title, "text": title + "\\n" + cur.strip()}) for i, c in enumerate(chunks): c["idx"] = i return chunks def main(force: str): tree = requests.get(GITEA + "/api/v1/repos/" + REPO + "/git/trees/main?recursive=true", headers=GH, timeout=20).json() paths = sorted(t["path"] for t in tree.get("tree", []) if t["path"].startswith("docs/") and t["path"].endswith(".md") and t["type"] == "blob") docs = {} for p in paths: docs[p] = raw(p) doc_hashes = {p: sha256(t) for p, t in docs.items()} global_hash = sha256(json.dumps(doc_hashes, sort_keys=True)) prev = {} state_sha = "" try: meta = requests.get(GITEA + "/api/v1/repos/" + REPO + "/contents/05_sync/rag_state.json", headers=GH, timeout=20).json() state_sha = meta.get("sha", "") import base64 prev = json.loads(base64.b64decode(meta["content"]).decode("utf-8")) except Exception: prev = {} prev_hashes = prev.get("doc_hashes", {}) changed = [p for p in paths if doc_hashes[p] != prev_hashes.get(p)] deleted = [p for p in prev_hashes if p not in doc_hashes] skip = (force or "").strip().lower() != "true" and not changed and not deleted changed_docs = [json.dumps({"path": p, "doc_hash": doc_hashes[p], "chunks": chunk_doc(p, docs[p])}, ensure_ascii=False) for p in changed] return {"skip": skip, "global_hash": global_hash, "state_sha": state_sha, "prev_state_json": json.dumps(prev, ensure_ascii=False), "changed_docs": changed_docs, "deleted_paths": deleted, "doc_hashes_json": json.dumps(doc_hashes, ensure_ascii=False), "chunk_counts_json": json.dumps({p: len(chunk_doc(p, docs[p])) for p in paths}, ensure_ascii=False)}`; const CODE_CLEAN = `import requests, json QDRANT = "http://192.168.50.176:6333" COLL = "mini_erp_docs" def main(deleted_paths: list): r = requests.get(QDRANT + "/collections/" + COLL, timeout=15) if r.status_code == 404: r = requests.put(QDRANT + "/collections/" + COLL, json={"vectors": {"size": 1024, "distance": "Cosine"}}, timeout=30) if r.status_code not in (200, 201): return {"clean_result": json.dumps({"ensure": "err", "resp": r.text[:150]}), "collection_ok": False} deleted_ok = [] errs = [] for p in deleted_paths: rr = requests.post(QDRANT + "/collections/" + COLL + "/points/delete?wait=true", json={"filter": {"must": [{"key": "doc_path", "match": {"value": p}}]}}, timeout=30) if rr.status_code == 200: deleted_ok.append(p) else: errs.append(p + ":" + rr.text[:80]) return {"clean_result": json.dumps({"ensure": "ok", "deleted_ok": deleted_ok, "errs": errs}, ensure_ascii=False), "collection_ok": True}`; const CODE_SYNC = `import requests, json, uuid, time QDRANT = "http://192.168.50.176:6333" COLL = "mini_erp_docs" OLLAMA = "http://192.168.50.176:11434" def main(item: str): doc = json.loads(item) path = doc["path"] chunks = doc["chunks"] texts = [c["text"] for c in chunks] emb = None err = "" for attempt in range(3): try: r = requests.post(OLLAMA + "/api/embed", json={"model": "bge-m3", "input": texts}, timeout=180) if r.status_code == 200: emb = r.json()["embeddings"] break err = r.text[:120] except Exception as e: err = str(e)[:120] time.sleep(3) if not emb or len(emb) != len(texts): return {"result": json.dumps({"path": path, "embed": "err", "detail": err}, ensure_ascii=False)} d = requests.post(QDRANT + "/collections/" + COLL + "/points/delete?wait=true", json={"filter": {"must": [{"key": "doc_path", "match": {"value": path}}]}}, timeout=30) points = [] for c, v in zip(chunks, emb): pid = str(uuid.uuid5(uuid.NAMESPACE_URL, "mini-erp-doc:" + path + ":" + str(c["idx"]))) points.append({"id": pid, "vector": v, "payload": {"doc_path": path, "chunk_idx": c["idx"], "title": c["title"], "text": c["text"], "doc_hash": doc["doc_hash"], "updated_at": time.strftime("%Y-%m-%d %H:%M:%S")}}) u = requests.put(QDRANT + "/collections/" + COLL + "/points?wait=true", json={"points": points}, timeout=60) ok = d.status_code == 200 and u.status_code == 200 return {"result": json.dumps({"path": path, "doc_hash": doc["doc_hash"], "chunks": len(points), "embed": "ok", "delete": "ok" if d.status_code == 200 else "err", "upsert": "ok" if u.status_code == 200 else "err", "detail": "" if ok else (d.text[:80] + u.text[:80])}, ensure_ascii=False)}`; const CODE_SAVE = `import requests, json, base64 from datetime import datetime GITEA = "http://gitea:3000" REPO = "admin/mini-erp-fabric-demo" GH = {"Authorization": "token 77c6bd2fdab535b2720821d36b4cfb74aa3bf87c", "Content-Type": "application/json"} def main(global_hash: str, doc_hashes_json: str, chunk_counts_json: str, prev_state_json: str, state_sha: str, sync_results: list, clean_result: str): prev = json.loads(prev_state_json) if prev_state_json else {} hashes = dict(prev.get("doc_hashes", {})) counts = dict(prev.get("chunk_counts", {})) cur_hashes = json.loads(doc_hashes_json) cur_counts = json.loads(chunk_counts_json) synced, failed = [], [] for x in sync_results: if not x: continue r = json.loads(x) if r.get("embed") == "ok" and r.get("upsert") == "ok": hashes[r["path"]] = r["doc_hash"] counts[r["path"]] = r["chunks"] synced.append(r["path"]) else: failed.append(r["path"]) clean = json.loads(clean_result) if clean_result else {} for p in clean.get("deleted_ok", []): hashes.pop(p, None) counts.pop(p, None) state = {"global_hash": global_hash if not failed else prev.get("global_hash", ""), "doc_hashes": hashes, "chunk_counts": counts, "updated_at": datetime.now().strftime("%Y-%m-%d %H:%M:%S"), "runs": int(prev.get("runs", 0)) + 1} content = base64.b64encode(json.dumps(state, ensure_ascii=True, indent=2).encode("utf-8")).decode() url = GITEA + "/api/v1/repos/" + REPO + "/contents/05_sync/rag_state.json" payload = {"content": content, "branch": "main", "message": "chore(sync): 更新文档向量化状态快照"} if state_sha: payload["sha"] = state_sha r = requests.put(url, headers=GH, json=payload, timeout=20) else: r = requests.post(url, headers=GH, json=payload, timeout=20) status = "ok" if r.status_code in (200, 201) else "err" summary = {"state_saved": status, "synced": synced, "failed": failed, "deleted": clean.get("deleted_ok", []), "points_total": sum(counts.values()), "http": r.status_code, "resp": r.text[:150] if status == "err" else ""} return {"status": json.dumps(summary, ensure_ascii=False)}`; 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, sh, th, extra = {}) { return { id: src + "-" + sh + "-" + tgt + "-" + th, source: src, target: tgt, sourceHandle: sh, targetHandle: th, type: "custom", zIndex: 0, data: { sourceType: extra.st, targetType: extra.tt, isInIteration: !!extra.inIter, isInLoop: false } }; } const graph = { nodes: [ node(N.start, { type: "start", title: "开始", desc: "", selected: false, variables: [{ type: "text-input", variable: "force", label: "force(填true强制全量重嵌入)", required: false, options: [], default: "", hint: "", placeholder: "" }] }, 40, 260, { height: 108 }), node(N.collect, codeData("采集文档指纹与语义分块", CODE_COLLECT, [{ name: "force", sel: [N.start, "force"] }], { skip: "boolean", global_hash: "string", state_sha: "string", prev_state_json: "string", changed_docs: "array[string]", deleted_paths: "array[string]", doc_hashes_json: "string", chunk_counts_json: "string" }), 340, 260, { height: 220 }), node(N.ifelse, { type: "if-else", title: "需要更新?", desc: "", selected: false, cases: [{ case_id: "true", logical_operator: "and", conditions: [{ id: "cond_skip", varType: "boolean", variable_selector: [N.collect, "skip"], comparison_operator: "is", value: "false" }] }] }, 700, 260, { height: 130 }), node(N.endNoChange, { type: "end", title: "无变更结束", desc: "", selected: false, outputs: [{ variable: "result", value_type: "string", value_selector: [N.collect, "global_hash"] }] }, 1040, 460, { height: 100 }), node(N.clean, codeData("确保集合+清理已删除文档", CODE_CLEAN, [{ name: "deleted_paths", sel: [N.collect, "deleted_paths"], type: "array[string]" }], { clean_result: "string", collection_ok: "boolean" }), 1040, 180, { height: 160 }), node(N.iteration, { type: "iteration", title: "逐文档嵌入+写入Qdrant", desc: "", selected: false, is_parallel: false, parallel_nums: 2, error_handle_mode: "continue-on-error", iterator_selector: [N.collect, "changed_docs"], iterator_input_type: "array[string]", output_selector: [N.sync, "result"], output_type: "array[string]", is_iterating: true, flatten_output: false, start_node_id: N.iterStart, width: 620, height: 220 }, 1400, 160, { width: 620, height: 220, zIndex: 1 }), { id: N.iterStart, type: "custom-iteration-start", parentId: N.iteration, position: { x: 24, y: 68 }, positionAbsolute: { x: 1424, y: 228 }, width: 44, height: 48, selected: false, sourcePosition: "right", targetPosition: "left", data: { type: "iteration-start", title: "", desc: "", selected: false, isInIteration: true } }, node(N.sync, codeData("嵌入并写入单文档", CODE_SYNC, [{ name: "item", sel: [N.iteration, "item"] }], { result: "string" }), 1560, 220, { height: 160, parentId: N.iteration, zIndex: 2 }), node(N.save, codeData("回写RAG状态", CODE_SAVE, [{ name: "global_hash", sel: [N.collect, "global_hash"] }, { name: "doc_hashes_json", sel: [N.collect, "doc_hashes_json"] }, { name: "chunk_counts_json", sel: [N.collect, "chunk_counts_json"] }, { name: "prev_state_json", sel: [N.collect, "prev_state_json"] }, { name: "state_sha", sel: [N.collect, "state_sha"] }, { name: "sync_results", sel: [N.iteration, "output"], type: "array[string]" }, { name: "clean_result", sel: [N.clean, "clean_result"] }], { status: "string" }), 2160, 260, { height: 200 }), node(N.end, { type: "end", title: "同步结果", desc: "", selected: false, outputs: [{ variable: "summary", value_type: "string", value_selector: [N.save, "status"] }] }, 2520, 260, { height: 100 }), ], edges: [ edge(N.start, N.collect, "source", "target", { st: "start", tt: "code" }), edge(N.collect, N.ifelse, "source", "target", { st: "code", tt: "if-else" }), edge(N.ifelse, N.endNoChange, "false", "target", { st: "if-else", tt: "end" }), edge(N.ifelse, N.clean, "true", "target", { st: "if-else", tt: "code" }), edge(N.clean, N.iteration, "source", "target", { st: "code", tt: "iteration" }), edge(N.iterStart, N.sync, "source", "target", { st: "iteration-start", tt: "code", inIter: true }), edge(N.iteration, N.save, "source", "target", { st: "iteration", tt: "code" }), edge(N.save, N.end, "source", "target", { st: "code", tt: "end" }), ], viewport: { x: 0, y: 0, zoom: 0.5 }, }; 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: "", suggested_questions: [] }, conversation_variables: [], environment_variables: [] }; console.log(JSON.stringify(draft));