LocalGPT 贡献指南:从开发环境搭建到代码提交流程的完整实践
【免费下载链接】localGPTChat with your documents on your local device using GPT models. No data leaves your device and 100% private.项目地址: https://gitcode.com/GitHub_Trending/lo/localGPT
本文是 LocalGPT(私有文档智能平台)的贡献者实践指南,围绕 CONTRIBUTING.md 的完整脉络展开:从开发环境搭建、分支工作流、代码规范,到测试策略、问题上报与发布流程。结合仓库内的 启动器、健康检查、主配置 等真实源码,给出可直接复制运行的命令与参数说明。读完本文,你将掌握为 LocalGPT 贡献代码的完整路径,包括如何本地启动整套 RAG 系统、如何用 health check 验证改动、如何编写符合项目规范的测试,以及如何提交一份高质量的 Pull Request。
一、项目定位与贡献者前置准备
LocalGPT 是一个"在本地设备上使用 GPT 模型与文档对话"的私有文档智能平台:数据不出设备、100% 本地私有化运行。其代码库由 Python 后端(backend/、rag_system/)与 Next.js/React 前端(src/)两部分组成,同时提供 Docker 部署方案(docker-compose.yml)。
在开始贡献前,请先确认以下前置条件已满足:
| 前置条件 | 说明(以项目实际测试版本为准) |
|---|---|
| Python 3.8+ | 项目测试环境使用 3.11.5 |
| Node.js 16+ | 项目测试环境使用 23.10.0 |
| Git | 版本管理与 PR 流程必需 |
| Ollama | 本地 AI 模型服务,用于本地推理与 embedding |
说明:CONTRIBUTING.md 中的命令示例(如
ollama pull qwen3:0.6b/qwen3:8b)与仓库配置保持一致——rag_system/main.py 中OLLAMA_CONFIG默认generation_model为qwen3:8b、enrichment_model为qwen3:0.6b,run_system.py 的ensure_models()也会在启动时自动检查并拉取这两个模型。
二、开发环境搭建(Quick Start)
1. Fork 与 Clone
# Fork 仓库后克隆自己的副本 git clone https://github.com/YOUR_USERNAME/multimodal_rag.git cd multimodal_rag # 添加上游远程仓库,用于同步主仓库更新 git remote add upstream https://github.com/PromtEngineer/multimodal_rag.git2. 安装依赖
# 安装 Python 依赖(后端 + RAG 系统) pip install -r requirements.txt # 安装 Node.js 依赖(前端) npm install # 安装 Ollama 并拉取本地模型 curl -fsSL https://ollama.ai/install.sh | sh ollama pull qwen3:0.6b ollama pull qwen3:8b从仓库看,Python 依赖被拆分为多个文件:requirements.txt(根级)、rag_system/requirements.txt(RAG 核心)、backend/requirements.txt(后端服务)与 requirements-docker.txt(Docker 场景)。本地开发以根级requirements.txt为主。
前端依赖位于 package.json:Next.js 15.3.3、React 19、TypeScript 5,以及class-variance-authority、lucide-react、react-markdown等 UI 库。安装后可用npm run dev启动开发服务器。
3. 验证环境
# 运行健康检查(6 项检查:导入、配置、数据库访问、Agent 初始化、Embedding 模型、样例查询) python system_health_check.py # 以开发模式启动整套系统 python run_system.py --mode dev健康检查脚本 system_health_check.py 依次验证:基础导入是否成功、配置是否一致、LanceDB 数据库是否能访问、Agent 是否能初始化、Embedding 模型维度(384 维 bge-small 兼容或 1024 维 Qwen3 兼容)以及真实样例查询。
统一启动器 run_system.py 会按依赖顺序启动四个服务并做实时日志聚合与进程监控:
| 服务 | 启动命令 | 端口 | 说明 |
|---|---|---|---|
| Ollama | ollama serve | 11434 | 本地模型服务(必需) |
| RAG API | python -m rag_system.api_server | 8001 | RAG 检索与生成 API |
| Backend | python backend/server.py | 8000 | 后端业务服务 |
| Frontend | npm run dev(dev)/npm run start(prod) | 3000 | Next.js 前端(可选) |
启动器支持的参数:--mode dev|prod、--logs-only、--no-frontend、--health、--stop;日志统一写入logs/目录(system.log与各服务独立日志),进程异常退出时每 30 秒检测并自动重启必需服务。
三、开发工作流(Development Workflow)
1. 分支策略
项目采用 feature branch 工作流:
main:生产就绪代码docker:Docker 部署特性与文档feature/*:新功能fix/*:Bug 修复docs/*:文档更新
2. 标准提交流程
# 更新 main 分支 git checkout main git pull upstream main # 创建功能分支 git checkout -b feature/your-feature-name # 编写代码并测试(见后文"测试策略") # 提交(建议遵循 Conventional Commits 风格) git add . git commit -m "feat: add new feature description" # 推送并创建 Pull Request git push origin feature/your-feature-name3. 提交前自检清单
# 运行健康检查 python system_health_check.py # 运行测试(仓库测试位于 tests/ 目录,用 pytest 执行) python -m pytest tests/ -v # 验证系统集成 python run_system.py --health需要注意:CONTRIBUTING.md 中的测试命令是通用示例,当前仓库的测试文件实际分布在 backend/test_backend.py、backend/test_ollama_connectivity.py 以及根目录的 test_docker_build.sh、test_markdown_streaming.js 等。请以仓库实际测试文件为准执行。
四、贡献类型与协作方式
Bug 修复
- 先检索已有 issues,避免重复提交
- 提供可复现步骤
- 编写回归测试防止问题复发
新功能
- 实现前先在 issues 中讨论方案
- 遵循现有架构模式(模块化、低耦合,见下文"文件组织")
- 包含完整测试并更新文档
文档改进
- 修正拼写与表述、补充示例与用例
- 更新 API 文档、改进安装/使用指南
测试贡献
- 单元测试、集成测试、性能基准
- 覆盖边界情况
五、编码规范(Coding Standards)
1. Python 规范:PEP 8 + 项目约定
项目在 PEP 8 基础上强调三件事:类型注解、描述性变量名、dataclass 结构化数据:
# 使用类型注解 def process_document(file_path: str, config: Dict[str, Any]) -> ProcessingResult: """Process a document with the given configuration. Args: file_path: Path to the document file config: Processing configuration dictionary Returns: ProcessingResult object with metadata and chunks """ pass # 使用描述性变量名 embedding_model_name = "Qwen/Qwen3-Embedding-0.6B" retrieval_results = retriever.search(query, top_k=20) # 使用 dataclass 组织结构化配置 @dataclass class IndexingConfig: embedding_batch_size: int = 50 enable_late_chunking: bool = True chunk_size: int = 512这些约定与真实源码一致:rag_system/main.py 中PIPELINE_CONFIGS["default"]的indexing段即使用embedding_batch_size: 50;run_system.py 的ServiceConfig也以 dataclass 形式定义。embedding 模型默认值Qwen/Qwen3-Embedding-0.6B同样来自 EXTERNAL_MODELS(1024 维,fresh start 基线),另有answerdotai/answerai-colbert-small-v1作为 ColBERT 重排序模型。
2. TypeScript/React 规范
// 使用 TypeScript 接口 interface ChatMessage { id: string; content: string; role: 'user' | 'assistant'; timestamp: Date; sources?: DocumentSource[]; } // 使用函数组件 + Hooks const ChatInterface: React.FC<ChatProps> = ({ sessionId }) => { const [messages, setMessages] = useState<ChatMessage[]>([]); const handleSendMessage = useCallback(async (content: string) => { // Implementation }, [sessionId]); return ( <div className="chat-interface"> {/* Component JSX */} </div> ); };仓库前端采用 Next.js App Router(src/app)与函数式组件写法,如 IndexWizard.tsx 使用useState管理文件、chunk size(默认 512)、chunk overlap(默认 64)与 embedding 模型选择等状态。
3. 文件组织约定
rag_system/ ├── agent/ # ReAct agent 实现(loop.py、verifier.py) ├── indexing/ # 文档处理与索引(contextualizer、embedders、graph_extractor 等) ├── retrieval/ # 检索组件(retrievers、query_transformer) ├── pipelines/ # 端到端流水线(indexing_pipeline、retrieval_pipeline) ├── rerankers/ # 重排序实现(reranker、sentence_pruner) └── utils/ # 共享工具(batch_processor、logging_utils、ollama_client 等) src/ ├── components/ # React 组件(ui/ 子目录含通用 UI 组件) ├── lib/ # 工具函数与 API 客户端(api.ts、types.ts、utils.ts) └── app/ # Next.js App Router 页面六、测试规范(Testing Guidelines)
单元测试示例
# Test file: tests/test_embeddings.py import pytest from rag_system.indexing.embedders import HuggingFaceEmbedder def test_embedding_generation(): embedder = HuggingFaceEmbedder("sentence-transformers/all-MiniLM-L6-v2") embeddings = embedder.create_embeddings(["test text"]) assert embeddings.shape[0] == 1 assert embeddings.shape[1] == 384 # Model dimension assert embeddings.dtype == np.float32说明:上述测试代码是 CONTRIBUTING.md 中的通用示例。当前仓库的实际 embedding 实现位于 rag_system/indexing/embedders.py,其中
VectorIndexer在写入 LanceDB 前会过滤 NaN/Inf 向量(on_bad_vectors兜底策略),并校验 chunk 与 embedding 数量一致、在 metadata 中保留original_text——编写 embedding 相关测试时可参考这些行为约定。
集成测试示例
# Test file: tests/test_integration.py def test_end_to_end_indexing(): """Test complete document indexing pipeline.""" agent = get_agent("test") result = agent.index_documents(["test_document.pdf"]) assert result.success assert len(result.indexed_chunks) > 0get_agent(mode)工厂函数定义于 rag_system/main.py:根据LLM_BACKEND环境变量选择 Ollama 或 WatsonX 后端,再从PIPELINE_CONFIGS(default/fast等)取出对应配置构造Agent。
前端测试示例
// Test file: src/components/__tests__/ChatInterface.test.tsx import { render, screen, fireEvent } from '@testing-library/react'; import { ChatInterface } from '../ChatInterface'; test('sends message when form is submitted', async () => { render(<ChatInterface sessionId="test-session" />); const input = screen.getByPlaceholderText('Type your message...'); const button = screen.getByRole('button', { name: /send/i }); fireEvent.change(input, { target: { value: 'test message' } }); fireEvent.click(button); expect(screen.getByText('test message')).toBeInTheDocument(); });当前仓库的 API 测试示例可参考 backend/test_backend.py 与 backend/test_ollama_connectivity.py,分别覆盖后端接口与 Ollama 连通性验证。
七、文档编写规范(Documentation Standards)
代码文档要求写出完整 docstring:功能描述、Args、Returns、Raises、Example 五要素齐全。
def create_index( documents: List[str], config: IndexingConfig, progress_callback: Optional[Callable[[float], None]] = None ) -> IndexingResult: """Create a searchable index from documents. This function processes documents through the complete indexing pipeline: 1. Text extraction and chunking 2. Embedding generation 3. Vector database storage 4. BM25 index creation Args: documents: List of document file paths to index config: Indexing configuration with model settings and parameters progress_callback: Optional callback function for progress updates Returns: IndexingResult containing success status, metrics, and any errors Raises: IndexingError: If document processing fails ModelLoadError: If embedding model cannot be loaded Example: >>> config = IndexingConfig(embedding_batch_size=32) >>> result = create_index(["doc1.pdf", "doc2.pdf"], config) >>> print(f"Indexed {result.chunk_count} chunks") """API 文档建议直接使用 FastAPI/OpenAPI 风格注解:
@app.post("/chat", response_model=ChatResponse) async def chat_endpoint(request: ChatRequest) -> ChatResponse: """Chat with indexed documents. Send a natural language query and receive an AI-generated response based on the indexed document collection. - **query**: The user's question or prompt - **session_id**: Chat session identifier - **search_type**: Type of search (vector, hybrid, bm25) - **retrieval_k**: Number of documents to retrieve Returns a response with the AI-generated answer and source documents. """仓库的 RAG API 服务实现在 rag_system/api_server.py 与 rag_system/api_server_with_progress.py(后者带进度跟踪),详细接口说明见 Documentation/api_reference.md。
八、开发工具链(Development Tools)
1. 推荐的 VS Code 扩展
{ "recommendations": [ "ms-python.python", "ms-python.pylint", "ms-python.black-formatter", "bradlc.vscode-tailwindcss", "esbenp.prettier-vscode", "ms-vscode.vscode-typescript-next" ] }2. Pre-commit 钩子
# 安装 pre-commit pip install pre-commit # 设置钩子 pre-commit install # 手动运行 pre-commit run --all-files3. 常用开发脚本
# Python 侧 python -m pylint rag_system/ # Lint python -m black rag_system/ # 格式化 python -m mypy rag_system/ # 类型检查 # TypeScript 侧 npm run lint # Lint(package.json 中定义为 next lint) npm run format # 格式化九、问题上报(Issue Reporting)
Bug 报告模板
环境信息
- OS: macOS 13.4 - Python: 3.11.5 - Node.js: 23.10.0 - Ollama: 0.9.5复现步骤
1. Start system with `python run_system.py` 2. Upload document via web interface 3. Ask question "What is this document about?" 4. Error occurs during response generation预期行为 vs 实际行为
错误信息与日志(可使用
tail -f logs/*.log查看运行日志)截图(如适用)
Feature 请求模板
- Use Case:为什么需要该功能?
- Proposed Solution:应该如何工作?
- Alternatives:考虑过哪些替代方案?
- Additional Context:相关示例或参考资料
十、发布流程(Release Process)
版本号规范
采用语义化版本(SemVer):MAJOR.MINOR.PATCH
- Major:破坏性变更
- Minor:新功能(向后兼容)
- Patch:Bug 修复
发布检查清单
- 所有测试通过
- 文档已更新
- 相关文件版本号已升级
- Changelog 已更新
- Docker 镜像已构建并测试(可参考 Dockerfile.backend、Dockerfile.frontend、Dockerfile.rag-api 与 docker-compose.yml)
- 发布说明已准备
十一、社区规范与项目优先级
社区行为准则
- 互相尊重、包容多元
- 聚焦建设性反馈
- 帮助他人学习成长
- 保持专业沟通
当前重点方向
- 性能优化:提升索引与检索速度
- 模型支持:增加更多 embedding 与生成模型
- 用户体验:增强 Web 界面
- 文档完善:改进安装与使用指南
- 测试扩展:扩大测试覆盖率
架构目标
- 模块化:组件松耦合
- 可扩展:易于接入新模型与新功能
- 高性能:优化速度与内存占用
- 可靠性:健壮的错误处理与恢复
- 隐私性:用户数据安全且全部本地化
十二、延伸阅读
以下文档可帮助你更深入地理解代码库结构,贡献前建议通读:
- Documentation/architecture_overview.md:RAG 系统架构总览
- Documentation/api_reference.md:API 参考
- Documentation/deployment_guide.md:部署指南
- DOCKER_TROUBLESHOOTING.md:Docker 排障手册
- Documentation/quick_start.md:快速上手
- Documentation/indexing_pipeline.md:索引流水线详解
在动手提交代码前,请先查阅已有文档、搜索既有 issues,必要时新建带question标签的 issue 寻求帮助。预祝贡献愉快!
【免费下载链接】localGPTChat with your documents on your local device using GPT models. No data leaves your device and 100% private.项目地址: https://gitcode.com/GitHub_Trending/lo/localGPT
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考