使用说明
AI代理MCP-项目流程文档
🏗️ 架构概述
该项目实现了 干净+六边形架构 和 MCP(模型上下文协议) 人工智能操作的集成。
📊 高级系统流
┌─────────────────────────────────────────────────────────────────────┐
│ USER INTERACTION │
└────────────┬────────────────────────────────────────────┬────────────┘
│ │
▼ ▼
┌────────────────┐ ┌──────────────────┐
│ FastAPI │ │ MCP Server │
│ REST API │ │ (Tool Server) │
└────────┬───────┘ └────────┬─────────┘
│ │
│ │
▼ ▼
┌─────────────────────────────────────────────────────────────────┐
│ PRESENTATION LAYER (API Routes) │
│ • /ai/chat • /email/send-ai │
│ • /charts/generate • /pdf/extract │
│ • /health • /pdf/analyze │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ APPLICATION LAYER (Use Cases) │
│ • SendEmailUseCase │
│ • GenerateChartUseCase │
│ • ProcessPDFUseCase │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ DOMAIN LAYER (Business Logic) │
│ • Email Entity & Repository Interface │
│ • Chart Entity & Repository Interface │
│ • PDF Entity & Repository Interface │
│ • AI Service Interface │
└────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ INFRASTRUCTURE LAYER (Implementations) │
│ • QwenAIService (Hugging Face) │
│ • EmailService (SMTP) │
│ • ChartService (Plotly) │
│ • PDFService (PyPDF/pdfplumber) │
└─────────────────────────┬────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────────┐
│ EXTERNAL SERVICES │
│ • Hugging Face API (Llama 3.2) │
│ • SMTP Server (Gmail) │
│ • File System (Charts/PDFs) │
└─────────────────────────────────────────────────────────────────┘
🔄 详细请求流
1️⃣ AI聊天流
graph TD
A[User sends POST /ai/chat] --> B[API Route Handler]
B --> C{Validate Request}
C -->|Invalid| D[Return 422 Error]
C -->|Valid| E[Extract prompt & context]
E --> F[QwenAIService.generate_response]
F --> G[Initialize InferenceClient]
G --> H[Format as chat messages]
H --> I[Call Hugging Face API]
I --> J{API Response}
J -->|Error| K[Log error & raise HTTPException]
J -->|Success| L[Extract response text]
L --> M[Return AIChatResponse]
M --> N[User receives AI response]
代码路径:
User Request
↓
src/presentation/api/routes/ai.py::chat()
↓
src/infrastructure/services/ai_service.py::QwenAIService.generate_response()
↓
huggingface_hub.InferenceClient.chat_completion()
↓
Hugging Face Router API (meta-llama/Llama-3.2-3B-Instruct)
↓
Response → User
2️⃣ 电子邮件发送流程(AI增强)
graph TD
A[User POST /email/send-ai] --> B[Email Route Handler]
B --> C[Extract recipient, subject, template]
C --> D[QwenAIService.generate_response]
D --> E[AI generates email body]
E --> F[SendEmailUseCase.execute]
F --> G[Create Email Entity]
G --> H[EmailService.send]
H --> I[Connect to SMTP Server]
I --> J{SMTP Authentication}
J -->|Fail| K[Return Error]
J -->|Success| L[Send Email via SMTP]
L --> M[Return Success Response]
代码路径:
POST /email/send-ai
↓
src/presentation/api/routes/email.py::send_email_with_ai()
↓
src/infrastructure/services/ai_service.py::generate_response()
↓
src/application/use_cases/send_email.py::SendEmailUseCase.execute()
↓
src/domain/entities/email.py::Email (entity created)
↓
src/infrastructure/services/email_service.py::EmailService.send()
↓
aiosmtplib → SMTP Server
3️⃣ 图表生成流程
graph TD
A[User POST /charts/generate] --> B[Chart Route Handler]
B --> C[Extract chart_type, data, config]
C --> D[GenerateChartUseCase.execute]
D --> E[Create Chart Entity]
E --> F[ChartService.generate]
F --> G{Chart Type?}
G -->|bar| H[Plotly Bar Chart]
G -->|line| I[Plotly Line Chart]
G -->|pie| J[Plotly Pie Chart]
G -->|scatter| K[Plotly Scatter Plot]
H --> L[Apply styling & config]
I --> L
J --> L
K --> L
L --> M[Export as PNG/HTML/JSON]
M --> N[Save to output/charts/]
N --> O[Return chart path & base64]
代码路径:
POST /charts/generate
↓
src/presentation/api/routes/charts.py::generate_chart()
↓
src/application/use_cases/generate_chart.py::GenerateChartUseCase.execute()
↓
src/domain/entities/chart.py::Chart (entity)
↓
src/infrastructure/services/chart_service.py::ChartService.generate()
↓
plotly.graph_objects → Chart file
4️⃣ PDF处理流程
graph TD
A[User POST /pdf/extract] --> B[PDF Route Handler]
B --> C[Receive uploaded PDF file]
C --> D[Save to temp directory]
D --> E[ProcessPDFUseCase.execute]
E --> F[Create PDF Entity]
F --> G[PDFService.extract_text]
G --> H[pdfplumber opens PDF]
H --> I[Extract text from all pages]
I --> J[Count pages, chars, words]
J --> K[Return extracted content]
L[User POST /pdf/analyze] --> M[PDF Analyze Handler]
M --> N[Extract text via PDFService]
N --> O[QwenAIService.generate_response]
O --> P[AI analyzes PDF content]
P --> Q[Return analysis + metadata]
代码路径(提取):
POST /pdf/extract
↓
src/presentation/api/routes/pdf.py::extract_pdf()
↓
src/application/use_cases/process_pdf.py::ProcessPDFUseCase.execute()
↓
src/domain/entities/pdf.py::PDF (entity)
↓
src/infrastructure/services/pdf_service.py::PDFService.extract_text()
↓
pdfplumber → Text extraction
代码路径(AI分析):
POST /pdf/analyze
↓
src/presentation/api/routes/pdf.py::analyze_pdf()
↓
src/infrastructure/services/pdf_service.py::extract_text()
↓
src/infrastructure/services/ai_service.py::generate_response()
↓
Hugging Face API → AI Analysis
5️⃣ MCP服务器流
graph TD
A[MCP Client connects] --> B[MCP Server initialized]
B --> C[List available tools]
C --> D{Tool requested}
D -->|send_email| E[EmailService]
D -->|generate_chart| F[ChartService]
D -->|process_pdf| G[PDFService]
D -->|ai_chat| H[QwenAIService]
E --> I[Execute operation]
F --> I
G --> I
H --> I
I --> J[Return result to MCP client]
可用MCP工具:
send_email-通过SMTP发送电子邮件generate_chart-创建可视化process_pdf-提取/分析PDFai_chat-与AI模型交互
🗂️ 层职责
1.域层 (src/domain/)
- 目的: 核心业务逻辑,独立于框架
- 组件:
- 实体:
Email,Chart,PDF - 接口:
IEmailRepository,IChartRepository,IPDFRepository,IAIService
- 实体:
- 规则: 无外部依赖,纯业务逻辑
2.应用层 (src/application/)
- 目的: 编排用例,协调领域对象
- 组件:
SendEmailUseCase-电子邮件发送工作流GenerateChartUseCase-图表创建工作流程ProcessPDFUseCase-PDF处理工作流程
- 规则: 使用域接口,无基础结构详细信息
3.基础设施层 (src/infrastructure/)
- 目的: 实现与具体技术的接口
- 组件:
QwenAIService-拥抱面部整合EmailService-SMTP实现ChartService-精心实施PDFService-PDF库实现Settings-配置管理
- 规则: 依赖于域接口,实现它们
4.表示层 (src/presentation/)
- 目的: 处理HTTP请求,公开API
- 组件:
- FastAPI应用程序
- API路线:
/ai,/email,/charts,/pdf,/health - 请求/响应模型(Pydantic)
- 规则: 薄层,委托给应用层
🔌 依赖注入流程
main.py
↓
Initialize FastAPI app
↓
Load Settings from .env
↓
Initialize Services:
• QwenAIService(api_key, model)
• EmailService(smtp_config)
• ChartService()
• PDFService()
↓
Initialize Use Cases:
• SendEmailUseCase(email_service)
• GenerateChartUseCase(chart_service)
• ProcessPDFUseCase(pdf_service)
↓
Register API Routes
↓
Start Uvicorn Server (0.0.0.0:8000)
🌐 API终结点摘要
| 端点 | 方法 | 目的 | 人工智能增强 |
|---|---|---|---|
/health |
GET | 健康检查 | ❌ |
/ai/chat |
POST | 与AI聊天 | ✅ |
/email/send |
POST | 发送普通电子邮件 | ❌ |
/email/send-ai |
POST | 人工智能生成的电子邮件 | ✅ |
/charts/generate |
POST | 创建图表 | ❌ |
/pdf/extract |
POST | 提取PDF文本 | ❌ |
/pdf/analyze |
POST | 人工智能PDF分析 | ✅ |
🔐 配置流程
.env file
↓
Load via python-dotenv
↓
Pydantic Settings class validates
↓
Settings injected into services
↓
Services use configuration at runtime
环境变量:
HUGGINGFACE_API_KEY→ QwenAIServiceSMTP_USERNAME,SMTP_PASSWORD→ 电子邮件服务AI_MODEL,AI_TEMPERATURE→ AI配置API_HOST,API_PORT→ 服务器绑定
🔄 错误处理流程
Exception occurs
↓
Service logs error
↓
Raise to use case layer
↓
Use case catches & wraps
↓
Route handler catches
↓
FastAPI HTTPException raised
↓
JSON error response returned
例子:
try:
result = await ai_service.generate_response(prompt)
except Exception as e:
logger.error(f"AI generation failed: {e}")
raise HTTPException(status_code=500, detail=str(e))
📈 数据流示例:AI增强电子邮件
1. User Request:
POST /email/send-ai
{
"to": "user@example.com",
"subject": "Welcome",
"content_template": "Write a welcome email for new users"
}
2. Route Handler (email.py):
- Validates request
- Calls QwenAIService
3. AI Service:
- Formats prompt: "Write a welcome email for new users"
- Calls Hugging Face: InferenceClient.chat_completion()
- Returns: "Dear valued user, welcome to our platform..."
4. Use Case (SendEmailUseCase):
- Creates Email entity with AI-generated body
- Passes to EmailService
5. Email Service:
- Connects to SMTP (Gmail)
- Authenticates with credentials
- Sends email via aiosmtplib
6. Response:
{
"message": "Email sent successfully",
"to": "user@example.com",
"generated_content": "Dear valued user..."
}
🚀 启动顺序
1. main.py execution
↓
2. Load environment from .env
↓
3. Initialize Settings (Pydantic validation)
↓
4. Create FastAPI app instance
↓
5. Register startup event:
- Log application start
- Initialize services
↓
6. Register shutdown event:
- Cleanup resources
- Log shutdown
↓
7. Include API routers:
- /ai routes
- /email routes
- /charts routes
- /pdf routes
- /health route
↓
8. Start Uvicorn server:
- Host: 0.0.0.0
- Port: 8000
- Reload: True (development)
↓
9. Server ready for requests
🧪 测试流程
Test Script (test_llama.py)
↓
Direct import: QwenAIService
↓
Initialize with .env credentials
↓
Run test prompts:
1. Simple greeting
2. Math calculation
3. Creative writing
4. Explanation
5. Fun fact
↓
Each test:
- Calls generate_response()
- Validates response
- Reports success/failure
↓
Summary: 5/5 tests passed ✅
🔧 技术栈流程
┌─────────────────────────────────────────┐
│ Application Entry Point │
│ main.py │
└──────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Web Framework │
│ FastAPI + Uvicorn │
└──────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ Core Services │
│ • HuggingFace Hub 1.2.1 │
│ • aiosmtplib (Email) │
│ • Plotly + Kaleido (Charts) │
│ • PyPDF + pdfplumber (PDF) │
└──────────────┬──────────────────────────┘
│
▼
┌─────────────────────────────────────────┐
│ External APIs │
│ • Hugging Face Router │
│ (meta-llama/Llama-3.2-3B-Instruct) │
│ • SMTP Server (Gmail) │
└─────────────────────────────────────────┘
📝 总结
架构模式: 清洁+六角形(端口和适配器)
优点:
- ✅ 可测试: 独立于基础设施的域逻辑
- ✅ 可维护: 明确区分关注点
- ✅ 可扩展性: 易于交换的实现
- ✅ 灵活: AI提供商可以在不涉及业务逻辑的情况下进行更改
关键原则: 依赖关系指向内部(来自基础设施→ 应用→ 域)
这确保了核心业务逻辑保持纯粹,独立于外部框架或服务。
