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

1000 lines
23 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.1 上下文加载器
```typescript
// backend/src/services/agent/context/context-loader.ts
import prisma from '../../../utils/prisma';
import { logger } from '../../../utils/logger';
export interface ContextLoadParams {
reportId?: number;
articleId?: number;
topicId: number;
}
export interface LoadedContext {
type: 'report' | 'article' | 'topic';
topic: {
id: number;
name: string;
description?: string;
};
report?: {
id: number;
title: string;
content: string;
generatedAt: Date;
};
article?: {
id: number;
title: string;
content: string;
summary?: string;
url?: string;
publishedAt?: Date;
};
relatedArticles?: Array<{
id: number;
title: string;
summary?: string;
}>;
}
export class ContextLoader {
/**
* 加载对话上下文
*/
async load(params: ContextLoadParams): Promise<LoadedContext> {
try {
// 1. 加载主题信息
const topic = await prisma.topic.findUnique({
where: { id: params.topicId },
select: {
id: true,
name: true,
description: true,
},
});
if (!topic) {
throw new Error('Topic not found');
}
const context: LoadedContext = {
type: 'topic',
topic,
};
// 2. 如果有报告 ID,加载报告
if (params.reportId) {
const report = await prisma.report.findUnique({
where: { id: params.reportId },
select: {
id: true,
title: true,
content: true,
generatedAt: true,
},
});
if (report) {
context.type = 'report';
context.report = report;
// 加载报告相关的资讯
const relatedArticles = await this.loadReportArticles(params.reportId);
context.relatedArticles = relatedArticles;
}
}
// 3. 如果有资讯 ID,加载资讯
if (params.articleId) {
const article = await prisma.article.findUnique({
where: { id: params.articleId },
select: {
id: true,
title: true,
content: true,
summary: true,
url: true,
publishedAt: true,
},
});
if (article) {
context.type = 'article';
context.article = article;
// 加载相关资讯
const relatedArticles = await this.loadRelatedArticles(params.articleId);
context.relatedArticles = relatedArticles;
}
}
return context;
} catch (error) {
logger.error('Context load error:', error);
throw error;
}
}
/**
* 加载报告关联的资讯
*/
private async loadReportArticles(reportId: number) {
const reportArticles = await prisma.reportArticle.findMany({
where: { reportId },
take: 10,
include: {
article: {
select: {
id: true,
title: true,
summary: true,
},
},
},
});
return reportArticles.map(ra => ra.article);
}
/**
* 加载相关资讯(基于主题和时间)
*/
private async loadRelatedArticles(articleId: number) {
const article = await prisma.article.findUnique({
where: { id: articleId },
select: { topicId: true, publishedAt: true },
});
if (!article) return [];
const relatedArticles = await prisma.article.findMany({
where: {
topicId: article.topicId,
id: { not: articleId },
publishedAt: {
gte: new Date(article.publishedAt.getTime() - 7 * 24 * 60 * 60 * 1000), // 7天内
},
},
take: 10,
orderBy: { publishedAt: 'desc' },
select: {
id: true,
title: true,
summary: true,
},
});
return relatedArticles;
}
}
```
---
### 1.2 Prompt 构建器
```typescript
// backend/src/services/agent/context/prompt-builder.ts
import { LoadedContext } from './context-loader';
export class PromptBuilder {
/**
* 构建系统 Prompt
*/
build(context: LoadedContext): string {
const parts: string[] = [];
// 1. 基础角色定义
parts.push(this.buildRolePrompt());
// 2. 上下文信息
parts.push(this.buildContextPrompt(context));
// 3. 能力说明
parts.push(this.buildCapabilitiesPrompt());
// 4. 行为规范
parts.push(this.buildGuidelinesPrompt());
return parts.join('\n\n');
}
/**
* 构建角色 Prompt
*/
private buildRolePrompt(): string {
return `你是一个专业的资讯分析助手,专注于帮助用户深入理解和分析新闻资讯。
你的核心职责:
1. 回答用户关于资讯和报告的问题
2. 提供深入的分析和洞察
3. 帮助用户发现资讯之间的关联
4. 在需要时主动获取更多信息`;
}
/**
* 构建上下文 Prompt
*/
private buildContextPrompt(context: LoadedContext): string {
const parts: string[] = ['当前上下文信息:'];
// 主题信息
parts.push(`\n主题:${context.topic.name}`);
if (context.topic.description) {
parts.push(`主题描述:${context.topic.description}`);
}
// 报告信息
if (context.report) {
parts.push(`\n当前报告:`);
parts.push(`标题:${context.report.title}`);
parts.push(`生成时间:${context.report.generatedAt.toISOString()}`);
parts.push(`\n报告内容:\n${this.truncateContent(context.report.content, 2000)}`);
}
// 资讯信息
if (context.article) {
parts.push(`\n当前资讯:`);
parts.push(`标题:${context.article.title}`);
if (context.article.publishedAt) {
parts.push(`发布时间:${context.article.publishedAt.toISOString()}`);
}
if (context.article.url) {
parts.push(`来源:${context.article.url}`);
}
if (context.article.summary) {
parts.push(`摘要:${context.article.summary}`);
}
parts.push(`\n内容:\n${this.truncateContent(context.article.content, 2000)}`);
}
// 相关资讯
if (context.relatedArticles && context.relatedArticles.length > 0) {
parts.push(`\n相关资讯(${context.relatedArticles.length}条):`);
context.relatedArticles.forEach((article, index) => {
parts.push(`${index + 1}. ${article.title}`);
if (article.summary) {
parts.push(` ${article.summary.substring(0, 100)}...`);
}
});
}
return parts.join('\n');
}
/**
* 构建能力说明 Prompt
*/
private buildCapabilitiesPrompt(): string {
return `你可以使用以下工具来增强回答:
1. searchArticles - 搜索资讯数据库
- 当用户询问特定主题或关键词的资讯时使用
- 可以按主题、数据源筛选
2. analyzeReport - 分析已生成的报告
- 当用户询问报告详情或需要深入分析时使用
- 支持摘要、关键词、趋势等分析类型
3. webSearch - 搜索互联网获取最新信息
- 当数据库中没有相关信息时使用
- 当需要最新的实时信息时使用
使用工具的原则:
- 优先使用数据库中的信息(searchArticles、analyzeReport)
- 只在必要时使用联网搜索(webSearch)
- 可以组合使用多个工具来提供更全面的回答`;
}
/**
* 构建行为规范 Prompt
*/
private buildGuidelinesPrompt(): string {
return `回答规范:
1. 语言风格
- 使用中文回答
- 保持专业但友好的语气
- 避免过于技术化的术语
2. 回答结构
- 先给出直接回答
- 然后提供详细分析
- 必要时引用具体资讯来源
3. 信息准确性
- 基于提供的上下文和工具结果回答
- 不确定时明确说明
- 引用资讯时注明来源和时间
4. 主动性
- 发现用户可能感兴趣的相关信息时主动提及
- 当信息不足时,主动使用工具获取
- 提供后续探索的建议
5. 格式化
- 使用 Markdown 格式
- 适当使用列表、标题等结构化元素
- 重要信息使用加粗或引用`;
}
/**
* 截断内容
*/
private truncateContent(content: string, maxLength: number): string {
if (content.length <= maxLength) {
return content;
}
return content.substring(0, maxLength) + '\n\n[内容过长,已截断...]';
}
}
```
---
### 1.3 对话管理器
```typescript
// backend/src/services/agent/conversation/conversation.manager.ts
import prisma from '../../../utils/prisma';
import { logger } from '../../../utils/logger';
export interface CreateConversationParams {
conversationId?: number;
userId?: string;
topicId: number;
reportId?: number;
articleId?: number;
}
export interface AddMessageParams {
role: string;
content: string;
toolCalls?: any;
}
export class ConversationManager {
/**
* 获取或创建对话
*/
async getOrCreate(params: CreateConversationParams) {
try {
// 如果提供了 conversationId,尝试获取
if (params.conversationId) {
const existing = await prisma.conversation.findUnique({
where: { id: params.conversationId },
});
if (existing) {
return existing;
}
}
// 创建新对话
const title = this.generateTitle(params);
const conversation = await prisma.conversation.create({
data: {
userId: params.userId,
topicId: params.topicId,
reportId: params.reportId,
articleId: params.articleId,
title,
},
});
logger.info(`Created conversation: ${conversation.id}`);
return conversation;
} catch (error) {
logger.error('Get or create conversation error:', error);
throw error;
}
}
/**
* 添加消息
*/
async addMessage(conversationId: number, params: AddMessageParams) {
try {
const message = await prisma.conversationMessage.create({
data: {
conversationId,
role: params.role,
content: params.content,
toolCalls: params.toolCalls,
},
});
// 更新对话的 updatedAt
await prisma.conversation.update({
where: { id: conversationId },
data: { updatedAt: new Date() },
});
return message;
} catch (error) {
logger.error('Add message error:', error);
throw error;
}
}
/**
* 获取对话消息
*/
async getMessages(conversationId: number) {
try {
const messages = await prisma.conversationMessage.findMany({
where: { conversationId },
orderBy: { createdAt: 'asc' },
});
return messages;
} catch (error) {
logger.error('Get messages error:', error);
throw error;
}
}
/**
* 获取对话详情
*/
async getConversation(conversationId: number) {
try {
const conversation = await prisma.conversation.findUnique({
where: { id: conversationId },
include: {
messages: {
orderBy: { createdAt: 'asc' },
},
topic: {
select: { name: true },
},
report: {
select: { title: true },
},
article: {
select: { title: true },
},
},
});
return conversation;
} catch (error) {
logger.error('Get conversation error:', error);
throw error;
}
}
/**
* 获取用户的对话列表
*/
async getUserConversations(userId: string) {
try {
const conversations = await prisma.conversation.findMany({
where: { userId },
orderBy: { updatedAt: 'desc' },
include: {
topic: {
select: { name: true },
},
messages: {
take: 1,
orderBy: { createdAt: 'desc' },
select: {
content: true,
createdAt: true,
},
},
},
});
return conversations;
} catch (error) {
logger.error('Get user conversations error:', error);
throw error;
}
}
/**
* 删除对话
*/
async deleteConversation(conversationId: number) {
try {
await prisma.conversation.delete({
where: { id: conversationId },
});
logger.info(`Deleted conversation: ${conversationId}`);
} catch (error) {
logger.error('Delete conversation error:', error);
throw error;
}
}
/**
* 生成对话标题
*/
private generateTitle(params: CreateConversationParams): string {
const timestamp = new Date().toLocaleString('zh-CN');
if (params.reportId) {
return `报告对话 - ${timestamp}`;
}
if (params.articleId) {
return `资讯对话 - ${timestamp}`;
}
return `主题对话 - ${timestamp}`;
}
}
```
---
## 二、前端实现
### 2.1 API 封装
```typescript
// frontend/src/api/agent.ts
import request from './request';
export interface ChatParams {
conversationId?: number;
reportId?: number;
articleId?: number;
topicId: number;
message: string;
llmConfigId: number;
userId?: string;
}
export interface Conversation {
id: number;
title: string;
topicId: number;
reportId?: number;
articleId?: number;
createdAt: string;
updatedAt: string;
messages: Message[];
}
export interface Message {
id: number;
role: string;
content: string;
toolCalls?: any;
createdAt: string;
}
/**
* 流式对话
*/
export async function streamChat(params: ChatParams): Promise<ReadableStream> {
const response = await fetch(`${import.meta.env.VITE_API_BASE_URL}/api/agent/chat`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(params),
});
if (!response.ok) {
throw new Error('Chat request failed');
}
return response.body!;
}
/**
* 获取对话详情
*/
export async function getConversation(id: number): Promise<Conversation> {
return request.get(`/agent/conversations/${id}`);
}
/**
* 获取对话列表
*/
export async function getConversations(userId: string): Promise<Conversation[]> {
return request.get('/agent/conversations', { params: { userId } });
}
/**
* 删除对话
*/
export async function deleteConversation(id: number): Promise<void> {
return request.delete(`/agent/conversations/${id}`);
}
```
---
### 2.2 Composable Hook
```typescript
// frontend/src/composables/useAgentChat.ts
import { ref, computed } from 'vue';
import { streamChat, type ChatParams, type Message } from '@/api/agent';
import { ElMessage } from 'element-plus';
export function useAgentChat() {
const messages = ref<Message[]>([]);
const isLoading = ref(false);
const currentStreamContent = ref('');
/**
* 发送消息
*/
async function sendMessage(params: ChatParams) {
isLoading.value = true;
currentStreamContent.value = '';
// 添加用户消息
messages.value.push({
id: Date.now(),
role: 'user',
content: params.message,
createdAt: new Date().toISOString(),
});
try {
const stream = await streamChat(params);
const reader = stream.getReader();
const decoder = new TextDecoder();
let assistantMessage: Message = {
id: Date.now() + 1,
role: 'assistant',
content: '',
createdAt: new Date().toISOString(),
};
messages.value.push(assistantMessage);
// 读取流
while (true) {
const { done, value } = await reader.read();
if (done) {
break;
}
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') {
continue;
}
try {
const parsed = JSON.parse(data);
// 处理文本流
if (parsed.type === 'text-delta') {
assistantMessage.content += parsed.textDelta;
currentStreamContent.value = assistantMessage.content;
}
// 处理工具调用
if (parsed.type === 'tool-call') {
// 可以在这里处理工具调用的显示
console.log('Tool call:', parsed);
}
} catch (e) {
// 忽略解析错误
}
}
}
}
} catch (error) {
console.error('Chat error:', error);
ElMessage.error('发送消息失败');
// 移除失败的消息
messages.value = messages.value.filter(m => m.id !== messages.value[messages.value.length - 1].id);
} finally {
isLoading.value = false;
currentStreamContent.value = '';
}
}
/**
* 清空消息
*/
function clearMessages() {
messages.value = [];
}
/**
* 加载历史消息
*/
function loadMessages(historyMessages: Message[]) {
messages.value = historyMessages;
}
return {
messages,
isLoading,
currentStreamContent,
sendMessage,
clearMessages,
loadMessages,
};
}
```
---
### 2.3 对话界面组件
```vue
<!-- frontend/src/views/agent/AgentChat.vue -->
<template>
<div class="agent-chat">
<el-card class="chat-container">
<!-- 头部 -->
<template #header>
<div class="chat-header">
<div class="header-left">
<h3>{{ title }}</h3>
<el-tag v-if="topicName" size="small">{{ topicName }}</el-tag>
</div>
<div class="header-right">
<el-button size="small" @click="handleClearChat">清空对话</el-button>
<el-button size="small" type="danger" @click="handleDeleteChat">删除对话</el-button>
</div>
</div>
</template>
<!-- 消息列表 -->
<div ref="messageListRef" class="message-list">
<MessageItem
v-for="message in messages"
:key="message.id"
:message="message"
/>
<!-- 流式输出中的消息 -->
<MessageItem
v-if="isLoading && currentStreamContent"
:message="{
id: 0,
role: 'assistant',
content: currentStreamContent,
createdAt: new Date().toISOString(),
}"
:streaming="true"
/>
<!-- 加载指示器 -->
<div v-if="isLoading && !currentStreamContent" class="loading-indicator">
<el-icon class="is-loading"><Loading /></el-icon>
<span>AI 正在思考...</span>
</div>
</div>
<!-- 输入区域 -->
<div class="input-area">
<el-input
v-model="inputMessage"
type="textarea"
:rows="3"
placeholder="输入你的问题... (Ctrl+Enter 发送)"
:disabled="isLoading"
@keydown.ctrl.enter="handleSendMessage"
/>
<div class="input-actions">
<el-button
type="primary"
:loading="isLoading"
:disabled="!inputMessage.trim()"
@click="handleSendMessage"
>
发送
</el-button>
</div>
</div>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, nextTick, watch } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Loading } from '@element-plus/icons-vue';
import MessageItem from '@/components/agent/MessageItem.vue';
import { useAgentChat } from '@/composables/useAgentChat';
import { getConversation, deleteConversation } from '@/api/agent';
const route = useRoute();
const router = useRouter();
const conversationId = computed(() => {
const id = route.query.conversationId;
return id ? Number(id) : undefined;
});
const reportId = computed(() => {
const id = route.query.reportId;
return id ? Number(id) : undefined;
});
const articleId = computed(() => {
const id = route.query.articleId;
return id ? Number(id) : undefined;
});
const topicId = computed(() => Number(route.query.topicId));
const llmConfigId = computed(() => Number(route.query.llmConfigId || 1));
const title = ref('AI 对话');
const topicName = ref('');
const inputMessage = ref('');
const messageListRef = ref<HTMLElement>();
const {
messages,
isLoading,
currentStreamContent,
sendMessage,
clearMessages,
loadMessages,
} = useAgentChat();
// 加载对话历史
onMounted(async () => {
if (conversationId.value) {
try {
const conversation = await getConversation(conversationId.value);
title.value = conversation.title;
topicName.value = conversation.topic?.name || '';
loadMessages(conversation.messages);
} catch (error) {
ElMessage.error('加载对话失败');
}
}
});
// 自动滚动到底部
watch([messages, currentStreamContent], () => {
nextTick(() => {
if (messageListRef.value) {
messageListRef.value.scrollTop = messageListRef.value.scrollHeight;
}
});
});
// 发送消息
async function handleSendMessage() {
if (!inputMessage.value.trim() || isLoading.value) {
return;
}
const message = inputMessage.value;
inputMessage.value = '';
await sendMessage({
conversationId: conversationId.value,
reportId: reportId.value,
articleId: articleId.value,
topicId: topicId.value,
message,
llmConfigId: llmConfigId.value,
userId: 'default-user', // TODO: 从用户状态获取
});
}
// 清空对话
async function handleClearChat() {
try {
await ElMessageBox.confirm('确定要清空当前对话吗?', '提示', {
type: 'warning',
});
clearMessages();
ElMessage.success('已清空对话');
} catch {
// 用户取消
}
}
// 删除对话
async function handleDeleteChat() {
if (!conversationId.value) {
ElMessage.warning('当前对话未保存');
return;
}
try {
await ElMessageBox.confirm('确定要删除这个对话吗?此操作不可恢复。', '提示', {
type: 'warning',
});
await deleteConversation(conversationId.value);
ElMessage.success('已删除对话');
router.push('/agent/conversations');
} catch (error) {
if (error !== 'cancel') {
ElMessage.error('删除对话失败');
}
}
}
</script>
<style scoped>
.agent-chat {
height: 100%;
padding: 20px;
}
.chat-container {
height: 100%;
display: flex;
flex-direction: column;
}
.chat-header {
display: flex;
justify-content: space-between;
align-items: center;
}
.header-left {
display: flex;
align-items: center;
gap: 10px;
}
.header-left h3 {
margin: 0;
}
.message-list {
flex: 1;
overflow-y: auto;
padding: 20px;
min-height: 400px;
max-height: 600px;
}
.loading-indicator {
display: flex;
align-items: center;
gap: 10px;
color: #909399;
padding: 10px;
}
.input-area {
border-top: 1px solid #e6e6e6;
padding: 20px;
}
.input-actions {
margin-top: 10px;
display: flex;
justify-content: flex-end;
}
</style>
```
---
## 三、下一步
继续创建消息组件和对话列表组件...