RAG-Anything README

项目的 README,来自 github.com/HKUDS/RAG-Anything。合并为一个 markdown 文件:README.md。

RAG-Anything Logo

🚀 RAG-Anything: All-in-One RAG Framework

HKUDS%2FRAG-Anything | Trendshift

Typing Animation

Selected organizations among the 225 identified from self-reported RAG-Anything stargazer affiliations on GitHub on November 23, 2026. Stars are personal.


🎉 News


🌟 System Overview

Next-Generation Multimodal Intelligence

Modern documents increasingly contain diverse multimodal content—text, images, tables, equations, charts, and multimedia—that traditional text-focused RAG systems cannot effectively process. RAG-Anything addresses this challenge as a comprehensive All-in-One Multimodal Document Processing RAG system built on LightRAG.

As a unified solution, RAG-Anything eliminates the need for multiple specialized tools. It provides seamless processing and querying across all content modalities within a single integrated framework. Unlike conventional RAG approaches that struggle with non-textual elements, our all-in-one system delivers comprehensive multimodal retrieval capabilities.

Users can query documents containing interleaved text, visual diagrams, structured tables, and mathematical formulations through one cohesive interface. This consolidated approach makes RAG-Anything particularly valuable for academic research, technical documentation, financial reports, and enterprise knowledge management where rich, mixed-content documents demand a unified processing framework.

RAG-Anything

🎯 Key Features

  • 🔄 End-to-End Multimodal Pipeline - Complete workflow from document ingestion and parsing to intelligent multimodal query answering
  • 📄 Universal Document Support - Seamless processing of PDFs, Office documents, images, and diverse file formats
  • 🧠 Specialized Content Analysis - Dedicated processors for images, tables, mathematical equations, and heterogeneous content types
  • 🔗 Multimodal Knowledge Graph - Automatic entity extraction and cross-modal relationship discovery for enhanced understanding
  • ⚡ Adaptive Processing Modes - Flexible MinerU-based parsing or direct multimodal content injection workflows
  • 📋 Direct Content List Insertion - Bypass document parsing by directly inserting pre-parsed content lists from external sources
  • 🎯 Hybrid Intelligent Retrieval - Advanced search capabilities spanning textual and multimodal content with contextual understanding

🏗️ Algorithm & Architecture

Core Algorithm

RAG-Anything implements an effective multi-stage multimodal pipeline that fundamentally extends traditional RAG architectures to seamlessly handle diverse content modalities through intelligent orchestration and cross-modal understanding.

📄
Document Parsing
→
🧠
Content Analysis
→
🔍
Knowledge Graph
→
🎯
Intelligent Retrieval

1. Document Parsing Stage

The system provides high-fidelity document extraction through adaptive content decomposition. It intelligently segments heterogeneous elements while preserving contextual relationships. Universal format compatibility is achieved via specialized optimized parsers.

Key Components:

  • ⚙️ MinerU Integration: Leverages MinerU for high-fidelity document structure extraction and semantic preservation across complex layouts.

  • 🧩 Adaptive Content Decomposition: Automatically segments documents into coherent text blocks, visual elements, structured tables, mathematical equations, and specialized content types while preserving contextual relationships.

  • 📁 Universal Format Support: Provides comprehensive handling of PDFs, Office documents (DOC/DOCX/PPT/PPTX/XLS/XLSX), images, and emerging formats through specialized parsers with format-specific optimization.

2. Multi-Modal Content Understanding & Processing

The system automatically categorizes and routes content through optimized channels. It uses concurrent pipelines for parallel text and multimodal processing. Document hierarchy and relationships are preserved during transformation.

Key Components:

  • 🎯 Autonomous Content Categorization and Routing: Automatically identify, categorize, and route different content types through optimized execution channels.

  • ⚡ Concurrent Multi-Pipeline Architecture: Implements concurrent execution of textual and multimodal content through dedicated processing pipelines. This approach maximizes throughput efficiency while preserving content integrity.

  • 🏗️ Document Hierarchy Extraction: Extracts and preserves original document hierarchy and inter-element relationships during content transformation.

3. Multimodal Analysis Engine

The system deploys modality-aware processing units for heterogeneous data modalities:

Specialized Analyzers:

  • 🔍 Visual Content Analyzer:

    • Integrate vision model for image analysis.
    • Generates context-aware descriptive captions based on visual semantics.
    • Extracts spatial relationships and hierarchical structures between visual elements.
  • 📊 Structured Data Interpreter:

    • Performs systematic interpretation of tabular and structured data formats.
    • Implements statistical pattern recognition algorithms for data trend analysis.
    • Identifies semantic relationships and dependencies across multiple tabular datasets.
  • 📐 Mathematical Expression Parser:

    • Parses complex mathematical expressions and formulas with high accuracy.
    • Provides native LaTeX format support for seamless integration with academic workflows.
    • Establishes conceptual mappings between mathematical equations and domain-specific knowledge bases.
  • 🔧 Extensible Modality Handler:

    • Provides configurable processing framework for custom and emerging content types.
    • Enables dynamic integration of new modality processors through plugin architecture.
    • Supports runtime configuration of processing pipelines for specialized use cases.

4. Multimodal Knowledge Graph Index

The multi-modal knowledge graph construction module transforms document content into structured semantic representations. It extracts multimodal entities, establishes cross-modal relationships, and preserves hierarchical organization. The system applies weighted relevance scoring for optimized knowledge retrieval.

Core Functions:

  • 🔍 Multi-Modal Entity Extraction: Transforms significant multimodal elements into structured knowledge graph entities. The process includes semantic annotations and metadata preservation.

  • 🔗 Cross-Modal Relationship Mapping: Establishes semantic connections and dependencies between textual entities and multimodal components. This is achieved through automated relationship inference algorithms.

  • 🏗️ Hierarchical Structure Preservation: Maintains original document organization through "belongs_to" relationship chains. These chains preserve logical content hierarchy and sectional dependencies.

  • ⚖️ Weighted Relationship Scoring: Assigns quantitative relevance scores to relationship types. Scoring is based on semantic proximity and contextual significance within the document structure.

5. Modality-Aware Retrieval

The hybrid retrieval system combines vector similarity search with graph traversal algorithms for comprehensive content retrieval. It implements modality-aware ranking mechanisms and maintains relational coherence between retrieved elements to ensure contextually integrated information delivery.

Retrieval Mechanisms:

  • 🔀 Vector-Graph Fusion: Integrates vector similarity search with graph traversal algorithms. This approach leverages both semantic embeddings and structural relationships for comprehensive content retrieval.

  • 📊 Modality-Aware Ranking: Implements adaptive scoring mechanisms that weight retrieval results based on content type relevance. The system adjusts rankings according to query-specific modality preferences.

  • 🔗 Relational Coherence Maintenance: Maintains semantic and structural relationships between retrieved elements. This ensures coherent information delivery and contextual integrity.


🚀 Quick Start

Initialize Your AI Journey

Installation

Python version: RAG-Anything supports Python 3.10 and later, but its default MinerU parser needs MinerU 3.x, which supports Python 3.10 to 3.13 only. On Python 3.14, RAG-Anything is installed without MinerU: use the Docling parser there (pip install docling, then RAGAnythingConfig(parser="docling")), or create the environment with Python 3.13 to use MinerU.

# Basic installation
pip install raganything

# With optional dependencies for extended format support:
pip install 'raganything[all]'              # All optional features (Docling not included)
pip install 'raganything[image]'            # Image format conversion (BMP, TIFF, GIF, WebP)
pip install 'raganything[text]'             # Text file processing (TXT, MD)
pip install 'raganything[image,text]'       # Multiple features

Option 2: Install from Source

# Install uv (if not already installed)
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone and setup the project with uv
git clone https://github.com/HKUDS/RAG-Anything.git
cd RAG-Anything

# Install the package and dependencies in a virtual environment
uv sync

# If you encounter network timeouts (especially for opencv packages):
# UV_HTTP_TIMEOUT=120 uv sync

# Run commands directly with uv (recommended approach)
uv run python examples/raganything_example.py --help

# Install with optional dependencies
uv sync --extra image --extra text  # Specific extras
uv sync --all-extras                 # All optional features

Optional Dependencies

⚠️ Office Document Processing Requirements:

  • Office documents (.doc, .docx, .ppt, .pptx, .xls, .xlsx) require LibreOffice installation
  • Download from LibreOffice official website
  • Windows: Download installer from official website
  • macOS: brew install --cask libreoffice
  • Ubuntu/Debian: sudo apt-get install libreoffice
  • CentOS/RHEL: sudo yum install libreoffice

Check MinerU installation:

On Python 3.10 to 3.13, RAG-Anything installs MinerU 3.x as a dependency (mineru[core]>=3.4.1,<4). MinerU 3.x does not support Python 3.14, so on Python 3.14 MinerU is not installed and the MinerU parser is unavailable (see the Python version note above). MinerU 4.x is not supported yet: it replaced the command-line interface that RAG-Anything drives. With MinerU 4.x installed, check_parser_installation() returns False and a RAGAnything instance using the MinerU parser fails to initialize with an error that asks for a 3.x release. If mineru --version reports 4.x, install a 3.x release in the same environment (Python 3.10 to 3.13):

pip install -U "mineru[core]>=3.4.1,<4"
# Optional: remove two packages only MinerU 4.x uses; docvortex otherwise makes
# `pip check` report a pypdfium2 conflict. Keep mineru-magika: it provides the
# `magika` module MinerU 3.x imports. A fresh virtual environment also works.
pip uninstall -y docvortex mineru-llama-cpp

On minimal Linux or Docker images (for example python:3.12-slim), MinerU 3.x also needs system libraries for OpenCV. Without them, mineru --version fails with libxcb.so.1 or libGL.so.1: cannot open shared object file, and the installation check reports that error. On Debian or Ubuntu:

apt-get update && apt-get install -y --no-install-recommends libgl1 libglib2.0-0
# Verify installation (should report a 3.x version)
mineru --version

# Check if properly configured
python -c "from raganything import RAGAnything; rag = RAGAnything(); print('✅ MinerU installed properly' if rag.check_parser_installation() else '❌ MinerU installation issue')"

Models are downloaded automatically on first use. For manual download, refer to MinerU Model Source Configuration (MinerU 3.x docs; MinerU's current docs describe MinerU 4.x, which RAG-Anything does not support yet).

Usage Examples

1. End-to-End Document Processing

import asyncio
import base64
from functools import partial
from raganything import RAGAnything, RAGAnythingConfig
from raganything.image_signature import image_mime_type
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc

async def main():
    # Set up API configuration
    api_key = "your-api-key"
    base_url = "your-base-url"  # Optional

    # Create RAGAnything configuration
    config = RAGAnythingConfig(
        working_dir="./rag_storage",
        parser="mineru",  # Parser selection: mineru, docling, or paddleocr
        parse_method="auto",  # Parse method: auto, ocr, or txt
        enable_image_processing=True,
        enable_table_processing=True,
        enable_equation_processing=True,
    )

    # Define LLM model function
    def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
        return openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        )

    # Define vision model function for image processing
    def vision_model_func(
        prompt, system_prompt=None, history_messages=[], image_data=None, messages=None, **kwargs
    ):
        # If messages format is provided (for multimodal VLM enhanced query), use it directly
        if messages:
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=messages,
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Traditional single image format
        elif image_data:
            # Label the image with its real media type (PNG, GIF, WebP, ...),
            # identified from its first bytes (24 base64 characters)
            mime_type = image_mime_type(base64.b64decode(image_data[:24])) or "image/jpeg"
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=[
                    {"role": "system", "content": system_prompt}
                    if system_prompt
                    else None,
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:{mime_type};base64,{image_data}"
                                },
                            },
                        ],
                    }
                    if image_data
                    else {"role": "user", "content": prompt},
                ],
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Pure text format
        else:
            return llm_model_func(prompt, system_prompt, history_messages, **kwargs)

    # Define embedding function
    embedding_func = EmbeddingFunc(
        embedding_dim=3072,
        max_token_size=8192,
        func=partial(
            openai_embed.func,
            model="text-embedding-3-large",
            api_key=api_key,
            base_url=base_url,
        ),
    )

    # Initialize RAGAnything
    rag = RAGAnything(
        config=config,
        llm_model_func=llm_model_func,
        vision_model_func=vision_model_func,
        embedding_func=embedding_func,
    )

    # Process a document
    await rag.process_document_complete(
        file_path="path/to/your/document.pdf",
        output_dir="./output",
        parse_method="auto"
    )

    # Query the processed content
    # Pure text query - for basic knowledge base search
    text_result = await rag.aquery(
        "What are the main findings shown in the figures and tables?",
        mode="hybrid"
    )
    print("Text query result:", text_result)

    # Multimodal query with specific multimodal content
    multimodal_result = await rag.aquery_with_multimodal(
    "Explain this formula and its relevance to the document content",
    multimodal_content=[{
        "type": "equation",
        "latex": "P(d|q) = \\frac{P(q|d) \\cdot P(d)}{P(q)}",
        "equation_caption": "Document relevance probability"
    }],
    mode="hybrid"
)
    print("Multimodal query result:", multimodal_result)

if __name__ == "__main__":
    asyncio.run(main())

Text indexing: process_document_complete() and insert_content_list() return only after LightRAG has indexed the document's text; if another insert is running LightRAG's pipeline, they wait for that run to process it. If LightRAG fails the text (for example, the LLM is unavailable) and no run is left to retry it, they raise RuntimeError and the document stays failed in doc_status; LightRAG retries it on its next pipeline run, such as when the file is processed again. See multimodal ingestion concurrency.

Multimodal retries: if both batch and individual multimodal processing fail to store an item, these entry points raise and leave the document failed. A normal retry runs its multimodal processing again, including after a failed forced reprocess. Successfully stored chunks remain linked to the document. A parse-cache hit is also reparsed when a referenced local media file is missing.

2. Direct Multimodal Content Processing

import asyncio
import base64
from functools import partial
from lightrag import LightRAG
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc
from raganything.modalprocessors import ImageModalProcessor, TableModalProcessor
from raganything.image_signature import image_mime_type

def image_data_url(image_data):
    # Label the image with its real media type (PNG, GIF, WebP, ...),
    # identified from its first bytes (24 base64 characters)
    mime_type = image_mime_type(base64.b64decode(image_data[:24])) or "image/jpeg"
    return f"data:{mime_type};base64,{image_data}"


async def process_multimodal_content():
    # Set up API configuration
    api_key = "your-api-key"
    base_url = "your-base-url"  # Optional

    # Initialize LightRAG
    rag = LightRAG(
        working_dir="./rag_storage",
        llm_model_func=lambda prompt, system_prompt=None, history_messages=[], **kwargs: openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        ),
        embedding_func=EmbeddingFunc(
            embedding_dim=3072,
            max_token_size=8192,
            func=partial(
                openai_embed.func,
                model="text-embedding-3-large",
                api_key=api_key,
                base_url=base_url,
            ),
        )
    )
    await rag.initialize_storages()

    # Process an image
    image_processor = ImageModalProcessor(
        lightrag=rag,
        modal_caption_func=lambda prompt, system_prompt=None, history_messages=[], image_data=None, **kwargs: openai_complete_if_cache(
            "gpt-4o",
            "",
            system_prompt=None,
            history_messages=[],
            messages=[
                {"role": "system", "content": system_prompt} if system_prompt else None,
                {"role": "user", "content": [
                    {"type": "text", "text": prompt},
                    {"type": "image_url", "image_url": {"url": image_data_url(image_data)}}
                ]} if image_data else {"role": "user", "content": prompt}
            ],
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        ) if image_data else openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        )
    )

    image_content = {
        "img_path": "path/to/image.jpg",
        "image_caption": ["Figure 1: Experimental results"],
        "image_footnote": ["Data collected in 2024"]
    }

    description, entity_info, _ = await image_processor.process_multimodal_content(
        modal_content=image_content,
        content_type="image",
        file_path="research_paper.pdf",
        entity_name="Experimental Results Figure"
    )

    # Process a table
    table_processor = TableModalProcessor(
        lightrag=rag,
        modal_caption_func=lambda prompt, system_prompt=None, history_messages=[], **kwargs: openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        )
    )

    table_content = {
        "table_body": """
        | Method | Accuracy | F1-Score |
        |--------|----------|----------|
        | RAGAnything | 95.2% | 0.94 |
        | Baseline | 87.3% | 0.85 |
        """,
        "table_caption": ["Performance Comparison"],
        "table_footnote": ["Results on test dataset"]
    }

    description, entity_info, _ = await table_processor.process_multimodal_content(
        modal_content=table_content,
        content_type="table",
        file_path="research_paper.pdf",
        entity_name="Performance Results Table"
    )

if __name__ == "__main__":
    asyncio.run(process_multimodal_content())

3. Batch Processing

# Process multiple documents
await rag.process_folder_complete(
    folder_path="./documents",
    output_dir="./output",
    file_extensions=[".pdf", ".docx", ".pptx"],
    recursive=True,
    max_workers=4
)

4. Custom Modal Processors

from raganything.modalprocessors import GenericModalProcessor

class CustomModalProcessor(GenericModalProcessor):
    async def process_multimodal_content(self, modal_content, content_type, file_path, entity_name):
        # Your custom processing logic
        enhanced_description = await self.analyze_custom_content(modal_content)
        entity_info = self.create_custom_entity(enhanced_description, entity_name)
        return await self._create_entity_and_chunk(enhanced_description, entity_info, file_path)

5. Query Options

RAG-Anything provides three types of query methods:

Pure Text Queries - Direct knowledge base search using LightRAG:

# Different query modes for text queries
text_result_hybrid = await rag.aquery("Your question", mode="hybrid")
text_result_local = await rag.aquery("Your question", mode="local")
text_result_global = await rag.aquery("Your question", mode="global")
text_result_naive = await rag.aquery("Your question", mode="naive")

# Synchronous version
sync_text_result = rag.query("Your question", mode="hybrid")

VLM Enhanced Queries - Automatically analyze images in retrieved context using VLM:

# VLM enhanced query (automatically enabled when vision_model_func is provided)
vlm_result = await rag.aquery(
    "Analyze the charts and figures in the document",
    mode="hybrid"
    # vlm_enhanced=True is automatically set when vision_model_func is available
)

# Manually control VLM enhancement
vlm_enabled = await rag.aquery(
    "What do the images show in this document?",
    mode="hybrid",
    vlm_enhanced=True  # Force enable VLM enhancement
)

vlm_disabled = await rag.aquery(
    "What do the images show in this document?",
    mode="hybrid",
    vlm_enhanced=False  # Force disable VLM enhancement
)

# When documents contain images, VLM can see and analyze them directly
# The system will automatically:
# 1. Retrieve relevant context containing image paths
# 2. Load and encode images as base64
# 3. Send both text context and images to VLM for comprehensive analysis

Streaming: with stream=True, a VLM enhanced query that sends retrieved images returns the vision model's async iterator instead of a string (without images it falls back to LightRAG's streaming answer). vision_model_func then receives stream=True, so a custom function must accept **kwargs and pass them to a client that can stream, as the example above does; one without **kwargs raises TypeError.

Multimodal Queries - Enhanced queries with specific multimodal content analysis:

# Query with table data
table_result = await rag.aquery_with_multimodal(
    "Compare these performance metrics with the document content",
    multimodal_content=[{
        "type": "table",
        "table_data": """Method,Accuracy,Speed
                        RAGAnything,95.2%,120ms
                        Traditional,87.3%,180ms""",
        "table_caption": "Performance comparison"
    }],
    mode="hybrid"
)

# Query with equation content
equation_result = await rag.aquery_with_multimodal(
    "Explain this formula and its relevance to the document content",
    multimodal_content=[{
        "type": "equation",
        "latex": "P(d|q) = \\frac{P(q|d) \\cdot P(d)}{P(q)}",
        "equation_caption": "Document relevance probability"
    }],
    mode="hybrid"
)

6. Loading Existing LightRAG Instance

import asyncio
import base64
from functools import partial
from raganything import RAGAnything, RAGAnythingConfig
from raganything.image_signature import image_mime_type
from lightrag import LightRAG
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.kg.shared_storage import initialize_pipeline_status
from lightrag.utils import EmbeddingFunc
import os

async def load_existing_lightrag():
    # Set up API configuration
    api_key = "your-api-key"
    base_url = "your-base-url"  # Optional

    # First, create or load existing LightRAG instance
    lightrag_working_dir = "./existing_lightrag_storage"

    # Check if previous LightRAG instance exists
    if os.path.exists(lightrag_working_dir) and os.listdir(lightrag_working_dir):
        print("✅ Found existing LightRAG instance, loading...")
    else:
        print("❌ No existing LightRAG instance found, will create new one")

    # Create/load LightRAG instance with your configuration
    lightrag_instance = LightRAG(
        working_dir=lightrag_working_dir,
        llm_model_func=lambda prompt, system_prompt=None, history_messages=[], **kwargs: openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        ),
        embedding_func=EmbeddingFunc(
            embedding_dim=3072,
            max_token_size=8192,
            func=partial(
                openai_embed.func,
                model="text-embedding-3-large",
                api_key=api_key,
                base_url=base_url,
            ),
        )
    )

    # Initialize storage (this will load existing data if available)
    await lightrag_instance.initialize_storages()
    await initialize_pipeline_status()

    # Define vision model function for image processing
    def vision_model_func(
        prompt, system_prompt=None, history_messages=[], image_data=None, messages=None, **kwargs
    ):
        # If messages format is provided (for multimodal VLM enhanced query), use it directly
        if messages:
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=messages,
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Traditional single image format
        elif image_data:
            # Label the image with its real media type (PNG, GIF, WebP, ...),
            # identified from its first bytes (24 base64 characters)
            mime_type = image_mime_type(base64.b64decode(image_data[:24])) or "image/jpeg"
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=[
                    {"role": "system", "content": system_prompt}
                    if system_prompt
                    else None,
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {
                                "type": "image_url",
                                "image_url": {
                                    "url": f"data:{mime_type};base64,{image_data}"
                                },
                            },
                        ],
                    }
                    if image_data
                    else {"role": "user", "content": prompt},
                ],
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Pure text format
        else:
            return lightrag_instance.llm_model_func(prompt, system_prompt, history_messages, **kwargs)

    # Now use existing LightRAG instance to initialize RAGAnything
    rag = RAGAnything(
        lightrag=lightrag_instance,  # Pass existing LightRAG instance
        vision_model_func=vision_model_func,
        # Note: working_dir, llm_model_func, embedding_func, etc. are inherited from lightrag_instance
    )

    # Query existing knowledge base
    result = await rag.aquery(
        "What data has been processed in this LightRAG instance?",
        mode="hybrid"
    )
    print("Query result:", result)

    # Add new multimodal document to existing LightRAG instance
    await rag.process_document_complete(
        file_path="path/to/new/multimodal_document.pdf",
        output_dir="./output"
    )

if __name__ == "__main__":
    asyncio.run(load_existing_lightrag())

7. Direct Content List Insertion

For scenarios where you already have a pre-parsed content list (e.g., from external parsers or previous processing), you can directly insert it into RAGAnything without document parsing:

import asyncio
import base64
from functools import partial
from raganything import RAGAnything, RAGAnythingConfig
from raganything.image_signature import image_mime_type
from lightrag.llm.openai import openai_complete_if_cache, openai_embed
from lightrag.utils import EmbeddingFunc

async def insert_content_list_example():
    # Set up API configuration
    api_key = "your-api-key"
    base_url = "your-base-url"  # Optional

    # Create RAGAnything configuration
    config = RAGAnythingConfig(
        working_dir="./rag_storage",
        enable_image_processing=True,
        enable_table_processing=True,
        enable_equation_processing=True,
    )

    # Define model functions
    def llm_model_func(prompt, system_prompt=None, history_messages=[], **kwargs):
        return openai_complete_if_cache(
            "gpt-4o-mini",
            prompt,
            system_prompt=system_prompt,
            history_messages=history_messages,
            api_key=api_key,
            base_url=base_url,
            **kwargs,
        )

    def vision_model_func(prompt, system_prompt=None, history_messages=[], image_data=None, messages=None, **kwargs):
        # If messages format is provided (for multimodal VLM enhanced query), use it directly
        if messages:
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=messages,
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Traditional single image format
        elif image_data:
            # Label the image with its real media type (PNG, GIF, WebP, ...),
            # identified from its first bytes (24 base64 characters)
            mime_type = image_mime_type(base64.b64decode(image_data[:24])) or "image/jpeg"
            return openai_complete_if_cache(
                "gpt-4o",
                "",
                system_prompt=None,
                history_messages=[],
                messages=[
                    {"role": "system", "content": system_prompt} if system_prompt else None,
                    {
                        "role": "user",
                        "content": [
                            {"type": "text", "text": prompt},
                            {"type": "image_url", "image_url": {"url": f"data:{mime_type};base64,{image_data}"}}
                        ],
                    } if image_data else {"role": "user", "content": prompt},
                ],
                api_key=api_key,
                base_url=base_url,
                **kwargs,
            )
        # Pure text format
        else:
            return llm_model_func(prompt, system_prompt, history_messages, **kwargs)

    embedding_func = EmbeddingFunc(
        embedding_dim=3072,
        max_token_size=8192,
        func=partial(
            openai_embed.func,
            model="text-embedding-3-large",
            api_key=api_key,
            base_url=base_url,
        ),
    )

    # Initialize RAGAnything
    rag = RAGAnything(
        config=config,
        llm_model_func=llm_model_func,
        vision_model_func=vision_model_func,
        embedding_func=embedding_func,
    )

    # Example: Pre-parsed content list from external source
    content_list = [
        {
            "type": "text",
            "text": "This is the introduction section of our research paper.",
            "page_idx": 0  # Page number where this content appears
        },
        {
            "type": "image",
            "img_path": "/absolute/path/to/figure1.jpg",  # IMPORTANT: Use absolute path
            "image_caption": ["Figure 1: System Architecture"],
            "image_footnote": ["Source: Authors' original design"],
            "page_idx": 1  # Page number where this image appears
        },
        {
            "type": "table",
            "table_body": "| Method | Accuracy | F1-Score |\n|--------|----------|----------|\n| Ours | 95.2% | 0.94 |\n| Baseline | 87.3% | 0.85 |",
            "table_caption": ["Table 1: Performance Comparison"],
            "table_footnote": ["Results on test dataset"],
            "page_idx": 2  # Page number where this table appears
        },
        {
            "type": "equation",
            "latex": "P(d|q) = \\frac{P(q|d) \\cdot P(d)}{P(q)}",
            "text": "Document relevance probability formula",
            "page_idx": 3  # Page number where this equation appears
        },
        {
            "type": "text",
            "text": "In conclusion, our method demonstrates superior performance across all metrics.",
            "page_idx": 4  # Page number where this content appears
        }
    ]

    # Insert the content list directly
    await rag.insert_content_list(
        content_list=content_list,
        file_path="research_paper.pdf",  # Reference file name for citation
        split_by_character=None,         # Optional text splitting
        split_by_character_only=False,   # Optional text splitting mode
        doc_id=None,                     # Optional custom document ID (will be auto-generated if not provided)
        display_stats=True               # Show content statistics
    )

    # Query the inserted content
    result = await rag.aquery(
        "What are the key findings and performance metrics mentioned in the research?",
        mode="hybrid"
    )
    print("Query result:", result)

    # You can also insert multiple content lists with different document IDs
    another_content_list = [
        {
            "type": "text",
            "text": "This is content from another document.",
            "page_idx": 0  # Page number where this content appears
        },
        {
            "type": "table",
            "table_body": "| Feature | Value |\n|---------|-------|\n| Speed | Fast |\n| Accuracy | High |",
            "table_caption": ["Feature Comparison"],
            "page_idx": 1  # Page number where this table appears
        }
    ]

    await rag.insert_content_list(
        content_list=another_content_list,
        file_path="another_document.pdf",
        doc_id="custom-doc-id-123"  # Custom document ID
    )

if __name__ == "__main__":
    asyncio.run(insert_content_list_example())

Content List Format:

For an image such as images/figure.png, pass the document path in file_path so ingestion can locate the file beside that document. Page indexes in the content list start at zero. Newly indexed multimodal chunks with a known page display one-based labels such as [Page 1] or [Page 2-3].

The content_list should follow the standard format with each item being a dictionary containing:

Important Notes:

This method is particularly useful when:

8. Re-processing Multimodal Content After a Storage Backend Change

By default, process_document_complete and insert_content_list skip multimodal (image/table/equation) processing for a document that is already marked as fully processed, to avoid redundant LLM calls. If you switch to a new graph/vector storage backend (e.g. migrating from the default file-based storage to Neo4j), the new backend will not yet contain the multimodal entities/relations that were written to the old one — see #154.

Pass force_multimodal_reprocess=True to explicitly re-run multimodal processing and re-populate the current storage backend for an already-processed document:

# Re-run multimodal processing so the current storage backend has the
# image/table/equation entities and relations (default is False, i.e. no change
# to existing behavior for documents that have not switched backends)
await rag.process_document_complete(
    file_path="path/to/your/document.pdf",
    doc_id="doc-already-processed-id",
    force_multimodal_reprocess=True,
)

# Same flag is available for direct content list insertion
await rag.insert_content_list(
    content_list=content_list,
    doc_id="doc-already-processed-id",
    force_multimodal_reprocess=True,
)

This flag only affects multimodal content; it is opt-in and defaults to False, so existing behavior is unchanged unless you explicitly set it.

Multimodal graph extraction defaults to multimodal_kg_extraction_mode="legacy", which retains full chunk templates and belongs_to relations. Set this config field to "packed" to group descriptions into fewer extraction calls; packed sources are stored and tracked for retrieval and deletion. Packing adds retrieval candidates and omits belongs_to, so evaluate retrieval quality for your data. "per_item" extracts each compact description separately; "skip" stores captions, chunks and main multimodal entities without further extraction. Optional max_parallel_modal_items controls caption concurrency independently of LightRAG's document-insert limit. See call-count controls.

9. Deleting Documents

Use adelete_by_doc_id to perform a cascading deletion of a document across both LightRAG and RAG-Anything. Core graph, vector, and document-status deletion is delegated to LightRAG.adelete_by_doc_id first; RAG-Anything's internal multimodal completion cache, pre-registration placeholder (doc-pre-<file_name>), and optional parsed output directory on disk are cleaned up only after core deletion succeeds:

# Delete a document from LightRAG (graph, vector chunks, doc_status) and
# RAG-Anything's multimodal status cache
result = await rag.adelete_by_doc_id("doc-12345")

# Optionally also remove the document's parsed output/media directory on disk
# and cached LLM extraction responses
result = await rag.adelete_by_doc_id(
    "doc-12345",
    delete_media_files=True,
    delete_llm_cache=True,
)
print(result["status"], result["media_files_deleted"])

Use RAGAnything.adelete_by_doc_id when documents share a caption entity. It retains the entity, its vector and references from the surviving documents. The last owner's deletion removes the entity. New multimodal chunks are scoped to their document ID, including identical figures or tables indexed under different document IDs.

For a legacy index, deletion recovers ownership from registered document chunks. If older documents share the same physical caption chunk ID, rebuild those documents from their sources in a fresh workspace before deleting either one. If a shared-caption refresh fails after core deletion, retry the same document ID. Nodes left by deletions that predate this fix require a separate index repair.

Only an explicit successful core result permits cleanup; a missing or unknown result leaves media and completion state intact. Parsed outputs are matched by document ID and recorded paths, including per-call output directories. Legacy records with only a basename cannot identify their media directory reliably; their core data is deleted, while unlocated media is left in place and media_files_deleted is False. Outputs referenced by another indexed document are also retained. The media flag is only True when removal succeeds; a filesystem error leaves it False even when core document deletion succeeded.


🛠️ Examples

Practical Implementation Demos

The examples/ directory contains comprehensive usage examples:

Run examples:

# End-to-end processing with parser selection
python examples/raganything_example.py path/to/document.pdf --api-key YOUR_API_KEY --parser mineru

# Direct modal processing
python examples/modalprocessors_example.py --api-key YOUR_API_KEY

# Office document parsing test (MinerU only)
python examples/office_document_test.py --file path/to/document.docx

# Image format parsing test (MinerU only)
python examples/image_format_test.py --file path/to/image.bmp

# Text format parsing test (MinerU only)
python examples/text_format_test.py --file path/to/document.md

# Check LibreOffice installation
python examples/office_document_test.py --check-libreoffice --file dummy

# Check PIL/Pillow installation
python examples/image_format_test.py --check-pillow --file dummy

# Check ReportLab installation
python examples/text_format_test.py --check-reportlab --file dummy

🔧 Configuration

System Optimization Parameters

Environment Variables

Create a .env file (refer to .env.example):

OPENAI_API_KEY=your_openai_api_key
OPENAI_BASE_URL=your_base_url  # Optional
OUTPUT_DIR=./output             # Default output directory for parsed documents
PARSER=mineru                   # Parser selection: mineru, docling, or paddleocr
PARSE_METHOD=auto              # Parse method: auto, ocr, or txt

Note: For backward compatibility, legacy environment variable names are still supported:

Note: API keys are only required for full RAG processing with LLM integration. The parsing test files (office_document_test.py and image_format_test.py) only test parser functionality and do not require API keys.

Troubleshooting and multimodal checklist

Public media URLs (CDN / object storage)

When ingestion runs on a server but your UI or another service needs HTTPS (or S3-style) links to figures, set:

# Base URL for assets (no trailing slash required)
RAGANYTHING_PUBLIC_ASSET_BASE_URL=https://my-bucket.s3.us-east-1.amazonaws.com/prefix
# Filesystem root that should be stripped from absolute paths under that tree
RAGANYTHING_PUBLIC_ASSET_STRIP_PREFIX=/var/rag/output

After parsing, each non-empty img_path, table_img_path, or equation_img_path may gain a sibling field *_public_url while the original path stays on disk for local processing. See #272.

Scope today: this mapping runs in the MinerU parser path only. Other parsers (e.g. Docling) keep working but will not produce *_public_url fields until the helper is wired into their content_list post-processing as well. If only one of the two env vars is set, RAG-Anything logs a warning and skips URL attachment.

Parser Configuration

The parser is chosen when RAGAnything is created: set RAGAnythingConfig(parser=...) to "mineru" (default), "docling", or "paddleocr", or use the PARSER environment variable (command-line tools: --parser). It cannot be switched per process_document_complete() call.

RAGAnything now supports multiple parsers, each with specific advantages:

MinerU Parser

Docling Parser

Install Docling (not included in raganything[all]):

pip install docling

PaddleOCR Parser

Install PaddleOCR parser extras:

pip install -e ".[paddleocr]"
# or
uv sync --extra paddleocr

Note: PaddleOCR also requires paddlepaddle (CPU/GPU package varies by platform). Install it with the official guide: https://www.paddlepaddle.org.cn/install/quick

MinerU Configuration

# MinerU 3.x uses command-line parameters instead of config files (MinerU 4.x is not supported)
# Check available options:
mineru --help

# Common configurations:
mineru -p input.pdf -o output_dir -m auto    # Automatic parsing mode
mineru -p input.pdf -o output_dir -m ocr     # OCR-focused parsing
mineru -p input.pdf -o output_dir -b pipeline --device cuda  # GPU acceleration

You can also configure parsing through RAGAnything parameters:

# The parser comes from RAGAnythingConfig (or PARSER), not from process_document_complete()
config = RAGAnythingConfig(parser="mineru")  # "mineru", "docling", or "paddleocr"
rag = RAGAnything(config=config, llm_model_func=llm_model_func, embedding_func=embedding_func)

# Basic parsing configuration
await rag.process_document_complete(
    file_path="document.pdf",
    output_dir="./output/",
    parse_method="auto"           # or "ocr", "txt"
)

# Advanced parsing configuration with special parameters
await rag.process_document_complete(
    file_path="document.pdf",
    output_dir="./output/",
    parse_method="auto",          # Parsing method: "auto", "ocr", "txt"

    # MinerU special parameters - all supported kwargs:
    lang="ch",                   # Document language for OCR optimization (e.g., "ch", "en", "ja")
    device="cuda:0",             # Inference device: "cpu", "cuda", "cuda:0", "npu", "mps"
    start_page=0,                # Starting page number (0-based, for PDF)
    end_page=10,                 # Ending page number (0-based, for PDF)
    formula=True,                # Enable formula parsing
    table=True,                  # Enable table parsing
    backend="pipeline",          # Parsing backend: pipeline|hybrid-auto-engine|hybrid-http-client|vlm-auto-engine|vlm-http-client.
    source="huggingface",        # Model source: "huggingface", "modelscope", "local"
    # vlm_url="http://127.0.0.1:3000" # Service address when using backend=vlm-http-client
    include_layout_blocks=False,  # Keep MinerU v2 headers, footers, and page numbers only when needed

    # Standard RAGAnything parameters
    display_stats=True,          # Display content statistics
    split_by_character=None,     # Optional character to split text by
    doc_id=None                  # Optional document ID
)

Note: MinerU 2.0 no longer uses the magic-pdf.json configuration file. All settings are now passed as command-line parameters or function arguments. RAG-Anything supports multiple document parsers, including MinerU, Docling, and PaddleOCR.

MinerU 3.x Content List v2

RAG-Anything natively reads MinerU 3.x *_content_list_v2.json and content_list_v2.json outputs when they are available, ahead of the legacy flat content list. Document-scoped output directories are preferred over shared roots; within one bundle, v2 is preferred over legacy and exact stem filenames are preferred over generic filenames. The v2 page-grouped representation is converted to the existing flat content_list contract while preserving page indexes, bounding boxes, anchors, heading levels, visual metadata, captions, and footnotes. Algorithm blocks use the compatible type="code", sub_type="algorithm" representation.

Charts with an img_path use the image processor for ingestion and multimodal queries, including their captions, footnotes and extracted text. Charts without an image keep generic text processing. The original parsed content and document IDs stay unchanged. To update previously indexed charts, re-ingest with force_multimodal_reprocess=True.

Page headers, footers, page numbers, aside text, and page footnotes are excluded by default so repeated layout artifacts do not enter semantic retrieval or graph construction. Set include_layout_blocks=True only when those blocks are meaningful for your use case:

await rag.process_document_complete(
    file_path="document.pdf",
    include_layout_blocks=True,
)

MinerU marks v2 as an evolving output schema. RAG-Anything skips unknown future block types with a warning, but falls back to the legacy content list when a v2 file is malformed, structurally invalid, or yields no supported semantic blocks and a legacy file is present.

Processing Requirements

Different content types require specific optional dependencies:

When constructing VideoModalProcessor directly, max_windows must be a positive integer or None. Window size estimates include explicit audio text alongside visual descriptions. A single oversized segment stays intact; a window-count cap can redistribute segments into larger windows.

📋 Quick Install: Use pip install raganything[all] to enable all format support (Python dependencies only - LibreOffice still needs separate installation, and HTML needs Docling: pip install docling)


Additional configuration

See model, parser and ingestion options for local/online/custom ASR, remote MinerU, importing preprocessed bundles, optional cross-page table merging, private prompt templates and retrieved media references. The Ollama example accepts --multimodal. Container usage describes the CPU batch image.

🧪 Supported Content Types

Document Formats

Multimodal Elements

For installation of format-specific dependencies, see the Configuration section.


📖 Citation

Academic Reference

📖

If you find RAG-Anything useful in your research, please cite our paper:

@misc{guo2025raganythingallinoneragframework,
      title={RAG-Anything: All-in-One RAG Framework},
      author={Zirui Guo and Xubin Ren and Lingrui Xu and Jiahao Zhang and Chao Huang},
      year={2025},
      eprint={2510.12323},
      archivePrefix={arXiv},
      primaryClass={cs.AI},
      url={https://arxiv.org/abs/2510.12323},
}

Ecosystem & Extensions

⚡
LightRAG
Simple and Fast RAG
🎥
VideoRAG
Extreme Long-Context Video RAG
✨
MiniRAG
Extremely Simple RAG

🤝 Contribution

Join the Innovation

We thank all our contributors for their valuable contributions.

⭐ Thank you for visiting RAG-Anything! ⭐
Building the Future of Multimodal AI

RAG-Anything (HKUDS/RAG-Anything)

正在搜索数据库…

这是什么?一个基于 LightRAG 构建的一体化多模态 RAG 框架:它能处理真实世界中混合了文本、图片、表格和公式的文档,然后通过同一套流程回答涵盖所有内容类型的查询,而不需要用多个专门的工具分别处理。
它是一个我要写代码调用的库,还是一个能直接运行的成品应用?它是一个供你在其上构建的 Python 框架:你需要在自己的脚本中导入 RAGAnything,通过 RAGAnythingConfig 以及自定义的 LLM 和视觉模型函数来配置它,并在异步代码中驱动处理和查询。它没有图形界面。
我该怎么把它跑起来?从 PyPI 安装(推荐方式),或从源码安装,另外可加上 [image]、[text] 或 [all] 等额外选项以支持更多格式。在代码里,你要创建一个 RAGAnythingConfig——选择解析器(mineru、docling 或 paddleocr),开关图片/表格/公式处理——然后把文档喂给它。
我需要自己准备 API 密钥和模型吗?是的——OpenAI 兼容的凭据和模型函数都需要你自己提供(示例中用 gpt-4o-mini 处理文本、gpt-4o 处理视觉,还可以自定义 base_url)。MinerU 的解析模型会在首次使用时自动下载,所以不需要手动配置模型。
所有文件类型都开箱即用吗?不是全部:TXT 和 MD 文件需要可选的 [text] 额外选项(ReportLab),BMP、TIFF、GIF 和 WebP 等额外图片格式需要 [image](Pillow),Office 文档还需要在系统上安装 LibreOffice。
它能接收哪些文档格式?PDF、Office 文件(DOC/DOCX/PPT/PPTX/XLS/XLSX)、图片等,通过专门的解析器处理,另外通过可选的 [text] 额外选项支持 TXT/MD。解析默认使用 MinerU,也可以在配置中选择 docling 或 paddleocr。
查询它和普通向量 RAG 有什么不同?摄取的内容会变成一个多模态知识图谱:跨模态抽取实体并通过跨模态关系把它们连接起来,检索时把向量相似度搜索和图遍历结合起来,并按模态相关性对结果排序,从而给出连贯的答案。
什么是 VLM-Enhanced Query 模式?当文档包含图片时,系统会在查询过程中把它们传给一个视觉语言模型,结合视觉和文本上下文来获得更深入的洞见——你需要单独提供视觉模型函数(示例中是 gpt-4o)。
如果我的内容已经处理过了,可以跳过解析吗?可以——直接内容列表插入(Direct Content List Insertion)让你完全跳过文档解析阶段,把来自外部来源的预解析内容列表直接插入到流程中。
有哪些类似的项目?LightRAG, knowhere, kotaemon, memvid, m_flow, llama_index, ragent, casecite
作者
HKUDS
大小
6.4 MB
星标
24.9K
时长
1年
提交 · 90 天