510 lines
15 KiB
Markdown
510 lines
15 KiB
Markdown
# 适配器架构设计
|
||
|
||
<cite>
|
||
**本文档引用的文件**
|
||
- [base.py](file://backend/app/workers/platforms/base.py)
|
||
- [kimi.py](file://backend/app/workers/platforms/kimi.py)
|
||
- [wenxin.py](file://backend/app/workers/platforms/wenxin.py)
|
||
- [citation_engine.py](file://backend/app/workers/citation_engine.py)
|
||
- [scheduler.py](file://backend/app/workers/scheduler.py)
|
||
- [queries.py](file://backend/app/api/queries.py)
|
||
- [query.py](file://backend/app/models/query.py)
|
||
- [main.py](file://backend/app/main.py)
|
||
- [platforms.ts](file://frontend/lib/platforms.ts)
|
||
- [platform-chart.tsx](file://frontend/components/charts/platform-chart.tsx)
|
||
</cite>
|
||
|
||
## 目录
|
||
1. [简介](#简介)
|
||
2. [项目结构](#项目结构)
|
||
3. [核心组件](#核心组件)
|
||
4. [架构概览](#架构概览)
|
||
5. [详细组件分析](#详细组件分析)
|
||
6. [依赖关系分析](#依赖关系分析)
|
||
7. [性能考虑](#性能考虑)
|
||
8. [故障排除指南](#故障排除指南)
|
||
9. [结论](#结论)
|
||
|
||
## 简介
|
||
|
||
本项目采用适配器模式设计了一个可扩展的AI平台查询系统。该架构通过统一的接口抽象,实现了对不同AI平台(如Kimi、文心一言等)的无缝集成和切换。适配器模式在此场景中的应用价值体现在:
|
||
|
||
- **统一接口**:为不同的AI平台提供一致的查询接口
|
||
- **可扩展性**:轻松添加新的AI平台适配器
|
||
- **资源管理**:统一的资源清理和生命周期管理
|
||
- **错误处理**:标准化的异常处理和重试机制
|
||
|
||
## 项目结构
|
||
|
||
该项目采用前后端分离的架构设计,后端使用Python FastAPI框架,前端使用Next.js React框架。适配器架构主要集中在后端的workers目录中。
|
||
|
||
```mermaid
|
||
graph TB
|
||
subgraph "前端层"
|
||
FE[前端应用<br/>Next.js React]
|
||
PC[平台图表组件<br/>platform-chart.tsx]
|
||
PL[平台映射<br/>platforms.ts]
|
||
end
|
||
subgraph "后端层"
|
||
API[FastAPI API]
|
||
CE[CitationEngine<br/>引用检测引擎]
|
||
SCH[Scheduler<br/>调度器]
|
||
subgraph "适配器层"
|
||
BA[BasePlatformAdapter<br/>抽象基类]
|
||
KA[KimiAdapter<br/>Kimi适配器]
|
||
WA[WenxinAdapter<br/>文心一言适配器]
|
||
end
|
||
end
|
||
subgraph "数据层"
|
||
DB[(PostgreSQL数据库)]
|
||
QM[Query模型]
|
||
CRM[CitationRecord模型]
|
||
end
|
||
FE --> API
|
||
API --> CE
|
||
CE --> SCH
|
||
CE --> BA
|
||
BA --> KA
|
||
BA --> WA
|
||
CE --> DB
|
||
QM --> DB
|
||
CRM --> DB
|
||
```
|
||
|
||
**图表来源**
|
||
- [main.py:13-22](file://backend/app/main.py#L13-L22)
|
||
- [citation_engine.py:148-157](file://backend/app/workers/citation_engine.py#L148-L157)
|
||
- [base.py:4-17](file://backend/app/workers/platforms/base.py#L4-L17)
|
||
|
||
**章节来源**
|
||
- [main.py:1-48](file://backend/app/main.py#L1-L48)
|
||
- [platforms.ts:1-18](file://frontend/lib/platforms.ts#L1-L18)
|
||
|
||
## 核心组件
|
||
|
||
### BasePlatformAdapter 抽象基类
|
||
|
||
BasePlatformAdapter是整个适配器架构的核心抽象类,定义了所有AI平台适配器必须实现的标准接口。
|
||
|
||
#### 设计理念
|
||
|
||
该类采用了Python的ABC(Abstract Base Classes)机制,确保子类必须实现指定的抽象方法。设计理念包括:
|
||
|
||
- **最小接口原则**:只定义必要的抽象方法,避免过度设计
|
||
- **职责单一原则**:专注于平台适配功能,不包含业务逻辑
|
||
- **扩展性优先**:为未来添加新平台预留空间
|
||
|
||
#### 核心属性
|
||
|
||
| 属性名称 | 类型 | 描述 | 示例值 |
|
||
|---------|------|------|--------|
|
||
| platform_name | str | 平台标识符,用于内部识别 | "kimi", "wenxin" |
|
||
| platform_url | str | 平台官方网站地址 | "https://kimi.moonshot.cn" |
|
||
|
||
#### 抽象方法
|
||
|
||
**query(keyword: str) -> str**
|
||
- **设计目的**:在AI平台上查询关键词并返回原始响应文本
|
||
- **参数规范**:
|
||
- keyword: str - 要查询的关键词
|
||
- 返回值: str - AI平台的原始响应文本
|
||
- **实现要求**:必须异步实现,支持重试机制
|
||
|
||
**close()**
|
||
- **设计目的**:清理适配器使用的系统资源
|
||
- **实现要求**:异步方法,确保资源正确释放
|
||
|
||
**章节来源**
|
||
- [base.py:4-17](file://backend/app/workers/platforms/base.py#L4-L17)
|
||
|
||
### 具体适配器实现
|
||
|
||
#### KimiAdapter
|
||
|
||
KimiAdapter是针对Moonshot AI平台的适配器实现,具有以下特点:
|
||
|
||
- **浏览器自动化**:使用Playwright进行页面交互
|
||
- **智能重试**:指数退避重试机制
|
||
- **稳定性保障**:超时处理和异常恢复
|
||
|
||
#### WenxinAdapter
|
||
|
||
WenxinAdapter是针对百度文心一言平台的适配器实现:
|
||
|
||
- **相似架构**:与KimiAdapter类似的实现模式
|
||
- **平台特定**:针对文心一言的界面结构优化
|
||
- **一致性保证**:保持与BasePlatformAdapter的接口兼容
|
||
|
||
**章节来源**
|
||
- [kimi.py:11-206](file://backend/app/workers/platforms/kimi.py#L11-L206)
|
||
- [wenxin.py:11-205](file://backend/app/workers/platforms/wenxin.py#L11-L205)
|
||
|
||
## 架构概览
|
||
|
||
整个系统采用分层架构设计,适配器模式位于中间层,向上提供统一接口,向下封装具体实现细节。
|
||
|
||
```mermaid
|
||
sequenceDiagram
|
||
participant Client as 客户端
|
||
participant API as FastAPI API
|
||
participant Engine as CitationEngine
|
||
participant Adapter as BasePlatformAdapter
|
||
participant Platform as AI平台
|
||
Client->>API : 发起查询请求
|
||
API->>Engine : execute_query()
|
||
Engine->>Engine : 创建BrandMatcher
|
||
Engine->>Adapter : execute_single_platform()
|
||
Adapter->>Adapter : query(keyword)
|
||
Adapter->>Platform : 执行平台查询
|
||
Platform-->>Adapter : 返回响应文本
|
||
Adapter-->>Engine : 返回原始响应
|
||
Engine->>Engine : 品牌匹配和竞争检测
|
||
Engine-->>API : 返回检测结果
|
||
API-->>Client : 返回查询结果
|
||
```
|
||
|
||
**图表来源**
|
||
- [citation_engine.py:159-234](file://backend/app/workers/citation_engine.py#L159-L234)
|
||
- [base.py:10-17](file://backend/app/workers/platforms/base.py#L10-L17)
|
||
|
||
## 详细组件分析
|
||
|
||
### CitationEngine 引用检测引擎
|
||
|
||
CitationEngine是系统的中央协调器,负责管理多个平台适配器并执行完整的查询流程。
|
||
|
||
#### 核心功能
|
||
|
||
1. **平台管理**:维护平台适配器字典
|
||
2. **查询执行**:协调单个平台的查询过程
|
||
3. **结果处理**:整合品牌匹配和竞争检测结果
|
||
4. **任务跟踪**:管理查询任务的状态和历史
|
||
|
||
#### 关键流程
|
||
|
||
```mermaid
|
||
flowchart TD
|
||
Start([开始查询]) --> InitMatcher["初始化BrandMatcher"]
|
||
InitMatcher --> GetPlatforms["获取平台列表"]
|
||
GetPlatforms --> LoopPlatforms{"遍历平台"}
|
||
LoopPlatforms --> CreateTask["创建或获取QueryTask"]
|
||
CreateTask --> UpdateStatus["更新任务状态为running"]
|
||
UpdateStatus --> ExecutePlatform["执行单个平台查询"]
|
||
ExecutePlatform --> BrandMatch["品牌匹配检测"]
|
||
BrandMatch --> CompetitorDetect["竞争品牌检测"]
|
||
CompetitorDetect --> CreateRecord["创建CitationRecord"]
|
||
CreateRecord --> UpdateTaskSuccess["更新任务状态为success"]
|
||
UpdateTaskSuccess --> NextPlatform{"还有平台吗?"}
|
||
NextPlatform --> |是| LoopPlatforms
|
||
NextPlatform --> |否| UpdateQueryTime["更新查询时间字段"]
|
||
UpdateQueryTime --> End([结束])
|
||
ExecutePlatform --> |异常| CreateFailedRecord["创建失败记录"]
|
||
CreateFailedRecord --> UpdateTaskFailed["更新任务状态为failed"]
|
||
UpdateTaskFailed --> NextPlatform
|
||
```
|
||
|
||
**图表来源**
|
||
- [citation_engine.py:159-234](file://backend/app/workers/citation_engine.py#L159-L234)
|
||
- [citation_engine.py:236-266](file://backend/app/workers/citation_engine.py#L236-L266)
|
||
|
||
#### 数据模型
|
||
|
||
```mermaid
|
||
erDiagram
|
||
QUERY {
|
||
uuid id PK
|
||
uuid user_id FK
|
||
string keyword
|
||
string target_brand
|
||
jsonb brand_aliases
|
||
jsonb platforms
|
||
string frequency
|
||
string status
|
||
datetime last_queried_at
|
||
datetime next_query_at
|
||
datetime created_at
|
||
datetime updated_at
|
||
}
|
||
CITATION_RECORD {
|
||
uuid id PK
|
||
uuid query_id FK
|
||
string platform
|
||
boolean cited
|
||
integer citation_position
|
||
text citation_text
|
||
jsonb competitor_brands
|
||
text raw_response
|
||
datetime created_at
|
||
datetime updated_at
|
||
}
|
||
QUERY_TASK {
|
||
uuid id PK
|
||
uuid query_id FK
|
||
string platform
|
||
string status
|
||
datetime started_at
|
||
datetime completed_at
|
||
text error_message
|
||
datetime created_at
|
||
datetime updated_at
|
||
}
|
||
USER ||--o{ QUERY : creates
|
||
QUERY ||--o{ CITATION_RECORD : generates
|
||
QUERY ||--o{ QUERY_TASK : tracks
|
||
```
|
||
|
||
**图表来源**
|
||
- [query.py:11-55](file://backend/app/models/query.py#L11-L55)
|
||
- [citation_engine.py:19-120](file://backend/app/workers/citation_engine.py#L19-L120)
|
||
|
||
**章节来源**
|
||
- [citation_engine.py:148-309](file://backend/app/workers/citation_engine.py#L148-L309)
|
||
- [query.py:11-55](file://backend/app/models/query.py#L11-L55)
|
||
|
||
### Scheduler 调度器
|
||
|
||
QueryScheduler负责定时执行查询任务,确保系统能够自动运行。
|
||
|
||
#### 核心特性
|
||
|
||
- **定时执行**:每小时检查一次到期的查询任务
|
||
- **异步处理**:使用AsyncIOScheduler支持异步操作
|
||
- **错误隔离**:单个查询失败不影响其他任务
|
||
- **优雅关闭**:提供资源清理机制
|
||
|
||
#### 生命周期管理
|
||
|
||
```mermaid
|
||
stateDiagram-v2
|
||
[*] --> 初始化
|
||
初始化 --> 启动 : start()
|
||
启动 --> 运行中 : 添加定时任务
|
||
运行中 --> 执行检查 : 每小时触发
|
||
执行检查 --> 处理查询 : 发现到期任务
|
||
处理查询 --> 运行中 : 继续监控
|
||
处理查询 --> 错误 : 异常处理
|
||
错误 --> 运行中 : 记录日志继续
|
||
运行中 --> 关闭 : shutdown()
|
||
关闭 --> [*]
|
||
```
|
||
|
||
**图表来源**
|
||
- [scheduler.py:25-95](file://backend/app/workers/scheduler.py#L25-L95)
|
||
|
||
**章节来源**
|
||
- [scheduler.py:25-95](file://backend/app/workers/scheduler.py#L25-L95)
|
||
|
||
### 前端集成
|
||
|
||
前端系统提供了完整的用户界面,支持平台选择和结果展示。
|
||
|
||
#### 平台映射
|
||
|
||
前端使用PLATFORM_MAP和PLATFORMS常量来管理平台信息:
|
||
|
||
| 平台键 | 中文名称 | 用途 |
|
||
|--------|----------|------|
|
||
| wenxin | 文心一言 | 百度AI平台 |
|
||
| kimi | Kimi | Moonshot AI平台 |
|
||
| tongyi | 通义千问 | 阿里云AI平台 |
|
||
| baidu_ai | 百度AI搜索 | 百度搜索服务 |
|
||
| yuanbao | 腾讯元宝 | 腾讯AI平台 |
|
||
| qingyan | 智谱清言 | 智谱AI平台 |
|
||
|
||
#### 图表可视化
|
||
|
||
平台图表组件使用Recharts库展示各平台的引用率统计:
|
||
|
||
```mermaid
|
||
graph LR
|
||
subgraph "数据处理"
|
||
RAW[原始统计数据]
|
||
TRANSFORM[数据转换]
|
||
end
|
||
subgraph "可视化组件"
|
||
CHART[柱状图]
|
||
XAXIS[X轴: 平台名称]
|
||
YAXIS[Y轴: 引用率百分比]
|
||
TOOLTIP[工具提示]
|
||
end
|
||
RAW --> TRANSFORM
|
||
TRANSFORM --> CHART
|
||
CHART --> XAXIS
|
||
CHART --> YAXIS
|
||
CHART --> TOOLTIP
|
||
```
|
||
|
||
**图表来源**
|
||
- [platform-chart.tsx:34-68](file://frontend/components/charts/platform-chart.tsx#L34-L68)
|
||
- [platforms.ts:1-18](file://frontend/lib/platforms.ts#L1-L18)
|
||
|
||
**章节来源**
|
||
- [platforms.ts:1-18](file://frontend/lib/platforms.ts#L1-L18)
|
||
- [platform-chart.tsx:1-68](file://frontend/components/charts/platform-chart.tsx#L1-L68)
|
||
|
||
## 依赖关系分析
|
||
|
||
### 组件依赖图
|
||
|
||
```mermaid
|
||
graph TB
|
||
subgraph "外部依赖"
|
||
PW[Playwright]
|
||
APS[APScheduler]
|
||
SQLA[SQLAlchemy]
|
||
FAST[FastAPI]
|
||
end
|
||
subgraph "核心模块"
|
||
BASE[BasePlatformAdapter]
|
||
KIMI[KimiAdapter]
|
||
WENXIN[WenxinAdapter]
|
||
CE[CitationEngine]
|
||
SCH[QueryScheduler]
|
||
API[FastAPI API]
|
||
end
|
||
subgraph "数据模型"
|
||
QUERY[Query模型]
|
||
CITE[CitationRecord模型]
|
||
TASK[QueryTask模型]
|
||
end
|
||
PW --> KIMI
|
||
PW --> WENXIN
|
||
APS --> SCH
|
||
SQLA --> CE
|
||
FAST --> API
|
||
BASE --> KIMI
|
||
BASE --> WENXIN
|
||
CE --> BASE
|
||
API --> CE
|
||
CE --> QUERY
|
||
CE --> CITE
|
||
CE --> TASK
|
||
```
|
||
|
||
**图表来源**
|
||
- [kimi.py:4-6](file://backend/app/workers/platforms/kimi.py#L4-L6)
|
||
- [wenxin.py:4-6](file://backend/app/workers/platforms/wenxin.py#L4-L6)
|
||
- [scheduler.py:13-20](file://backend/app/workers/scheduler.py#L13-L20)
|
||
- [citation_engine.py:7-14](file://backend/app/workers/citation_engine.py#L7-L14)
|
||
|
||
### 耦合度分析
|
||
|
||
该系统展现了良好的内聚性和低耦合性:
|
||
|
||
- **高内聚**:每个适配器专注于单一平台的实现
|
||
- **低耦合**:通过抽象基类实现松散耦合
|
||
- **清晰边界**:各层职责明确,接口清晰
|
||
- **可测试性**:依赖注入和抽象接口便于单元测试
|
||
|
||
**章节来源**
|
||
- [base.py:4-17](file://backend/app/workers/platforms/base.py#L4-L17)
|
||
- [citation_engine.py:148-157](file://backend/app/workers/citation_engine.py#L148-L157)
|
||
|
||
## 性能考虑
|
||
|
||
### 异步编程模型
|
||
|
||
系统全面采用异步编程模式,提升了并发处理能力:
|
||
|
||
- **异步适配器**:所有适配器方法都使用async/await
|
||
- **异步数据库**:使用SQLAlchemy异步会话
|
||
- **异步调度**:APScheduler的异步版本
|
||
- **异步HTTP**:FastAPI的异步路由
|
||
|
||
### 资源管理策略
|
||
|
||
```mermaid
|
||
flowchart TD
|
||
InitBrowser["初始化浏览器"] --> UseBrowser["使用浏览器"]
|
||
UseBrowser --> CloseBrowser["关闭浏览器"]
|
||
CloseBrowser --> CleanupResources["清理系统资源"]
|
||
CleanupResources --> End([资源释放完成])
|
||
InitBrowser --> Error["异常发生"]
|
||
Error --> CleanupOnError["异常时清理资源"]
|
||
CleanupOnError --> End
|
||
```
|
||
|
||
**图表来源**
|
||
- [kimi.py:17-31](file://backend/app/workers/platforms/kimi.py#L17-L31)
|
||
- [kimi.py:198-206](file://backend/app/workers/platforms/kimi.py#L198-L206)
|
||
|
||
### 缓存和重试机制
|
||
|
||
- **指数退避**:最多3次重试,间隔呈指数增长
|
||
- **超时控制**:页面加载和操作都有超时限制
|
||
- **资源池化**:浏览器实例复用,减少启动开销
|
||
|
||
## 故障排除指南
|
||
|
||
### 常见问题及解决方案
|
||
|
||
#### Playwright浏览器问题
|
||
|
||
**症状**:启动浏览器失败,提示需要安装Playwright浏览器
|
||
|
||
**解决方案**:
|
||
1. 安装Playwright浏览器:`python -m playwright install chromium`
|
||
2. 检查网络连接和代理设置
|
||
3. 确认Docker环境中的浏览器可用性
|
||
|
||
#### 页面元素定位失败
|
||
|
||
**症状**:无法找到输入框或发送按钮
|
||
|
||
**解决方案**:
|
||
1. 检查平台URL是否正确
|
||
2. 更新选择器表达式以适应页面变化
|
||
3. 实现更健壮的元素等待机制
|
||
|
||
#### 超时问题
|
||
|
||
**症状**:页面加载或响应超时
|
||
|
||
**解决方案**:
|
||
1. 增加超时时间配置
|
||
2. 检查网络连接稳定性
|
||
3. 实现重试机制
|
||
|
||
**章节来源**
|
||
- [kimi.py:27-31](file://backend/app/workers/platforms/kimi.py#L27-L31)
|
||
- [kimi.py:116-118](file://backend/app/workers/platforms/kimi.py#L116-L118)
|
||
- [wenxin.py:27-31](file://backend/app/workers/platforms/wenxin.py#L27-L31)
|
||
|
||
### 调试技巧
|
||
|
||
1. **启用详细日志**:查看适配器的详细执行过程
|
||
2. **检查数据库状态**:验证查询任务的状态更新
|
||
3. **监控资源使用**:观察浏览器进程和内存使用情况
|
||
4. **测试独立适配器**:单独测试某个平台的适配器
|
||
|
||
## 结论
|
||
|
||
该适配器架构设计成功地实现了以下目标:
|
||
|
||
### 架构优势
|
||
|
||
1. **高度可扩展**:新增平台只需实现BasePlatformAdapter接口
|
||
2. **统一管理**:通过CitationEngine集中管理所有平台
|
||
3. **资源优化**:统一的资源管理和清理机制
|
||
4. **错误处理**:完善的异常处理和重试机制
|
||
|
||
### 最佳实践建议
|
||
|
||
1. **遵循接口契约**:严格实现BasePlatformAdapter的所有抽象方法
|
||
2. **资源管理**:确保close()方法能够正确清理所有资源
|
||
3. **错误处理**:实现适当的异常处理和重试逻辑
|
||
4. **配置管理**:将平台特定的配置参数化
|
||
5. **测试覆盖**:为新适配器编写充分的单元测试
|
||
|
||
### 扩展指南
|
||
|
||
要为新平台创建适配器,需要:
|
||
|
||
1. 继承BasePlatformAdapter类
|
||
2. 设置platform_name和platform_url属性
|
||
3. 实现query()方法的平台特定逻辑
|
||
4. 实现close()方法清理资源
|
||
5. 在CitationEngine中注册新适配器
|
||
6. 编写相应的测试用例
|
||
|
||
该架构为AI平台集成提供了一个稳健、可扩展的基础,能够支持未来更多的平台集成需求。 |