Skip to main content

gov-modular-rag

一个面向政务问答场景的模块化 RAG 检索包:连接已经建好的 Chroma 知识库,提供向量检索、BM25 混合检索、RRF 融合、去重、相似度过滤、重排和上下文压缩。

说明:教程中的 langchain-modular-rag 已由其他作者发布到 PyPI;本项目使用 gov-modular-rag,避免同名冲突。

本包只做在线检索,不包含你的知识库数据,也不会自动创建或导入知识库。

安装

从源码目录安装:

pip install -e .

发布到 PyPI 后可以这样安装:

pip install gov-modular-rag

Python 3.11 及以上。

准备知识库

先准备一个 Chroma 持久化目录。下面是最小入库示例:

from langchain_chroma import Chroma
from langchain_community.embeddings import DashScopeEmbeddings
from langchain_core.documents import Document

embeddings = DashScopeEmbeddings(model="text-embedding-v4")

docs = [
    Document(
        page_content="社保卡丢失后,先挂失,再携带身份证到社保卡服务窗口补换。",
        metadata={"title": "社保卡补换", "chunk_id": "policy-1"},
    ),
    Document(
        page_content="租房提取公积金需要身份证、银行卡、租赁合同或租房发票。",
        metadata={"title": "公积金租房提取", "chunk_id": "policy-2"},
    ),
]

Chroma.from_documents(
    documents=docs,
    embedding=embeddings,
    ids=[doc.metadata["chunk_id"] for doc in docs],
    persist_directory="./chroma_db",
    collection_name="study",
)

使用

from gov_modular_rag 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,
    },
})

results = rag.search("公司打卡时间?")
for document in results:
    print(document.metadata)
    print(document.page_content)

search() 返回 list[Document],可以直接拿来拼 Prompt:

context = "\n\n".join(
    f"[{i}] {doc.page_content}"
    for i, doc in enumerate(results, start=1)
)

配置说明

参数 默认值 作用
persist_directory 必填 已有 Chroma 持久化目录
collection_name study Chroma 集合名
embedding_model text-embedding-v4 通义向量模型
top_k 5 最终返回条数
recall_top_k 20 向量/BM25 每路召回条数
pre_retrieval.enabled False 是否启用查询预处理
pre_retrieval.rewrite_query False 是否做查询改写
pre_retrieval.hyde False 是否生成 HyDE 假设答案
pre_retrieval.model qwen-plus 改写/HyDE 使用的模型
hybrid_retrieval.enabled True 是否启用向量 + BM25 混合检索
hybrid_retrieval.weights [0.5, 0.5] 两路 RRF 权重
post_retrieval.enabled True 是否启用后处理
post_retrieval.deduplicate True 按 chunk_id 和正文去重
post_retrieval.similarity_filter False 是否按余弦相似度过滤
post_retrieval.similarity_threshold 0.4 相似度阈值
post_retrieval.rerank False 是否调用 DashScope 重排
post_retrieval.rerank_model qwen3-rerank 重排模型
post_retrieval.compress_context False 是否用 LLM 抽取相关句
post_retrieval.llm_model qwen-plus 压缩使用的模型
post_retrieval.reorder False 是否按余弦相似度重排

预处理、重排和压缩都会产生额外的大模型调用,第一次调试建议先保持关闭。

环境变量

# Windows PowerShell
$env:DASHSCOPE_API_KEY="你的 API Key"

# macOS / Linux
export DASHSCOPE_API_KEY="你的 API Key"

代码也支持 DASHSCOPE_BASE_URL;不设置时默认使用:

https://dashscope.aliyuncs.com/compatible-mode/v1

说明与限制

  • 只读取已有 Chroma 库;如果集合为空,search() 会返回空列表。
  • BM25 语料在第一次检索时从 Chroma 读取并缓存;知识库更新后调用 rag.refresh()。
  • 混合检索使用 RRF 排名融合,分数是排名分,不是余弦相似度。
  • rerank、compress_context、rewrite_query、hyde 需要可用的通义 API Key。
  • 当前不包含文档切分和自动入库;入库请参考上面的“准备知识库”。

本地构建

pip install build twine
python -m build

构建完成后会在 dist/ 下生成:

  • gov_modular_rag-0.1.0-py3-none-any.whl
  • gov_modular_rag-0.1.0.tar.gz

发布到 PyPI

先注册 PyPI 账号并创建 API Token,然后执行:

twine upload dist/*

用户名填 __token__,密码填 PyPI Token。

License

MIT

Metadata

Release files for gov-modular-rag 0.1.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for gov-modular-rag 0.1.0
File Size Uploaded Provenance Actions
gov_modular_rag-0.1.0.tar.gz 9.1 kB Without provenance Details for gov_modular_rag-0.1.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for gov-modular-rag 0.1.0
File Interpreter ABI Platform Actions
gov_modular_rag-0.1.0-py3-none-any.whl Python 3 none any Details for gov_modular_rag-0.1.0-py3-none-any.whl

Total release size: 18.3 kB

Release files / gov_modular_rag-0.1.0.tar.gz

Download URL gov_modular_rag-0.1.0.tar.gz
Size 9.1 kB
Tags Source
SHA-256 checksum
How to use checksums
ddcd96b27d6b347381616cccdf3dd4a247a979bf12eb475fa7ae11f85a90c38f
BLAKE2b-256 checksum
How to use checksums
14b4afadb62a704dc3cc3ce11d465bbd7ded39394c9914b32e389c62b1918df9
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Release files / gov_modular_rag-0.1.0-py3-none-any.whl

Download URL gov_modular_rag-0.1.0-py3-none-any.whl
Size 9.2 kB
Tags Python 3
SHA-256 checksum
How to use checksums
628d46b059b43d2cf4c796ff4dd27a30c1c281d4174740c7af868ed71288b404
BLAKE2b-256 checksum
How to use checksums
e58694d1b84d5d6cc1cf6d7ad1057182966fbbb0c3f21d7c5769b4227eab632a
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.18

Security for gov-modular-rag 0.1.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.0 This release

2 release files No provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page