NexusRAG

LeDat98更新放缓

把向量检索、知识图谱和交叉编码器重排揉在一起的混合 RAG 系统,支持 Docling 解析文档、图片表格理解、流式对话和行内引用,可接 Gemini 或本地 Ollama。

Hybrid RAG system combining vector search, knowledge graph (LightRAG), and cross-encoder reranking — with Docling document parsing, visual intelligence (image/table captioning), agentic streaming chat, and inline citations. Powered by Gemini or local Ollama models.

暂无版本530star113fork同步于 2026-11-07 07:31 UTC

怎么上手

由 README 提炼,执行前请确认
git clone https://github.com/LeDat98/NexusRAG.git
cd NexusRAG
cp .env.example .env
docker compose up -d
硬件要求按 README 说明

README 给出系统要求:内存最低 4GB、推荐 8GB 以上,磁盘最低 5GB。Docling 解析含公式增强时约占 18-20GB 显存,切到 Marker 约 2-4GB 显存。未说明支持的 GPU 厂商与型号。

支持 Apple Silicon有 Docker 镜像
下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

把向量检索、知识图谱和交叉编码器重排合成一条 RAG 流水线,带引用和图片表格理解

把向量检索、知识图谱和交叉编码器重排揉在一起的混合 RAG 系统,支持 Docling 解析文档、图片表格理解、流式对话和行内引用,可接 Gemini 或本地 Ollama。

核心能力

  • 用 Docling 或 Marker 解析文档,保留标题层级与页码
  • 图片和表格由视觉模型生成描述后并入向量检索
  • 向量召回与 LightRAG 实体查找并行,再用交叉编码器重排
  • 自动生成带页码和标题路径的引用 ID
  • 内置 MCP 服务,可接入 Cursor 或 Claude Desktop

容易踩的坑

首次构建需下载约 2.5GB 的 ML 模型,耗时 5-10 分钟;使用 Gemini 必须先在 .env 填 GOOGLE_AI_API_KEY,否则要切到 Ollama;KG 嵌入维度必须与所选模型匹配,默认 3072 对应 Gemini。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

0 个版本

暂无 release 数据(可能没有发版,或尚未同步)。

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    NexusRAG

    Hybrid Knowledge Base with Agentic Chat, Citations & Knowledge Graph

    Python React FastAPI Docker License: MIT LinkedIn

    Upload documents. Ask questions. Get cited answers.

    NexusRAG combines vector search, knowledge graph, and cross-encoder reranking into one seamless RAG pipeline — powered by Gemini, local Ollama, or fully offline sentence-transformers.

    Features · Quick Start · Model Recommendations · Tech Stack


    Architecture

    NexusRAG Architecture

    Showcase

    https://github.com/user-attachments/assets/fa845fab-dcc3-4a64-86ac-6dda2c073156


    Beyond Traditional RAG

    Most RAG systems follow a simple pipeline: split text → embed → retrieve → generate. NexusRAG goes further at every stage:

    AspectTraditional RAGNexusRAG
    Document ParsingPlain text extraction, structure lostDocling or Marker: preserves headings, page boundaries, formulas, layout — switchable via config
    Images & TablesIgnored entirelyExtracted, captioned by vision LLM, embedded as searchable vectors
    ChunkingFixed-size splits, breaks mid-sentenceHybrid semantic + structural chunking (respects headings, tables)
    EmbeddingsSingle model for everythingDual-model: BAAI/bge-m3 (1024d, search) + KG embedding (Gemini 3072d / Ollama / sentence-transformers)
    RetrievalVector similarity only3-way parallel: Vector over-fetch + KG entity lookup + Cross-encoder rerank
    KnowledgeNo entity awarenessLightRAG graph: entity extraction, relationship mapping, multi-hop traversal
    ContextRaw chunks dumped to LLMStructured assembly: KG insights → cited chunks → related images/tables
    CitationsNone or manualAuto-generated 4-char IDs with page number and heading path
    Page awarenessLost after chunkingPreserved end-to-end: chunk → citation → document viewer navigation

    Features

    NexusRAG supports two document parsers, switchable via NEXUSRAG_DOCUMENT_PARSER env config:

    FeatureDocling (default)Marker
    Math/FormulaBasic (known LaTeX issues)Superior LaTeX via Surya
    GPU footprint~18-20GB VRAM (formula enrichment)~2-4GB VRAM
    FormatsPDF, DOCX, PPTX, HTMLPDF, DOCX, PPTX, XLSX, HTML, EPUB
    ChunkingHybridChunker (semantic + structural)Heading-aware + page-based
    Image extractionVia Docling pipelineVia Marker pipeline
    Table extractionStructured exportMarkdown tables

    Both parsers share the same output contract (ParsedDocument) — downstream pipeline (dedup, embedding, KG, retrieval) works identically regardless of parser choice.

    Common features across both parsers:

    • Structural preservation — Heading hierarchy, page boundaries, paragraph grouping
    • Multi-format — PDF, DOCX, PPTX, TXT with consistent output
    • Page-aware metadata — Every chunk carries its page number, heading path, and references to images/tables on the same page
    • LLM captioning — Images and tables captioned by vision/text LLM for semantic search
    # Switch parser in .env
    NEXUSRAG_DOCUMENT_PARSER=marker   # or "docling" (default)
    
    StageTechnologyDetails
    Vector EmbeddingBAAI/bge-m31024-dim multilingual bi-encoder (100+ languages)
    KG EmbeddingGemini / Ollama / sentence-transformersConfigurable: Gemini (3072d), Ollama, or local sentence-transformers (e.g. bge-m3 1024d)
    Vector SearchChromaDBCosine similarity, over-fetch top-20 candidates
    Knowledge GraphLightRAGEntity/relationship extraction, keyword-to-entity matching
    RerankingBAAI/bge-reranker-v2-m3Cross-encoder joint scoring — encodes (query, chunk) pairs together
    GenerationGemini / OllamaAgentic streaming chat with function calling

    Why two embedding models? Vector search needs speed (local bge-m3, 1024-dim). Knowledge graph extraction needs semantic richness for entity recognition — choose Gemini Embedding (3072-dim, cloud), Ollama, or sentence-transformers (fully local, no API needed). Each model is optimized for its role.

    Retrieval flow:

    1. Parallel retrieval — Vector over-fetch (top-20) + KG entity lookup run simultaneously
    2. Cross-encoder reranking — All 20 candidates scored jointly with the query through a transformer (far more precise than cosine similarity alone)
    3. Filtering — Keep top-8 above relevance threshold (0.15), with fallback to top-3 if all below
    4. Media discovery — Find images and tables on the same pages as retrieved chunks

    Images and tables are embedded into chunk vectors — not stored separately. When the parser extracts an image on page 5, its LLM-generated caption is appended to the text chunks on that page before embedding. This means searching for "revenue chart" finds chunks that contain the chart description, without needing a separate image search index.

    Image Pipeline

    1. Parser (Docling or Marker) extracts images from PDF/DOCX/PPTX (up to 50 per document)
    2. Vision LLM (Gemini Vision or Ollama multimodal) generates captions: specific numbers, labels, trends
    3. Captions appended to page chunks: [Image on page 5]: Graph showing 12% revenue growth YoY
    4. Chunk is embedded → image becomes vector-searchable through its description
    5. During retrieval, images on matched pages are surfaced as [IMG-p4f2] references

    Table Pipeline

    1. Parser exports tables as structured Markdown (preserving rows, columns, dimensions)
    2. Text LLM summarizes each table: purpose, key columns, notable values (max 500 chars)
    3. Summaries appended to page chunks: [Table on page 5 (3x4)]: Annual sales by region
    4. Table summaries injected back into document Markdown as blockquotes for the document viewer

    Enhance RAG accuracy and organization by attaching custom key-value metadata during document upload:

    • Metadata Filtering — Perform hybrid search (semantic + metadata filtering) to narrow down the search space and prevent hallucinations.
    • Flexible Organization — Tag documents with attributes like year, category, or author without needing separate workspaces.
    • Optimized Retrieval — Pre-filtering in ChromaDB reduces processing time and latency during vector search.
    • Supported Endpoints — Pass custom_metadata (list of key-values) in the upload API, and metadata_filter in query/chat APIs.

    Every answer is grounded in source documents with 4-character citation IDs (e.g., [a3z1]):

    • Inline citations — Clickable badges embedded directly in the answer text
    • Source cards — Each citation shows filename, page number, heading path, and relevance score
    • Cross-navigation — Click a citation to jump to the exact section in the document viewer
    • Image references — Visual content cited separately as [IMG-p4f2] with page tracking
    • Strict grounding — The LLM is instructed to only cite sources that directly support claims, max 3 per sentence

    Interactive force-directed graph built from extracted entities and relationships:

    • Entity types — Person, Organization, Product, Location, Event, Technology, Financial Metric, Date, Regulation (configurable)
    • Force simulation — Repulsion + spring forces + center gravity with real-time physics
    • Pan & zoom — Mouse drag, scroll wheel (0.3x-3x), keyboard reset
    • Node interaction — Click to select, hover to highlight connected edges, drag to reposition
    • Entity scaling — Node radius proportional to connectivity (degree)
    • Query modes — Naive, Local (multi-hop), Global (summary), Hybrid (default)
    • No extra services — LightRAG uses file-based storage (NetworkX + NanoVectorDB), zero Docker overhead

    Switch between cloud and local models with a single environment variable:

    Gemini (Cloud)
    ModelBest ForThinking
    gemini-2.5-flashGeneral chat, fast responsesBudget-based (auto)
    gemini-3.1-flash-liteHigh throughput, cost-effective Recommended defaultLevel-based: minimal / low / medium / high

    Extended thinking is automatically configured — Gemini 2.5 uses thinking_budget_tokens, Gemini 3.x uses thinking_level.

    Ollama (Local / Self-hosted)
    ModelParametersTool CallingRecommendation
    gemma4:e4b4.5B effective (8B total)NativeRecommended default — best quality/size ratio, 128K context, vision + thinking + native tool calling
    gemma4:e2b2.3B effective (5.1B total)NativeUltra-lightweight, fast responses. Needs thinking enabled for reliable tool calls
    qwen3.5:9b9BNativeGood multilingual support, solid tool calling
    qwen3.5:4b4BNativeLightweight, works on 8GB RAM. May miss some tool calls
    gemma3:12b12BPrompt-basedBest balance of quality and speed for older Ollama versions

    Tip: Gemma 4 models require Ollama v0.20.0+. NexusRAG auto-detects native tool calling support — models that support it use Ollama's native tools API (more reliable), others fall back to prompt-based tool calling automatically.

    Tip: For Knowledge Graph extraction, larger models (12B+) produce significantly better entity/relationship quality. Smaller models (4B) may extract zero entities on complex documents.

    Provider switching — Comment/uncomment blocks in .env:

    # Cloud (Gemini)
    LLM_PROVIDER=gemini
    GOOGLE_AI_API_KEY=your-key
    
    # Local (Ollama) — uncomment to switch
    # LLM_PROVIDER=ollama
    # OLLAMA_MODEL=gemma4:e4b
    
    KG Embedding Providers

    The Knowledge Graph embedding model is configured separately from the chat LLM:

    ProviderConfigAPI RequiredDimension
    Gemini (default)KG_EMBEDDING_PROVIDER=geminiGoogle AI API key3072
    OllamaKG_EMBEDDING_PROVIDER=ollamaOllama serverVaries
    sentence-transformersKG_EMBEDDING_PROVIDER=sentence_transformersNone (fully local)Model-dependent (e.g. 1024 for bge-m3)
    # Fully local KG embeddings — no API or external service needed
    KG_EMBEDDING_PROVIDER=sentence_transformers
    KG_EMBEDDING_MODEL=BAAI/bge-m3
    KG_EMBEDDING_DIMENSION=1024
    

    Tip: sentence_transformers reuses the same BAAI/bge-m3 model already downloaded for vector search — zero extra disk space, zero API costs, fully offline.

    The chat system uses a semi-agentic architecture with real-time SSE streaming:

    • Agent steps — Visual timeline: Analyzing → Retrieving → Generating → Done (with live timers)
    • Extended thinking — Gemini/Ollama reasoning displayed in a collapsible panel
    • Function calling — 3-tier: Native (Gemini), Native (Ollama — Gemma 4, Qwen 3.5), or prompt-based fallback (older models). Auto-detected via probe
    • Force-search mode — Pre-retrieval before LLM generation for guaranteed grounded answers
    • Heartbeat — 15s SSE keepalive prevents TCP timeout on slow responses
    • Fallback — If Ollama produces empty output, auto-triggers search + retry
    • Chat history — Persistent per workspace with message ratings (thumbs up/down)

    Theme & Layout

    • Dark / Light mode with smooth transition, persisted preference
    • Collapsible sidebar with workspace navigation (icon-only mode at narrow width)
    • Responsive grid layouts — mobile to desktop

    Chat Interface

    • Streaming token rendering with memoized paragraph blocks (only active block re-renders)
    • Inline citation badges with hover tooltips (source file, page, heading path, relevance %)
    • Agent step timeline with spinner animations and elapsed timers
    • Thinking panel — scrollable, auto-follow, collapsible after completion
    • Code blocks with syntax highlighting (Python, JS, SQL, etc.) and one-click copy

    Document Management

    • Drag-and-drop upload (PDF, DOCX, PPTX, TXT, MD — up to 50MB)
    • Status badges with shimmer animation during processing
    • Per-document chips: pages, chunks, images, tables, file size, processing time

    Search

    • 4 query modes: Hybrid, Vector, Local KG, Global KG
    • Adjustable result count (1-20) with slider + direct input
    • Document scope filtering (multi-select)
    • Relevance score bars with color coding (green / amber / red)

    Analytics Dashboard

    • Stat cards: documents, indexed, chunks, images, entities, relationships
    • Entity type distribution bar with animated widths
    • Top entities ranked by connectivity
    • Per-document chunk breakdown chart

    Micro-interactions

    • Framer Motion animations throughout (staggered entrances, layout transitions)
    • Loading skeletons, toast notifications, empty state illustrations
    • Keyboard shortcuts: / to focus search, Enter to send, Escape to cancel
    • Multiple isolated knowledge bases, each with its own documents, ChromaDB collection, and KG
    • Custom system prompt per workspace (override default Q&A behavior)
    • Independent chat history with message persistence and ratings

    Evaluation

    NexusRAG was evaluated using two complementary methods: 16 hand-crafted tests (rule-based metrics) and 30 RAGAS synthetic tests (LLM-as-judge). Test corpus: TechVina Annual Report 2025 (Vietnamese, 26 chunks) + DeepSeek-V3.2 Technical Paper (English, 57 chunks).

    Phase 1 Evaluation

    16 tests across 6 categories using 8 rule-based metrics (keyword coverage, refusal accuracy, citation format, language match, etc.) — no LLM judge involved.

    CategoryPass RateAvg Score
    Fact Extraction (VI + EN)5/50.93
    Table Data2/30.83
    Cross-Document Reasoning2/20.89
    Anti-Hallucination3/31.00
    Multi-turn History2/20.87
    Citation Accuracy1/10.85
    Overall15/160.89 — EXCELLENT

    RAGAS Model Comparison

    30 auto-generated Q&A pairs evaluated by Gemini 2.0 Flash as RAGAS judge. Same questions tested on both models:

    Metricgemma3:12b (local)gemini-2.5-flash (cloud)Winner
    Overall score0.8320.846Gemini
    Pass rate25/30 (83%)26/30 (87%)Gemini
    Faithfulness0.7490.812Gemini (+0.063)
    Factual correctness0.7730.749gemma3 (+0.024)
    Context recall0.8330.833Tie
    Table extraction0.6970.905Gemini (+0.208)
    Avg latency3076ms3283msgemma3 (-207ms)
    AspectStatusDetail
    Anti-hallucination:green_circle: StrongPerfect refusal on out-of-scope questions
    Citation format:green_circle: Strong100% correct format across all tests
    Cross-doc reasoning:green_circle: StrongSuccessfully synthesizes across multiple sources
    Table parsing:yellow_circle: Model-dependentgemma3 fails complex tables; Gemini handles well
    Language consistency:yellow_circle: Model-dependentgemma3 occasionally responds in wrong language
    Retrieval coverage:red_circle: Weak5 cases with context_recall = 0 (specific facts missed by retrieval)
    Faithfulness:red_circle: Weak4 FAIL cases — LLM adds unsupported details when elaborating

    Full evaluation methodology and per-sample results: rag_evaluation_report.md

    Upcoming model benchmarks on the same 30 RAGAS test suite:

    ModelTypeStatus
    gemma3:12bLocal (Ollama):white_check_mark: Done
    gemini-2.5-flashCloud (Google AI):white_check_mark: Done
    qwen3.5:4bLocal (Ollama):hourglass: Planned
    qwen3.5:9bLocal (Ollama):hourglass: Planned
    gemini-3.1-flash-liteCloud (Google AI):hourglass: Planned

    Goal: compare cost-efficiency (local 4B/9B) vs cloud quality across faithfulness, table extraction, and multilingual consistency.


    Tech Stack

    TechnologyPurpose
    FastAPIAsync web framework with SSE streaming
    SQLAlchemy 2.0Async ORM with PostgreSQL (asyncpg)
    ChromaDBVector store — cosine similarity, per-workspace collections
    LightRAGKnowledge graph — entity extraction, multi-hop queries
    Docling / MarkerDocument parsing — PDF, DOCX, PPTX, HTML with structural extraction (switchable via config)
    sentence-transformersBAAI/bge-m3 embeddings + BAAI/bge-reranker-v2-m3 reranking
    google-genaiGemini API — chat, vision, function calling, extended thinking
    ollamaLocal LLM — tool calling via prompt tags, multimodal support
    TechnologyPurpose
    React 19 + TypeScript 5.9UI framework with strict typing
    Vite 7Dev server and production bundler
    TailwindCSS 4Utility-first styling with dark / light theme
    Zustand 5Lightweight state management
    React Query 5Async data fetching, caching, and mutations
    Framer Motion 12Layout animations, transitions, staggered entrances
    react-markdown + KaTeXRich markdown with LaTeX math rendering
    Lucide ReactIcon library
    TechnologyPurpose
    PostgreSQL 15Document metadata, chat history, workspace config
    ChromaDBVector embeddings (HTTP client, containerized)
    LightRAGFile-based KG (NetworkX + NanoVectorDB — no extra services)
    Docker ComposeFull-stack deployment (4 containers)
    nginxProduction frontend serving + API/SSE reverse proxy

    Quick Start

    Option A: Docker (Full Stack)

    git clone https://github.com/LeDat98/NexusRAG.git
    cd NexusRAG
    cp .env.example .env
    # Edit .env — set GOOGLE_AI_API_KEY (or switch to Ollama)
    docker compose up -d
    

    First build takes ~5-10 minutes (downloads ML models ~2.5GB). Open http://localhost:5174

    Option B: Local Development

    git clone https://github.com/LeDat98/NexusRAG.git
    cd NexusRAG
    ./setup.sh
    

    The script checks prerequisites, creates venv, installs deps, starts PostgreSQL + ChromaDB, and optionally downloads ML models.

    # Terminal 1 — Backend (port 8080)
    ./run_bk.sh
    
    # Terminal 2 — Frontend (port 5174)
    ./run_fe.sh
    

    Open http://localhost:5174

    ResourceMinimumRecommended
    RAM4 GB8 GB+
    Disk5 GB10 GB+
    Python3.10+3.11+
    Node.js18+22 LTS
    Docker20+Latest

    Copy .env.example and configure:

    cp .env.example .env
    

    Required

    VariableDescription
    GOOGLE_AI_API_KEYGoogle AI API key (required for Gemini provider)

    LLM

    VariableDefaultDescription
    LLM_PROVIDERgeminigemini or ollama
    LLM_MODEL_FASTgemini-2.5-flashModel for chat and KG extraction
    LLM_THINKING_LEVELmediumGemini 3.x thinking: minimal / low / medium / high
    LLM_MAX_OUTPUT_TOKENS8192Max output tokens (includes thinking)
    OLLAMA_HOSThttp://localhost:11434Ollama server URL
    OLLAMA_MODELgemma3:12bOllama model name

    KG Embedding

    VariableDefaultDescription
    KG_EMBEDDING_PROVIDERgeminigemini, ollama, or sentence_transformers
    KG_EMBEDDING_MODELtext-embedding-004Model name (provider-specific)
    KG_EMBEDDING_DIMENSION3072Embedding dimension (must match model)

    RAG Pipeline

    VariableDefaultDescription
    NEXUSRAG_EMBEDDING_MODELBAAI/bge-m3Embedding model (1024-dim)
    NEXUSRAG_RERANKER_MODELBAAI/bge-reranker-v2-m3Cross-encoder reranker
    NEXUSRAG_VECTOR_PREFETCH20Candidates before reranking
    NEXUSRAG_RERANKER_TOP_K8Final results after reranking
    NEXUSRAG_ENABLE_KGtrueEnable knowledge graph extraction
    NEXUSRAG_DOCUMENT_PARSERdoclingDocument parser: docling (default) or marker (lighter, better math)
    NEXUSRAG_MARKER_USE_LLMfalseEnable LLM-enhanced mode for Marker (better tables, equations)
    NEXUSRAG_ENABLE_IMAGE_EXTRACTIONtrueExtract images from documents
    NEXUSRAG_ENABLE_IMAGE_CAPTIONINGtrueLLM-caption images for search
    NEXUSRAG_KG_LANGUAGEVietnameseKG extraction language

    Roadmap

    • Multimodal Retrieval — Integrate Gemini Embedding 2 (multimodal) for audio and video input retrieval — ask questions about podcasts, lectures, or video content directly
    • Marker PDF Parser — Add Marker as an alternative document parser with superior math/formula extraction (LaTeX via Surya), lighter GPU footprint (~2-4GB VRAM vs Docling's ~18-20GB), and switchable via NEXUSRAG_DOCUMENT_PARSER=marker env config

    MCP Server

    NexusRAG includes a Model Context Protocol (MCP) server that exposes its core functionalities:

    • get_workspace_list: List all knowledge bases.
    • get_document_by_id: Get details for a specific document.
    • query: Query indexed documents using semantic search.

    Connecting to the MCP Server

    The MCP Server is automatically started by default via docker-compose up -d on port 8000 using the Streamable HTTP transport (latest protocol version).

    Cursor / Claude Desktop

    You can directly add the NexusRAG MCP server to Cursor or Claude as an SSE connection using the URL: http://localhost:8000/mcp (Note: some clients still label this as an SSE connection, but use the /mcp endpoint to connect via Streamable HTTP).


    API

    All endpoints prefixed with /api/v1. Interactive docs at http://localhost:8080/docs

    MethodEndpointDescription
    GET/workspacesList all workspaces
    POST/workspacesCreate workspace
    PUT/workspaces/{id}Update workspace
    DELETE/workspaces/{id}Delete workspace + all data
    MethodEndpointDescription
    POST/documents/upload/{workspace_id}Upload file (supports custom_metadata)
    GET/documents/{id}/markdownGet parsed content
    GET/documents/{id}/imagesList extracted images
    DELETE/documents/{id}Delete document
    MethodEndpointDescription
    POST/rag/query/{workspace_id}Hybrid search (supports metadata_filter)
    POST/rag/chat/{workspace_id}/streamAgentic streaming chat (SSE) (supports metadata_filter)
    GET/rag/chat/{workspace_id}/historyChat history
    POST/rag/process/{document_id}Process document
    GET/rag/graph/{workspace_id}Knowledge graph data
    GET/rag/analytics/{workspace_id}Full analytics

    Star History

    Star History


    ⭐ If you find NexusRAG useful, please consider giving it a star — it helps others discover the project and motivates continued development!

    MIT License © 2026 Le Duc Dat