Metadata-Version: 2.4
Name: demon-slaying-rag
Version: 0.1.0
Summary: A modular RAG retrieval class based on LangChain and Chroma
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.11
Description-Content-Type: text/markdown
Requires-Dist: chromadb>=1.0
Requires-Dist: langchain-chroma>=1.0
Requires-Dist: langchain-core>=1.0
Requires-Dist: langchain-community>=0.4
Requires-Dist: langchain-openai>=1.0
Requires-Dist: langchain-classic>=1.0
Requires-Dist: dashscope>=2.0
Requires-Dist: python-dotenv>=1.0
Requires-Dist: jieba>=0.42
Requires-Dist: rank-bm25>=0.2
Provides-Extra: publish
Requires-Dist: build; extra == "publish"
Requires-Dist: twine; extra == "publish"

# demon-slaying-rag

一个可配置的**模块化 RAG 检索器**：只负责"从已有 Chroma 知识库里把最相关的片段取回来"，不包含入库、切分与答案生成。

核心是 `ModularRAG` 类，把早期脚本里散落的检索参数集中成一份 `config` 字典，并按三阶段流水线执行：

```
问题
 │
 ├─ 检索前优化  pre_retrieval   归一化 → (可选)查询改写 → (可选)HyDE 假设答案
 │
 ├─ 混合召回    hybrid_retrieval 纯向量检索 或 向量+BM25 经 RRF 融合
 │
 └─ 检索后处理  post_retrieval   去重 → (可选)重排 → (可选)相似度过滤
                               → 截断 top_k → (可选)上下文压缩 → (可选)重排顺序
 │
返回 List[Document]（带 retrieval_rank / context_position 等元数据）
```

---

## 环境要求

- Python >= 3.11（已在 3.13 上验证）
- 依赖（`pip install .` 会自动安装）：

| 依赖 | 用途 |
| --- | --- |
| `chromadb` / `langchain-chroma` | 向量库连接（`Chroma`） |
| `langchain-core` | `Document`、`RunnableLambda` |
| `langchain-community` | `DashScopeEmbeddings`、`BM25Retriever`、`DashScopeRerank`、`LongContextReorder` |
| `langchain-openai` | 通过 DashScope 兼容接口调用 `qwen-plus` 做改写 / HyDE / 压缩 |
| `langchain-classic` | `EnsembleRetriever`（RRF 融合）、`LLMChainExtractor`（上下文压缩） |
| `dashscope` | 通义 Embedding / Rerank 的 SDK |
| `jieba` + `rank-bm25` | 混合检索的 BM25 分词与实现（仅混合检索需要） |
| `python-dotenv` | 读取 `.env` 中的 `DASHSCOPE_API_KEY` |

## 安装

本项目未发布到 PyPI，使用本地安装：

```bash
# 可编辑安装（推荐本地开发）
pip install -e .

# 或普通安装
pip install .

# 额外安装打包发布工具
pip install -e ".[publish]"
```

## 前置条件

1. **知识库必须已存在**：`persist_directory` 指向的目录下必须有 `chroma.sqlite3`，否则构造函数直接抛 `FileNotFoundError`。
2. **不会自动建集合**：内部使用 `create_collection_if_not_exists=False`，集合不存在时报错，而不是静默创建一个空库（避免"检索结果永远为空"的排查黑洞）。
3. **API Key**：在项目根目录放一个 `.env`，或直接设置环境变量。

```bash
# Linux / macOS
export DASHSCOPE_API_KEY="sk-xxxx"

# Windows PowerShell
setx DASHSCOPE_API_KEY "sk-xxxx"
```

```ini
# .env
DASHSCOPE_API_KEY=sk-xxxx
```

> 入库（切分 + 向量化 + 写 Chroma）不在本模块职责内，请用你已有的离线建库脚本生成知识库。

---

## 快速开始

```python
from demon_slaying_rag import ModularRAG

rag = ModularRAG({
    # ---- 基础连接 ----
    "persist_directory": "./chroma_db",     # Chroma 目录（含 chroma.sqlite3）
    "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],              # [向量权重, BM25 权重]
    },
    # ---- 检索后处理 ----
    "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,
    },
})

documents = rag.search("公司打卡时间？")
for document in documents:
    print(document.metadata["retrieval_rank"], document.metadata["context_position"])
    print(document.page_content)
    print("-" * 40)
```

带元数据过滤与临时 top_k：

```python
documents = rag.search(
    "试用期规定",
    top_k=8,
    filters={"source": "员工手册.pdf"},          # 与 config["filters"] 以 $and 合并
)
```

---

## 配置项

### 基础连接与召回

| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `persist_directory` | `./chroma_db` | Chroma 目录，**相对当前工作目录**解析（支持 `~`） |
| `collection_name` | `study` | 集合名 |
| `embedding_model` | `text-embedding-v4` | DashScope Embedding 模型，必须与建库时一致 |
| `top_k` | `5` | 最终返回条数 |
| `recall_top_k` | `20` | 召回阶段条数；实际取 `max(recall_top_k, top_k)` |
| `filters` | 无 | Chroma `where` 过滤条件，如 `{"source": "a.pdf"}` |

### 检索前优化 `pre_retrieval`

| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `enabled` | `False` | 总开关，关闭时下列子项**全部不生效** |
| `rewrite_query` | `False` | 用 `qwen-plus` 把问题改写为独立查询，向量与 BM25 都用改写后结果 |
| `hyde` | `False` | 用 `qwen-plus` 生成约 100 字假设答案，**仅替换向量检索的查询** |
| `model` | `qwen-plus` | 改写 / HyDE 使用的 LLM |

开启 `enabled` 后，`normalize_query`（合并多余空白）总是执行，没有单独开关。

### 混合召回 `hybrid_retrieval`

| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `enabled` | `False` | 开启后走 向量 + BM25 + RRF 融合；关闭则纯向量检索 |
| `weights` | `[0.5, 0.5]` | `EnsembleRetriever` 权重，顺序为 `[向量, BM25]` |

RRF 的 `c` 参数固定为 `60`（`rrf_fusion` 的 `rrf_k`）。

### 检索后处理 `post_retrieval`

| 键 | 默认值 | 说明 |
| --- | --- | --- |
| `enabled` | `False` | 总开关，关闭时下列子项全部不生效 |
| `deduplicate` | `True` | 按 `page_content` 去重 |
| `rerank` | `False` | 调用 DashScope Rerank 重排 |
| `rerank_model` | `qwen3-rerank` | 重排模型 |
| `similarity_filter` | `False` | 按余弦相似度过滤 |
| `similarity_threshold` | `0.4` | 相似度阈值，低于该值丢弃 |
| `compress_context` | `False` | 用 `LLMChainExtractor` 抽取与问题相关的句子（表格类文档跳过） |
| `llm_model` | `qwen-plus` | 压缩使用的 LLM |
| `reorder` | `False` | `LongContextReorder`：把关键内容放到上下文首尾（"中间遗忘"缓解） |

### 执行顺序（`search` 内部）

1. 校验：问题非空、`top_k` 为正整数，否则抛 `ValueError`
2. `count = max(recall_top_k, top_k)`
3. 检索前：归一化 → 改写 →（可选）HyDE 生成 `dense_query`
4. 过滤条件：`config["filters"]` 与 `search(filters=...)` 合并为 `$and`
5. 召回：
   - `hybrid.enabled`：`db.get(where=...)` 拉全集 → 建 `BM25Retriever`（jieba 分词）+ 向量检索器 → `EnsembleRetriever` RRF 融合
   - 否则：`vector_search`
6. 后处理（`post.enabled`）：去重 → 重排 `top_n=len(documents)` → 相似度过滤
7. 截断到 `top_k`，写入 `metadata["retrieval_rank"]`（1 起）
8. 后处理第二阶段：上下文压缩 → 重排顺序，写入 `metadata["context_position"]`

---

## API

### `ModularRAG(config: dict)`

连接知识库并初始化 Embedding 模型。`config` 中缺失的键一律走默认值。

### `search(question: str, top_k: int | None = None, filters: dict | None = None) -> list[Document]`

在线检索，返回按相关性排好序的 `Document` 列表。返回的 `metadata` 除知识库原始字段外，可能包含：

| 字段 | 出现条件 | 含义 |
| --- | --- | --- |
| `chunk_id` | 纯向量检索分支 | 文档在 Chroma 中的 id |
| `retrieval_rank` | 总是 | 截断后的最终名次（1 起） |
| `context_position` | 总是 | 送入上下文时的位置（1 起） |
| `cosine_similarity` | 开启 `similarity_filter` | 与问题的余弦相似度 |

### 可独立复用的静态方法

| 方法 | 说明 |
| --- | --- |
| `normalize_query(question)` | 合并空白并去首尾空格 |
| `rewrite_query(question, model)` | 改写为适合检索的独立查询 |
| `generate_hyde(question, model)` | 生成假设性答案（约 100 字） |
| `vector_search(question, db, top_k, filters)` | 稠密检索 |
| `bm25_search(question, documents, top_k)` | 稀疏检索（需自行提供语料） |
| `rrf_fusion(question, vector_retriever, bm25_retriever, weights, rrf_k)` | RRF 融合两路召回 |
| `deduplicate(documents)` | 按内容去重 |
| `rerank_documents(question, documents, top_k, model)` | DashScope 重排 |
| `similarity_filter(question, documents, embeddings, threshold)` | 余弦相似度过滤 |
| `compress_context(question, documents, model)` | LLM 抽取式压缩 |
| `reorder_documents(documents)` | 长上下文重排（首尾优先） |

### 异常

| 场景 | 异常 |
| --- | --- |
| 目录下没有 `chroma.sqlite3` | `FileNotFoundError` |
| 问题为空 / `top_k` 非正整数 | `ValueError` |
| 集合名不存在 | `chromadb` 抛出的 `NotFoundError` 类异常 |
| 未安装 `jieba` / `rank-bm25` 却开启混合检索 | `ImportError` |

---

## 已知限制与注意事项

- **键名拼错不会报错**：全篇使用 `config.get(k, default)`，写错键名只会静默走默认值，排障时优先怀疑键名。
- **总开关优先**：`pre_retrieval.enabled=False` / `post_retrieval.enabled=False` 时，其下所有子项（含默认为 `True` 的 `deduplicate`）一律不生效。
- **路径与工作目录绑定**：`persist_directory` 相对当前工作目录解析，从不同目录启动会连到不同的库；工作区内根目录与 `day_1106/` 下各有一个 `chroma_db`。
- **混合检索的开销**：每次查询都会 `db.get()` 全量拉取文档并重建 BM25 索引，数据量大时延迟明显，且不支持大数据集分页。
- **重复的 Embedding 调用**：`similarity_filter` 会对每条候选文档重新调用 Embedding API（向量库里其实已存有向量），有额外耗时与费用。
- **压缩逐条调用 LLM**：`compress_context` 对每个文档单独请求一次 `qwen-plus`，条数越多越慢。
- **模型一致性**：`embedding_model` 必须与建库时相同，否则相似度与过滤结果都会失真。

## 目录结构

```
project/
├── demon_slaying_rag.py   # ModularRAG 类（单模块）
├── pyproject.toml         # 打包与依赖声明
└── README.md
```

## 打包与发布

```bash
pip install -e ".[publish]"
python -m build
twine check dist/*
twine upload dist/*        # 需要 PyPI Token
```
