diff --git a/README.en.md b/README.en.md new file mode 100644 index 0000000000000000000000000000000000000000..cbd787d73dd9921433256b3e779490ba54a7dfc1 --- /dev/null +++ b/README.en.md @@ -0,0 +1,151 @@ +# RAG Knowledge Base System + +## 📖 Project Introduction + +This project is a Knowledge Base Question Answering System based on **RAG (Retrieval-Augmented Generation)** technology. It helps users manage massive amounts of documents and provides accurate, reliable context information for Large Language Models (LLMs) through a combination of semantic search and keyword search, thereby generating high-quality responses. + +The system provides complete capabilities for **Document Management**, **Conversation Management**, **Retrieval Augmentation**, and **Automated Evaluation**, suitable for various scenarios such as enterprise knowledge bases, intelligent customer service, and document analysis. + +## ✨ Key Features + +1. **Intelligent Document Ingestion**: + * Supports parsing of mainstream formats including PDF, DOCX, Markdown, and HTML. + * Automatically performs text splitting, vectorization processing, and stores data in the vector database. + * Supports incremental updates and failure retry mechanisms. +2. **Hybrid Retrieval**: + * **Vector Retrieval**: Implements semantic similarity search based on `pgvector`. + * **Keyword Retrieval**: Implements Chinese full-text search based on `zhparser`. + * **Fusion Ranking**: Uses the RRF (Reciprocal Rank Fusion) algorithm to fuse both retrieval results, balancing semantics and exact matching. +3. **Agent Routing & Multi-step Reasoning**: + * Built-in Query Rewriter and Router nodes. + * Supports `HyDE` (Hypothetical Document Embeddings) and Multi-Query generation strategies. + * Capable of Context Quality Assessment (`Judge Context`), deciding whether to refuse answers or optimize queries based on retrieval result quality. +4. **Conversation Management**: + * Supports multi-turn conversations while maintaining context memory. + * Provides **Semantic Cache** capabilities to accelerate response speeds for frequent questions. + * Comprehensive answer attribution functionality, visualizing cited fragments. +5. **Automated Evaluation**: + * Integrated with the Ragas evaluation framework. + * Supports custom evaluation sets (JSONL format). + * Automatically calculates metrics such as Faithfulness and Answer Relevancy, and supports Bad Case Attribution Analysis. +6. **Permission & User Management**: + * RBAC (Role-Based Access Control) permission model. + * Supports Document Permission Tags control to ensure data security. + +## 🛠️ Tech Stack + +### Backend +* **Language & Framework**: Python 3.11+ / FastAPI +* **ORM**: SQLAlchemy (Async) +* **Task Queue**: Celery + Redis +* **Database**: PostgreSQL 16 + * Plugins: `pgvector` (Vector Index), `zhparser` (Chinese Tokenization) +* **Observability**: LangSmith (Optional Integration), Structured Logging +* **Storage**: Supports local storage or S3-compatible object storage (e.g., Tencent Cloud COS) + +### Frontend +* **Language**: TypeScript +* **Framework**: React 18 + Vite +* **UI Components**: Ant Design (Estimated) +* **Build Tool**: openapi-ts (Auto-generates TS types and request methods based on OpenAPI schema) + +## 📂 Project Structure + +```text +rag-knowledge-base/ +├── backend/ # FastAPI Backend Service +│ ├── app/ +│ │ ├── api/ # API Routes (Auth, Chat, Documents, Evaluations...) +│ │ ├── core/ # Core modules: Configuration, Security, Redis, Logging, Rate Limiting, etc. +│ │ ├── db/ # Database Models (SQLAlchemy) and Migration Scripts (Alembic) +│ │ ├── ingestion/ # Document Parsing, Splitting, Vectorization Pipeline +│ │ ├── llm/ # LLM Wrappers, Prompt Engineering, Rewrite/Route/Rerank Logic +│ │ ├── retrieval/ # Vector Retriever, Keyword Retriever, Hybrid Retrieval Fusion Logic +│ │ ├── services/ # Business Logic Layer (Chat, Document, User, Evaluation) +│ │ ├── storage/ # File Upload, Object Storage Client Wrappers +│ │ └── workflows/ # LangGraph or similar State Machine Graph Orchestration +│ ├── alembic/ # Database Migration Scripts +│ ├── pyproject.toml # Python Dependency Configuration (Ruff, Pytest, etc.) +│ └── celery_app.py # Celery Async Task Configuration +├── frontend/ # React + Vite Frontend Application +│ ├── src/ +│ │ ├── api/ # API Client Code +│ │ ├── client/ # Auto-generated SDKs and Type Definitions +│ │ ├── components/ # Common UI Components (AgentSteps, Citations...) +│ │ ├── layouts/ # Page Layouts +│ │ ├── pages/ # Business Pages (Chat, Document, Eval...) +│ │ └── stores/ # State Management (Auth Store) +├── docker-compose.yml # Docker Compose Orchestration Config +└── postgres.Dockerfile # Custom PostgreSQL Image (Includes zhparser) +``` + +## 🚀 Quick Start + +This project recommends deployment using Docker, which includes all necessary dependencies (PostgreSQL, Redis, Web Services). + +### 1. Environment Preparation + +Ensure [Docker](https://www.docker.com/) and [Docker Compose](https://docs.docker.com/compose/) are installed on your machine. + +### 2. Configure Environment Variables + +Copy the `.env.example` file in the backend directory to `.env`, and modify the configuration according to actual needs: + +```bash +cd backend +cp .env.example .env +# Edit the .env file (Configure database passwords, API Keys, etc.) +``` + +### 3. Start Services + +Execute in the project root directory: + +```bash +docker-compose up -d +``` + +This command will start the following services: +* **db**: PostgreSQL Database (Port 5432) +* **redis**: Cache & Message Queue (Port 6379) +* **backend**: FastAPI Application (Default Port 8000) +* **frontend**: React Development Server (Usually 5173) + +### 4. Access the Application + +* **Frontend Interface**: `http://localhost:5173` (or the port mapped by Docker) +* **Backend API Documentation**: `http://localhost:8000/docs` + +## 📖 Usage Guide + +### 1. Upload Knowledge Base Documents +After logging into the system, enter the **Document Management** page and upload PDF, Word, or Markdown files. The system will automatically parse the text, split it into Chunks, calculate vectors, and store them in the database. + +### 2. Start Intelligent Q&A +Enter the **Conversation** page, create a new session, and input your question. The system will automatically execute the following workflow: +1. **Route**: Determine if the question requires knowledge base retrieval or casual chat. +2. **Retrieve**: If knowledge is needed, the hybrid retrieval module performs both vector search and keyword search simultaneously. +3. **Rerank**: Refine the ranking of retrieval results. +4. **Generate**: The LLM generates the final answer based on the retrieved context, including citation sources. + +### 3. Effect Evaluation +On the **Evaluation** page, you can load preset evaluation sets or custom sets. The system will use the LLM as a judgment model to score each Q&A pair (Faithfulness, Context Precision, etc.) and compile a report. + +## ⚙️ Configuration Details + +Main configuration items are located in `backend/.env`: + +* `DATABASE_URL`: PostgreSQL connection string. +* `REDIS_URL`: Redis connection string. +* `LLM_API_KEY`: LLM Provider API Key (e.g., OpenAI, DashScope). +* `EMBEDDING_API_KEY`: Embedding Model API Key. +* `COS_*`: Tencent Cloud COS Configuration (Used for storing files). +* `LANGSMITH_*`: Observability Configuration (Optional). + +## 🤝 Contribution Guide + +Issues or Pull Requests for this project are welcome. + +## 📄 License + +This project is open source under the [MIT License](https://opensource.org/licenses/MIT). \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2680b7f7efb3568aa206396506b883e45ecae4a1 --- /dev/null +++ b/README.md @@ -0,0 +1,153 @@ + + +# RAG 知识库系统 + +## 📖 项目简介 + +本项目是一个基于 **RAG (Retrieval-Augmented Generation)** 技术的知识库问答系统。它能够帮助用户管理海量文档,并通过语义搜索和关键词搜索相结合的方式,为大语言模型(LLM)提供准确、可靠的上下文信息,从而生成高质量的回答。 + +系统提供了完整的 **文档管理**、**对话管理**、**检索增强** 以及 **自动化评测** 能力,适用于企业知识库、智能客服、文档分析等多种场景。 + +## ✨ 主要功能 + +1. **文档智能入库**: + * 支持 PDF、DOCX、Markdown、HTML 等主流格式的解析。 + * 自动进行文本切分、向量化处理,并存入向量数据库。 + * 支持增量更新和失败重试机制。 +2. **混合检索 (Hybrid Retrieval)**: + * **向量检索**:基于 `pgvector` 实现语义相似度搜索。 + * **关键词检索**:基于 `zhparser` 实现中文全文检索。 + * **融合排序**:使用 RRF (Reciprocal Rank Fusion) 算法融合两种检索结果,兼顾语义和精确匹配。 +3. **Agent 路由与多步推理**: + * 内置 Query Rewriter (查询重写) 和 Router (路由) 节点。 + * 支持 `HyDE` (假设性文档嵌入) 和 Multi-Query (多查询生成) 策略。 + * 具备上下文质量判断 (`Judge Context`) 能力,可根据检索结果质量决定是否拒答或优化查询。 +4. **对话管理**: + * 支持多轮对话,保持上下文记忆。 + * 提供 **语义缓存 (Semantic Cache)** 能力,加速高频问题的响应速度。 + * 完善的答案溯源功能,可视化展示引用片段。 +5. **自动化评测 (Evaluation)**: + * 内置 Ragas 评测框架集成。 + * 支持自定义评测集 (JSONL 格式)。 + * 自动计算 Faithfulness, Answer Relevancy 等指标,并支持 Bad Case 归因分析。 +6. **权限与用户管理**: + * 基于 RBAC (Role-Based Access Control) 的权限模型。 + * 支持文档权限标签 (Permission Tags) 控制,确保数据安全。 + +## 🛠️ 技术栈 + +### 后端 (Backend) +* **语言与框架**: Python 3.11+ / FastAPI +* **ORM**: SQLAlchemy (Async) +* **任务队列**: Celery + Redis +* **数据库**: PostgreSQL 16 + * 插件: `pgvector` (向量索引), `zhparser` (中文分词) +* **可观测性**: LangSmith (可选集成), 结构化日志 +* **存储**: 支持本地存储或兼容 S3 协议的对象存储 (如腾讯云 COS) + +### 前端 (Frontend) +* **语言**: TypeScript +* **框架**: React 18 + Vite +* **UI 组件**: Ant Design (推测) +* **构建工具**: openapi-ts (基于 OpenAPI schema 自动生成 TS 类型和请求方法) + +## 📂 项目结构 + +```text +rag-knowledge-base/ +├── backend/ # FastAPI 后端服务 +│ ├── app/ +│ │ ├── api/ # API 路由 (Auth, Chat, Documents, Evaluations...) +│ │ ├── core/ # 配置、安全、Redis、日志、限流等核心模块 +│ │ ├── db/ # 数据库模型 (SQLAlchemy) 和迁移脚本 (Alembic) +│ │ ├── ingestion/ # 文档解析、切分、向量化管道 +│ │ ├── llm/ # LLM 封装、提示词工程、重写/路由/重排逻辑 +│ │ ├── retrieval/ # 向量检索器、关键词检索器、混合检索融合逻辑 +│ │ ├── services/ # 业务逻辑层 (Chat, Document, User, Evaluation) +│ │ ├── storage/ # 文件上传、对象存储客户端封装 +│ │ └── workflows/ # LangGraph 或类似的状态机图编排 +│ ├── alembic/ # 数据库迁移脚本 +│ ├── pyproject.toml # Python 依赖配置 (Ruff, Pytest, etc.) +│ └── celery_app.py # Celery 异步任务配置 +├── frontend/ # React + Vite 前端应用 +│ ├── src/ +│ │ ├── api/ # API 客户端代码 +│ │ ├── client/ # 自动生成的 SDK 和类型定义 +│ │ ├── components/ # 通用 UI 组件 (AgentSteps, Citations...) +│ │ ├── layouts/ # 页面布局 +│ │ ├── pages/ # 业务页面 (Chat, Document, Eval...) +│ │ └── stores/ # 状态管理 (Auth Store) +├── docker-compose.yml # Docker Compose 编排配置 +└── postgres.Dockerfile # 自定义 PostgreSQL 镜像 (包含 zhparser) +``` + +## 🚀 快速开始 + +本项目推荐使用 Docker 进行部署,它包含了所有必要的依赖(PostgreSQL, Redis, Web 服务)。 + +### 1. 环境准备 + +确保你的机器上安装了 [Docker](https://www.docker.com/) 和 [Docker Compose](https://docs.docker.com/compose/)。 + +### 2. 配置环境变量 + +复制后端目录下的 `.env.example` 文件为 `.env`,并根据实际情况修改配置: + +```bash +cd backend +cp .env.example .env +# 编辑 .env 文件 (配置数据库密码、API Key 等) +``` + +### 3. 启动服务 + +在项目根目录下执行: + +```bash +docker-compose up -d +``` + +此命令将启动以下服务: +* **db**: PostgreSQL 数据库 (端口 5432) +* **redis**: 缓存与消息队列 (端口 6379) +* **backend**: FastAPI 应用 (默认端口 8000) +* **frontend**: React 开发服务器 (通常在 5173) + +### 4. 访问应用 + +* **前端界面**: `http://localhost:5173` (或 Docker 映射的端口) +* **后端 API 文档**: `http://localhost:8000/docs` + +## 📖 使用指南 + +### 1. 上传知识库文档 +登录系统后,进入 **文档管理** 页面,上传 PDF、Word 或 Markdown 文件。系统会自动解析文本、切分为 Chunk,并计算向量存入数据库。 + +### 2. 开始智能问答 +进入 **对话** 页面,创建一个新的会话,输入你的问题。系统会自动执行以下流程: +1. **路由 (Route)**: 判断问题是需要检索知识库还是闲聊。 +2. **检索 (Retrieve)**: 如果需要知识,混合检索模块会同时进行向量搜索和关键词搜索。 +3. **重排 (Rerank)**: 对检索结果进行精排。 +4. **生成 (Generate)**: LLM 根据检索到的上下文生成最终答案,并附带引用来源。 + +### 3. 效果评测 +在 **评测** 页面,你可以加载预设的评测集或自定义评测集,系统会利用 LLM 作为评判模型,对每一次问答进行打分 (Faithfulness, Context Precision 等),并汇总成报表。 + +## ⚙️ 配置说明 + +主要配置项位于 `backend/.env`: + +* `DATABASE_URL`: PostgreSQL 连接字符串。 +* `REDIS_URL`: Redis 连接字符串。 +* `LLM_API_KEY`: LLM 服务商 API Key (如 OpenAI, DashScope)。 +* `EMBEDDING_API_KEY`: Embedding 模型 API Key。 +* `COS_*: 腾讯云 COS 配置 (用于存储文件)。 +* `LANGSMITH_*: 可观测性配置 (可选)。 + +## 🤝 贡献指南 + +欢迎对本项目提出 Issue 或 Pull Request。 + +## 📄 许可证 + +本项目基于 [MIT License](https://opensource.org/licenses/MIT) 开源。 \ No newline at end of file