Files
md-vector-db/CLAUDE.md
T

94 lines
4.1 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# CLAUDE.md
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
## 项目概述
Markdown 文档向量数据库 — 将 .md 文件分块 → 嵌入 → 存入 ChromaDB,通过 FastAPI HTTP 或 CLI 提供语义检索。
## 常用命令
```bash
uv sync # 安装依赖
uv run pytest tests/ -v # 全部测试 (46 个)
uv run pytest tests/test_api.py -v # 单个测试模块
uv run pytest tests/ -v -k "test_search" # 按名称过滤
# CLI(所有命令支持 --config/-c 指定配置文件)
uv run python -m src.cli.main ingest <file.md>
uv run python -m src.cli.main ingest-dir ./md_docs/
uv run python -m src.cli.main search "关键词" -k 5
uv run python -m src.cli.main stats
uv run python -m src.cli.main serve --port 8000
```
## 架构
```
core/ # 核心逻辑(不依赖 server/cli
├── config.py # YAML → dataclass, load_dotenv() 加载 .env
├── db.py # VectorDB: 线程安全的 ChromaDB 封装
├── embedder.py # 策略模式: LocalEmbedder / OpenAIEmbedder / DashscopeEmbedder
├── ingest.py # MarkdownSplitter(混合分块) + DocumentIngestor(分批嵌入)
└── search.py # Searcher: 语义检索 + 源文件管理
server/ # FastAPI HTTP 层
├── app.py # Depends(get_state) 依赖注入, 速率限制中间件
├── deps.py # AppState: 集中管理 db/embedder/searcher/ingestor
└── auth.py # API Key 认证 (MD_VECTOR_API_KEY) + 速率限制器
cli/main.py # Typer CLI5 个命令 + --config 选项
```
**数据流**: MD 文件 → `MarkdownSplitter.split()``batch_embed()``ChromaDB collection.add()``Searcher.search()`
**依赖方向**: `config``db``embedder``ingest`/`search``server`/`cli`
## 关键实现细节
### 嵌入 Provider 架构 (embedder.py)
策略模式,接口 `Embedder(Protocol)`:
| Provider | 类 | API 格式 | 默认模型 |
|----------|-----|---------|----------|
| `local` | `LocalEmbedder` | sentence-transformers | BAAI/bge-small-zh-v1.5 |
| `openai` | `OpenAIEmbedder` | OpenAI 兼容 | text-embedding-3-small |
| `dashscope` | `DashscopeEmbedder` | 阿里云自定义 HTTP | text-embedding-v4 |
`config.api_base` / `config.model` 可覆盖默认值。`batch_embed()` 分批嵌入(每批 32 条)防 OOM。本地模型未缓存时自动通过 `hf-mirror.com` 下载。
### 线程安全 (db.py + ingest.py + search.py)
`VectorDB._write_lock` (`threading.Lock`) 保护所有写操作(`collection.add` / `delete` / `get+delete`)。
### 认证与安全 (auth.py + app.py)
- **API Key**: 环境变量 `MD_VECTOR_API_KEY``verify_api_key` 依赖注入到 ingest/search/delete 端点;未设置则跳过
- **速率限制**: `RateLimiter` 中间件,默认 60s 窗口内最多 30 请求
- **路径遍历防护**: `_is_safe_path()` 拒绝绝对路径和 `..` 穿越
- **错误信息**: 500 返回通用消息,详细错误记入 `logger.exception`
### 配置系统 (config.py)
`config.py` 顶部 `load_dotenv()` 自动加载 `.env``EMBED_API_KEY` 从环境变量读取。`DEFAULT_CONFIG_PATH = "config.yaml"` 统一引用。
### 服务层 (deps.py + app.py)
`AppState` 类集中管理 `db`/`embedder`/`searcher`/`ingestor` 单例。端点通过 `FastAPI Depends(get_state)` 获取,可测试、可替换。`is_healthy()` 真实验证 ChromaDB 和 Embedder 可用性。
## 配置
`config.yaml` + `.env` 联合控制。复制 `.env.example``.env` 填入密钥。
## HTTP API
| 方法 | 路径 | 认证 | 说明 |
|------|------|------|------|
| GET | `/` | - | 重定向到 /docs |
| GET | `/api/v1/health` | - | 真实健康检查 (ChromaDB + Embedder) |
| GET | `/api/v1/collections` | - | 集合和源文件列表 |
| POST | `/api/v1/ingest` | API Key | 入库 (file_path 或 content+file_name) |
| POST | `/api/v1/search` | API Key | 语义检索 (query + top_k 1-100) |
| DELETE | `/api/v1/documents/{file_name}` | API Key | 按文件名删除 |