Skip to main content
Glama
ce23b006-byte

hybrid-rag-project

混合 RAG 项目

Python 3.9+ License: MIT Code style: black

一个具有混合搜索能力的通用检索增强生成(RAG)系统,可与您提供的任何文档配合使用。结合语义(稠密向量)搜索和关键词(稀疏 BM25)搜索,实现最佳文档检索,并提供 MCP 服务器 API 以便轻松集成。

🎯 核心特性:多格式支持 • 本地 LLM • Claude Desktop 集成 • 结构化数据查询 • 文档类型感知检索

🚀 快速开始(无需 MCP!)

您不需要 Claude Desktop 或 MCP 即可使用此项目! 只需运行:

# 1. Make sure Ollama is running
ollama serve

# 2. Activate virtual environment
source .venv/bin/activate

# 3. Start conversational demo (recommended)
python scripts/demos/conversational.py

# Or use the shortcut
./scripts/bin/ask.sh

就这样! 针对示例数据集中的 43,835 个文档块提问即可。

📖 参见 快速入门指南 获取完整使用说明。 📚 浏览所有文档,请查看 docs/ 文件夹,或从 docs/README.md 开始。


Related MCP server: Hybrid RAG Project MCP Server

概述

本项目实现了一个结合以下能力的混合 RAG 系统:

  • 语义搜索:稠密向量嵌入,用于理解含义和上下文

  • 关键词搜索:BM25 稀疏检索,用于精确关键词匹配

  • 混合融合:倒数排名融合(RRF),用于合并两种方法的结果

  • MCP 服务器:同时提供 REST API 和 Model Context Protocol 服务器,用于 Claude 集成

  • 多格式支持:自动加载各种文件格式的文档

混合方法通过利用两种搜索方法的优势,确保更高的检索准确性。

特性

  • 使用 Chroma 和 Ollama 嵌入进行基于向量的语义搜索

  • 用于精确术语匹配的 BM25 关键词搜索

  • 使用倒数排名融合(RRF)的集成检索器

  • 与本地 Ollama LLM 集成以生成答案

  • 支持多种文档格式(TXT、PDF、MD、DOCX、CSV)

  • 从数据目录自动加载文档

  • 提供 /ingest/query 端点的 RESTful API 服务器

  • 用于 Claude Desktop/API 集成的 Model Context Protocol(MCP)服务器

  • 配置驱动的架构(无硬编码值)

  • 持久化向量存储,加快后续查询速度

架构

User Documents → data/ directory
                      ↓
            Document Loader
                      ↓
Query → Hybrid Retriever → [Vector Retriever + BM25 Retriever]
                         → RRF Fusion
                         → Retrieved Context
                         → LLM (Ollama)
                         → Final Answer

前提条件

  1. Python 3.9+

  2. Ollama 已安装并在本地运行

  3. 所需的 Ollama 模型:

    • llama3.1:latest(或其他 LLM 模型)

    • nomic-embed-text(或其他嵌入模型)

安装 Ollama

访问 ollama.ai 下载并安装适用于您平台的 Ollama。

安装后,拉取所需模型:

ollama pull llama3.1:latest
ollama pull nomic-embed-text

验证 Ollama 正在运行:

curl http://localhost:11434/api/tags

安装

  1. 克隆仓库:

git clone <your-repo-url>
cd hybrid-rag-project
  1. 创建虚拟环境:

python -m venv .venv
source .venv/bin/activate  # On Windows: .venv\Scripts\activate
  1. 安装依赖:

pip install -r requirements.txt

项目结构

hybrid-rag-project/
├── src/
│   └── hybrid_rag/            # Core application package
│       ├── __init__.py        # Package initialization
│       ├── document_loader.py # Document loading utility
│       ├── structured_query.py# CSV query engine
│       └── utils.py           # Logging and utility functions
├── scripts/
│   ├── run_demo.py            # Main demonstration script
│   ├── mcp_server.py          # REST API server
│   └── mcp_server_claude.py   # MCP server for Claude integration
├── config/
│   ├── config.yaml            # Configuration file
│   └── claude_desktop_config.json # Sample Claude Desktop MCP config
├── docs/
│   ├── INSTALLATION.md        # Detailed installation guide
│   ├── STRUCTURED_QUERIES.md  # CSV query documentation
│   ├── ASYNC_INGESTION.md     # Async ingestion guide
│   └── SHUTDOWN.md            # Shutdown handling guide
├── data/                      # Sample data files (13 files included)
│   ├── *.csv                  # 7 CSV files (structured data)
│   ├── *.md                   # 5 Markdown files (unstructured)
│   └── *.txt                  # 1 Text file (technical specs)
├── chroma_db/                 # Vector store (auto-created)
├── tests/                     # Unit tests
│   └── extract_fields_tests.py
├── setup.py                   # Package setup file
├── requirements.txt           # Python dependencies
├── TESTING_RESULTS.md         # Comprehensive test results
├── CONTRIBUTING.md            # Contribution guidelines
├── CHANGELOG.md               # Version history
├── LICENSE                    # MIT License
└── README.md                  # This file

示例数据(UCSC 扩展项目)

此仓库包含 13 个示例数据文件,用于演示和测试目的。这些文件代表了 TechVision Electronics 的真实业务场景,旨在展示系统在多种文档类型上的能力。

📊 包含的示例文件

结构化数据(CSV)- 7 个文件:

  • product_catalog.csv - 带规格的产品库存(5,000 行)

  • inventory_levels.csv - 库存水平和仓库数据(10,000 行)

  • sales_orders_november.csv - 月度销售交易(8,000 行)

  • warranty_claims_q4.csv - 客户保修索赔(3,000 行)

  • production_schedule_dec2024.csv - 生产计划(4,000 行)

  • supplier_pricing.csv - 供应商定价信息(6,000 行)

  • shipping_manifests.csv - 运输和物流数据(5,000 行)

非结构化数据(Markdown)- 5 个文件:

  • customer_feedback_q4_2024.md - 客户评价和反馈(600 个块)

  • market_analysis_2024.md - 市场研究和趋势(400 个块)

  • quality_control_report_nov2024.md - 质量控制发现和问题(501 个块)

  • return_policy_procedures.md - 政策文档(300 个块)

  • support_tickets_summary.md - 技术支持摘要(700 个块)

文本数据 - 1 个文件:

  • product_specifications.txt - 技术规格(334 个块)

数据集总计:

  • 41,000 行 CSV(按每块 10 行分块为 41,000 个文档)

  • 2,835 个文本/Markdown 块(按 1000 字符分块,200 字符重叠)

  • 43,835 个可搜索文档块

🎯 用途

这些示例文件用于:

  1. 演示系统的混合搜索能力

  2. 测试语义(向量)和词汇(关键词)检索

  3. 验证文档类型感知检索架构

  4. 提供无需额外设置即可使用的即时工作示例

  5. 展示跨文档查询综合能力

📖 测试结果

全面的测试结果记录在 TESTING_RESULTS.md 中,显示:

  • 所有文档类型的检索成功率为 100%

  • 17 个测试查询及详细结果

  • 性能指标和对比分析

  • 语义 vs 词汇 vs 混合搜索对比

💡 使用示例数据

快速开始:

# 1. Run setup
./setup.sh

# 2. The sample data is already in data/ - ready to use!

# 3. Run the demo
python scripts/run_demo.py

# 4. Or use Claude Desktop
# Configure MCP server and query: "What are the prices in the product catalog?"

用于生产环境: 要改用您自己的数据:

  1. data/ 中删除或备份示例文件

  2. 添加您自己的文档(TXT、PDF、MD、DOCX、CSV)

  3. 重新运行摄取

  4. 可选:取消注释 .gitignore 中的数据排除项


## Configuration

All settings are managed in `config/config.yaml`:

```yaml
# Ollama Configuration
ollama:
  base_url: "http://localhost:11434"
  embedding_model: "nomic-embed-text"
  llm_model: "llama3.1:latest"

# Data Configuration
data:
  directory: "./data"
  supported_formats:
    - "txt"
    - "pdf"
    - "md"
    - "docx"
    - "csv"

# Retrieval Configuration
retrieval:
  vector_search_k: 2
  keyword_search_k: 2

# MCP Server Configuration
mcp_server:
  host: "0.0.0.0"
  port: 8000

# Vector Store Configuration
vector_store:
  persist_directory: "./chroma_db"

修改此文件以:

  • 使用不同的 Ollama 模型

  • 更改数据目录位置

  • 调整检索参数(k 值)

  • 配置服务器主机/端口

  • 更改向量存储持久化位置

使用方法

选项 1:命令行脚本

  1. 将您的文档添加到 data/ 目录:

cp /path/to/your/documents/*.pdf data/
cp /path/to/your/documents/*.txt data/
  1. 运行脚本

python scripts/run_demo.py

该脚本将:

  • data/ 目录加载所有支持的文档

  • 初始化 Ollama 嵌入和 LLM

  • 创建向量和 BM25 检索器

  • 构建混合 RAG 链

  • 执行示例查询并显示结果

选项 2:REST API 服务器

  1. 启动 REST API 服务器

python scripts/mcp_server.py

服务器将在 http://localhost:8000 上启动

停止服务器:Ctrl+C 进行优雅关闭

  1. 摄取文档(请先执行此操作):

curl -X POST http://localhost:8000/ingest

响应:

{
  "status": "success",
  "message": "Documents ingested successfully",
  "documents_loaded": 15
}
  1. 查询文档

curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"query": "What is the main topic of these documents?"}'

响应:

{
  "answer": "Based on the documents...",
  "context": [
    {
      "content": "Document text...",
      "source": "example.pdf",
      "type": ".pdf"
    }
  ]
}
  1. 检查服务器状态

curl http://localhost:8000/status

API 端点

端点

方法

描述

/

GET

健康检查

/ingest

POST

从 data/ 目录加载文档

/query

POST

使用混合搜索查询文档

/status

GET

获取系统状态和配置

选项 3:通过 MCP 使用 Claude Desktop/API

MCP(Model Context Protocol)服务器允许 Claude 直接查询您的本地 RAG 系统。

Claude Desktop 设置

  1. 首先,将文档添加到您的数据目录

cp /path/to/your/documents/*.pdf data/
  1. 编辑 config/claude_desktop_config.json 文件以使用正确的绝对路径:

{
  "mcpServers": {
    "hybrid-rag": {
      "command": "python",
      "args": [
        "/absolute/path/to/hybrid-rag-project/scripts/mcp_server_claude.py"
      ],
      "env": {
        "PYTHONPATH": "/absolute/path/to/hybrid-rag-project"
      }
    }
  }
}
  1. 将此配置添加到 Claude Desktop

    在 macOS 上

    # Copy the configuration
    mkdir -p ~/Library/Application\ Support/Claude
    # Edit the file and add your MCP server configuration
    nano ~/Library/Application\ Support/Claude/claude_desktop_config.json

    在 Windows 上

    %APPDATA%\Claude\claude_desktop_config.json

    在 Linux 上

    ~/.config/Claude/claude_desktop_config.json
  2. 重启 Claude Desktop

  3. 在 Claude Desktop 中,您现在会看到可用的 MCP 工具。您可以询问 Claude:

    • "使用 ingest_documents 工具加载我的文档"

    • "查询我的文档关于 [您的问题]"

    • "检查 RAG 系统的状态"

可用的 MCP 工具

Claude 将可以访问以下工具:

文档摄取与搜索:

  • ingest_documents:从 data/ 目录异步开始加载和索引文档

  • get_ingestion_status:监控文档摄取的进度(百分比、当前文件、阶段)

  • query_documents:使用混合搜索(语义 + 关键词)查询文档

  • get_status:检查 RAG 系统状态

结构化数据查询(用于 CSV 文件):

  • list_datasets:列出所有可用的 CSV 数据集,包含列和行数

  • count_by_field:统计字段匹配某个值的行数(例如,"统计名为 Michael 的人数")

  • filter_dataset:获取所有符合字段条件的行(例如,"所有来自 X 公司的人")

  • get_dataset_stats:获取数据集的统计信息(行数、列数、内存使用量)

带进度跟踪的异步摄取

摄取过程现在以异步方式运行,并提供实时进度更新:

  • 非阻塞:摄取在后台运行

  • 进度跟踪:查看完成百分比(0-100%)

  • 文件级更新:了解当前正在处理哪个文件

  • 阶段信息:加载文件(0-80%)→ 构建索引(80-100%)→ 完成

  • 状态监控:随时使用 get_ingestion_status 检查进度

与 Claude 的示例用法

You: "Please start ingesting my documents"
Claude: [Uses ingest_documents tool]
        "Ingestion started. Use get_ingestion_status to monitor progress."

You: "Check the ingestion status"
Claude: [Uses get_ingestion_status tool]
        "Ingestion Status: In Progress
         Progress: 45%
         Stage: loading_files
         Files Processed: 9/20
         Current File: document.pdf
         Documents Loaded: 15"

You: "Check status again"
Claude: [Uses get_ingestion_status tool]
        "Ingestion Status: Completed ✅
         Progress: 100%
         Total Files Processed: 20
         Total Documents Loaded: 35

         You can now use query_documents to search the documents."

You: "What are the main topics in my documents?"
Claude: [Uses query_documents tool with your question]
        "Based on the documents, the main topics are..."

结构化数据查询

对于 CSV 文件,使用结构化查询工具进行精确计数和过滤:

You: "List available datasets"
Claude: [Uses list_datasets tool]
        "Available Datasets:
         📊 contacts
            Rows: 24,697
            Columns (7): First Name, Last Name, URL, Email Address, Company, Position, Connected On"

You: "Count how many people are named Michael in the contacts dataset"
Claude: [Uses count_by_field tool with dataset="contacts", field="First Name", value="Michael"]
        "Count Result:
         Dataset: contacts
         Field: First Name
         Value: Michael
         Count: 226 out of 24,697 total rows (0.92%)"

You: "Show me all the Michaels"
Claude: [Uses filter_dataset tool]
        "Filter Results:
         Found: 226 rows
         Showing: 100 rows (truncated to 100)

         [1] First Name: Michael | Last Name: Randel | Company: Randel Consulting Associates ..."

何时使用每种方法:

  • 结构化查询count_by_fieldfilter_dataset):用于精确计数、过滤和结构化数据

  • 语义搜索query_documents):用于概念性问题、理解内容、摘要

支持的文件格式

系统自动加载并处理以下格式:

  • .txt - 纯文本文件

  • .pdf - PDF 文档

  • .md - Markdown 文件

  • .docx - Microsoft Word 文档

  • .csv - CSV 文件

只需将任何受支持的文件放入 data/ 目录即可!

工作原理

文档加载

DocumentLoaderUtility 类:

  1. 递归扫描 data/ 目录

  2. 识别支持的文件格式

  3. 为每种格式使用相应的加载器

  4. 为每个文档添加元数据(源文件、文件类型)

  5. 返回准备好进行索引的 Document 对象列表

混合检索

EnsembleRetriever 使用倒数排名融合(RRF):

  1. 从向量搜索(语义)中检索 top-k 结果

  2. 从 BM25 搜索(关键词)中检索 top-k 结果

  3. 为每个结果分配倒数排名分数

  4. 合并分数以产生统一排名

  5. 返回整体最相关的文档

此方法处理:

  • 语义查询("我如何申请休假?")

  • 关键词查询("PTO 表格 HR-42")

  • 受益于两种方法的复杂查询

自定义

使用不同的模型

编辑 config/config.yaml 以更改模型:

ollama:
  embedding_model: "your-embedding-model"
  llm_model: "your-llm-model"

调整检索参数

修改 config/config.yaml 中的 k 值:

retrieval:
  vector_search_k: 5   # Return top 5 from semantic search
  keyword_search_k: 5  # Return top 5 from keyword search

添加更多文件格式支持

编辑 src/hybrid_rag/document_loader.py 以添加更多加载器:

self.supported_loaders = {
    '.txt': TextLoader,
    '.pdf': PyPDFLoader,
    '.json': JSONLoader,  # Add this
    # ... more formats
}

自定义提示词

编辑 scripts/run_demo.pyscripts/mcp_server.py 中的提示词模板:

prompt = ChatPromptTemplate.from_template("""
Your custom prompt here...

<context>
{context}
</context>

Question: {input}
""")

开发工作流

  1. 将文档添加到 data/ 目录

  2. 根据需要修改 config/config.yaml 中的配置

  3. 使用命令行测试python scripts/run_demo.py

  4. 部署 MCP 服务器python scripts/mcp_server.py

  5. 在您的应用中通过 API 集成

故障排除

"Error connecting to Ollama"

  • 确保 Ollama 已安装并正在运行

  • 检查 Ollama 服务在配置的 URL 上可访问

  • 验证模型已下载:ollama list

"No documents found in data directory"

  • data/ 目录添加文件

  • 确保文件具有受支持的扩展名(.txt、.pdf、.md、.docx、.csv)

  • 检查 config/config.yaml 中的数据目录路径是否正确

"ModuleNotFoundError"

  • 确保虚拟环境已激活:source .venv/bin/activate

  • 重新安装依赖:pip install -r requirements.txt

检索结果不佳

  • data/ 目录添加更多相关文档

  • 调整 config/config.yaml 中的 k

  • 尝试不同的嵌入模型

  • 确保查询术语与文档内容匹配

API 错误

  • 确保在调用 /query 之前先调用 /ingest

  • 查看服务器日志以获取详细的错误信息

  • 确认 Ollama 正在运行且可访问

  • 检查文档是否已成功加载

示例:完整工作流程

# 1. Activate environment
source .venv/bin/activate

# 2. Add your documents
cp ~/my-docs/*.pdf data/

# 3. Start MCP server
python scripts/mcp_server.py &

# 4. Ingest documents
curl -X POST http://localhost:8000/ingest

# 5. Query your documents
curl -X POST http://localhost:8000/query \
  -H "Content-Type: application/json" \
  -d '{"query": "Summarize the key points"}'

# 6. Check status
curl http://localhost:8000/status

依赖项

核心库:

  • langchain:用于 LLM 应用的框架

  • langchain-community:社区集成

  • langchain-ollama:Ollama 集成

  • chromadb:用于嵌入向量的向量数据库

  • rank-bm25:用于关键词搜索的 BM25 实现

  • fastapi:用于 API 的 Web 框架

  • uvicorn:ASGI 服务器

  • pyyaml:YAML 配置解析

文档加载器:

  • pypdf:PDF 处理

  • python-docx:Word 文档处理

  • unstructured:Markdown 及其他格式

性能提示

  1. 向量存储持久化:摄入后,向量存储会持久化到磁盘(chroma_db/),使后续查询更快。

  2. 批量处理:添加大量文档时,请一次性使用 /ingest 端点,而不是多次调用。

  3. 检索参数:较低的 k 值(例如 2-3)速度更快,通常足以应对小型文档集。

  4. 模型选择:较小的嵌入模型速度更快,但可能会牺牲一些准确性。

许可证

本项目按原样提供,仅供教育和演示用途。

贡献

欢迎提交 issue、fork 仓库,并为任何改进创建 pull request。

资源

更新日志

版本 2.0.0

  • 将系统泛化,使其适用于任何文档

  • 新增 data/ 目录用于文档摄入

  • 创建 DocumentLoaderUtility 以支持多种格式

  • 重构项目以遵循 Python 最佳实践(src 布局)

  • 将所有配置移至 config/ 目录

  • 将所有文档移至 docs/ 目录

  • 使用 setup.py 创建了规范的 Python 包结构

  • 将脚本整理到 scripts/ 目录

  • 更新了所有导入路径和文档

版本 1.0.0

  • 使用示例 HR 文档的初始实现

  • 使用向量和 BM25 检索器的基本混合搜索

A
license - permissive license
Not graded
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables Claude Desktop to search and query personal document collections (PDF, Word, Markdown, text) using semantic search and conversational AI with full context preservation across exchanges.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables Claude to perform hybrid search across local documents by combining semantic vector retrieval and BM25 keyword matching for optimal context recovery. It supports multiple file formats including PDF, CSV, and Markdown, leveraging local Ollama models for private and efficient document querying.
    4
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    Enables intelligent file search with Git-like staging and indexing, offering semantic and hybrid search for documents, and integrates with Claude Desktop via MCP.
    5
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables querying enterprise documents (DOCX, PDF, PPTX) using natural language, with hybrid search and MCP integration for Claude Desktop and other agents.
    MIT

View all related MCP servers

Related MCP Connectors

  • Search your knowledge bases from any AI assistant using hybrid RAG.

  • Connect your team's living knowledge base — docs, data, issues, CRM — to Claude and ChatGPT.

  • OCR, transcription, file extraction, and image generation for AI agents via MCP.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/ce23b006-byte/hybrid-rag-project'

If you have feedback or need assistance with the MCP directory API, please join our Discord server