代码知识检索增强生成服务

一个生产就绪的RAG微服务,用于通过自然语言索引和查询本地代码库,支持混合搜索、多格式文件处理和LLM集成。

  • by ChrisH1000
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 ChrisH1000/MCP-Knowledge-Base

使用说明

RAG服务器-代码知识检索增强生成

一个生产就绪的RAG(检索增强生成)微服务,用于用自然语言索引和查询本地代码库。内置FastAPI、FAISS和句子转换器。

特性

  • 🔍 混合搜索:结合语义(向量)和关键字(BM25)搜索
  • 📁 多格式支持:Python、PHP、JavaScript、TypeScript、Markdown等
  • 🤖 LLM集成:适用于OpenAI、Ollama或仅检索模式
  • 📊 增量索引:仅重新索引更改的文件
  • 🐳 Docker就绪:使用Docker和Docker compose轻松部署
  • 🔐 API密钥验证:保护您的端点
  • 📝 来源引用:所有答案都包括文件:行引用
  • 🔬 LangSmith追踪:LLM操作的内置可观察性

快速开始

地方发展

# Install dependencies
make install

# Run the server
make run

# In another terminal, build the index
make index SRC=/path/to/your/code

# Query the codebase (retrieval only)
make query Q="How does authentication work?"

# Generate LLM-powered answer (with LangSmith tracing)
make answer Q="How does authentication work?"

使用Docker

# Build and run
docker-compose up

# Build index
curl -X POST http://localhost:8000/index/build \
  -H "x-api-key: dev-secret" \
  -H "Content-Type: application/json" \
  -d '{"root":"./","clean":true}'

配置

复制 .env.example 到 .env 并配置:

# Data directories
RAG_DATA_DIR=./data
RAG_INDEX_DIR=./data/index

# File types to index
RAG_ALLOWED_FILETYPES=.py,.php,.js,.ts,.md,.mdx,.json,.yml,.yaml

# Embedding model
RAG_EMBEDDING_MODEL=sentence-transformers/all-MiniLM-L6-v2

# API Security
RAG_API_KEY=dev-secret

# LLM Provider (openai, ollama, or none)
RAG_LLM_PROVIDER=openai
OPENAI_API_KEY=sk-your-key-here
OLLAMA_ENDPOINT=http://localhost:11434
LLM_MODEL=gpt-4o-mini

# LangSmith Tracing (optional but recommended)
LANGSMITH_TRACING=true
LANGSMITH_API_KEY=lsv2_pt_your-key-here
LANGCHAIN_PROJECT=my-rag-project

API终点

健康与配置

# Health check
curl http://localhost:8000/health

# Get configuration
curl http://localhost:8000/config

索引管理

# Build index
curl -X POST http://localhost:8000/index/build \
  -H "x-api-key: dev-secret" \
  -H "Content-Type: application/json" \
  -d '{
    "root": "./",
    "clean": true,
    "patterns": ["**/*.py", "**/*.md"],
    "exclude": ["node_modules/**", ".git/**"]
  }'

# Get index stats
curl http://localhost:8000/index/stats \
  -H "x-api-key: dev-secret"

# Incremental update
curl -X POST http://localhost:8000/index/incremental \
  -H "x-api-key: dev-secret" \
  -H "Content-Type: application/json" \
  -d '{"root": "./"}'

查询与回答

# Search for relevant code (retrieval only, no LLM)
curl -X POST http://localhost:8000/query \
  -H "x-api-key: dev-secret" \
  -H "Content-Type: application/json" \
  -d '{
    "q": "Where is the file reader implemented?",
    "top_k": 8
  }'

# Or use the Make command
make query Q="Where is the file reader implemented?"

# Generate answer with LLM (creates LangSmith traces)
curl -X POST http://localhost:8000/answer \
  -H "x-api-key: dev-secret" \
  -H "Content-Type: application/json" \
  -d '{
    "q": "How does the ingestion pipeline work?",
    "top_k": 8,
    "max_tokens": 500
  }'

# Or use the Make command
make answer Q="How does the ingestion pipeline work?"

建筑

┌─────────────┐
│ Filesystem  │
│ (code+docs) │
└──────┬──────┘
       │
       ▼
┌──────────────────┐
│ Ingestion        │
│ Pipeline         │
│ - File discovery │
│ - Parsing        │
│ - Chunking       │
└──────┬───────────┘
       │
       ├──────────────────┐
       │                  │
       ▼                  ▼
┌─────────────┐   ┌──────────────┐
│ Vector      │   │ Keyword      │
│ Store       │   │ Index        │
│ (FAISS)     │   │ (BM25)       │
└──────┬──────┘   └──────┬───────┘
       │                 │
       └────────┬────────┘
                │
                ▼
        ┌───────────────┐
        │ Hybrid        │
        │ Retriever     │
        │ (RRF Fusion)  │
        └───────┬───────┘
                │
                ▼
        ┌───────────────┐
        │ LLM           │
        │ (LangChain)   │
        └───────┬───────┘
                │
                ├──────────────────┐
                │                  │
                ▼                  ▼
        ┌───────────────┐  ┌──────────────┐
        │ FastAPI       │  │ LangSmith    │
        │ Response      │  │ Tracing      │
        └───────────────┘  └──────────────┘

LangSmith可观测性

此RAG服务器包括用于LLM操作的内置LangSmith跟踪:

设置

  1. 获取LangSmith API密钥 在 smith.langchain.com

  2. 配置您的 .env:

    LANGSMITH_TRACING=true
    LANGSMITH_API_KEY=lsv2_pt_your-key-here
    LANGCHAIN_PROJECT=my-rag-project
    
    # Must also configure an LLM provider
    RAG_LLM_PROVIDER=openai
    OPENAI_API_KEY=sk-your-openai-key
    
  3. 重新启动服务器 -您将看到: langsmith_enabled project=my-rag-project

什么被追踪

当你使用 /answer 端点(或 make answer),LangSmith自动捕获:

  • 📝 发送给LLM的完整提示(包括检索到的上下文)
  • 🤖 LLM回复
  • ⏱️ 令牌使用和延迟
  • ❌ 错误和异常
  • 🔗 请求元数据

注: 这 /query 端点不使用LLM,因此不会创建跟踪。

查看痕迹

  1. 首选 smith.langchain.com
  2. 导航到您的项目(例如,“我的抹布项目”)
  3. 查看每个LLM调用的详细跟踪!

有关更多详细信息,请参阅 LANGSMITH_TRACING_GUIDE.md

建筑

┌─────────────┐
│ Filesystem  │
│ (code+docs) │
└──────┬──────┘
       │
       ▼
┌──────────────────┐
│ Ingestion        │
│ Pipeline         │
│ - File discovery │
│ - Parsing        │
│ - Chunking       │
└──────┬───────────┘
       │
       ├──────────────────┐
       │                  │
       ▼                  ▼
┌─────────────┐   ┌──────────────┐
│ Vector      │   │ Keyword      │
│ Store       │   │ Index        │
│ (FAISS)     │   │ (BM25)       │
└──────┬──────┘   └──────┬───────┘
       │                 │
       └────────┬────────┘
                │
                ▼
        ┌───────────────┐
        │ Hybrid        │
        │ Retriever     │
        │ (RRF Fusion)  │
        └───────┬───────┘
                │
                ▼
        ┌───────────────┐
        │ LLM           │
        │ (Optional)    │
        └───────┬───────┘
                │
                ▼
        ┌───────────────┐
        │ FastAPI       │
        │ Response      │
        └───────────────┘

项目结构

rag-server/
├── src/
│   ├── rag_server/
│   │   ├── api/
│   │   │   ├── routes_admin.py    # Health & config endpoints
│   │   │   ├── routes_index.py    # Index management
│   │   │   └── routes_query.py    # Query & answer
│   │   ├── core/
│   │   │   ├── config.py          # Settings management
│   │   │   ├── schemas.py         # Pydantic models
│   │   │   └── logging.py         # Structured logging
│   │   ├── ingest/
│   │   │   ├── readers.py         # File discovery
│   │   │   ├── parsers.py         # Code/doc parsing
│   │   │   ├── chunking.py        # Text chunking
│   │   │   └── pipeline.py        # Ingestion orchestration
│   │   ├── search/
│   │   │   ├── vector_store.py    # FAISS vector search
│   │   │   ├── keyword_index.py   # BM25 keyword search
│   │   │   └── retriever.py       # Hybrid retrieval
│   │   ├── llm/
│   │   │   ├── openai_client.py   # OpenAI integration
│   │   │   ├── ollama_client.py   # Ollama integration
│   │   │   └── prompt_templates.py# Grounding prompts
│   │   └── server.py              # FastAPI app
│   └── main.py                    # Entry point
├── tests/
├── Dockerfile
├── docker-compose.yml
├── Makefile
├── pyproject.toml
└── README.md

发展

# Install dev dependencies
uv pip install -e ".[dev]"

# Run tests
pytest -v

# Lint code
ruff check .

# Format code
ruff format .

# Type check
mypy src

发出命令

# Show all available commands
make help

# Install dependencies
make install

# Run the server
make run

# Build index for a directory
make index SRC=/path/to/code PATTERNS='["**/*.py","**/*.js"]'

# Quick index for PHP servers (example)
make index-php

# Query without LLM (fast retrieval only)
make query Q="your question here"

# Answer with LLM (creates LangSmith traces)
make answer Q="your question here"

# Run tests
make test

# Lint and format
make lint
make format

# Clean build artifacts
make clean

发展

# Install dev dependencies
uv pip install -e ".[dev]"

# Run tests
pytest -v

# Lint code
ruff check .

# Format code
ruff format .

# Type check
mypy src

查询示例

在代码库中尝试以下示例查询:

  • “数据库连接在哪里配置?”
  • “显示处理用户身份验证的所有函数”
  • “缓存层是如何工作的?”
  • “有什么副作用 process_data 功能?"
  • “解释API速率限制的实施”

演出

  • 索引:SSD上>5 MB/s
  • 查询延迟:<800ms P95(温指数)
  • 记忆:典型代码库小于2 GB
  • 索引大小:每块约1.5 KB

许可证

MIT许可证-请参阅许可证文件

贡献

欢迎投稿!拜托:

  1. 分叉回购
  2. 创建要素分支
  3. 添加新功能的测试
  4. 提交拉取请求

致谢

内置: