Files
learn-ai/docs/tasks/task-15-agent-summary.md
hughhuang(黄健铭)andClaude Sonnet 4.5 e6a434e516 实现 AI Agent 对话功能(Task 15)
后端实现:
- 集成 Vercel AI SDK 实现流式对话
- 实现工具系统(文章搜索、报告分析、网络搜索)
- 实现上下文加载和提示词构建
- 实现对话管理和消息存储
- 添加 Agent API 路由(流式对话、历史记录)

前端实现:
- 实现聊天界面(配置选择、消息展示、历史记录)
- 支持 Markdown 渲染和代码高亮
- 实现流式响应解析和展示
- 优化布局(单侧边栏 + 可折叠历史面板)
- 修复 API 路径和 CORS 问题

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-02-06 09:58:47 +08:00

656 lines
16 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.
# 任务 15:AI Agent 实现总结
## 📋 文档导航
本任务包含以下文档:
1. **[架构设计](./task-15-agent-architecture.md)** - 整体架构、技术选型、数据库设计
2. **[详细实现(第二部分)](./task-15-agent-implementation-part2.md)** - 辅助模块、前端实现
3. **[详细实现(第三部分)](./task-15-agent-implementation-part3.md)** - 前端组件、配置、测试
4. **[部署与优化](./task-15-agent-deployment.md)** - 性能优化、监控、安全
5. **[快速开始指南](./task-15-quick-start.md)** - 5分钟快速上手
---
## 🎯 项目概述
### 核心目标
基于 **Vercel AI SDK** 实现一个智能对话系统,支持:
- 基于报告/资讯的深入对话
- 自动工具调用(资讯检索、报告分析、联网搜索)
- 流式响应,提升用户体验
- 多轮对话,上下文保持
### 技术栈
| 层级 | 技术 |
|------|------|
| AI 框架 | Vercel AI SDK 3.0+ |
| LLM 提供商 | OpenAI / DeepSeek / 通义千问 |
| 后端 | Node.js + TypeScript + Fastify |
| 前端 | Vue 3 + TypeScript + Element Plus |
| 数据库 | MySQL + Prisma |
| 流式传输 | Server-Sent Events (SSE) |
---
## 🏗️ 架构概览
```
┌─────────────────────────────────────────────────────────────┐
│ 前端层 │
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
│ │ AgentChat │ │ MessageItem │ │ useAgentChat │ │
│ │ 对话界面 │ │ 消息渲染 │ │ 对话逻辑 │ │
│ └──────────────┘ └──────────────┘ └──────────────┘ │
└─────────────────────────────────────────────────────────────┘
│ HTTP/SSE
▼
┌─────────────────────────────────────────────────────────────┐
│ 后端层 │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ AgentService (核心服务) │ │
│ │ • 对话管理 • 工具调度 • 上下文加载 │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ Vercel AI SDK │ │
│ │ • streamText • Tool System • Multi-step │ │
│ └──────────────────────────────────────────────────────┘ │
│ │ │
│ ┌──────────────────────────────────────────────────────┐ │
│ │ 工具层 │ │
│ │ • 资讯检索 • 报告分析 • 联网搜索 │ │
│ └──────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ 数据层 │
│ • conversations • conversation_messages • articles │
└─────────────────────────────────────────────────────────────┘
```
---
## 📦 核心模块
### 1. AgentService(核心服务)
**位置**: `backend/src/services/agent/agent.service.ts`
**职责**:
- 管理对话生命周期
- 调度工具执行
- 处理流式响应
- 保存对话历史
**关键方法**:
```typescript
async streamChat(params: AgentChatParams): Promise<StreamTextResult>
async getConversation(conversationId: number): Promise<Conversation>
async getUserConversations(userId: string): Promise<Conversation[]>
async deleteConversation(conversationId: number): Promise<void>
```
### 2. 工具系统
#### 2.1 资讯检索工具
**位置**: `backend/src/services/agent/tools/article-search.tool.ts`
**功能**: 搜索数据库中的资讯
**参数**: query, topicId, sourceId, limit
**返回**: 匹配的资讯列表
#### 2.2 报告分析工具
**位置**: `backend/src/services/agent/tools/report-analysis.tool.ts`
**功能**: 分析已生成的报告
**参数**: reportId, analysisType
**返回**: 报告分析结果
#### 2.3 联网搜索工具
**位置**: `backend/src/services/agent/tools/web-search.tool.ts`
**功能**: 搜索互联网获取最新信息
**参数**: query, limit
**返回**: 搜索结果列表
### 3. 上下文管理
#### 3.1 ContextLoader(上下文加载器)
**位置**: `backend/src/services/agent/context/context-loader.ts`
**功能**:
- 加载主题信息
- 加载报告/资讯内容
- 加载相关资讯
#### 3.2 PromptBuilder(Prompt 构建器)
**位置**: `backend/src/services/agent/context/prompt-builder.ts`
**功能**:
- 构建系统 Prompt
- 定义 Agent 角色
- 说明工具能力
- 设置行为规范
### 4. 对话管理
**位置**: `backend/src/services/agent/conversation/conversation.manager.ts`
**功能**:
- 创建/获取对话
- 添加消息
- 查询历史消息
- 删除对话
### 5. 前端组件
#### 5.1 AgentChat(对话界面)
**位置**: `frontend/src/views/agent/AgentChat.vue`
**功能**:
- 显示对话历史
- 处理用户输入
- 渲染流式响应
- 管理对话状态
#### 5.2 MessageItem(消息项)
**位置**: `frontend/src/components/agent/MessageItem.vue`
**功能**:
- Markdown 渲染
- 代码高亮
- 工具调用展示
- 流式输出动画
#### 5.3 useAgentChat(对话 Hook)
**位置**: `frontend/src/composables/useAgentChat.ts`
**功能**:
- 管理消息状态
- 处理流式响应
- 错误处理
- 消息持久化
---
## 🔧 关键技术实现
### 1. 流式响应
**后端实现**:
```typescript
const result = streamText({
model,
system: systemPrompt,
messages,
tools,
maxSteps: 5,
});
// 设置 SSE 响应头
reply.raw.setHeader('Content-Type', 'text/event-stream');
reply.raw.setHeader('Cache-Control', 'no-cache');
reply.raw.setHeader('Connection', 'keep-alive');
return result.toDataStream();
```
**前端实现**:
```typescript
const stream = await streamChat(params);
const reader = stream.getReader();
const decoder = new TextDecoder();
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
// 处理流式数据
}
```
### 2. 工具调用
**定义工具**:
```typescript
import { tool } from 'ai';
import { z } from 'zod';
const searchTool = tool({
description: '搜索资讯数据库',
parameters: z.object({
query: z.string().describe('搜索关键词'),
limit: z.number().default(10),
}),
execute: async ({ query, limit }) => {
const results = await prisma.article.findMany({
where: {
OR: [
{ title: { contains: query } },
{ content: { contains: query } },
],
},
take: limit,
});
return { success: true, results };
},
});
```
**使用工具**:
```typescript
const result = streamText({
model,
tools: {
searchArticles: searchTool,
analyzeReport: reportTool,
},
maxSteps: 5, // 允许多步工具调用
});
```
### 3. 上下文增强
**加载上下文**:
```typescript
const context = await contextLoader.load({
reportId: params.reportId,
articleId: params.articleId,
topicId: params.topicId,
});
```
**构建 Prompt**:
```typescript
const systemPrompt = promptBuilder.build(context);
// 包含:角色定义、上下文信息、工具说明、行为规范
```
### 4. 多轮对话
**保存消息**:
```typescript
await conversationManager.addMessage(conversationId, {
role: 'user',
content: message,
});
```
**加载历史**:
```typescript
const messages = await conversationManager.getMessages(conversationId);
```
---
## 📊 数据库设计
### 核心表结构
```sql
-- 对话表
CREATE TABLE conversations (
id INT PRIMARY KEY AUTO_INCREMENT,
userId VARCHAR(255),
topicId INT,
reportId INT,
articleId INT,
title VARCHAR(255),
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
INDEX idx_userId (userId),
INDEX idx_topicId (topicId)
);
-- 消息表
CREATE TABLE conversation_messages (
id INT PRIMARY KEY AUTO_INCREMENT,
conversationId INT,
role VARCHAR(50),
content TEXT,
toolCalls JSON,
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
INDEX idx_conversationId (conversationId),
FOREIGN KEY (conversationId) REFERENCES conversations(id) ON DELETE CASCADE
);
```
---
## 🚀 部署流程
### 1. 环境准备
```bash
# 安装依赖
cd backend && npm install ai @ai-sdk/openai zod
cd frontend && npm install markdown-it highlight.js
# 配置环境变量
cp .env.example .env
# 编辑 .env,设置 LLM API Key
```
### 2. 数据库迁移
```bash
cd backend
npx prisma migrate dev --name add_agent_tables
npx prisma generate
```
### 3. 构建和启动
```bash
# 开发环境
npm run dev
# 生产环境
npm run build
npm run start:prod
```
### 4. 验证部署
```bash
# 测试 API
curl -X POST http://localhost:3000/api/agent/chat \
-H "Content-Type: application/json" \
-d '{"topicId":1,"message":"Hello","llmConfigId":1}'
```
---
## 📈 性能指标
### 目标性能
| 指标 | 目标值 |
|------|--------|
| 首字响应时间 | < 2s |
| 平均响应时间 | < 5s |
| 并发对话数 | 100+ |
| 工具调用延迟 | < 500ms |
| 上下文加载时间 | < 200ms |
### 优化策略
1. **缓存优化**
- LLM 配置缓存
- 上下文缓存
- 工具结果缓存
2. **数据库优化**
- 添加全文索引
- 优化查询语句
- 限制历史消息数量
3. **并发控制**
- 限制并发对话数
- 请求队列管理
- 超时控制
---
## 🔒 安全措施
### 1. 输入验证
```typescript
// 长度限制
if (message.length > 10000) {
throw new Error('消息过长');
}
// 内容过滤
const dangerousPatterns = [/<script/i, /javascript:/i];
for (const pattern of dangerousPatterns) {
if (pattern.test(message)) {
throw new Error('消息包含不安全内容');
}
}
```
### 2. 速率限制
```typescript
// 每分钟最多 20 次请求
const rateLimitMap = new Map();
if (userLimit.count > 20) {
throw new Error('请求过于频繁');
}
```
### 3. 敏感信息过滤
```typescript
// 过滤信用卡号、手机号等
const filtered = content.replace(/\b\d{15,19}\b/g, '[已隐藏]');
```
---
## 📝 API 文档
### POST /api/agent/chat
**描述**: 创建或继续对话
**请求体**:
```json
{
"conversationId": 123,
"reportId": 456,
"articleId": 789,
"topicId": 1,
"message": "你的问题",
"llmConfigId": 1,
"userId": "user-123"
}
```
**响应**: SSE 流
### GET /api/agent/conversations/:id
**描述**: 获取对话详情
**响应**:
```json
{
"id": 123,
"title": "对话标题",
"messages": [...]
}
```
### GET /api/agent/conversations
**描述**: 获取用户对话列表
**查询参数**: `userId`
**响应**: 对话列表数组
### DELETE /api/agent/conversations/:id
**描述**: 删除对话
**响应**: `{ "success": true }`
---
## 🧪 测试策略
### 1. 单元测试
```typescript
describe('AgentService', () => {
it('should create conversation', async () => {
const result = await agentService.streamChat({...});
expect(result).toBeDefined();
});
});
```
### 2. 集成测试
```typescript
describe('Agent Integration', () => {
it('should handle tool calls', async () => {
const result = await agentService.streamChat({
message: '搜索最新的 AI 新闻',
});
// 验证工具被调用
});
});
```
### 3. E2E 测试
```typescript
describe('Agent E2E', () => {
it('should complete full conversation flow', async () => {
// 1. 创建对话
// 2. 发送消息
// 3. 验证响应
// 4. 验证历史保存
});
});
```
---
## 📚 学习资源
### 官方文档
- [Vercel AI SDK](https://sdk.vercel.ai/docs)
- [OpenAI API](https://platform.openai.com/docs)
- [Prisma](https://www.prisma.io/docs)
### 示例项目
- [AI SDK Examples](https://github.com/vercel/ai/tree/main/examples)
- [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)
### 社区
- [Vercel Discord](https://discord.gg/vercel)
- [AI SDK Discussions](https://github.com/vercel/ai/discussions)
---
## 🎯 下一步计划
### 短期(1-2 周)
- [ ] 完成基础功能开发
- [ ] 编写单元测试
- [ ] 完成集成测试
- [ ] 部署到测试环境
### 中期(1 个月)
- [ ] 添加向量数据库支持(RAG)
- [ ] 实现多模态输入
- [ ] 优化性能
- [ ] 添加监控和告警
### 长期(3 个月)
- [ ] 实现 Agent 记忆系统
- [ ] 支持多 Agent 协作
- [ ] 添加更多专业工具
- [ ] 优化用户体验
---
## 💡 常见问题
### Q1: 如何切换 LLM 提供商?
**A**: 修改 LLM 配置即可:
```typescript
// OpenAI
const model = createOpenAI({
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-xxx',
})('gpt-4');
// DeepSeek
const model = createOpenAI({
baseURL: 'https://api.deepseek.com/v1',
apiKey: 'sk-xxx',
})('deepseek-chat');
```
### Q2: 如何添加新工具?
**A**: 参考现有工具创建新工具:
```typescript
export class MyTool {
static create() {
return tool({
description: '工具描述',
parameters: z.object({...}),
execute: async (params) => {...},
});
}
}
```
### Q3: 如何优化响应速度?
**A**:
1. 使用更快的模型(gpt-3.5-turbo)
2. 减少上下文长度
3. 限制工具调用步数
4. 启用缓存
### Q4: 如何处理长对话?
**A**:
1. 限制历史消息数量(只保留最近 10 条)
2. 压缩上下文内容
3. 使用对话摘要
---
## 📞 支持
如有问题,请:
1. 查看文档
2. 搜索 GitHub Issues
3. 在 Discord 社区提问
4. 提交 Issue
---
**文档版本**: v1.0
**创建日期**: 2026-02-05
**维护者**: Claude Code
**状态**: ✅ 已完成
---
## 🎉 总结
本任务完成了基于 **Vercel AI SDK** 的 AI Agent 系统设计和实现,包括:
✅ **完整的架构设计**
✅ **详细的实现文档**
✅ **前后端代码示例**
✅ **部署和优化指南**
✅ **快速开始教程**
系统具备以下核心能力:
- 🤖 智能对话
- 🔧 工具调用
- 📊 上下文增强
- 💬 多轮对话
- ⚡ 流式响应
可以开始实施开发了!