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

21 KiB
Raw Blame History

任务 15:AI Agent 架构设计(基于 Vercel AI SDK)

一、架构概览

1.1 整体架构

┌─────────────────────────────────────────────────────────────┐
│                        前端 (Vue 3)                          │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ 对话界面     │  │ 流式渲染     │  │ 上下文管理   │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
└─────────────────────────────────────────────────────────────┘
                            │ HTTP/SSE
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    后端 (Fastify + TypeScript)               │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              Agent Service Layer                      │   │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐     │   │
│  │  │ 对话管理   │  │ 工具调度   │  │ 上下文加载 │     │   │
│  │  └────────────┘  └────────────┘  └────────────┘     │   │
│  └──────────────────────────────────────────────────────┘   │
│                            │                                 │
│  ┌──────────────────────────────────────────────────────┐   │
│  │              Vercel AI SDK Core                       │   │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐     │   │
│  │  │ streamText │  │ Tool System│  │ Multi-step │     │   │
│  │  └────────────┘  └────────────┘  └────────────┘     │   │
│  └──────────────────────────────────────────────────────┘   │
│                            │                                 │
│  ┌──────────────────────────────────────────────────────┐   │
│  │                   Tools Layer                         │   │
│  │  ┌────────────┐  ┌────────────┐  ┌────────────┐     │   │
│  │  │ 资讯检索   │  │ 报告分析   │  │ 联网搜索   │     │   │
│  │  └────────────┘  └────────────┘  └────────────┘     │   │
│  └──────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────┘
                            │
                            ▼
┌─────────────────────────────────────────────────────────────┐
│                    数据层 (MySQL + Prisma)                   │
│  ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│  │ 资讯数据     │  │ 报告数据     │  │ 对话历史     │      │
│  └──────────────┘  └──────────────┘  └──────────────┘      │
└─────────────────────────────────────────────────────────────┘

1.2 核心能力

  1. 对话管理:多轮对话、上下文保持
  2. 工具调用:资讯检索、报告分析、联网搜索
  3. 流式响应:实时输出,提升用户体验
  4. 上下文增强:基于报告/资讯的 RAG
  5. 多 LLM 支持:OpenAI、DeepSeek、通义千问等

二、技术选型

2.1 核心依赖

{
  "dependencies": {
    "ai": "^3.0.0",                    // Vercel AI SDK
    "@ai-sdk/openai": "^0.0.50",       // OpenAI Provider
    "zod": "^3.22.4",                  // 参数验证
    "eventsource-parser": "^1.1.2"     // SSE 解析
  }
}

2.2 LLM 提供商支持

提供商 包名 模型示例
OpenAI @ai-sdk/openai gpt-4, gpt-4-turbo
Anthropic @ai-sdk/anthropic claude-3-opus
Google @ai-sdk/google gemini-pro
自定义 @ai-sdk/openai-compatible DeepSeek, 通义千问

三、数据库设计

3.1 对话会话表

model Conversation {
  id        Int      @id @default(autoincrement())
  userId    String?  // 用户标识(可选)
  topicId   Int?     // 关联主题
  reportId  Int?     // 关联报告
  articleId Int?     // 关联资讯
  title     String   // 对话标题
  createdAt DateTime @default(now())
  updatedAt DateTime @updatedAt

  messages  ConversationMessage[]

  topic     Topic?   @relation(fields: [topicId], references: [id])
  report    Report?  @relation(fields: [reportId], references: [id])
  article   Article? @relation(fields: [articleId], references: [id])

  @@index([userId])
  @@index([topicId])
  @@index([reportId])
  @@index([articleId])
}

model ConversationMessage {
  id             Int      @id @default(autoincrement())
  conversationId Int
  role           String   // 'user' | 'assistant' | 'system' | 'tool'
  content        String   @db.Text
  toolCalls      Json?    // 工具调用记录
  createdAt      DateTime @default(now())

  conversation   Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)

  @@index([conversationId])
}

四、后端实现

4.1 目录结构

backend/src/
├── services/
│   ├── agent/
│   │   ├── agent.service.ts          # Agent 核心服务
│   │   ├── tools/
│   │   │   ├── article-search.tool.ts    # 资讯检索工具
│   │   │   ├── report-analysis.tool.ts   # 报告分析工具
│   │   │   ├── web-search.tool.ts        # 联网搜索工具
│   │   │   └── index.ts
│   │   ├── context/
│   │   │   ├── context-loader.ts         # 上下文加载器
│   │   │   └── prompt-builder.ts         # Prompt 构建器
│   │   └── conversation/
│   │       ├── conversation.manager.ts   # 对话管理器
│   │       └── message.store.ts          # 消息存储
│   └── llm/
│       └── llm-provider.factory.ts   # LLM 提供商工厂
├── routes/
│   └── agent.routes.ts               # Agent API 路由
└── types/
    └── agent.types.ts                # Agent 类型定义

4.2 核心服务实现

4.2.1 Agent Service

// backend/src/services/agent/agent.service.ts
import { streamText, generateText, tool } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import { z } from 'zod';
import prisma from '../../utils/prisma';
import { logger } from '../../utils/logger';
import { ArticleSearchTool } from './tools/article-search.tool';
import { ReportAnalysisTool } from './tools/report-analysis.tool';
import { WebSearchTool } from './tools/web-search.tool';
import { ContextLoader } from './context/context-loader';
import { PromptBuilder } from './context/prompt-builder';
import { ConversationManager } from './conversation/conversation.manager';

export interface AgentChatParams {
  conversationId?: number;
  reportId?: number;
  articleId?: number;
  topicId: number;
  message: string;
  llmConfigId: number;
  userId?: string;
}

export class AgentService {
  private conversationManager: ConversationManager;
  private contextLoader: ContextLoader;
  private promptBuilder: PromptBuilder;

  constructor() {
    this.conversationManager = new ConversationManager();
    this.contextLoader = new ContextLoader();
    this.promptBuilder = new PromptBuilder();
  }

  /**
   * 流式对话
   */
  async streamChat(params: AgentChatParams) {
    try {
      // 1. 获取或创建对话
      const conversation = await this.conversationManager.getOrCreate({
        conversationId: params.conversationId,
        userId: params.userId,
        topicId: params.topicId,
        reportId: params.reportId,
        articleId: params.articleId,
      });

      // 2. 保存用户消息
      await this.conversationManager.addMessage(conversation.id, {
        role: 'user',
        content: params.message,
      });

      // 3. 加载上下文
      const context = await this.contextLoader.load({
        reportId: params.reportId,
        articleId: params.articleId,
        topicId: params.topicId,
      });

      // 4. 构建系统 Prompt
      const systemPrompt = this.promptBuilder.build(context);

      // 5. 获取历史消息
      const messages = await this.conversationManager.getMessages(conversation.id);

      // 6. 获取 LLM 配置
      const llmConfig = await prisma.llmConfig.findUnique({
        where: { id: params.llmConfigId },
      });

      if (!llmConfig) {
        throw new Error('LLM config not found');
      }

      // 7. 创建 LLM 实例
      const model = createOpenAI({
        baseURL: llmConfig.baseUrl,
        apiKey: llmConfig.apiKey,
      })(llmConfig.model);

      // 8. 定义工具
      const tools = {
        searchArticles: ArticleSearchTool.create(),
        analyzeReport: ReportAnalysisTool.create(),
        webSearch: WebSearchTool.create(),
      };

      // 9. 流式生成
      const result = streamText({
        model,
        system: systemPrompt,
        messages: [
          ...messages.map(m => ({
            role: m.role as 'user' | 'assistant',
            content: m.content,
          })),
        ],
        tools,
        maxSteps: 5, // 最多 5 步工具调用
      });

      // 10. 保存助手消息(异步)
      this.saveAssistantMessage(conversation.id, result);

      return result;
    } catch (error) {
      logger.error('Agent chat error:', error);
      throw error;
    }
  }

  /**
   * 保存助手消息
   */
  private async saveAssistantMessage(conversationId: number, result: any) {
    try {
      const response = await result.response;
      const messages = response.messages;

      for (const msg of messages) {
        await this.conversationManager.addMessage(conversationId, {
          role: msg.role,
          content: msg.content,
          toolCalls: msg.toolCalls,
        });
      }
    } catch (error) {
      logger.error('Save assistant message error:', error);
    }
  }

  /**
   * 获取对话历史
   */
  async getConversation(conversationId: number) {
    return this.conversationManager.getConversation(conversationId);
  }

  /**
   * 获取用户的对话列表
   */
  async getUserConversations(userId: string) {
    return this.conversationManager.getUserConversations(userId);
  }

  /**
   * 删除对话
   */
  async deleteConversation(conversationId: number) {
    return this.conversationManager.deleteConversation(conversationId);
  }
}

4.3 工具实现

4.3.1 资讯检索工具

// backend/src/services/agent/tools/article-search.tool.ts
import { tool } from 'ai';
import { z } from 'zod';
import prisma from '../../../utils/prisma';

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.article.findMany({
            where: {
              AND: [
                {
                  OR: [
                    { title: { contains: query } },
                    { content: { contains: query } },
                    { summary: { contains: query } },
                  ],
                },
                topicId ? { topicId } : {},
                sourceId ? { sourceId } : {},
              ],
            },
            take: limit,
            orderBy: { publishedAt: 'desc' },
            include: {
              source: {
                select: { name: true },
              },
              topic: {
                select: { name: true },
              },
            },
          });

          return {
            success: true,
            count: articles.length,
            articles: articles.map(a => ({
              id: a.id,
              title: a.title,
              summary: a.summary,
              url: a.url,
              publishedAt: a.publishedAt,
              source: a.source.name,
              topic: a.topic.name,
            })),
          };
        } catch (error) {
          return {
            success: false,
            error: error.message,
          };
        }
      },
    });
  }
}

4.3.2 报告分析工具

// backend/src/services/agent/tools/report-analysis.tool.ts
import { tool } from 'ai';
import { z } from 'zod';
import prisma from '../../../utils/prisma';

export class ReportAnalysisTool {
  static create() {
    return tool({
      description: '分析已生成的报告,提取关键信息和洞察',
      parameters: z.object({
        reportId: z.number().describe('报告 ID'),
        analysisType: z.enum(['summary', 'keywords', 'trends', 'full'])
          .default('summary')
          .describe('分析类型'),
      }),
      execute: async ({ reportId, analysisType }) => {
        try {
          const report = await prisma.report.findUnique({
            where: { id: reportId },
            include: {
              topic: {
                select: { name: true },
              },
            },
          });

          if (!report) {
            return {
              success: false,
              error: 'Report not found',
            };
          }

          // 根据分析类型返回不同内容
          let analysis: any = {
            id: report.id,
            title: report.title,
            topic: report.topic.name,
            generatedAt: report.generatedAt,
          };

          switch (analysisType) {
            case 'summary':
              analysis.summary = report.content.substring(0, 500);
              break;
            case 'full':
              analysis.content = report.content;
              break;
            // 可以添加更多分析类型
          }

          return {
            success: true,
            analysis,
          };
        } catch (error) {
          return {
            success: false,
            error: error.message,
          };
        }
      },
    });
  }
}

4.3.3 联网搜索工具

// backend/src/services/agent/tools/web-search.tool.ts
import { tool } from 'ai';
import { z } from 'zod';

export class WebSearchTool {
  static create() {
    return tool({
      description: '搜索互联网获取最新信息(需要配置搜索 API)',
      parameters: z.object({
        query: z.string().describe('搜索查询'),
        limit: z.number().default(5).describe('返回结果数量'),
      }),
      execute: async ({ query, limit }) => {
        try {
          // TODO: 集成搜索 API(如 Google Custom Search, Bing Search 等)
          // 这里提供一个示例实现

          return {
            success: true,
            message: '联网搜索功能需要配置搜索 API',
            query,
            results: [],
          };
        } catch (error) {
          return {
            success: false,
            error: error.message,
          };
        }
      },
    });
  }
}

五、API 路由设计

5.1 路由定义

// backend/src/routes/agent.routes.ts
import { FastifyInstance } from 'fastify';
import { AgentService } from '../services/agent/agent.service';

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

  /**
   * POST /api/agent/chat
   * 流式对话
   */
  fastify.post('/chat', async (request, reply) => {
    const {
      conversationId,
      reportId,
      articleId,
      topicId,
      message,
      llmConfigId,
      userId,
    } = request.body as any;

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

      // 设置 SSE 响应头
      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) {
      reply.status(500).send({ error: error.message });
    }
  });

  /**
   * GET /api/agent/conversations/:id
   * 获取对话详情
   */
  fastify.get('/conversations/:id', async (request, reply) => {
    const { id } = request.params as any;

    try {
      const conversation = await agentService.getConversation(Number(id));
      return conversation;
    } catch (error) {
      reply.status(500).send({ error: error.message });
    }
  });

  /**
   * GET /api/agent/conversations
   * 获取用户对话列表
   */
  fastify.get('/conversations', async (request, reply) => {
    const { userId } = request.query as any;

    try {
      const conversations = await agentService.getUserConversations(userId);
      return conversations;
    } catch (error) {
      reply.status(500).send({ error: error.message });
    }
  });

  /**
   * DELETE /api/agent/conversations/:id
   * 删除对话
   */
  fastify.delete('/conversations/:id', async (request, reply) => {
    const { id } = request.params as any;

    try {
      await agentService.deleteConversation(Number(id));
      return { success: true };
    } catch (error) {
      reply.status(500).send({ error: error.message });
    }
  });
}

六、前端实现

6.1 目录结构

frontend/src/
├── views/
│   └── agent/
│       ├── AgentChat.vue           # 对话界面
│       └── ConversationList.vue    # 对话列表
├── components/
│   └── agent/
│       ├── MessageList.vue         # 消息列表
│       ├── MessageItem.vue         # 消息项
│       ├── InputArea.vue           # 输入区域
│       └── ToolCallDisplay.vue     # 工具调用展示
├── composables/
│   └── useAgentChat.ts             # Agent 对话 Hook
└── api/
    └── agent.ts                    # Agent API

6.2 核心组件实现

详细的前端实现将在下一部分文档中说明...


七、部署和配置

7.1 环境变量

# LLM 配置(默认)
DEFAULT_LLM_PROVIDER=openai
DEFAULT_LLM_MODEL=gpt-4
DEFAULT_LLM_API_KEY=sk-xxx
DEFAULT_LLM_BASE_URL=https://api.openai.com/v1

# Agent 配置
AGENT_MAX_STEPS=5
AGENT_TIMEOUT=30000

7.2 数据库迁移

# 生成迁移文件
npx prisma migrate dev --name add_conversation_tables

# 应用迁移
npx prisma migrate deploy

八、测试计划

8.1 单元测试

  • Agent Service 测试
  • 工具调用测试
  • 上下文加载测试
  • 对话管理测试

8.2 集成测试

  • 端到端对话流程测试
  • 流式响应测试
  • 工具链调用测试

8.3 性能测试

  • 并发对话测试
  • 长对话上下文测试
  • 流式响应延迟测试

九、后续优化方向

  1. RAG 增强:向量数据库集成(Pinecone、Weaviate)
  2. 多模态支持:图片、文件上传分析
  3. Agent 记忆:长期记忆、用户偏好学习
  4. 多 Agent 协作:专业 Agent 分工协作
  5. 可观测性:LangSmith 集成、Trace 追踪

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