# 任务 15:AI Agent 部署与优化(第四部分) ## 一、部署准备 ### 1.1 生产环境配置 ```env # backend/.env.production NODE_ENV=production PORT=3000 HOST=0.0.0.0 # 数据库 DATABASE_URL=mysql://user:password@localhost:3306/news_aggregator # LLM 配置 DEFAULT_LLM_PROVIDER=openai DEFAULT_LLM_MODEL=gpt-4-turbo DEFAULT_LLM_API_KEY=${LLM_API_KEY} DEFAULT_LLM_BASE_URL=https://api.openai.com/v1 # Agent 配置 AGENT_MAX_STEPS=5 AGENT_TIMEOUT=60000 AGENT_MAX_CONTEXT_LENGTH=8000 # 日志 LOG_LEVEL=info # CORS CORS_ORIGIN=https://your-domain.com ``` ### 1.2 构建脚本 ```json // backend/package.json { "scripts": { "build": "tsc", "start": "node dist/app.js", "start:prod": "NODE_ENV=production node dist/app.js", "build:prod": "npm run prisma:generate && npm run build" } } ``` --- ## 二、性能优化 ### 2.1 流式响应优化 ```typescript // backend/src/services/agent/agent.service.ts export class AgentService { /** * 优化的流式对话 */ async streamChat(params: AgentChatParams) { try { // 1. 并行加载上下文和历史消息 const [conversation, context] = await Promise.all([ this.conversationManager.getOrCreate({ conversationId: params.conversationId, userId: params.userId, topicId: params.topicId, reportId: params.reportId, articleId: params.articleId, }), this.contextLoader.load({ reportId: params.reportId, articleId: params.articleId, topicId: params.topicId, }), ]); // 2. 保存用户消息(异步,不阻塞) this.conversationManager.addMessage(conversation.id, { role: 'user', content: params.message, }).catch(err => logger.error('Save user message error:', err)); // 3. 获取历史消息(限制数量) const messages = await this.conversationManager.getRecentMessages( conversation.id, 10 // 只获取最近 10 条消息 ); // 4. 构建 Prompt(缓存优化) const systemPrompt = this.promptBuilder.build(context); // 5. 获取 LLM 配置(缓存) const llmConfig = await this.getLLMConfig(params.llmConfigId); // 6. 创建 LLM 实例 const model = this.createModel(llmConfig); // 7. 定义工具 const tools = this.getTools(); // 8. 流式生成 const result = streamText({ model, system: systemPrompt, messages: [ ...messages.map(m => ({ role: m.role as 'user' | 'assistant', content: m.content, })), ], tools, maxSteps: 5, temperature: 0.7, // 添加温度参数 }); // 9. 异步保存助手消息 this.saveAssistantMessage(conversation.id, result); return result; } catch (error) { logger.error('Agent chat error:', error); throw error; } } /** * 获取最近的消息(优化版) */ private async getRecentMessages(conversationId: number, limit: number = 10) { return prisma.conversationMessage.findMany({ where: { conversationId }, orderBy: { createdAt: 'desc' }, take: limit, select: { role: true, content: true, createdAt: true, }, }).then(messages => messages.reverse()); } /** * LLM 配置缓存 */ private llmConfigCache = new Map(); private async getLLMConfig(id: number) { if (this.llmConfigCache.has(id)) { return this.llmConfigCache.get(id); } const config = await prisma.llmConfig.findUnique({ where: { id }, }); if (!config) { throw new Error('LLM config not found'); } this.llmConfigCache.set(id, config); // 5 分钟后清除缓存 setTimeout(() => { this.llmConfigCache.delete(id); }, 5 * 60 * 1000); return config; } } ``` ### 2.2 上下文压缩 ```typescript // backend/src/services/agent/context/context-compressor.ts export class ContextCompressor { /** * 压缩上下文内容 */ compress(context: LoadedContext, maxLength: number = 8000): LoadedContext { const compressed = { ...context }; // 1. 压缩报告内容 if (compressed.report) { compressed.report.content = this.truncateText( compressed.report.content, maxLength * 0.6 // 报告占 60% ); } // 2. 压缩资讯内容 if (compressed.article) { compressed.article.content = this.truncateText( compressed.article.content, maxLength * 0.3 // 资讯占 30% ); } // 3. 限制相关资讯数量 if (compressed.relatedArticles) { compressed.relatedArticles = compressed.relatedArticles.slice(0, 5); } return compressed; } /** * 智能截断文本 */ private truncateText(text: string, maxLength: number): string { if (text.length <= maxLength) { return text; } // 尝试在段落边界截断 const truncated = text.substring(0, maxLength); const lastParagraph = truncated.lastIndexOf('\n\n'); if (lastParagraph > maxLength * 0.8) { return truncated.substring(0, lastParagraph) + '\n\n[内容已截断...]'; } return truncated + '\n\n[内容已截断...]'; } } ``` ### 2.3 工具调用优化 ```typescript // backend/src/services/agent/tools/article-search.tool.ts export class ArticleSearchTool { static create() { return tool({ description: '搜索资讯数据库,查找相关的新闻和文章', parameters: z.object({ query: z.string().describe('搜索关键词'), topicId: z.number().optional().describe('主题 ID'), sourceId: z.number().optional().describe('数据源 ID'), limit: z.number().default(10).describe('返回结果数量'), }), execute: async ({ query, topicId, sourceId, limit }) => { try { // 使用全文搜索优化查询 const articles = await prisma.$queryRaw` SELECT a.id, a.title, a.summary, a.url, a.publishedAt, s.name as sourceName, t.name as topicName, MATCH(a.title, a.content, a.summary) AGAINST(${query} IN NATURAL LANGUAGE MODE) as relevance FROM articles a LEFT JOIN sources s ON a.sourceId = s.id LEFT JOIN topics t ON a.topicId = t.id WHERE MATCH(a.title, a.content, a.summary) AGAINST(${query} IN NATURAL LANGUAGE MODE) ${topicId ? Prisma.sql`AND a.topicId = ${topicId}` : Prisma.empty} ${sourceId ? Prisma.sql`AND a.sourceId = ${sourceId}` : Prisma.empty} ORDER BY relevance DESC, a.publishedAt DESC LIMIT ${limit} `; return { success: true, count: articles.length, articles: articles.map((a: any) => ({ id: a.id, title: a.title, summary: a.summary, url: a.url, publishedAt: a.publishedAt, source: a.sourceName, topic: a.topicName, relevance: a.relevance, })), }; } catch (error) { logger.error('Article search error:', error); return { success: false, error: error.message, }; } }, }); } } ``` --- ## 三、监控和日志 ### 3.1 Agent 性能监控 ```typescript // backend/src/services/agent/monitoring/agent-monitor.ts export class AgentMonitor { /** * 记录对话指标 */ async recordChatMetrics(params: { conversationId: number; duration: number; tokenCount?: number; toolCallCount: number; success: boolean; error?: string; }) { try { await prisma.agentMetrics.create({ data: { conversationId: params.conversationId, duration: params.duration, tokenCount: params.tokenCount, toolCallCount: params.toolCallCount, success: params.success, error: params.error, timestamp: new Date(), }, }); } catch (error) { logger.error('Record metrics error:', error); } } /** * 获取性能统计 */ async getPerformanceStats(timeRange: { start: Date; end: Date }) { const stats = await prisma.agentMetrics.aggregate({ where: { timestamp: { gte: timeRange.start, lte: timeRange.end, }, }, _avg: { duration: true, tokenCount: true, toolCallCount: true, }, _count: { id: true, }, _sum: { tokenCount: true, }, }); const successRate = await prisma.agentMetrics.count({ where: { timestamp: { gte: timeRange.start, lte: timeRange.end, }, success: true, }, }); return { totalChats: stats._count.id, avgDuration: stats._avg.duration, avgTokenCount: stats._avg.tokenCount, avgToolCallCount: stats._avg.toolCallCount, totalTokens: stats._sum.tokenCount, successRate: (successRate / stats._count.id) * 100, }; } } ``` ### 3.2 日志增强 ```typescript // backend/src/services/agent/agent.service.ts export class AgentService { private monitor: AgentMonitor; constructor() { this.conversationManager = new ConversationManager(); this.contextLoader = new ContextLoader(); this.promptBuilder = new PromptBuilder(); this.monitor = new AgentMonitor(); } async streamChat(params: AgentChatParams) { const startTime = Date.now(); let toolCallCount = 0; let success = false; let error: string | undefined; try { logger.info('Agent chat started', { conversationId: params.conversationId, topicId: params.topicId, userId: params.userId, }); // ... 对话逻辑 ... success = true; return result; } catch (err) { error = err.message; logger.error('Agent chat error:', err); throw err; } finally { const duration = Date.now() - startTime; // 记录指标 if (params.conversationId) { await this.monitor.recordChatMetrics({ conversationId: params.conversationId, duration, toolCallCount, success, error, }); } logger.info('Agent chat completed', { duration, success, toolCallCount, }); } } } ``` --- ## 四、安全性增强 ### 4.1 输入验证 ```typescript // backend/src/services/agent/validation/input-validator.ts export class InputValidator { /** * 验证用户输入 */ validateMessage(message: string): { valid: boolean; error?: string } { // 1. 长度检查 if (message.length === 0) { return { valid: false, error: '消息不能为空' }; } if (message.length > 10000) { return { valid: false, error: '消息长度不能超过 10000 字符' }; } // 2. 内容检查(防止注入攻击) const dangerousPatterns = [ /