Skip to content

MackDing/zh-policy-rag

Repository files navigation

zh-policy-rag — 中文政策制度智能问答系统

English | 中文

一个面向企业内部知识库的中文政策/法规文档 RAG 系统。支持多路检索融合、Corrective RAG 质量门控和 SSE 流式输出,开箱即用地对接任何 OpenAI 兼容的大模型端点。


项目简介

zh-policy-rag 将企业内部的政策文件、管理办法、审批流程等非结构化文档转化为可对话的知识库。用户提问后,系统并发调用向量检索、BM25 关键词检索、知识图谱和页面索引四路召回源,通过 RRF 融合与交叉编码器重排后,由 CRAG 评估器决定是否直接生成答案、改写查询重试,还是向用户说明无结果。整个过程通过 SSE 实时推送到前端。

适用场景: 企业制度查询、法规合规问答、内部流程咨询


目录


特性

检索层

  • 四路并发检索:ChromaDB 向量 + BM25 关键词 + 知识图谱 (RAGAnything) + PageIndex
  • 加权 RRF 融合(多源命中加分),Qwen3-Reranker / BGE-Reranker 交叉编码器重排
  • 中文分词同义词扩展(jieba),HyDE 假设文档生成

质量门控

  • Corrective RAG (CRAG) 三色评估:绿色直接生成,琥珀色改写重试,红色告知用户
  • 语义答案缓存(余弦相似度阈值 0.95,LRU 1 万条)

文档解析

  • MinerU(PDF/DOCX 高质量)、Excel(openpyxl/xlrd)、Legacy(旧版 doc/wps 降级)三套解析器
  • pdfplumber 二次兜底:MinerU 把流程图/架构图判为整页图像时自动切换,恢复 PDF 文本层里的文字(详见 docs/PDF_OCR_DIAGNOSIS.md
  • 解析错误分类:加密、损坏、扫描件、编码错误等,并给出具体修复建议
  • 政策感知分块:尊重"第X条"、编号条目等中文文档边界

生成与对话

  • SSE 实时流式输出,逐 token 推送到前端
  • 对话历史持久化(SQLModel + SQLite)
  • LLM 主备端点自动故障转移
  • 支持任何 OpenAI 兼容端点(Qwen、Llama、OpenAI API 等)

评估

  • 三框架评估:DeepEval + TruLens + Arize Phoenix
  • 内置 CRAG 分布统计、引用率、检索/生成耗时指标

系统架构

用户浏览器 (React + Ant Design)
     │  POST /api/qa/ask → SSE 流式响应
     ▼
  Nginx :80
  ├─ /api/* ──────────────────────────────────┐
  └─ /*  → frontend :3000                     │
                                              ▼
                                   FastAPI 后端 :8000
                                        │
                           ┌────────────▼────────────┐
                           │       RAGEngine          │
                           │                          │
                           │  ┌─ QueryEnhancer ──┐   │
                           │  │  同义词扩展 + HyDE │   │
                           │  └──────────────────┘   │
                           │                          │
                           │  ToolOrchestrator        │
                           │  ┌──────┬──────┬──────┐  │
                           │  │BM25  │Vec   │Graph │  │
                           │  │检索  │检索  │检索  │  │
                           │  └──┬───┴──┬───┴──┬───┘  │
                           │     └──────▼──────┘      │
                           │       RRF 融合            │
                           │          │               │
                           │     Reranker             │
                           │  (Qwen3/BGE-Reranker)    │
                           │          │               │
                           │   CRAGEvaluator          │
                           │  绿/琥珀/红  三色门控    │
                           │          │               │
                           │    LLMClient             │
                           │  (主备端点 + 流式)        │
                           └──────────────────────────┘
                                        │
                           ┌────────────┼────────────┐
                           ▼            ▼            ▼
                       ChromaDB     SQLite        BM25 index
                       (向量)      (元数据 +      (pickle,
                                   对话历史)      内存加载)

快速开始(Docker)

前置要求:

  • Docker + Docker Compose
  • 已运行的 OpenAI 兼容 LLM 端点(如 vLLM 部署的 Qwen、本地 Ollama 等)
  • 已运行的 Embedding 端点(如 BGE-M3)
  • 已运行的 Reranker 端点(可选,但强烈推荐)
# 1. 克隆仓库
git clone https://github.com/MackDing/zh-policy-rag.git
cd zh-policy-rag

# 2. 初始化环境
./setup.sh

# 3. 编辑 .env,填写你的 LLM / Embedding / Reranker 端点
#    以及 SOURCE_DIR(政策文档所在目录)
nano .env

# 4. 启动服务
docker compose up -d --build

# 5. 访问
#    前端:http://localhost
#    后端 API:http://localhost/api/docs

首次启动不含文档数据。完成文档入库后才能进行 QA 对话,参见文档入库


本地开发

前置要求: Python 3.11+,Node 20+,uv

# 后端
uv sync --dev                              # 安装依赖(含 dev 包)
cp .env.example .env                       # 配置环境变量
uv run uvicorn backend.app.main:app \
    --reload --host 0.0.0.0 --port 8000   # 启动开发服务器

# 前端(另开终端)
cd frontend
npm install
npm run dev                                # Vite 开发服务器 :5173

# 测试
uv run pytest                              # 运行所有测试
uv run pytest --cov=backend tests/         # 含覆盖率报告

# 代码检查
uv run ruff check backend/ tests/          # Lint
uv run ruff format --check backend/ tests/ # 格式检查

文档入库

# 1. 将政策文档放入 SOURCE_DIR(支持 .docx .pdf .xlsx .eml)

# 2. 解析文档(扫描 + 解析 → data/parsed/)
uv run python scripts/ingest.py

# 3. 构建检索索引(BM25 + 向量)
uv run python scripts/rebuild_index.py

# 4. 构建知识图谱(可选,需要较长时间)
uv run python scripts/build_graph.py

目录结构

zh-policy-rag/
├── backend/
│   ├── app/
│   │   ├── api/routes/       # FastAPI 路由 (qa, documents, conversations...)
│   │   ├── core/
│   │   │   ├── generation/   # RAGEngine, CRAG, LLMClient, QueryEnhancer
│   │   │   ├── retrieval/    # BM25/向量/图谱/PageIndex 检索器 + RRF 融合
│   │   │   ├── indexing/     # 向量库、BM25索引、语义缓存
│   │   │   └── ingestion/    # 文档解析 Pipeline(MinerU/Excel/Legacy)
│   │   ├── models/           # Pydantic/SQLModel 数据模型
│   │   ├── config.py         # pydantic-settings 配置
│   │   └── main.py           # FastAPI 应用入口
│   └── Dockerfile
├── frontend/
│   └── src/
│       ├── pages/            # QAPage(主对话页)、StatusPage、GraphPage
│       └── components/       # ConversationList 等
├── scripts/
│   ├── ingest.py             # 文档入库脚本
│   ├── rebuild_index.py      # 索引重建
│   ├── build_graph.py        # 知识图谱构建
│   └── local_embedding_server.py  # 本地 Embedding 服务器
├── tests/                    # pytest 测试套件
├── nginx/nginx.conf           # SSE 反向代理配置
├── docker-compose.yml
├── pyproject.toml
└── .env.example

评估框架

系统集成三套评估框架,可组合使用:

# 内置评估器(无外部依赖)
uv run python scripts/rag_quality.py

# DeepEval(需要配置评估用 LLM)
uv run python -m backend.app.core.evaluation.deepeval_adapter

# TruLens
uv run python -m backend.app.core.evaluation.trulens_adapter

# Arize Phoenix
uv run python -m backend.app.core.evaluation.phoenix_adapter

评估指标:答案相关性评分(0-10)、引用率、CRAG 分布、检索/生成耗时。


常见问题

Q: 支持哪些文档格式?
A: .docx(Word)、.pdf(MinerU 高质量解析 + pdfplumber 二次兜底)、.xlsx/.xls(Excel)、.eml(邮件)。对嵌入图片型 PDF(流程图、架构图等),MinerU 把整页判为图像时系统会自动切换到 pdfplumber 恢复文本层,保证文字内容进入索引;纯扫描件(无文本层)建议先走 OCR 服务再导入。

Q: 可以使用 OpenAI 官方 API 吗?
A: 可以。将 LLM_BASE_URL 设为 https://api.openai.com/v1LLM_API_KEY 设为真实的 API Key 即可。

Q: 如何替换 Embedding 模型?
A: 修改 .env 中的 EMBEDDING_BASE_URLEMBEDDING_MODEL,然后重建索引(scripts/rebuild_index.py --clear)。

Q: CRAG 总是返回 RED?
A: 通常意味着文档未完成入库,或 Reranker 端点不可用。检查 data/ 目录是否有解析后的文档,以及 Reranker 端点是否可访问。

Q: 可以禁用 Reranker 吗?
A: 可以。Reranker 不可用时系统会自动降级为仅 RRF 排名,但质量会有所下降。


使用 Claude Code

本项目包含 CLAUDE.md,Claude Code 启动时会自动读取,获得完整的项目上下文。

claude    # 在项目根目录启动 Claude Code,即可获得完整上下文

License

MIT License — 详见 LICENSE


贡献指南

欢迎 PR 和 Issue!详见 CONTRIBUTING.md



zh-policy-rag — Chinese Policy Document RAG System

A Chinese-language RAG system for enterprise internal policy and regulation knowledge bases. Features multi-source retrieval fusion, Corrective RAG (CRAG) quality gating, and real-time SSE streaming — works with any OpenAI-compatible LLM endpoint.

Features

  • Multi-source retrieval: ChromaDB vector + BM25 keyword + knowledge graph (RAGAnything) + PageIndex, all queried concurrently
  • Weighted RRF fusion with cross-encoder reranking (Qwen3-Reranker / BGE-Reranker)
  • Corrective RAG (CRAG): traffic-light quality gate — GREEN generates, AMBER rewrites and retries, RED informs user
  • Semantic answer cache: cosine similarity threshold 0.95, LRU 10K entries
  • Chinese synonym expansion + HyDE hypothetical document generation
  • Robust PDF handling: MinerU + pdfplumber recovery fallback — when MinerU misclassifies a diagram/flowchart page as a single image, pdfplumber recovers the underlying text layer so searchable content still reaches the index (see docs/PDF_OCR_DIAGNOSIS.md)
  • Three document parsers: MinerU (high-quality PDF/DOCX), Excel, and Legacy fallback
  • Policy-aware chunking: respects 第X条 / numbered article boundaries
  • Triple evaluation framework: DeepEval + TruLens + Arize Phoenix
  • SSE streaming from backend to frontend, token by token
  • Conversation history persisted via SQLModel + SQLite

Prerequisites

  • Docker + Docker Compose (for containerised deployment)
  • Python 3.11+, Node 20+ (for local development)
  • An OpenAI-compatible LLM endpoint (Qwen, Llama, OpenAI API, etc.)
  • An OpenAI-compatible Embedding endpoint (BGE-M3, Qwen3-Embedding, etc.)
  • An OpenAI-compatible Reranker endpoint (BGE-Reranker, Qwen3-Reranker — optional but recommended)
  • Source policy documents to ingest (.docx, .pdf, .xlsx, .eml)

Quick Start

git clone https://github.com/MackDing/zh-policy-rag.git
cd zh-policy-rag
./setup.sh
# Edit .env with your LLM/embedding/reranker endpoints
docker compose up -d --build
# Visit http://localhost

Key .env settings: LLM_BASE_URL, LLM_MODEL, EMBEDDING_BASE_URL, EMBEDDING_MODEL, SOURCE_DIR

Using with Claude Code

claude    # Claude Code reads CLAUDE.md automatically for full project context

License

MIT — see LICENSE


🦞 OPC Ecosystem

Built by @MackDing — One-Person Company infrastructure powered by AI agents.

Project What it does
opc.ren OPC founder hub — tools, signals, community
CodexClaw Telegram bot for remote Codex access with MCP + subagent routing
awesome-ai-api Leaderboard of 200+ AI API gateways & relays
claude-context-health Diagnose & fix Claude Code session degradation
opc-daily-signal AI-powered daily decision intelligence for OPC founders
doc-preprocess-hub Enterprise document preprocessing — MinerU + docling

About

Chinese policy/regulation document RAG system with multi-source retrieval, Corrective RAG, and OpenAI-compatible LLM integration

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors