Files
learn-ai/docs/tasks/task-15-agent-deployment.md
T
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

18 KiB

任务 15:AI Agent 部署与优化(第四部分)

一、部署准备

1.1 生产环境配置

# 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 构建脚本

// 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 流式响应优化

// 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<number, any>();

  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 上下文压缩

// 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 工具调用优化

// 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 性能监控

// 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 日志增强

// 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 输入验证

// 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 = [
      /<script/i,
      /javascript:/i,
      /on\w+\s*=/i,
    ];

    for (const pattern of dangerousPatterns) {
      if (pattern.test(message)) {
        return { valid: false, error: '消息包含不安全内容' };
      }
    }

    return { valid: true };
  }

  /**
   * 清理用户输入
   */
  sanitizeMessage(message: string): string {
    return message
      .trim()
      .replace(/\r\n/g, '\n')
      .replace(/\r/g, '\n');
  }
}

4.2 速率限制

// backend/src/middleware/rate-limiter.ts

import { FastifyRequest, FastifyReply } from 'fastify';

const rateLimitMap = new Map<string, { count: number; resetTime: number }>();

export async function rateLimiter(
  request: FastifyRequest,
  reply: FastifyReply
) {
  const userId = (request.body as any)?.userId || 'anonymous';
  const now = Date.now();

  let userLimit = rateLimitMap.get(userId);

  if (!userLimit || now > userLimit.resetTime) {
    userLimit = {
      count: 0,
      resetTime: now + 60000, // 1 分钟
    };
    rateLimitMap.set(userId, userLimit);
  }

  userLimit.count++;

  if (userLimit.count > 20) {
    // 每分钟最多 20 次请求
    reply.status(429).send({
      error: 'Too many requests',
      message: '请求过于频繁,请稍后再试',
    });
    return;
  }
}

4.3 敏感信息过滤

// backend/src/services/agent/security/content-filter.ts

export class ContentFilter {
  private sensitivePatterns = [
    /\b\d{15,19}\b/g, // 信用卡号
    /\b\d{3}-\d{2}-\d{4}\b/g, // 社保号
    /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, // 邮箱
    /\b\d{11}\b/g, // 手机号
  ];

  /**
   * 过滤敏感信息
   */
  filterSensitiveInfo(content: string): string {
    let filtered = content;

    for (const pattern of this.sensitivePatterns) {
      filtered = filtered.replace(pattern, '[已隐藏]');
    }

    return filtered;
  }

  /**
   * 检测是否包含敏感信息
   */
  containsSensitiveInfo(content: string): boolean {
    return this.sensitivePatterns.some(pattern => pattern.test(content));
  }
}

五、错误处理

5.1 全局错误处理

// backend/src/routes/agent.routes.ts

export async function agentRoutes(fastify: FastifyInstance) {
  const agentService = new AgentService();
  const inputValidator = new InputValidator();

  // 错误处理装饰器
  fastify.setErrorHandler((error, request, reply) => {
    logger.error('Agent route error:', error);

    if (error.statusCode === 429) {
      reply.status(429).send({
        error: 'Too Many Requests',
        message: '请求过于频繁,请稍后再试',
      });
      return;
    }

    reply.status(500).send({
      error: 'Internal Server Error',
      message: '服务器内部错误,请稍后再试',
    });
  });

  fastify.post('/chat', {
    preHandler: rateLimiter,
  }, async (request, reply) => {
    const {
      conversationId,
      reportId,
      articleId,
      topicId,
      message,
      llmConfigId,
      userId,
    } = request.body as any;

    // 输入验证
    const validation = inputValidator.validateMessage(message);
    if (!validation.valid) {
      reply.status(400).send({
        error: 'Invalid Input',
        message: validation.error,
      });
      return;
    }

    try {
      const result = await agentService.streamChat({
        conversationId,
        reportId,
        articleId,
        topicId,
        message: inputValidator.sanitizeMessage(message),
        llmConfigId,
        userId,
      });

      reply.raw.setHeader('Content-Type', 'text/event-stream');
      reply.raw.setHeader('Cache-Control', 'no-cache');
      reply.raw.setHeader('Connection', 'keep-alive');
      reply.raw.setHeader('X-Vercel-AI-Data-Stream', 'v1');

      return result.toDataStream();
    } catch (error) {
      throw error;
    }
  });
}

六、测试策略

6.1 集成测试

// backend/src/services/agent/__tests__/agent.integration.test.ts

import { describe, it, expect, beforeAll, afterAll } from 'vitest';
import { AgentService } from '../agent.service';
import prisma from '../../../utils/prisma';

describe('Agent Integration Tests', () => {
  let agentService: AgentService;
  let testTopicId: number;
  let testLlmConfigId: number;

  beforeAll(async () => {
    agentService = new AgentService();

    // 创建测试数据
    const topic = await prisma.topic.create({
      data: {
        name: 'Test Topic',
        description: 'Test Description',
      },
    });
    testTopicId = topic.id;

    const llmConfig = await prisma.llmConfig.create({
      data: {
        name: 'Test LLM',
        provider: 'openai',
        model: 'gpt-4',
        apiKey: process.env.TEST_LLM_API_KEY || 'test-key',
        baseUrl: 'https://api.openai.com/v1',
      },
    });
    testLlmConfigId = llmConfig.id;
  });

  afterAll(async () => {
    // 清理测试数据
    await prisma.conversation.deleteMany({
      where: { topicId: testTopicId },
    });
    await prisma.topic.delete({ where: { id: testTopicId } });
    await prisma.llmConfig.delete({ where: { id: testLlmConfigId } });
  });

  it('should create conversation and stream response', async () => {
    const result = await agentService.streamChat({
      topicId: testTopicId,
      message: 'Hello, AI!',
      llmConfigId: testLlmConfigId,
      userId: 'test-user',
    });

    expect(result).toBeDefined();
    expect(result.toDataStream).toBeDefined();
  });

  it('should handle tool calls', async () => {
    const result = await agentService.streamChat({
      topicId: testTopicId,
      message: '搜索最新的 AI 新闻',
      llmConfigId: testLlmConfigId,
      userId: 'test-user',
    });

    expect(result).toBeDefined();
  });
});

七、部署清单

7.1 部署前检查

  • 环境变量配置完成
  • 数据库迁移已执行
  • LLM API 密钥已配置
  • 后端构建成功
  • 前端构建成功
  • 单元测试通过
  • 集成测试通过
  • 性能测试通过
  • 安全审计完成
  • 日志配置正确
  • 监控配置完成

7.2 部署步骤

# 1. 拉取最新代码
git pull origin main

# 2. 安装依赖
cd backend && npm ci
cd ../frontend && npm ci

# 3. 数据库迁移
cd ../backend
npx prisma migrate deploy
npx prisma generate

# 4. 构建后端
npm run build:prod

# 5. 构建前端
cd ../frontend
npm run build

# 6. 重启服务
pm2 restart ecosystem.config.js

# 7. 验证部署
curl http://localhost:3000/api/health

八、监控和维护

8.1 性能监控

# 查看 PM2 状态
pm2 status

# 查看日志
pm2 logs backend

# 查看监控面板
pm2 monit

8.2 数据库维护

-- 清理旧对话(30 天前)
DELETE FROM conversations
WHERE updatedAt < DATE_SUB(NOW(), INTERVAL 30 DAY);

-- 优化表
OPTIMIZE TABLE conversations;
OPTIMIZE TABLE conversation_messages;

-- 查看索引使用情况
SHOW INDEX FROM conversations;

九、故障排查

9.1 常见问题

问题 1:流式响应中断

  • 检查网络连接
  • 检查 LLM API 配额
  • 检查超时配置

问题 2:工具调用失败

  • 检查数据库连接
  • 检查工具参数验证
  • 查看错误日志

问题 3:性能下降

  • 检查数据库查询性能
  • 检查上下文长度
  • 优化缓存策略

文档版本: v1.0 创建日期: 2026-02-05 作者: Claude Code