Files
SuperBizAgent-java/mvp/architecture/knowledge-retrieval-architecture.md
zhuyongxin 36abfc4675 docs(mvp): 添加知识库检索架构和使用文档
新增文档:
- mvp/architecture/knowledge-retrieval-architecture.md
  * 架构位置和数据流说明
  * L0+L1 混合检索流程图
  * 核心组件详细设计
  * 与现有架构的集成方式
  * 性能指标和可观测性

- mvp/architecture/knowledge-retrieval-usage.md
  * 快速开始指南
  * 文档格式要求和最佳实践
  * 使用场景和示例
  * 故障排查和性能优化
  * 维护知识库的完整流程

更新文档:
- mvp/README.md - 添加知识库检索文档入口

完善 MVP 架构文档,为后续开发和维护提供完整参考
2026-06-24 16:26:15 +08:00

410 lines
10 KiB
Markdown
Raw Permalink 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.
# 知识库检索架构说明
## 一、架构位置
知识库检索是 Agent 工具层的一部分,为所有 Agent 提供知识查询能力。
```
Agent 层
├── Supervisor Agent
├── Planner Agent
├── SubAgents (ExternalApi, InternalError, Database...)
└── Verifier Agent
↓ 调用
工具层 (Tools)
├── searchDoc (文档检索 - L1 向量检索)
├── lookup_knowledge (混合检索 - L0+L1) ← 新增
├── queryLogs (日志查询)
├── queryTrace (链路追踪)
└── queryOrder (订单查询)
↓ 依赖
服务层 (Services)
├── VectorSearchService (L1 语义检索 - Milvus)
├── KnowledgeIndexService (L0 精确匹配 - 内存) ← 新增
├── FrontmatterParser (元数据解析) ← 新增
└── DocumentManagementService (文档管理)
↓ 持久化
数据层
├── MySQL (api_document + metadata 字段) ← 增强
├── Milvus (向量索引)
└── Local Files (knowledge_base/) ← 新增
```
---
## 二、L0+L1 混合检索架构
### 2.1 检索流程
```
Agent 调用 lookup_knowledge(query)
↓
┌─────────────────────────────────────────┐
│ LookupKnowledgeTool │
│ (工具入口) │
└────────────┬────────────────────────────┘
│
↓
┌────────────────┐
│ Step 1: L0 精确匹配 │ < 10ms
│ (内存索引) │
└────────┬───────────┘
│
┌───────┴────────┐
│ │
唯一匹配 多个/零个匹配
│ │
↓ ↓
高置信度 低置信度
(不调用L1) (调用L1补充)
│ │
│ ┌──────────────────┐
│ │ Step 2: L1 语义检索 │ 200-500ms
│ │ (Milvus) │
│ └──────────┬─────────┘
│ │
└────────┬───────────┘
↓
┌─────────────────────┐
│ Step 3: 组装结果 │
│ primary + supplement │
└─────────────────────┘
↓
返回给 Agent
```
### 2.2 数据流
```
文档上传流程:
POST /api/documents/upload
↓
DocumentManagementService.uploadDocument()
↓
1. 文本提取
2. 保存原始文件 → knowledge_base/{category}/{filename}
3. 解析 frontmatter (FrontmatterParser)
4. 分块 → 向量化 → Milvus 索引 (L1)
5. 元数据存 MySQL (metadata 字段 JSON)
6. 更新 L0 内存索引 (KnowledgeIndexService)
↓
完成
文档查询流程:
Agent 调用 lookup_knowledge("ERR_TIMEOUT")
↓
KnowledgeIndexService.exactMatch()
↓
遍历内存索引 (keywords 精确匹配)
↓
找到唯一匹配 → 读取本地文件 (前 2000 字符)
↓
返回 primary (高置信度)
```
---
## 三、核心组件说明
### 3.1 FrontmatterParser
**职责**:解析 Markdown 文件头的 YAML frontmatter
**输入**:
```markdown
---
title: 支付网关错误码定义
keywords: [ERR_TIMEOUT, 超时, 支付网关]
summary: 记录了支付网关所有核心错误码的含义及排查方向
category: api
---
# 正文内容
```
**输出**:
```java
Frontmatter {
title: "支付网关错误码定义",
keywords: ["ERR_TIMEOUT", "超时", "支付网关"],
summary: "...",
category: "api"
}
```
### 3.2 KnowledgeIndexService
**职责**:维护 L0 内存索引,提供精确关键词匹配
**核心方法**:
- `@PostConstruct loadIndex()` - 启动时扫描 knowledge_base/
- `exactMatch(String query)` - 精确匹配(不区分大小写)
- `readDocument(String filePath, int maxChars)` - 读取文档内容
- `addToIndex(KnowledgeEntry entry)` - 添加到索引
- `removeFromIndex(String filePath)` - 从索引移除
**数据结构**:
```java
List<KnowledgeEntry> knowledgeIndex = new CopyOnWriteArrayList<>();
KnowledgeEntry {
filePath: "knowledge_base/api/payment-errors.md",
title: "支付网关错误码定义",
keywords: ["ERR_TIMEOUT", "超时", "支付网关"],
summary: "...",
category: "api"
}
```
### 3.3 LookupKnowledgeTool
**职责**:L0+L1 混合检索工具,Agent 可调用
**工具定义**:
```java
@Tool(description = "查询知识库文档。优先精确匹配关键词,未命中或多个匹配时自动补充语义相关片段。" +
"参数 query: 查询关键词,例如 'ERR_TIMEOUT'、'支付网关超时'")
public LookupResult lookupKnowledge(String query)
```
**返回格式**:
```json
{
"found": true,
"primary": {
"content": "文档内容(前 2000 字符)",
"source": "knowledge_base/api/payment-errors.md",
"matchType": "exact_L0",
"confidence": "high"
},
"supplement": {
"content": "语义相关片段(L1)",
"source": "metadata",
"matchType": "semantic_L1"
}
}
```
---
## 四、与现有架构的集成
### 4.1 Agent 使用场景
**ExternalApiSubAgent** (接口专家):
```
诊断步骤:
1. 提取错误码(如 "ERR_TIMEOUT")
2. 调用 lookup_knowledge("ERR_TIMEOUT")
3. 获得完整错误码定义和排查方向
4. 结合日志/链路追踪进行分析
```
**DatabaseSubAgent** (数据库专家):
```
诊断步骤:
1. 识别数据库问题(如 "连接池满")
2. 调用 lookup_knowledge("HikariCP")
3. 获得连接池配置最佳实践
4. 提供优化建议
```
**Planner Agent** (规划者):
```
规划阶段:
1. 分析问题类型
2. 调用 lookup_knowledge("故障诊断")
3. 获得标准诊断流程
4. 制定排查策略
```
### 4.2 与现有工具对比
| 工具 | 检索方式 | 响应时间 | 适用场景 | 置信度 |
|------|---------|---------|---------|--------|
| searchDoc | L1 语义检索 | 200-500ms | 模糊查询、语义理解 | 依赖相似度 |
| lookup_knowledge | L0+L1 混合 | < 10ms (高置信) | 精确关键词 + 语义补充 | high/low |
**推荐使用策略**:
- 已知精确关键词(错误码、配置项)→ `lookup_knowledge`
- 模糊描述、需要语义理解 → `searchDoc`
---
## 五、数据库变更
### 5.1 api_document 表增强
**新增字段**:
```sql
ALTER TABLE api_document
ADD COLUMN metadata TEXT COMMENT 'Frontmatter 元数据 (JSON)';
```
**字段说明**:
- 类型:TEXT(最大 64KB)
- 格式:JSON 字符串
- 内容:frontmatter 解析结果
**示例数据**:
```json
{
"title": "支付网关错误码定义",
"keywords": ["ERR_TIMEOUT", "超时", "支付网关"],
"summary": "记录了支付网关所有核心错误码的含义及排查方向",
"category": "api",
"version": "1.0",
"author": "zhangsan"
}
```
### 5.2 filePath 字段用途变更
**原用途**:存储相对路径或 URL
**新用途**:存储本地文件绝对路径
```
knowledge_base/api/payment-errors.md
knowledge_base/infrastructure/redis-config.md
```
**用途**:
1. L0 索引读取完整文档
2. 支持未来的章节锚点功能
---
## 六、配置说明
### 6.1 application.yml 新增配置
```yaml
knowledge:
base-path: knowledge_base/
```
**说明**:
- 相对于项目根目录
- 启动时递归扫描此目录
- 建议按 category 组织子目录
### 6.2 目录结构规范
```
knowledge_base/
├── api/ # API 相关文档
│ └── payment-errors.md
├── infrastructure/ # 基础设施配置
│ ├── redis-config.md
│ ├── mysql-connection-pool.md
│ └── flyway-best-practices.md
├── domain/ # 领域知识
│ └── spring-ai-tool-best-practices.md
└── troubleshooting/ # 故障排查
└── fault-diagnosis-process.md
```
---
## 七、性能指标
### 7.1 查询性能
| 场景 | L0 耗时 | L1 耗时 | 总耗时 |
|------|---------|---------|--------|
| 唯一匹配(高置信) | < 5ms | 0 (不调用) | < 10ms |
| 多个匹配(低置信) | < 5ms | 200-500ms | < 500ms |
| 未匹配(仅L1) | < 5ms | 200-500ms | < 500ms |
### 7.2 索引性能
| 指标 | 实测值 | 目标值 |
|------|--------|--------|
| 启动扫描时间 | < 20ms (6 个文档) | < 1s (500 个文档) |
| 内存占用 | < 1MB (6 个文档) | < 5MB (500 个文档) |
| L0 匹配时间 | < 5ms | < 10ms |
---
## 八、可观测性
### 8.1 日志追踪
所有查询都带 requestId(8 位 UUID),可追踪完整流程:
```
[a1b2c3d4] 收到知识库查询请求: query=ERR_TIMEOUT
[a1b2c3d4] L0精确匹配完成: matches=1, time=2ms
[a1b2c3d4] 置信度判断: highConfidence=true, reason=唯一匹配
[a1b2c3d4] L0唯一匹配,跳过L1检索
[a1b2c3d4] 查询完成: found=true, confidence=high, totalTime=5ms
```
### 8.2 关键指标
**监控指标**:
- L0 查询耗时(P50/P95/P99)
- L1 调用频率(低置信度比例)
- 查询总耗时(端到端)
- 高置信度命中率
**告警阈值**:
- 查询总耗时 > 2s
- L0 索引加载失败
- 高置信度命中率 < 20%
---
## 九、限制与注意事项
### 9.1 MVP 阶段限制
1. **L0 索引无持久化**
- 应用重启需要重新扫描
- 缓解:启动扫描通常 < 1s
2. **章节锚点未实现**
- sectionTitle 参数预留
- availableSections 返回 null
3. **批量导入不支持**
- 当前仅支持单文件上传
### 9.2 最佳实践
1. **编写高质量 frontmatter**
- keywords 精准且全面
- 避免关键词重复(导致多匹配)
2. **知识库目录组织**
- 按 category 分类
- 文件命名语义化
3. **监控告警配置**
- 慢查询告警
- L0 索引加载失败告警
---
## 十、后续增强方向(Phase 2)
1. **章节锚点**
- 支持 sectionTitle 参数
- 直接定位到文档特定章节
2. **L0 索引持久化**
- 序列化到文件
- 避免重启扫描
3. **批量导入工具**
- 支持目录批量导入
- 进度监控
4. **知识库管理 API**
- CRUD 接口
- 在线编辑
5. **向量化元数据**
- title/summary 也参与 L1 检索
- 提升语义检索准确度