From 3dba4066448ba8201d771a348b51a2b0b346b011 Mon Sep 17 00:00:00 2001
From: hyb <468949484@qq.com>
Date: Sat, 25 Jan 2025 18:38:46 +0800
Subject: [PATCH] feat: Added webui management, including file upload, text
upload, Q&A query, graph database management (can view tags, view knowledge
graph based on tags), system status (whether it is good, data storage status,
model status, path),request /webui/index.html
---
lightrag/api/lightrag_server.py | 27 +-
lightrag/api/webui/static/css/graph.css | 92 ++++
lightrag/api/webui/static/css/lightrag.css | 390 ++++++++++++++++
lightrag/api/webui/static/index.html | 292 ++++++++++++
lightrag/api/webui/static/js/graph.js | 214 +++++++++
lightrag/api/webui/static/js/lightrag.js | 503 +++++++++++++++++++++
lightrag/kg/neo4j_impl.py | 172 +++++++
lightrag/lightrag.py | 9 +
8 files changed, 1698 insertions(+), 1 deletion(-)
create mode 100644 lightrag/api/webui/static/css/graph.css
create mode 100644 lightrag/api/webui/static/css/lightrag.css
create mode 100644 lightrag/api/webui/static/index.html
create mode 100644 lightrag/api/webui/static/js/graph.js
create mode 100644 lightrag/api/webui/static/js/lightrag.js
diff --git a/lightrag/api/lightrag_server.py b/lightrag/api/lightrag_server.py
index 87a72a98..b25e085f 100644
--- a/lightrag/api/lightrag_server.py
+++ b/lightrag/api/lightrag_server.py
@@ -733,6 +733,8 @@ def create_app(args):
azure_openai_complete_if_cache,
azure_openai_embed,
)
+ if args.llm_binding_host == "openai-ollama" or args.embedding_binding == "ollama":
+ from lightrag.llm.openai import openai_complete_if_cache, openai_embed
async def openai_alike_model_complete(
prompt,
@@ -1380,7 +1382,16 @@ def create_app(args):
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
- # -------------------------------------------------
+ # query all graph labels
+ @app.get("/graph/label/list")
+ async def get_graph_labels():
+ return await rag.get_graph_labels()
+
+ # query all graph
+ @app.get("/graphs")
+ async def get_graphs(label: str):
+ return await rag.get_graps(nodel_label=label, max_depth=100)
+
# Ollama compatible API endpoints
# -------------------------------------------------
@app.get("/api/version")
@@ -1751,6 +1762,7 @@ def create_app(args):
"working_directory": str(args.working_dir),
"input_directory": str(args.input_dir),
"indexed_files": doc_manager.indexed_files,
+ "indexed_files_count": len(doc_manager.scan_directory()),
"configuration": {
# LLM configuration binding/host address (if applicable)/model (if applicable)
"llm_binding": args.llm_binding,
@@ -1761,9 +1773,22 @@ def create_app(args):
"embedding_binding_host": args.embedding_binding_host,
"embedding_model": args.embedding_model,
"max_tokens": args.max_tokens,
+ "kv_storage": KV_STORAGE,
+ "doc_status_storage": DOC_STATUS_STORAGE,
+ "graph_storage": GRAPH_STORAGE,
+ "vector_storage": VECTOR_STORAGE,
},
}
+ # webui mount /webui/index.html
+ app.mount(
+ "/webui",
+ StaticFiles(
+ directory=Path(__file__).resolve().parent / "webui" / "static", html=True
+ ),
+ name="webui_static",
+ )
+
# Serve the static files
static_dir = Path(__file__).parent / "static"
static_dir.mkdir(exist_ok=True)
diff --git a/lightrag/api/webui/static/css/graph.css b/lightrag/api/webui/static/css/graph.css
new file mode 100644
index 00000000..098ff2f6
--- /dev/null
+++ b/lightrag/api/webui/static/css/graph.css
@@ -0,0 +1,92 @@
+/* css/lightrag.css */
+
+/* 模态框样式 */
+.modal {
+ display: none;
+ position: fixed;
+ top: 0;
+ left: 0;
+ width: 100%;
+ height: 100%;
+ background-color: rgba(0, 0, 0, 0.5);
+ justify-content: center;
+ align-items: center;
+ z-index: 1000;
+}
+
+.modal-content {
+ background-color: var(--surface);
+ padding: 1.5rem;
+ border-radius: 8px;
+ width: 80%;
+ max-width: 1200px;
+ box-shadow: var(--shadow);
+}
+
+.modal-header {
+ display: flex;
+ justify-content: space-between;
+ align-items: center;
+ margin-bottom: 1rem;
+}
+
+.modal-body {
+ margin-bottom: 1rem;
+}
+
+.modal-footer {
+ text-align: right;
+}
+
+.btn-close {
+ background: none;
+ border: none;
+ font-size: 1.5rem;
+ cursor: pointer;
+ color: var(--text-secondary);
+}
+
+.btn-close:hover {
+ color: var(--text-primary);
+}
+
+/* 图谱节点样式 */
+.node {
+ cursor: pointer;
+ fill: var(--primary);
+ stroke: var(--surface);
+ stroke-width: 2px;
+}
+
+.node:hover {
+ fill: var(--secondary);
+}
+
+.link {
+ stroke: var(--text-secondary);
+ stroke-width: 2px;
+}
+
+.label {
+ font-size: 12px;
+ fill: var(--text-primary);
+ pointer-events: none;
+}
+
+/* 添加边样式 */
+.link {
+ stroke: #999; /* 连线颜色 */
+ stroke-width: 2px; /* 连线粗细 */
+ stroke-opacity: 0.6;/* 透明度 */
+}
+/* 边样式 */
+.link {
+ stroke: #999; /* 边颜色 */
+ stroke-width: 2px; /* 边粗细 */
+ stroke-opacity: 0.8; /* 边透明度 */
+}
+
+/* 箭头颜色匹配边颜色 */
+#arrow path {
+ fill: #999 !important; /* 覆盖默认颜色 */
+}
diff --git a/lightrag/api/webui/static/css/lightrag.css b/lightrag/api/webui/static/css/lightrag.css
new file mode 100644
index 00000000..e803f51a
--- /dev/null
+++ b/lightrag/api/webui/static/css/lightrag.css
@@ -0,0 +1,390 @@
+
+* {
+ box-sizing: border-box;
+ margin: 0;
+ padding: 0;
+}
+
+body {
+ font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;
+ line-height: 1.6;
+ background-color: var(--background);
+ color: var(--text-primary);
+}
+
+/* 主容器 */
+.app-container {
+ max-width: 1600px;
+ margin: 0 auto;
+ padding: 2rem;
+ display: grid;
+ grid-template-columns: 240px 1fr;
+ gap: 2rem;
+ min-height: 100vh;
+}
+
+/* 导航侧边栏 */
+.nav-panel {
+ position: sticky;
+ top: 2rem;
+ height: fit-content;
+ background: var(--surface);
+ border-radius: 12px;
+ padding: 1.5rem;
+ box-shadow: var(--shadow);
+}
+
+.nav-title {
+ font-size: 1.25rem;
+ font-weight: 600;
+ color: var(--primary);
+ padding-bottom: 1rem;
+ margin-bottom: 1rem;
+ border-bottom: 1px solid var(--border);
+}
+
+/* 主内容区 */
+.main-content {
+ display: grid;
+ gap: 1.5rem;
+ align-content: start;
+}
+
+/* 卡片式模块 */
+.card {
+ background: var(--surface);
+ border-radius: 12px;
+ padding: 1.5rem;
+ box-shadow: var(--shadow);
+ transition: transform 0.2s ease;
+}
+
+.card:hover {
+ transform: translateY(-2px);
+}
+
+.card-title {
+ font-size: 1.125rem;
+ font-weight: 600;
+ margin-bottom: 1rem;
+ color: var(--primary);
+}
+
+/* 文件上传区域 */
+.file-dropzone {
+ border: 2px dashed var(--border);
+ border-radius: 8px;
+ padding: 2rem;
+ text-align: center;
+ transition: all 0.3s ease;
+ background: rgba(241, 245, 249, 0.5);
+}
+
+.file-dropzone.active {
+ border-color: var(--primary);
+ background: rgba(79, 70, 229, 0.05);
+}
+
+/* 按钮样式 */
+.btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.5rem;
+ padding: 0.75rem 1.5rem;
+ border: none;
+ border-radius: 8px;
+ font-weight: 500;
+ cursor: pointer;
+ transition: all 0.2s ease;
+}
+
+.btn-primary {
+ background: var(--primary);
+ color: white;
+}
+
+.btn-primary:hover {
+ background: #4338CA;
+}
+
+.btn-secondary {
+ background: var(--secondary);
+ color: white;
+}
+
+.btn-secondary:hover {
+ background: #059669;
+}
+
+/* 输入框样式 */
+.input-field {
+ width: 100%;
+ padding: 0.875rem;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ font-size: 1rem;
+ transition: border-color 0.2s ease;
+}
+
+.input-field:focus {
+ outline: none;
+ border-color: var(--primary);
+ box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
+}
+
+/* 响应式设计 */
+@media (max-width: 768px) {
+ .app-container {
+ grid-template-columns: 1fr;
+ padding: 1rem;
+ }
+
+ .nav-panel {
+ position: static;
+ margin-bottom: 1.5rem;
+ }
+
+ /* 添加按钮激活状态样式 */
+ .btn.active {
+ box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
+ transform: translateY(1px);
+ }
+}
+
+.toast {
+ position: fixed;
+ bottom: 20px;
+ right: 20px;
+ padding: 12px 24px;
+ border-radius: 8px;
+ background: var(--surface);
+ box-shadow: var(--shadow);
+ z-index: 1000;
+}
+
+.toast.success {
+ background: var(--secondary);
+ color: white;
+}
+
+.toast.error {
+ background: #EF4444;
+ color: white;
+}
+
+.loading {
+ position: relative;
+ opacity: 0.6;
+}
+
+.loading::after {
+ content: "···";
+ animation: loading 1s infinite;
+}
+
+@keyframes loading {
+ 0% {
+ content: "·";
+ }
+ 33% {
+ content: "··";
+ }
+ 66% {
+ content: "···";
+ }
+}
+
+.text-upload-form {
+ display: grid;
+ gap: 1.5rem;
+}
+
+.form-group label {
+ display: block;
+ margin-bottom: 0.5rem;
+ color: var(--text-primary);
+ font-weight: 500;
+}
+
+.action-bar {
+ display: flex;
+ align-items: center;
+ gap: 1rem;
+ margin-top: 1rem;
+}
+
+.status-indicator {
+ padding: 0.5rem 1rem;
+ border-radius: 6px;
+ font-size: 0.9em;
+ transition: all 0.3s ease;
+}
+
+.status-indicator.success {
+ background: var(--secondary);
+ color: white;
+}
+
+.status-indicator.error {
+ background: #ef4444;
+ color: white;
+}
+
+/* 添加以下CSS样式 */
+.status-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
+ gap: 1.5rem;
+ margin-top: 1rem;
+}
+
+.status-card {
+ background: var(--surface);
+ border-radius: 12px;
+ padding: 1.5rem;
+ box-shadow: var(--shadow);
+}
+
+.status-header {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ margin-bottom: 1rem;
+}
+
+.status-icon {
+ font-size: 1.5rem;
+ color: var(--primary);
+}
+
+.progress-container {
+ margin-top: 1rem;
+}
+
+.progress-labels {
+ display: flex;
+ justify-content: space-between;
+ margin-top: 0.5rem;
+ font-size: 0.875rem;
+ color: var(--text-secondary);
+}
+
+.config-list {
+ display: grid;
+ grid-template-columns: max-content 1fr;
+ gap: 0.75rem 1.5rem;
+ margin-top: 1rem;
+}
+
+.config-list dt {
+ font-weight: 500;
+ color: var(--text-secondary);
+}
+
+.config-list dd {
+ margin: 0;
+ color: var(--text-primary);
+}
+
+.directory-list {
+ margin-top: 1rem;
+}
+
+.directory-item {
+ display: flex;
+ gap: 0.5rem;
+ margin-bottom: 0.5rem;
+}
+
+.directory-label {
+ font-weight: 500;
+ color: var(--text-secondary);
+ flex-shrink: 0;
+}
+
+.directory-path {
+ color: var(--text-primary);
+ word-break: break-all;
+}
+
+.status-badge {
+ display: inline-block;
+ padding: 0.5rem 1rem;
+ border-radius: 20px;
+ font-size: 0.875rem;
+ font-weight: 500;
+ margin-top: 1rem;
+}
+
+.health-status .status-badge {
+ background: rgba(16, 185, 129, 0.1);
+ color: #10B981;
+ border: 1px solid rgba(16, 185, 129, 0.2);
+}
+
+/* 加载状态 */
+.status-badge.loading {
+ background: rgba(79, 70, 229, 0.1);
+ color: var(--primary);
+}
+
+/* 错误状态 */
+.status-badge.error {
+ background: rgba(239, 68, 68, 0.1);
+ color: #EF4444;
+}
+
+.label-container {
+ max-height: 60vh;
+ overflow-y: auto;
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 1rem;
+}
+
+.label-item {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 0.75rem;
+ margin-bottom: 0.5rem;
+ background: var(--surface);
+ border-radius: 6px;
+ box-shadow: var(--shadow);
+}
+
+.label-item:hover {
+ transform: translateX(4px);
+ transition: transform 0.2s ease;
+}
+
+.label-actions {
+ display: flex;
+ gap: 0.5rem;
+}
+
+.toast {
+ position: fixed;
+ bottom: 2rem;
+ left: 50%;
+ transform: translateX(-50%);
+ padding: 0.75rem 1.5rem;
+ border-radius: 999px;
+ font-size: 0.9rem;
+ z-index: 1000;
+}
+
+.toast-success {
+ background: var(--secondary);
+ color: white;
+}
+
+.toast-info {
+ background: var(--primary);
+ color: white;
+}
+
+.toast-error {
+ background: #EF4444;
+ color: white;
+}
diff --git a/lightrag/api/webui/static/index.html b/lightrag/api/webui/static/index.html
new file mode 100644
index 00000000..8884eb7a
--- /dev/null
+++ b/lightrag/api/webui/static/index.html
@@ -0,0 +1,292 @@
+
+
+
+
+
+ LightRAG
+
+
+
+
+
+
+
+
+
+
+ DOC MANAGE
+
+
+
Drap file
+
+
+
+
+
+
+
+ TEXT UPLOAD
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ GRAPH MANAGE(neo4j)
+
+
+
+
+
+
+
+
+
+
+
+
+ System Status
+
+
+
+
+
+
+
+
+
+ Indexed files:0
+ Use ratio:0%
+
+
+
+
+
+
+
+ - LLM MODEL
+ - Loading...
+
+ - Embedded model
+ - Loading...
+
+ - Max token
+ - 0
+
+
+
+
+
+
+
+ Work directory:
+
+
+
+ Input directory:
+
+
+
+
+
+
+
+
+
+ kv_storage:
+
+
+
+ doc_status_storage:
+
+
+
+ graph_storage:
+
+
+
+ vector_storage:
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/lightrag/api/webui/static/js/graph.js b/lightrag/api/webui/static/js/graph.js
new file mode 100644
index 00000000..5c3318c7
--- /dev/null
+++ b/lightrag/api/webui/static/js/graph.js
@@ -0,0 +1,214 @@
+// js/graph.js
+function openGraphModal(label) {
+ const modal = document.getElementById("graph-modal");
+ const graphTitle = document.getElementById("graph-title");
+
+ if (!modal || !graphTitle) {
+ console.error("Key element not found");
+ return;
+ }
+
+ graphTitle.textContent = `Knowledge Graph - ${label}`;
+ modal.style.display = "flex";
+
+ renderGraph(label);
+}
+
+function closeGraphModal() {
+ const modal = document.getElementById("graph-modal");
+ modal.style.display = "none";
+ clearGraph();
+}
+
+function clearGraph() {
+ const svg = document.getElementById("graph-svg");
+ svg.innerHTML = "";
+}
+
+
+async function getGraph(label) {
+ try {
+ const response = await fetch(`/graphs?label=${label}`);
+ const rawData = await response.json();
+ console.log({data: JSON.parse(JSON.stringify(rawData))});
+
+ const nodes = rawData.nodes
+
+ nodes.forEach(node => {
+ node.id = Date.now().toString(36) + Math.random().toString(36).substring(2); // 使用 crypto.randomUUID() 生成唯一 UUID
+ });
+
+ // 严格验证边数据 Strictly verify edge data
+ const edges = (rawData.edges || []).map(edge => {
+ const sourceNode = nodes.find(n => n.labels.includes(edge.source));
+ const targetNode = nodes.find(n => n.labels.includes(edge.target)
+ )
+ ;
+ if (!sourceNode || !targetNode) {
+ console.warn("NOT VALID EDGE:", edge);
+ return null;
+ }
+ return {
+ source: sourceNode,
+ target: targetNode,
+ type: edge.type || ""
+ };
+ }).filter(edge => edge !== null);
+
+ return {nodes, edges};
+ } catch (error) {
+ console.error("Loading graph failed:", error);
+ return {nodes: [], edges: []};
+ }
+}
+
+async function renderGraph(label) {
+ const data = await getGraph(label);
+
+
+ if (!data.nodes || data.nodes.length === 0) {
+ d3.select("#graph-svg")
+ .html(`No valid nodes`);
+ return;
+ }
+
+ //
+ const svg = d3.select("#graph-svg");
+ const width = svg.node().clientWidth;
+ const height = svg.node().clientHeight;
+
+ //
+ svg.selectAll("*").remove();
+
+ // 创建力导向图布局 Create a force oriented diagram layout
+ const simulation = d3.forceSimulation(data.nodes)
+ .force("charge", d3.forceManyBody().strength(-300))
+ .force("center", d3.forceCenter(width / 2, height / 2));
+
+ // 添加连线(如果存在有效边) Add a connection (if there are valid edges)
+ if (data.edges.length > 0) {
+ simulation.force("link",
+ d3.forceLink(data.edges)
+ .id(d => d.id)
+ .distance(100)
+ );
+ }
+
+
+
+ // 绘制节点 Draw nodes
+ const nodes = svg.selectAll(".node")
+ .data(data.nodes)
+ .enter()
+ .append("circle")
+ .attr("class", "node")
+ .attr("r", 10)
+ .call(d3.drag()
+ .on("start", dragStarted)
+ .on("drag", dragged)
+ .on("end", dragEnded)
+ );
+
+
+ svg.append("defs")
+ .append("marker")
+ .attr("id", "arrow-out")
+ .attr("viewBox", "0 0 10 10")
+ .attr("refX", 8)
+ .attr("refY", 5)
+ .attr("markerWidth", 6)
+ .attr("markerHeight", 6)
+ .attr("orient", "auto")
+ .append("path")
+ .attr("d", "M0,0 L10,5 L0,10 Z")
+ .attr("fill", "#999");
+
+ // 绘制边(带箭头) Draw edges (with arrows)
+ const links = svg.selectAll(".link")
+ .data(data.edges)
+ .enter()
+ .append("line")
+ .attr("class", "link")
+ .attr("marker-end", "url(#arrow-out)"); // 始终在 target 侧绘制箭头 Always draw arrows on the target side
+
+ // 边样式配置 Edge style configuration
+ links
+ .attr("stroke", "#999")
+ .attr("stroke-width", 2)
+ .attr("stroke-opacity", 0.8);
+
+ // 绘制标签(带背景框) Draw label (with background box)
+ const labels = svg.selectAll(".label")
+ .data(data.nodes)
+ .enter()
+ .append("text")
+ .attr("class", "label")
+ .text(d => d.labels[0] || "")
+ .attr("text-anchor", "start")
+ .attr("dy", "0.3em")
+ .attr("fill", "#333");
+
+ // 更新位置 Update Location
+ simulation.on("tick", () => {
+ links
+ .attr("x1", d => {
+ // 计算源节点到目标节点的方向向量 Calculate the direction vector from the source node to the target node
+ const dx = d.target.x - d.source.x;
+ const dy = d.target.y - d.source.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ if (distance === 0) return d.source.x; // 避免除以零 Avoid dividing by zero
+ // 根据半径 10 调整起点坐标(源节点边缘)Adjust the starting point coordinates (source node edge) based on radius 10
+ return d.source.x + (dx / distance) * 10;
+ })
+ .attr("y1", d => {
+ const dx = d.target.x - d.source.x;
+ const dy = d.target.y - d.source.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ if (distance === 0) return d.source.y;
+ return d.source.y + (dy / distance) * 10;
+ })
+ .attr("x2", d => {
+ // 根据半径 10 调整终点坐标(目标节点边缘) Adjust the endpoint coordinates (target node edge) based on a radius of 10
+ const dx = d.target.x - d.source.x;
+ const dy = d.target.y - d.source.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ if (distance === 0) return d.target.x;
+ return d.target.x - (dx / distance) * 10;
+ })
+ .attr("y2", d => {
+ const dx = d.target.x - d.source.x;
+ const dy = d.target.y - d.source.y;
+ const distance = Math.sqrt(dx * dx + dy * dy);
+ if (distance === 0) return d.target.y;
+ return d.target.y - (dy / distance) * 10;
+ });
+
+ // 更新节点和标签的位置(保持不变) Update the position of nodes and labels (keep unchanged)
+ nodes
+ .attr("cx", d => d.x)
+ .attr("cy", d => d.y);
+
+ labels
+ .attr("x", d => d.x + 12)
+ .attr("y", d => d.y + 4);
+ });
+
+ // 拖拽逻辑 Drag and drop logic
+ function dragStarted(event, d) {
+ if (!event.active) simulation.alphaTarget(0.3).restart();
+ d.fx = d.x;
+ d.fy = d.y;
+ }
+
+ function dragged(event, d) {
+ d.fx = event.x;
+ d.fy = event.y;
+ simulation.alpha(0.3).restart();
+ }
+
+ function dragEnded(event, d) {
+ if (!event.active) simulation.alphaTarget(0);
+ d.fx = null;
+ d.fy = null;
+ }
+}
diff --git a/lightrag/api/webui/static/js/lightrag.js b/lightrag/api/webui/static/js/lightrag.js
new file mode 100644
index 00000000..ddfb3b70
--- /dev/null
+++ b/lightrag/api/webui/static/js/lightrag.js
@@ -0,0 +1,503 @@
+// lightrag.js
+const API_BASE = 'http://localhost:9621'; // 根据实际API地址修改
+
+// init
+function initializeApp() {
+ setupFileUpload();
+ setupQueryHandler();
+ setupSectionObserver();
+ updateFileList();
+ // 文本输入框实时字数统计 textarea count
+ const textArea = document.getElementById('textContent');
+ if (textArea) {
+ const charCount = document.createElement('div');
+ charCount.className = 'char-count';
+ textArea.parentNode.appendChild(charCount);
+
+ textArea.addEventListener('input', () => {
+ const count = textArea.value.length;
+ charCount.textContent = `input ${count} character`;
+ charCount.style.color = count > 10000 ? '#ef4444' : 'var (--text-secondary)'
+ });
+ }
+}
+
+// 通用请求方法 api request
+async function apiRequest(endpoint, method = 'GET', body = null) {
+ const options = {
+ method,
+ headers: {
+ 'Content-Type': 'application/json'
+ }
+ };
+
+ if (body) {
+ options.body = JSON.stringify(body);
+ }
+
+ try {
+ const response = await fetch(`${API_BASE}${endpoint}`, options);
+ if (!response.ok) {
+ throw new Error(`request failed: ${response.status}`);
+ }
+ return response.json();
+ } catch (error) {
+ console.error('API REQUEST ERROR:', error);
+ showToast(error.message, 'error');
+ throw error;
+ }
+}
+
+async function handleTextUpload() {
+ const description = document.getElementById('textDescription').value;
+ const content = document.getElementById('textContent').value.trim();
+ const statusDiv = document.getElementById('textUploadStatus');
+
+ // 清空状态提示 clear status tip
+ statusDiv.className = 'status-indicator';
+ statusDiv.textContent = '';
+
+ // 输入验证 input valid
+ if (!content) {
+ showStatus('error', 'TEXT CONTENT NOT NULL', statusDiv);
+ return;
+ }
+
+ try {
+ showStatus('loading', 'UPLOADING...', statusDiv);
+
+ //
+ const payload = {
+ text: content,
+ ...(description && {description})
+ };
+
+ const response = await fetch(`${API_BASE}/documents/text`, {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(payload)
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json();
+ throw new Error(errorData.detail || '上传失败');
+ }
+
+ const result = await response.json();
+
+ showStatus('success', `✅ ${result.message} (文档数: ${result.document_count})`, statusDiv);
+
+
+ document.getElementById('textContent').value = '';
+
+ // 更新文件列表 update file list
+ updateFileList();
+
+ } catch (error) {
+ showStatus('error', `❌ ERROR: ${error.message}`, statusDiv);
+ console.error('FILE UPLOAD FAILED:', error);
+ }
+}
+
+function showStatus(type, message, container) {
+ container.textContent = message;
+ container.className = `status-indicator ${type}`;
+
+ // 自动清除成功状态 auto clear success status
+ if (type === 'success') {
+ setTimeout(() => {
+ container.textContent = '';
+ container.className = 'status-indicator';
+ }, 5000);
+ }
+}
+
+// 文件上传处理 upload file
+function setupFileUpload() {
+ const dropzone = document.getElementById('dropzone');
+ const fileInput = document.getElementById('fileInput');
+
+
+ // 拖放事件处理 Drag and drop event handling
+ dropzone.addEventListener('dragover', (e) => {
+ e.preventDefault();
+ dropzone.classList.add('active');
+ });
+
+ dropzone.addEventListener('dragleave', () => {
+ dropzone.classList.remove('active');
+ });
+
+ dropzone.addEventListener('drop', async (e) => {
+ e.preventDefault();
+ dropzone.classList.remove('active');
+ await handleFiles(e.dataTransfer.files);
+ });
+
+
+ fileInput.addEventListener('change', async (e) => {
+ await handleFiles(e.target.files);
+ });
+}
+
+async function handleFiles(files) {
+ const formData = new FormData();
+ for (const file of files) {
+ formData.append('file', file);
+ }
+ const statusDiv = document.getElementById('fileUploadStatus');
+
+
+ statusDiv.className = 'status-indicator';
+ statusDiv.textContent = '';
+ try {
+ showStatus('loading', 'UPLOADING...', statusDiv);
+ const response = await fetch(`${API_BASE}/documents/upload`, {
+ method: 'POST',
+ body: formData
+ });
+ const result = await response.json();
+ showStatus('success', `✅ ${result.message} `, statusDiv);
+ updateFileList();
+ } catch (error) {
+ showToast(error.message, 'error');
+ }
+}
+
+
+async function updateFileList() {
+ const fileList = document.querySelector('.file-list');
+ try {
+ const status = await apiRequest('/health');
+ fileList.innerHTML = `
+ INDEXED FILE: ${status.indexed_files_count}
+ `;
+ } catch (error) {
+ fileList.innerHTML = 'UNABLE TO OBTAIN FILE LIST';
+ }
+}
+
+// 智能检索处理 Intelligent retrieval processing
+function setupQueryHandler() {
+ document.querySelector('#query .btn-primary').addEventListener('click', handleQuery);
+}
+
+async function handleQuery() {
+ const queryInput = document.querySelector('#query textarea');
+ const modeSelect = document.querySelector('#query select');
+ const streamCheckbox = document.querySelector('#query input[type="checkbox"]');
+ const resultsDiv = document.querySelector('#query .results');
+
+ const payload = {
+ query: queryInput.value,
+ mode: modeSelect.value,
+ stream: streamCheckbox.checked
+ };
+
+ resultsDiv.innerHTML = 'SEARCHING...
';
+
+ try {
+ if (payload.stream) {
+ await handleStreamingQuery(payload, resultsDiv);
+ } else {
+ const result = await apiRequest('/query', 'POST', payload);
+ resultsDiv.innerHTML = `${result.response}
`;
+ }
+ } catch (error) {
+ resultsDiv.innerHTML = `SEARCH FAILED: ${error.message}
`;
+ }
+}
+
+// 处理流式响应 handle stream api
+async function handleStreamingQuery(payload, resultsDiv) {
+ try {
+ const response = await fetch(`${API_BASE}/query/stream`, {
+ method: 'POST',
+ headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify(payload)
+ });
+
+
+ const contentType = response.headers.get('Content-Type') || '';
+ const validTypes = ['application/x-ndjson', 'application/json'];
+ if (!validTypes.some(t => contentType.includes(t))) {
+ throw new Error(`INVALID CONTENT TYPE: ${contentType}`);
+ }
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder('utf-8');
+ let buffer = '';
+
+ resultsDiv.innerHTML = '';
+
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) break;
+
+ buffer += decoder.decode(value, {stream: true});
+
+ // 按换行符分割(NDJSON格式要求) Split by line break (NDJSON format requirement)
+ let lineEndIndex;
+ while ((lineEndIndex = buffer.indexOf('\n')) >= 0) {
+ const line = buffer.slice(0, lineEndIndex).trim();
+ buffer = buffer.slice(lineEndIndex + 1);
+
+ if (!line) continue;
+
+ try {
+ const data = JSON.parse(line);
+
+ if (data.response) {
+ resultsDiv.innerHTML += data.response;
+ resultsDiv.scrollTop = resultsDiv.scrollHeight;
+ }
+
+ if (data.error) {
+ resultsDiv.innerHTML += `${data.error}
`;
+ }
+ } catch (error) {
+ console.error('JSON PARSING FAILED:', {
+ error,
+ rawLine: line,
+ bufferRemaining: buffer
+ });
+ }
+ }
+ }
+
+ // 处理剩余数据 Process remaining data
+ if (buffer.trim()) {
+ try {
+ const data = JSON.parse(buffer.trim());
+ if (data.response) {
+ resultsDiv.innerHTML += data.response;
+ }
+ } catch (error) {
+ console.error('TAIL DATA PARSING FAILED:', error);
+ }
+ }
+
+ } catch (error) {
+ resultsDiv.innerHTML = `REQUEST FAILED: ${error.message}
`;
+ }
+}
+
+
+// 知识问答处理 Knowledge Q&A Processing
+function setupChatHandler() {
+ const sendButton = document.querySelector('#chat button');
+ const chatInput = document.querySelector('#chat input');
+
+ sendButton.addEventListener('click', () => handleChat(chatInput));
+ chatInput.addEventListener('keypress', (e) => {
+ if (e.key === 'Enter') handleChat(chatInput);
+ });
+}
+
+async function handleChat(chatInput) {
+ const chatHistory = document.querySelector('#chat .chat-history');
+
+
+ const userMessage = document.createElement('div');
+ userMessage.className = 'message user';
+ userMessage.textContent = chatInput.value;
+ chatHistory.appendChild(userMessage);
+
+
+ const botMessage = document.createElement('div');
+ botMessage.className = 'message bot loading';
+ botMessage.textContent = 'THINKING...';
+ chatHistory.appendChild(botMessage);
+ chatHistory.scrollTop = chatHistory.scrollHeight;
+
+ try {
+ const response = await fetch(`${API_BASE}/api/chat`, {
+ method: 'POST',
+ headers: {'Content-Type': 'application/json'},
+ body: JSON.stringify({
+ messages: [{role: "user", content: chatInput.value}],
+ stream: true
+ })
+ });
+
+ const reader = response.body.getReader();
+ const decoder = new TextDecoder();
+ botMessage.classList.remove('loading');
+ botMessage.textContent = '';
+
+ while (true) {
+ const {done, value} = await reader.read();
+ if (done) break;
+
+ const chunk = decoder.decode(value);
+ const data = JSON.parse(chunk);
+ botMessage.textContent += data.message?.content || '';
+ chatHistory.scrollTop = chatHistory.scrollHeight;
+ }
+ } catch (error) {
+ botMessage.textContent = `ERROR: ${error.message}`;
+ botMessage.classList.add('error');
+ }
+
+ chatInput.value = '';
+}
+
+// 系统状态更新 system status update
+async function updateSystemStatus() {
+ const statusElements = {
+ health: document.getElementById('healthStatus'),
+ storageProgress: document.getElementById('storageProgress'),
+ indexedFiles: document.getElementById('indexedFiles'),
+ storageUsage: document.getElementById('storageUsage'),
+ llmModel: document.getElementById('llmModel'),
+ embedModel: document.getElementById('embedModel'),
+ maxTokens: document.getElementById('maxTokens'),
+ workingDir: document.getElementById('workingDir'),
+ inputDir: document.getElementById('inputDir'),
+ kv_storage: document.getElementById("kv_storage"),
+ doc_status_storage: document.getElementById("doc_status_storage"),
+ graph_storage: document.getElementById("graph_storage"),
+ vector_storage: document.getElementById("vector_storage")
+ };
+
+ try {
+ const status = await apiRequest('/health');
+
+ // 健康状态 heath status
+ statusElements.health.className = 'status-badge';
+ statusElements.health.textContent = status.status === 'healthy' ?
+ '✅ Healthy operation in progress' : '⚠️ Service exception';
+
+ // 存储状态(示例逻辑,可根据实际需求修改) kv status
+ const progressValue = Math.min(Math.round((status.indexed_files_count / 1000) * 100), 100);
+ statusElements.storageProgress.value = progressValue;
+ statusElements.indexedFiles.textContent = `INDEXED FILES:${status.indexed_files_count}`;
+ statusElements.storageUsage.textContent = `USE PERCENT:${progressValue}%`;
+
+ // 模型配置 model state
+ statusElements.llmModel.textContent = `${status.configuration.llm_model} (${status.configuration.llm_binding})`;
+ statusElements.embedModel.textContent = `${status.configuration.embedding_model} (${status.configuration.embedding_binding})`;
+ statusElements.maxTokens.textContent = status.configuration.max_tokens.toLocaleString();
+
+ // 目录信息 dir msg
+ statusElements.workingDir.textContent = status.working_directory;
+ statusElements.inputDir.textContent = status.input_directory;
+
+ //存储信息 stack msg
+ statusElements.kv_storage.textContent = status.configuration.kv_storage;
+ statusElements.doc_status_storage.textContent = status.configuration.doc_status_storage;
+ statusElements.graph_storage.textContent = status.configuration.graph_storage;
+ statusElements.vector_storage.textContent = status.configuration.vector_storage
+
+ } catch (error) {
+ statusElements.health.className = 'status-badge error';
+ statusElements.health.textContent = '❌GET STATUS FAILED';
+ statusElements.storageProgress.value = 0;
+ statusElements.indexedFiles.textContent = 'INDEXED FILES:GET FAILED';
+ console.error('STATUS UPDATE FAILED:', error);
+ }
+}
+
+
+// 区域切换监听 Area switching monitoring
+function setupSectionObserver() {
+ const observer = new MutationObserver(mutations => {
+ mutations.forEach(mutation => {
+ if (mutation.attributeName === 'style') {
+ const isVisible = mutation.target.style.display !== 'none';
+ if (isVisible && mutation.target.id === 'status') {
+ updateSystemStatus();
+ }
+ }
+ });
+ });
+
+ document.querySelectorAll('.card').forEach(section => {
+ observer.observe(section, {attributes: true});
+ });
+}
+
+// 显示提示信息 Display prompt information
+function showToast(message, type = 'info') {
+ const toast = document.createElement('div');
+ toast.className = `toast ${type}`;
+ toast.textContent = message;
+ document.body.appendChild(toast);
+
+ setTimeout(() => {
+ toast.remove();
+ }, 3000);
+}
+
+
+// 动态加载标签列表 Dynamically load tag list
+async function loadLabels() {
+ try {
+ const response = await fetch('/graph/label/list');
+ const labels = await response.json();
+ renderLabels(labels);
+ } catch (error) {
+ console.error('DYNAMICALLY LOAD TAG LIST FAILED:', error);
+ }
+}
+
+async function loadGraph(label) {
+ try {
+ // 渲染标签列表 render label list
+ openGraphModal(label)
+ } catch (error) {
+ console.error('LOADING LABEL FAILED:', error);
+
+
+ const labelList = document.getElementById("label-list");
+ labelList.innerHTML = `
+
+ LOADING ERROR: ${error.message}
+
+ `;
+ }
+}
+
+// 渲染标签列表 render graph label list
+function renderLabels(labels) {
+ const container = document.getElementById('label-list');
+ container.innerHTML = labels.map(label => `
+
+
+ ${label}
+
+
+
+
+
+ `).join('');
+}
+
+
+function handleLabelAction(label) {
+ loadGraph(label)
+}
+
+
+function refreshLabels() {
+ showToast('LOADING GRAPH LABELS...', 'info');
+ loadLabels();
+}
+
+function showToast(message, type = 'info') {
+ const toast = document.createElement('div');
+ toast.className = `toast toast-${type}`;
+ toast.textContent = message;
+ document.body.appendChild(toast);
+
+ setTimeout(() => {
+ toast.remove();
+ }, 3000);
+}
+
+document.addEventListener('DOMContentLoaded', initializeApp);
diff --git a/lightrag/kg/neo4j_impl.py b/lightrag/kg/neo4j_impl.py
index 8c2afb5d..6cc88e7c 100644
--- a/lightrag/kg/neo4j_impl.py
+++ b/lightrag/kg/neo4j_impl.py
@@ -339,3 +339,175 @@ class Neo4JStorage(BaseGraphStorage):
async def _node2vec_embed(self):
print("Implemented but never called.")
+
+ async def get_knowledge_graph(
+ self, node_label: str, max_depth: int = 5
+ ) -> Dict[str, List[Dict]]:
+ """
+ 获取指定节点的完整连通子图(包含起始节点本身)
+
+ 修复要点:
+ 1. 包含起始节点自身
+ 2. 处理多标签节点
+ 3. 明确关系方向
+ 4. 添加深度控制
+ """
+ label = node_label.strip('"')
+ result = {"nodes": [], "edges": []}
+ seen_nodes = set()
+ seen_edges = set()
+
+ async with self._driver.session(database=self._DATABASE) as session:
+ try:
+ # 关键调试步骤:先验证起始节点是否存在
+ validate_query = f"MATCH (n:`{label}`) RETURN n LIMIT 1"
+ validate_result = await session.run(validate_query)
+ if not await validate_result.single():
+ logger.warning(f"起始节点 {label} 不存在!")
+ return result
+
+ # 优化后的查询语句(包含方向处理和自循环)
+ main_query = f"""
+ MATCH (start:`{label}`)
+ WITH start
+ CALL apoc.path.subgraphAll(start, {{
+ relationshipFilter: '>',
+ minLevel: 0,
+ maxLevel: {max_depth},
+ bfs: true
+ }})
+ YIELD nodes, relationships
+ RETURN nodes, relationships
+ """
+ result_set = await session.run(main_query)
+ record = await result_set.single()
+
+ if record:
+ # 处理节点(兼容多标签情况)
+ for node in record["nodes"]:
+ # 使用节点ID + 标签组合作为唯一标识
+ node_id = f"{node.id}_{'_'.join(node.labels)}"
+ if node_id not in seen_nodes:
+ node_data = dict(node)
+ node_data["labels"] = list(node.labels) # 保留所有标签
+ result["nodes"].append(node_data)
+ seen_nodes.add(node_id)
+
+ # 处理关系(包含方向信息)
+ for rel in record["relationships"]:
+ edge_id = f"{rel.id}_{rel.type}"
+ if edge_id not in seen_edges:
+ start = rel.start_node
+ end = rel.end_node
+ edge_data = dict(rel)
+ edge_data.update(
+ {
+ "source": f"{start.id}_{'_'.join(start.labels)}",
+ "target": f"{end.id}_{'_'.join(end.labels)}",
+ "type": rel.type,
+ "direction": rel.element_id.split(
+ "->" if rel.end_node == end else "<-"
+ )[1],
+ }
+ )
+ result["edges"].append(edge_data)
+ seen_edges.add(edge_id)
+
+ logger.info(
+ f"子图查询成功 | 节点数: {len(result['nodes'])} | 边数: {len(result['edges'])}"
+ )
+
+ except neo4jExceptions.ClientError as e:
+ logger.error(f"APOC查询失败: {str(e)}")
+ return await self._robust_fallback(label, max_depth)
+
+ return result
+
+ async def _robust_fallback(
+ self, label: str, max_depth: int
+ ) -> Dict[str, List[Dict]]:
+ """强化版降级查询方案"""
+ result = {"nodes": [], "edges": []}
+ visited_nodes = set()
+ visited_edges = set()
+
+ async def traverse(current_label: str, current_depth: int):
+ if current_depth > max_depth:
+ return
+
+ # 获取当前节点详情
+ node = await self.get_node(current_label)
+ if not node:
+ return
+
+ node_id = f"{current_label}"
+ if node_id in visited_nodes:
+ return
+ visited_nodes.add(node_id)
+
+ # 添加节点数据(带完整标签)
+ node_data = {k: v for k, v in node.items()}
+ node_data["labels"] = [current_label] # 假设get_node方法返回包含标签信息
+ result["nodes"].append(node_data)
+
+ # 获取所有出边和入边
+ query = f"""
+ MATCH (a)-[r]-(b)
+ WHERE a:`{current_label}` OR b:`{current_label}`
+ RETURN a, r, b,
+ CASE WHEN startNode(r) = a THEN 'OUTGOING' ELSE 'INCOMING' END AS direction
+ """
+ async with self._driver.session(database=self._DATABASE) as session:
+ results = await session.run(query)
+ async for record in results:
+ # 处理边
+ rel = record["r"]
+ edge_id = f"{rel.id}_{rel.type}"
+ if edge_id not in visited_edges:
+ edge_data = dict(rel)
+ edge_data.update(
+ {
+ "source": list(record["a"].labels)[0],
+ "target": list(record["b"].labels)[0],
+ "type": rel.type,
+ "direction": record["direction"],
+ }
+ )
+ result["edges"].append(edge_data)
+ visited_edges.add(edge_id)
+
+ # 递归遍历相邻节点
+ next_label = (
+ list(record["b"].labels)[0]
+ if record["direction"] == "OUTGOING"
+ else list(record["a"].labels)[0]
+ )
+ await traverse(next_label, current_depth + 1)
+
+ await traverse(label, 0)
+ return result
+
+ async def get_all_labels(self) -> List[str]:
+ """
+ 获取数据库中所有存在的节点标签
+ Returns:
+ ["Person", "Company", ...] # 按字母排序的标签列表
+ """
+ async with self._driver.session(database=self._DATABASE) as session:
+ # 方法1:直接查询元数据(Neo4j 4.3+ 可用)
+ # query = "CALL db.labels() YIELD label RETURN label"
+
+ # 方法2:兼容旧版本的查询方式
+ query = """
+ MATCH (n)
+ WITH DISTINCT labels(n) AS node_labels
+ UNWIND node_labels AS label
+ RETURN DISTINCT label
+ ORDER BY label
+ """
+
+ result = await session.run(query)
+ labels = []
+ async for record in result:
+ labels.append(record["label"])
+ return labels
diff --git a/lightrag/lightrag.py b/lightrag/lightrag.py
index 69b165cb..0918c1ba 100644
--- a/lightrag/lightrag.py
+++ b/lightrag/lightrag.py
@@ -292,6 +292,15 @@ class LightRAG:
embedding_func=None,
)
+ async def get_graph_labels(self):
+ text = await self.chunk_entity_relation_graph.get_all_labels()
+ return text
+
+ async def get_graps(self, nodel_label: str, max_depth: int):
+ return await self.chunk_entity_relation_graph.get_knowledge_graph(
+ node_label=nodel_label, max_depth=max_depth
+ )
+
def _get_storage_class(self, storage_name: str) -> dict:
import_path = STORAGES[storage_name]
storage_class = lazy_external_import(import_path, storage_name)