架构与模块
分层总览
app/
├── main.py FastAPI 入口:lifespan、路由注册、异常处理器、/health、/admin
├── config.py Settings(pydantic-settings,35 个键,环境变量注入)
├── api/ 接口层
│ ├── deps.py session 鉴权依赖(get_current_user / require_admin)
│ ├── response.py ok() / error() / ApiError
│ └── v1/ search / document / auth / knowledge / settings(未注册)
├── core/ 业务逻辑(检索、入库、总结、分类、切分、用户、会话)
├── services/ 外部服务客户端(Qdrant / Redis / Ollama / LLM / Reranker)
├── models/ Pydantic 数据模型
├── static/ admin.html(单文件旧版后台)
└── utils/ 空包(仅 __init__.py)
各模块职责
api 层
| 文件 |
职责 |
关键内容 |
app/main.py |
应用装配 |
lifespan 里 QdrantService().ensure_collections() 与 ensure_default_admin(),两者失败都只记日志不阻断启动;注册 4 个 router;三个异常处理器:ApiError→原码、RequestValidationError→1001、Exception→2000 |
app/api/response.py |
统一响应 |
ok(data)→{"code":0,"data":...,"message":"ok"};error(code,msg)→data=None |
app/api/deps.py |
session 鉴权 |
_parse_bearer→_resolve_user→get_current_user→require_admin;UserStore/SessionStore 模块级懒加载;Redis 不可达时先同步 ping() 再决定降级内存 |
app/api/v1/search.py |
检索接口 |
_retriever 懒加载单例;_cache_key = `sha256(query |
app/api/v1/document.py |
文档接口 |
5 条路由;_ingester/_qdrant/_task_manager 懒加载单例;任务管理器构造时传 Settings() |
app/api/v1/auth.py |
认证与用户 |
9 条路由;5 个请求模型;_public_user() 脱敏(去 password_hash/salt) |
app/api/v1/knowledge.py |
类目与统计 |
_get_taxonomy() 带 @lru_cache(maxsize=1);统计分页 100 条聚合 L1 类目 |
app/api/v1/settings.py |
运行时配置 |
未被 main.py 注册,代码存在但不可达 |
core 层
| 文件 |
职责 |
关键实现 |
retriever.py |
分层检索编排 |
L1→L2→L3→chunk,_search_collection() 按集合是否支持 sparse 选择 hybrid/dense |
query_parser.py |
query 解析与路由 |
LLM 出 JSON,_validate_categories() 丢弃非 taxonomy 类目与越界置信度;decide_route() 为纯函数 |
summarizer.py |
三级总结 |
MIN_TEXT_LENGTH_FOR_L3=500 硬编码;L2 优先标题树 |
classifier.py |
文档分类 |
LLM JSON → CategoryResult;标签清洗最多 3 个 |
chunker.py |
分块 |
标题 section + 长度二次切分 + 段落累加 + 硬切 |
headings.py |
标题树 |
ATX / 第X章节篇 / 中文序号 / 数字编号 |
sparse.py |
稀疏编码 |
CJK bigram + 英文整词,blake2b 哈希到 2**18 |
ranker.py |
融合与截断 |
rrf_fuse(k=60)、finalize() |
ingestion.py |
入库流水线 |
总结→分类→切分→批量 embedding→写四层;IngestionError 携带 stage 与已产出 summary |
ingest_tasks.py |
异步任务 |
内存注册表 + Redis 镜像;asyncio.Semaphore(ingest_max_concurrency) 限流 |
dedup.py |
去重策略 |
none / sha256 / simhash(全表扫描海明距离) |
embeddings.py |
嵌入 |
OpenAI SDK 或 Ollama /api/embed;维度不符仅告警 |
file_parser.py |
多格式解析 |
txt/md/html/pdf/docx 插件化;PDF 文本层空时 OCR 降级 |
result_summarizer.py |
结果总结 |
取前 result_summary_max_hits 条拼接上下文 |
runtime_settings.py |
运行时配置 |
持久化 ./data/runtime_settings.json,原子写(临时文件 + rename) |
auth.py |
JWT 认证 |
bcrypt + PyJWT;Redis 键 auth:user:{username} |
users.py |
用户存储 |
PBKDF2-SHA256(100000 轮)+ 16 字节 salt;Redis 键 user:{username} |
sessions.py |
会话存储 |
session:{token},TTL 43200s,token = secrets.token_hex(32) |
services 层
| 文件 |
职责 |
容错行为 |
qdrant.py |
集合初始化、四层 upsert、dense/hybrid 检索、scroll、删除 |
无容错:异常向上抛,由 API 层转 2000 |
redis.py |
JSON 缓存 get_json/set_json |
全操作 try/except,失败降级为未命中 / 写入失败 |
ollama.py |
/api/generate(json_mode 加 format=json)、/api/tags 探活 |
异常抛出,由调用方决定降级 |
llm.py |
LLM 抽象:OllamaLLMClient / OpenAICompatibleLLMClient |
进程级客户端缓存,配置更新时 invalidate_llm_client_cache() |
reranker.py |
调 Ollama /api/rerank 打分 |
上层 try/except,失败退化为 RRF 顺序 |
models 层
| 文件 |
模型 |
search.py |
SearchRequest(query/top_k/summarize)、SearchHit、ExtractedInfo、SearchResponse |
document.py |
SummaryLevel(L3/L2.5)、DocumentSummary、DocumentInput、ChunkModel、IngestionResult |
knowledge.py |
TaxonomyCategory、CategoryResult、UNCATEGORIZED、load_taxonomy() |
auth.py |
LoginRequest、RegisterRequest(未被使用)、AuthUser、StoredUser、TokenResponse(未被使用) |
鉴权依赖(两套并存)
| 维度 |
app/api/deps.py(auth.py 使用) |
app/core/auth.py(document.py 使用) |
| 凭证 |
服务端 session token |
JWT |
| token 形态 |
secrets.token_hex(32),64 位 hex |
jwt.encode({"sub","role","iat","exp"}) |
| 存储 |
Redis session:{token},TTL 43200s |
无状态;用户画像在 Redis auth:user:{username} |
| 用户存储 |
app/core/users.py,user:{username},PBKDF2 |
core/auth.UserStore,auth:user:{username},bcrypt |
| 依赖函数 |
get_current_user / require_admin |
get_current_user / require_admin |
| 错误码 |
1005 未认证、1006 权限不足、2001 存储不可用 |
1003 未提供凭证、1005 token 无效、1006 权限不足 |
两者互不识别:/auth/login 签发的是 session token,/documents* 却用 JWT 验签,因此登录拿到的 token 无法调用文档接口。详见 已知限制与未实现。
统一响应封装
# app/api/response.py
def ok(data): return {"code": 0, "data": data, "message": "ok"}
def error(code, message): return {"code": code, "data": None, "message": message}
| 场景 |
处理位置 |
输出 |
| 正常返回 |
各端点 return ok(...) |
code=0 |
| 业务异常 |
ApiError 处理器 |
code=异常自带码 |
| 参数校验失败 |
RequestValidationError 处理器 |
code=1001,message 拼第一条 msg |
| 未捕获异常 |
Exception 处理器 |
code=2000,message 固定「服务器内部错误」 |
| 例外 |
/api/v1/health |
裸 {"status":"ok"},不套 ok() |
注意:HTTP 状态码只用于 202(入库)与 404(框架级,非统一包装),其余业务错误仍是 HTTP 200 + 非 0 code。
请求在系统中的流转
检索 POST /api/v1/search
Router(search.py)
→ RedisCache.get_json("search:<sha16>") 命中 → 直接返回缓存
→ Retriever.search(SearchRequest) 未命中 → 走检索
→ QueryParser.parse_and_route() LLM 解析 + 纯函数路由(结果缓存 qparse:<sha16>)
→ EmbeddingService.embed([query_text]) dense 向量
→ SparseEncoder.encode(query_text) sparse 向量(sparse_enabled=true)
→ QdrantService.search_hybrid / search_dense L1 → L2 → L3 → chunks
→ RerankerService.rerank() 失败退化
→ ResultSummarizer.summarize() 仅 summarize=true
→ ok(response.model_dump()) 并 set_json 回写缓存
入库 POST /api/v1/documents
Router(document.py) → AuthUser(get_current_user) → 空文本校验
→ IngestTaskManager.submit(doc)
→ DedupStrategy.lookup(text) 命中 → 直接 done + deduplicated=true
→ 登记 pending → asyncio.create_task(_run)
→ Semaphore(ingest_max_concurrency) 内执行 Ingester.ingest()
summarizing → classifying → embedding → writing
→ 成功写 result / 失败写 error{stage,message,partial_summary}
→ 每次状态迁移 _mirror_to_redis(ingest_task:{task_id}, ttl)
→ 202 {"task_id": ..., "status": "pending"}