Maintainers
Pricing
Enterprise
More
More
Documentation
Try Live
Rankings
Install
Blog
Docs7
Ask
New
Add Docs
RAG-Anything
https://github.com/hkuds/rag-anything
Admin
"RAG-Anything: All-in-One RAG System"
Tokens:
21,703
Snippets:
189
Trust Score:
9.5
License:
MIT
Update:
2 months ago
Context
Chat
Benchmark
70.82
Latest
Show doc for...
Code
Info
Show Results
Tokens:
Raw
Copy
Link
Tokens:
Raw
Copy
Link
### Run RAG-Anything Examples Source: https://github.com/hkuds/rag-anything/blob/main/README.md Commands to execute document processing and format parsing tests using the provided example scripts. ```bash # 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 ``` -------------------------------- ### Install RAG-Anything Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Install the core package and optional dependencies required for specific parsers or progress tracking. ```bash # Basic installation pip install raganything[all] # Required for batch processing pip install tqdm # Optional for parser='paddleocr' pip install raganything[paddleocr] ``` -------------------------------- ### Install Optional Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/README.md Install specific extras to support additional file formats and OCR engines. ```bash pip install raganything[image] ``` ```bash pip install raganything[text] ``` ```bash pip install raganything[paddleocr] ``` ```bash pip install raganything[all] ``` -------------------------------- ### Install RAG-Anything via PyPI Source: https://github.com/hkuds/rag-anything/blob/main/README.md Use pip to install the core package or include optional dependencies for extended file format support. ```bash # Basic installation pip install raganything # With optional dependencies for extended format support: pip install 'raganything[all]' # All optional features 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 ``` -------------------------------- ### Install RAG-Anything from Source Source: https://github.com/hkuds/rag-anything/blob/main/README.md Clone the repository and use uv to manage the virtual environment and dependencies. ```bash # 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 ``` -------------------------------- ### Comprehensive Context Configuration (Python) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md An example of configuring RAGAnything for comprehensive context analysis. This setup uses a larger context window (`context_window=2`), page-based context mode (`context_mode="page"`), and allows up to 3000 context tokens. It includes both headers and captions and considers 'text', 'image', and 'table' content types. ```python config = RAGAnythingConfig( context_window=2, context_mode="page", max_context_tokens=3000, include_headers=True, include_captions=True, context_filter_content_types=["text", "image", "table"] ) ``` -------------------------------- ### Verify MinerU Installation Source: https://github.com/hkuds/rag-anything/blob/main/README.md Check the version and configuration of the MinerU parser to ensure it is correctly installed. ```bash # Verify installation 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')" ``` -------------------------------- ### Install Pandoc Backend Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Installs Pandoc and wkhtmltopdf, which are optional dependencies for the Pandoc backend. Instructions are provided for Ubuntu/Debian, macOS using Homebrew, and Conda environments. ```bash # Ubuntu/Debian: sudo apt-get install pandoc wkhtmltopdf # macOS: brew install pandoc wkhtmltopdf # Or using conda: conda install -c conda-forge pandoc wkhtmltopdf ``` -------------------------------- ### Direct Content List Insertion Setup Source: https://github.com/hkuds/rag-anything/blob/main/README.md Boilerplate imports for scenarios where pre-parsed content lists are inserted directly into RAGAnything. ```python import asyncio from functools import partial from raganything import RAGAnything, RAGAnythingConfig from lightrag.llm.openai import openai_complete_if_cache, openai_embed from lightrag.utils import EmbeddingFunc ``` -------------------------------- ### Install WeasyPrint System Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Installs the necessary system-level dependencies for the WeasyPrint PDF generation backend on Ubuntu/Debian systems. This includes build tools, Python development headers, and Cairo/Pango libraries. ```bash sudo apt-get install -y build-essential python3-dev python3-pip \ python3-setuptools python3-wheel python3-cffi libcairo2 \ libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 \ libffi-dev shared-mime-info ``` -------------------------------- ### MinerU Content Format Example (JSON) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md An example illustrating the MinerU format for content sources, which is a list of dictionaries. Each dictionary represents a content item and can include types like 'text' or 'image', along with relevant metadata such as text content, page index, image paths, and captions. ```json [ { "type": "text", "text": "Document content here...", "text_level": 1, "page_idx": 0 }, { "type": "image", "img_path": "images/figure1.jpg", "image_caption": ["Figure 1: Architecture"], "image_footnote": [], "page_idx": 1 } ] ``` -------------------------------- ### Install PaddleOCR Parser Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/README.md Install the necessary extras to enable the PaddleOCR parser functionality. ```bash pip install -e ".[paddleocr]" # or uv sync --extra paddleocr ``` -------------------------------- ### Install System Dependencies for PDF Conversion Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Provides shell commands to install necessary system-level dependencies for WeasyPrint and Pandoc on Ubuntu/Debian systems. ```bash # Ubuntu/Debian: Install system dependencies sudo apt-get update sudo apt-get install -y build-essential python3-dev libcairo2 \ libpango-1.0-0 libpangocairo-1.0-0 libgdk-pixbuf2.0-0 \ libffi-dev shared-mime-info # Then reinstall WeasyPrint pip install --force-reinstall weasyprint ``` ```bash # Check if Pandoc is installed pandoc --version # Install Pandoc (Ubuntu/Debian) sudo apt-get install pandoc wkhtmltopdf ``` -------------------------------- ### Execute RAG-Anything Application Source: https://github.com/hkuds/rag-anything/blob/main/docs/offline_setup.md Command to execute the RAG-Anything example script once the offline cache is properly configured. ```bash uv run examples/raganything_example.py requirements.txt ``` -------------------------------- ### Install RAG-Anything with Enhanced Markdown Dependencies Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Installs the RAG-Anything package with all optional dependencies, specifically including those required for enhanced markdown conversion like markdown, weasyprint, and pygments. ```bash pip install raganything[all] pip install markdown weasyprint pygments ``` -------------------------------- ### Header Formatting Example (Markdown) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Illustrates how headers are formatted when the `include_headers=True` configuration option is enabled. Headers are presented using markdown-style prefixes to denote their level, such as '# Level 1 Header', '## Level 2 Header', and '### Level 3 Header'. ```markdown # Level 1 Header ## Level 2 Header ### Level 3 Header ``` -------------------------------- ### Bypass Parser Installation Checks Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Disables the automatic installation verification for the parser, useful in restricted environments. ```python # Solution: Skip installation check batch_parser = BatchParser(skip_installation_check=True) ``` -------------------------------- ### Caption Integration Example (Text) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Shows the format for integrating image and table captions when `include_captions=True`. Captions are enclosed in square brackets, prefixed with 'Image:' or 'Table:', followed by the caption text. ```text [Image: Figure 1 caption text] [Table: Table 1 caption text] ``` -------------------------------- ### Chunk-Based Analysis Configuration (Python) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md An example demonstrating configuration for chunk-based context analysis. This configuration uses a context window of 5 items (`context_window=5`), specifies chunk-based context mode (`context_mode="chunk"`), and sets a maximum of 2000 context tokens. It excludes headers and captions and filters context to only include 'text' content types. ```python config = RAGAnythingConfig( context_window=5, context_mode="chunk", max_context_tokens=2000, include_headers=False, include_captions=False, context_filter_content_types=["text"] ) ``` -------------------------------- ### High-Precision Context Configuration (Python) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md An example of configuring RAGAnything for high-precision context analysis. This configuration uses a small context window (`context_window=1`), page-based context mode (`context_mode="page"`), and limits context tokens to 1000. It includes headers but excludes captions and filters context to only include 'text' content types. ```python config = RAGAnythingConfig( context_window=1, context_mode="page", max_context_tokens=1000, include_headers=True, include_captions=False, context_filter_content_types=["text"] ) ``` -------------------------------- ### BatchParser.__init__ Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Initializes the BatchParser with specific configuration parameters. ```APIDOC ## BatchParser.__init__(parser_type: str = "mineru", max_workers: int = 4, show_progress: bool = True, timeout_per_file: int = 300, skip_installation_check: bool = False) ### Description Initializes a new instance of the BatchParser with the specified configuration. ### Parameters - **parser_type** (str) - Optional - The parser engine to use: "mineru", "docling", or "paddleocr". Default: "mineru". - **max_workers** (int) - Optional - Number of parallel workers. Default: 4. - **show_progress** (bool) - Optional - Whether to show a progress bar. Default: True. - **timeout_per_file** (int) - Optional - Timeout per file in seconds. Default: 300. - **skip_installation_check** (bool) - Optional - Whether to skip the parser installation check. Default: False. ``` -------------------------------- ### Initialize LightRAG with Environment Variables Source: https://github.com/hkuds/rag-anything/blob/main/docs/offline_setup.md Python implementation showing how to load environment variables before importing LightRAG to ensure the tiktoken cache path is correctly registered. ```python import os import sys from pathlib import Path from dotenv import load_dotenv # Add project root directory to Python path sys.path.insert(0, str(Path(__file__).parent.parent)) # Load environment variables FIRST - before any imports that use tiktoken load_dotenv(dotenv_path=".env", override=False) # Now import LightRAG from lightrag import LightRAG from lightrag.utils import logger ``` -------------------------------- ### Initialize and Process Documents with RAGAnything Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Demonstrates how to initialize the RAGAnything system with specific configuration settings and trigger a complete document processing workflow. ```python from raganything import RAGAnything # Initialize system rag = RAGAnything(config={ "working_dir": "./storage", "enable_image_processing": True }) # Process document await rag.process_document_complete("document.pdf") ``` -------------------------------- ### Execute Basic Batch Processing Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Initialize a BatchParser and process a list of files or directories synchronously. ```python from raganything.batch_parser import BatchParser # Create batch parser batch_parser = BatchParser( parser_type="mineru", # or "docling" or "paddleocr" max_workers=4, show_progress=True, timeout_per_file=300, skip_installation_check=False # Set to True if having parser installation issues ) # Process multiple files result = batch_parser.process_batch( file_paths=["doc1.pdf", "doc2.docx", "folder/"], output_dir="./batch_output", parse_method="auto", recursive=True ) # Check results print(result.summary()) print(f"Success rate: {result.success_rate:.1f}%") print(f"Processing time: {result.processing_time:.2f} seconds") ``` -------------------------------- ### Check Available Backends and Select Specific Backend Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Demonstrates how to check the availability of different PDF conversion backends (WeasyPrint, Pandoc) using `get_backend_info()` and how to explicitly select a backend during the conversion process. ```python # Check available backends converter = EnhancedMarkdownConverter() backend_info = converter.get_backend_info() print("Available backends:") for backend, available in backend_info["available_backends"].items(): status = "✅" if available else "❌" print(f" {status} {backend}") print(f"Recommended backend: {backend_info['recommended_backend']}") # Use specific backend converter.convert_file_to_pdf( input_path="document.md", output_path="document.pdf", method="weasyprint" # or "pandoc", "pandoc_system", "auto" ) ``` -------------------------------- ### Process Multimodal Content with LightRAG Source: https://github.com/hkuds/rag-anything/blob/main/README.md Initializes LightRAG with OpenAI models and demonstrates processing image and table content using specialized processors. ```python import asyncio 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 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": f"data:image/jpeg;base64,{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()) ``` -------------------------------- ### Configure MinerU via Command Line Source: https://github.com/hkuds/rag-anything/blob/main/README.md Use command-line parameters to control MinerU 2.0 parsing behavior and hardware acceleration. ```bash # MinerU 2.0 uses command-line parameters instead of config files # 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 ``` -------------------------------- ### Load Existing LightRAG Instance Source: https://github.com/hkuds/rag-anything/blob/main/README.md Initializes a RAGAnything instance using an existing LightRAG storage directory and custom LLM/vision model functions. ```python import asyncio from functools import partial from raganything import RAGAnything, RAGAnythingConfig 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: 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:image/jpeg;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()) ``` -------------------------------- ### Configure Environment Variables Source: https://github.com/hkuds/rag-anything/blob/main/README.md Define essential configuration parameters in a .env file for API access and parser selection. ```bash 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 ``` -------------------------------- ### Configure RAGAnything Context Settings Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Demonstrates how to define context extraction parameters using Python configuration objects and environment variables. These settings control window size, token limits, and content filtering. ```python context_window: int = 1 context_mode: str = "page" max_context_tokens: int = 2000 include_headers: bool = True include_captions: bool = True context_filter_content_types: List[str] = ["text"] content_format: str = "minerU" ``` ```bash CONTEXT_WINDOW=2 CONTEXT_MODE=page MAX_CONTEXT_TOKENS=3000 INCLUDE_HEADERS=true INCLUDE_CAPTIONS=true CONTEXT_FILTER_CONTENT_TYPES=text,image CONTENT_FORMAT=minerU ``` -------------------------------- ### Initialize and Use RAGAnything with Context Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Shows the instantiation of RAGAnything with a custom configuration and the execution of document processing. It also covers runtime updates to context settings and manual content source configuration. ```python from raganything import RAGAnything, RAGAnythingConfig config = RAGAnythingConfig( context_window=2, context_mode="page", max_context_tokens=3000, include_headers=True, include_captions=True, context_filter_content_types=["text", "image"], content_format="minerU" ) rag_anything = RAGAnything( config=config, llm_model_func=your_llm_function, embedding_func=your_embedding_function ) # Automatic processing await rag_anything.process_document_complete("document.pdf") # Manual updates rag_anything.set_content_source_for_context(content_list, "minerU") rag_anything.update_context_config(context_window=1, max_context_tokens=1500, include_captions=False) ``` -------------------------------- ### Setting Content Source and Processing Multimodal Content (Python) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Demonstrates how to set a content source using a list of content items and then process multimodal content, such as an image, with associated metadata. This involves specifying the content type, file path, entity name, and item information for context-aware processing. ```python processor.set_content_source(content_list, "minerU") item_info = { "page_idx": 2, "index": 5, "type": "image" } result = await processor.process_multimodal_content( modal_content=image_data, content_type="image", file_path="document.pdf", entity_name="Architecture Diagram", item_info=item_info ) ``` -------------------------------- ### Configure Public Asset URLs Source: https://github.com/hkuds/rag-anything/blob/main/README.md Set environment variables to enable HTTPS or S3-style links for assets generated during ingestion. ```bash # 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 ``` -------------------------------- ### Direct Modal Processor Integration Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Illustrates how to manually initialize a ContextExtractor and inject it into a modal processor for targeted multimodal analysis. ```python from raganything.modalprocessors import ( ContextExtractor, ContextConfig, ImageModalProcessor ) config = ContextConfig( context_window=1, context_mode="page", max_context_tokens=2000, include_headers=True, include_captions=True, filter_content_types=["text"] ) context_extractor = ContextExtractor(config) processor = ImageModalProcessor(lightrag, caption_func, context_extractor) ``` -------------------------------- ### Configure CSS and Debugging for PDF Converter Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Shows how to apply custom CSS for font styling and how to enable debug logging for the EnhancedMarkdownConverter. ```python # Use web-safe fonts config = MarkdownConfig( custom_css=""" body { font-family: 'Arial', 'Helvetica', sans-serif; } """ ) ``` ```python import logging # Enable debug logging logging.basicConfig( level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s' ) # Create converter with debug logging converter = EnhancedMarkdownConverter() result = converter.convert_file_to_pdf("test.md", "test.pdf") ``` -------------------------------- ### Configure MinerU via RAGAnything API Source: https://github.com/hkuds/rag-anything/blob/main/README.md Pass parsing parameters directly to the process_document_complete method to customize MinerU execution. ```python # Basic parsing configuration with parser selection await rag.process_document_complete( file_path="document.pdf", output_dir="./output/", parse_method="auto", # or "ocr", "txt" parser="mineru" # Optional: "mineru", "docling", or "paddleocr" ) ``` ```python # 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" parser="mineru", # Parser selection: "mineru", "docling", or "paddleocr" # 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 # 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 ) ``` -------------------------------- ### CLI Markdown Conversion Commands Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Provides common command-line interface patterns for converting markdown files to PDF, including options for specifying backends, custom CSS, and help documentation. ```bash # Basic conversion python -m raganything.enhanced_markdown document.md --output document.pdf # With specific backend python -m raganything.enhanced_markdown document.md --method weasyprint # With custom CSS file python -m raganything.enhanced_markdown document.md --css custom_style.css # Show backend information python -m raganything.enhanced_markdown --info # Help python -m raganything.enhanced_markdown --help ``` -------------------------------- ### Configure OpenAI Embedding Environment Variables Source: https://github.com/hkuds/rag-anything/blob/main/docs/vllm_integration.md Sets the required environment variables to integrate OpenAI's embedding API with the RAG-Anything system. Requires a valid API key and model configuration. ```bash EMBEDDING_BINDING=openai EMBEDDING_MODEL=text-embedding-3-large EMBEDDING_DIM=3072 EMBEDDING_BINDING_HOST=https://api.openai.com/v1 EMBEDDING_BINDING_API_KEY=sk-... ``` -------------------------------- ### Insert Content List into RAG Source: https://github.com/hkuds/rag-anything/blob/main/README.md Demonstrates how to define a list of content dictionaries and insert them into the RAG system with a specific file path and document ID. ```python # 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()) ``` -------------------------------- ### Basic Markdown to PDF Conversion Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Demonstrates the basic usage of the EnhancedMarkdownConverter to convert a markdown file to a PDF. It initializes the converter with default settings and uses the 'auto' method to select the best available backend. ```python from raganything.enhanced_markdown import EnhancedMarkdownConverter, MarkdownConfig # Create converter with default settings converter = EnhancedMarkdownConverter() # Convert markdown file to PDF success = converter.convert_file_to_pdf( input_path="document.md", output_path="document.pdf", method="auto" # Automatically select best available backend ) if success: print("✅ Conversion successful!") else: print("❌ Conversion failed") ``` -------------------------------- ### Integrate Batch Processing with RAG-Anything Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Use the RAGAnything class to process documents in batch directly through the main interface. ```python from raganything import RAGAnything rag = RAGAnything() # Process documents with batch functionality result = rag.process_documents_batch( file_paths=["doc1.pdf", "doc2.docx"], output_dir="./output", max_workers=4, show_progress=True ) print(f"Processed {len(result.successful_files)} files successfully") ``` -------------------------------- ### Plain Text Content Format (Python) Source: https://github.com/hkuds/rag-anything/blob/main/docs/context_aware_processing.md Illustrates the simplest format for providing content, which is a single string containing the entire document's text. This is suitable for documents where content is primarily textual and does not require complex structuring. ```python full_document = "Complete document text with all content..." ``` -------------------------------- ### Execute Pure Text Queries Source: https://github.com/hkuds/rag-anything/blob/main/README.md Perform knowledge base searches using different modes like hybrid, local, global, or naive. Both asynchronous and synchronous methods are supported. ```python # 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") ``` -------------------------------- ### Convert Markdown to PDF Programmatically Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Demonstrates how to use the converter class to transform markdown content into a PDF file. The method supports automatic backend selection for rendering. ```python success = converter.convert_markdown_to_pdf( markdown_content=markdown_content, output_path="sample.pdf", method="auto" ) ``` -------------------------------- ### RAG-Anything Integration Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Shows how to integrate the markdown conversion utility into the RAG-Anything pipeline for automated document processing. ```python from raganything import RAGAnything # Initialize RAG-Anything rag = RAGAnything() # Process markdown files - enhanced conversion is used automatically await rag.process_document_complete("document.md") # Batch processing with enhanced markdown conversion result = rag.process_documents_batch( file_paths=["doc1.md", "doc2.md", "doc3.md"], output_dir="./output" ) ``` -------------------------------- ### Run Batch Processing via CLI Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Execute batch processing tasks directly from the command line with various configuration flags. ```bash # Basic batch processing python -m raganything.batch_parser examples/sample_docs/ --output ./output --workers 4 # With specific parser python -m raganything.batch_parser examples/sample_docs/ --parser mineru --method auto python -m raganything.batch_parser examples/sample_docs/ --parser paddleocr --method ocr # Without progress bar python -m raganything.batch_parser examples/sample_docs/ --output ./output --no-progress # Only process files directly inside the specified directories python -m raganything.batch_parser examples/sample_docs/ --output ./output --no-recursive # Dry run (list supported files without processing) python -m raganything.batch_parser examples/sample_docs/ --output ./output --dry-run # Incremental run (skip files unchanged since the last successful batch) python -m raganything.batch_parser examples/sample_docs/ --output ./output --incremental # Help python -m raganything.batch_parser --help ``` -------------------------------- ### Cite RAG-Anything in BibTeX Source: https://github.com/hkuds/rag-anything/blob/main/README.md Use this BibTeX entry to cite the RAG-Anything framework in academic research papers. ```bibtex @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}, } ``` -------------------------------- ### Implement Robust PDF Conversion with Fallback Backends Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md A robust implementation that attempts to convert markdown to PDF by iterating through multiple available backends until success or exhaustion. ```python def robust_conversion(input_path, output_path): """Convert with fallback backends""" converter = EnhancedMarkdownConverter() # Try backends in order of preference backends = ["weasyprint", "pandoc", "auto"] for backend in backends: try: success = converter.convert_file_to_pdf( input_path=input_path, output_path=output_path, method=backend ) if success: print(f"✅ Conversion successful with {backend}") return True except Exception as e: print(f"❌ {backend} failed: {str(e)}") continue print("❌ All backends failed") return False ``` -------------------------------- ### Insert Content List into RAG-Anything Source: https://github.com/hkuds/rag-anything/blob/main/README.md Configures the RAG-Anything instance with model functions and inserts a list of pre-parsed content items for indexing. ```python 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: 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:image/jpeg;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) ``` -------------------------------- ### Process Documents with RAG Integration Source: https://github.com/hkuds/rag-anything/blob/main/docs/batch_processing.md Process documents in batch and automatically add them to the RAG system. ```python # Process documents in batch and then add them to RAG result = await rag.process_documents_with_rag_batch( file_paths=["doc1.pdf", "doc2.docx"], output_dir="./output", max_workers=4, show_progress=True ) print(f"Processed {result['successful_rag_files']} files with RAG") print(f"Total processing time: {result['total_processing_time']:.2f} seconds") ``` -------------------------------- ### Execute Multimodal Queries Source: https://github.com/hkuds/rag-anything/blob/main/README.md Perform queries incorporating specific multimodal content such as tables or LaTeX equations for enhanced analysis. ```python # 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" ) ``` -------------------------------- ### POST /convert_file_to_pdf Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Converts a local markdown file to a PDF document using a specified or automatic backend engine. ```APIDOC ## POST /convert_file_to_pdf ### Description Converts a markdown file located at the input path to a PDF file at the specified output path. ### Method POST ### Endpoint /convert_file_to_pdf ### Parameters #### Request Body - **input_path** (string) - Required - The filesystem path to the source markdown file. - **output_path** (string) - Required - The destination path for the generated PDF. - **method** (string) - Optional - The backend engine to use: "weasyprint", "pandoc", or "auto". Defaults to "auto". ### Request Example { "input_path": "./docs/manual.md", "output_path": "./dist/manual.pdf", "method": "auto" } ### Response #### Success Response (200) - **success** (boolean) - Returns true if the conversion was successful. #### Response Example { "success": true } ``` -------------------------------- ### POST /convert_markdown_to_pdf Source: https://github.com/hkuds/rag-anything/blob/main/docs/enhanced_markdown.md Converts raw markdown string content directly into a PDF file. ```APIDOC ## POST /convert_markdown_to_pdf ### Description Processes raw markdown text and renders it into a PDF file. ### Method POST ### Endpoint /convert_markdown_to_pdf ### Parameters #### Request Body - **markdown_content** (string) - Required - The raw markdown string to be converted. - **output_path** (string) - Required - The destination path for the generated PDF. - **method** (string) - Optional - The backend engine to use: "weasyprint", "pandoc", or "auto". ### Request Example { "markdown_content": "# Hello World\nThis is a test.", "output_path": "./output.pdf", "method": "weasyprint" } ### Response #### Success Response (200) - **success** (boolean) - Returns true if the conversion was successful. #### Response Example { "success": true } ``` -------------------------------- ### Verify vLLM Server Connectivity Source: https://github.com/hkuds/rag-anything/blob/main/docs/vllm_integration.md Uses curl to verify that the vLLM server is active and responding to requests on the specified port. This is a primary diagnostic step for connection refused errors. ```bash curl http://localhost:8000/v1/models ``` -------------------------------- ### Create Custom Modal Processor Source: https://github.com/hkuds/rag-anything/blob/main/README.md Extends the GenericModalProcessor to implement custom logic for analyzing and creating entities from multimodal content. ```python 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) ```