Metadata-Version: 2.4
Name: langchain-modular-rag-hjh
Version: 0.1.0
Summary: 模块化 RAG 在线检索：基于 LangChain + Chroma，支持混合召回、RRF 融合、改写、HyDE、重排、过滤与压缩，可切换 DashScope 云端或本地 Ollama 模型
Author: hjh
License-Expression: MIT
Keywords: rag,langchain,chroma,retrieval,bm25,hybrid-search
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: chromadb
Requires-Dist: langchain-chroma
Requires-Dist: langchain-classic
Requires-Dist: langchain-community
Requires-Dist: langchain-core
Requires-Dist: langchain-openai
Requires-Dist: jieba
Requires-Dist: rank-bm25
Requires-Dist: python-dotenv
Requires-Dist: dashscope
Provides-Extra: ollama
Requires-Dist: langchain-ollama; extra == "ollama"
Provides-Extra: publish
Requires-Dist: build; extra == "publish"
Requires-Dist: twine; extra == "publish"

# langchain-modular-rag-hjh

提供一个 `ModularRAG` 类：连接**已有的 Chroma 知识库**，用字典开关自由组合模块化 RAG 在线检索流程。

- 检索前：查询规范化、查询改写、HyDE 假设答案
- 召回融合：向量检索、BM25 关键词检索（jieba 中文分词）、RRF 融合
- 检索后：去重、Rerank 精排、余弦相似度过滤、上下文压缩、长上下文位置调整

模型提供方二选一：

| 提供方 | 说明 |
| --- | --- |
| `dashscope`（默认） | 通义千问云端模型，需配置 `DASHSCOPE_API_KEY` |
| `ollama` | 本地 Ollama 模型（如 `bge-m3` 向量、`qwen2.5:0.5b` 对话），离线可用 |

要求 Python 3.11 及以上。本包只提供在线检索，不包含知识库数据，也不会自动建库；`persist_directory` 需指向已完成入库的 Chroma 数据库。

## 安装

```bash
pip install langchain-modular-rag-hjh
# 如需本地 Ollama 模型支持：
pip install "langchain-modular-rag-hjh[ollama]"
```

## 快速开始（DashScope 云端）

配置通义 API Key（或在项目根目录 `.env` 中写入 `DASHSCOPE_API_KEY=你的Key`）：

```bash
# Linux / macOS
export DASHSCOPE_API_KEY="你的 API Key"
# Windows
setx DASHSCOPE_API_KEY="你的 API Key"
```

```python
from langchain_modular_rag_hjh import ModularRAG

rag = ModularRAG({
    "persist_directory": "./chroma_db",
    "collection_name": "study",
    "embedding_model": "text-embedding-v4",
    "top_k": 5,
    "recall_top_k": 20,
    "pre_retrieval": {
        "enabled": False,
        "rewrite_query": False,
        "hyde": False,
        "model": "qwen-plus",
    },
    "hybrid_retrieval": {
        "enabled": True,
        "weights": [0.5, 0.5],
    },
    "post_retrieval": {
        "enabled": True,
        "deduplicate": True,
        "rerank": False,
        "rerank_model": "qwen3-rerank",
        "similarity_filter": False,
        "similarity_threshold": 0.4,
        "compress_context": False,
        "llm_model": "qwen-plus",
        "reorder": False,
    },
})

for document in rag.search("公司打卡时间？"):
    print(document.metadata)
    print(document.page_content)
```

## 使用本地 Ollama 模型

先启动本地 Ollama 服务并拉取模型（如 `bge-m3`、`qwen2.5:0.5b`），建库时使用同一个本地向量模型，然后：

```python
from langchain_modular_rag_hjh import ModularRAG

rag = ModularRAG({
    "persist_directory": "./chroma_db",
    "collection_name": "study",
    "embedding_provider": "ollama",
    "embedding_model": "bge-m3",
    "llm_provider": "ollama",
    "llm_model": "qwen2.5:0.5b",
    # "ollama_base_url": "http://localhost:11434",  # 默认值，可省略
    "hybrid_retrieval": {"enabled": True},
    "post_retrieval": {"enabled": True, "deduplicate": True},
})

results = rag.search("公司打卡时间？")
```

注意：Rerank 精排依赖 DashScope 重排模型，即使其他功能使用 Ollama，开启 `rerank` 仍需 `DASHSCOPE_API_KEY`。

## 配置说明

| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `persist_directory` | `./chroma_db` | Chroma 数据库目录，必须已存在 |
| `collection_name` | `study` | 集合名称 |
| `embedding_provider` | `dashscope` | 向量提供方：`dashscope` / `ollama` |
| `embedding_model` | `text-embedding-v4` | 向量模型（ollama 默认 `bge-m3`），须与建库时一致 |
| `llm_provider` | `dashscope` | 对话模型提供方：`dashscope` / `ollama` |
| `llm_model` | `qwen-plus` | 对话模型（ollama 默认 `qwen2.5:0.5b`） |
| `ollama_base_url` | `http://localhost:11434` | Ollama 服务地址 |
| `top_k` | `5` | 最终返回条数 |
| `recall_top_k` | `20` | 召回条数 |
| `filters` | `None` | 常驻元数据过滤条件，与 `search()` 参数合并 |

`search(question, top_k=None, filters=None)` 返回 `Document` 列表，元数据中带 `retrieval_rank`（截取后排名）与 `context_position`（最终上下文位置）；开启重排或相似度过滤时另有 `relevance_score` / `cosine_similarity`。

## License

MIT
