# 任务 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 async getConversation(conversationId: number): Promise async getUserConversations(userId: string): Promise async deleteConversation(conversationId: number): Promise ``` ### 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 = [/