hybrid-rag-project
Hybrid RAG プロジェクト
提供された任意のドキュメントで動作する、ハイブリッド検索機能を備えた汎用 Retrieval-Augmented Generation(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 スパース検索
ハイブリッド融合: Reciprocal Rank Fusion(RRF)による両手法の結果の統合
MCP サーバー: Claude 統合のための REST API と Model Context Protocol サーバーの両方
マルチフォーマット対応: さまざまなファイル形式からドキュメントを自動的に読み込み
ハイブリッドアプローチにより、両方の検索手法の強みを活かして検索精度を向上させます。
特徴
Chroma と Ollama 埋め込みを使用したベクトルベースのセマンティック検索
正確な用語一致のための BM25 キーワード検索
Reciprocal Rank Fusion(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前提条件
Python 3.9+
Ollama がインストールされ、ローカルで実行されていること
必要な Ollama モデル:
llama3.1:latest(または別の LLM モデル)nomic-embed-text(または別の埋め込みモデル)
Ollama のインストール
ollama.ai にアクセスして、お使いのプラットフォーム用の Ollama をダウンロードしてインストールしてください。
インストール後、必要なモデルを取得します:
ollama pull llama3.1:latest
ollama pull nomic-embed-textOllama が実行されていることを確認します:
curl http://localhost:11434/api/tagsインストール
リポジトリをクローンします:
git clone <your-repo-url>
cd hybrid-rag-project仮想環境を作成します:
python -m venv .venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate依存関係をインストールします:
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 Extension プロジェクト)
このリポジトリには、デモとテスト用に 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- QC 調査結果と問題点(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 の検索可能なドキュメントチャンク
🎯 目的
これらのサンプルファイルは以下の目的で含まれています:
システムのハイブリッド検索機能をデモンストレーションする
セマンティック(ベクトル)検索と語彙(キーワード)検索の両方をテストする
ドキュメントタイプを考慮した検索アーキテクチャを検証する
追加設定なしで即座に動作する例を提供する
ドキュメント横断的なクエリ合成を紹介する
📖 テスト結果
包括的なテスト結果は 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?"本番環境での使用: 代わりに独自のデータを使用するには:
data/からサンプルファイルを削除またはバックアップします独自のドキュメント(TXT、PDF、MD、DOCX、CSV)を追加します
インジェストを再実行します
必要に応じて
.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: コマンドラインスクリプト
ドキュメントを
data/ディレクトリに追加します:
cp /path/to/your/documents/*.pdf data/
cp /path/to/your/documents/*.txt data/スクリプトを実行します:
python scripts/run_demo.pyスクリプトは以下を行います:
data/ディレクトリからサポートされているすべてのドキュメントを読み込むOllama の埋め込みと LLM を初期化する
ベクトル検索と BM25 検索を作成する
ハイブリッド RAG チェーンを構築する
サンプルクエリを実行して結果を表示する
オプション 2: REST API サーバー
REST API サーバーを起動します:
python scripts/mcp_server.pyサーバーは http://localhost:8000 で起動します
サーバーを停止するには: グレースフルシャットダウンのために Ctrl+C を押します
ドキュメントをインジェストします(最初にこれを行います):
curl -X POST http://localhost:8000/ingest応答:
{
"status": "success",
"message": "Documents ingested successfully",
"documents_loaded": 15
}ドキュメントをクエリします:
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"
}
]
}サーバーのステータスを確認します:
curl http://localhost:8000/statusAPI エンドポイント
エンドポイント | メソッド | 説明 |
| GET | ヘルスチェック |
| POST | data/ ディレクトリからドキュメントを読み込む |
| POST | ハイブリッド検索でドキュメントをクエリする |
| GET | システムステータスと設定を取得する |
オプション 3: MCP 経由の Claude Desktop/API
MCP(Model Context Protocol)サーバーにより、Claude がローカルの RAG システムを直接クエリできるようになります。
Claude Desktop のセットアップ
まず、データディレクトリにドキュメントを追加します:
cp /path/to/your/documents/*.pdf data/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"
}
}
}
}この設定を 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.jsonWindows の場合:
%APPDATA%\Claude\claude_desktop_config.jsonLinux の場合:
~/.config/Claude/claude_desktop_config.jsonClaude Desktop を再起動します
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: フィールド条件に一致するすべての行を取得します(例:「Company 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_field、filter_dataset): 正確なカウント、フィルタリング、構造化データ用セマンティック検索(
query_documents): 概念的な質問、内容の理解、要約用
サポートされているファイル形式
システムは以下の形式を自動的に読み込んで処理します:
.txt- プレーンテキストファイル.pdf- PDF ドキュメント.md- Markdown ファイル.docx- Microsoft Word ドキュメント.csv- CSV ファイル
サポートされているファイルを data/ ディレクトリにドロップするだけです!
仕組み
ドキュメントの読み込み
DocumentLoaderUtility クラス:
data/ディレクトリを再帰的にスキャンしますサポートされているファイル形式を識別します
各形式に適したローダーを使用します
各ドキュメントにメタデータ(ソースファイル、ファイルタイプ)を追加します
インデックス作成用の
Documentオブジェクトのリストを返します
ハイブリッド検索
EnsembleRetriever は Reciprocal Rank Fusion(RRF)を使用して:
ベクトル検索(セマンティック)から上位 k 件の結果を取得します
BM25 検索(キーワード)から上位 k 件の結果を取得します
各結果に逆順位スコアを割り当てます
スコアを組み合わせて統合ランキングを生成します
全体的に最も関連性の高いドキュメントを返します
このアプローチは以下を処理します:
セマンティッククエリ(「休暇の申請方法は?」)
キーワードクエリ(「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.py または scripts/mcp_server.py のプロンプトテンプレートを編集します:
prompt = ChatPromptTemplate.from_template("""
Your custom prompt here...
<context>
{context}
</context>
Question: {input}
""")開発ワークフロー
data/ディレクトリにドキュメントを追加します必要に応じて
config/config.yamlの設定を変更しますコマンドラインでテストします:
python scripts/run_demo.pyMCP サーバーをデプロイします:
python scripts/mcp_server.pyアプリケーションで API を介して統合します
トラブルシューティング
「Error connecting to Ollama」
Ollama がインストールされ、実行されていることを確認します
設定された URL で Ollama サービスにアクセスできることを確認します
モデルがダウンロードされていることを確認します:
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 およびその他の形式
パフォーマンスのヒント
ベクターストアの永続化: ベクターストアはインジェスト後にディスク (
chroma_db/) に永続化されるため、その後のクエリが高速になります。バッチ処理: 多数のドキュメントを追加する場合は、
/ingestエンドポイントを複数回ではなく一度に使用してください。検索パラメータ:
kの値を小さくすると (例: 2〜3) 高速になり、小規模なドキュメントセットでは多くの場合十分です。モデルの選択: より小さい埋め込みモデルは高速ですが、精度が犠牲になる場合があります。
ライセンス
このプロジェクトは教育およびデモンストレーション目的で現状のまま提供されます。
コントリビューション
改善のための issue の提出、リポジトリのフォーク、プルリクエストの作成は自由に行ってください。
リソース
変更履歴
バージョン 2.0.0
任意のドキュメントで動作するようにシステムを一般化
ドキュメントのインジェスト用に
data/ディレクトリを追加マルチフォーマット対応の
DocumentLoaderUtilityを作成Python のベストプラクティスに従うようにプロジェクトを再構成 (src レイアウト)
すべての設定を
config/ディレクトリに移動すべてのドキュメントを
docs/ディレクトリに移動setup.pyを使用して適切な Python パッケージ構造を作成スクリプトを
scripts/ディレクトリに整理すべてのインポートパスとドキュメントを更新
バージョン 1.0.0
サンプル HR ドキュメントによる初期実装
ベクターと BM25 リトリーバーによる基本的なハイブリッド検索
This server cannot be installed
Maintenance
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
- AlicenseNot gradedqualityDmaintenanceEnables 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
- AlicenseNot gradedqualityDmaintenanceEnables 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.4MIT
- AlicenseNot gradedqualityDmaintenanceEnables intelligent file search with Git-like staging and indexing, offering semantic and hybrid search for documents, and integrates with Claude Desktop via MCP.5MIT
- AlicenseNot gradedqualityBmaintenanceEnables querying enterprise documents (DOCX, PDF, PPTX) using natural language, with hybrid search and MCP integration for Claude Desktop and other agents.MIT
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.
Latest Blog Posts
- Who's Calling? MCP Hosts Are an Identity Blind Spot (And the Spec Knows It)By Om-Shree-0709 on .mcpAgent IdentityOAuth 2.1
- Your AI Chatbot Just Exposed Your CEO's Salary to an InternBy Om-Shree-0709 on .Agent IdentityMCP SecurityOAuth Delegation
- Why MCP Servers Need Execution Sandboxing (And Why Your Current Stack Isn't Enough)By Om-Shree-0709 on .Agentic AiPrompt InjectionWebAssembly
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