Files
learn-ai/docs/tasks/task-15-agent-implementation-part3.md
T

803 lines
16 KiB
Markdown
Raw Normal View History

2026-02-06 09:58:47 +08:00
# 任务 15:AI Agent 详细实现(第三部分)
## 一、前端组件实现
### 1.1 消息项组件
```vue
<!-- frontend/src/components/agent/MessageItem.vue -->
<template>
<div :class="['message-item', message.role]">
<div class="message-avatar">
<el-avatar v-if="message.role === 'user'" :size="40">
<el-icon><User /></el-icon>
</el-avatar>
<el-avatar v-else :size="40" style="background-color: #409eff">
<el-icon><ChatDotRound /></el-icon>
</el-avatar>
</div>
<div class="message-content-wrapper">
<div class="message-meta">
<span class="message-role">{{ roleLabel }}</span>
<span class="message-time">{{ formattedTime }}</span>
</div>
<div class="message-content">
<!-- Markdown 渲染 -->
<div v-if="message.role === 'assistant'" v-html="renderedContent" class="markdown-body" />
<!-- 用户消息 -->
<div v-else class="user-message">{{ message.content }}</div>
<!-- 流式输出指示器 -->
<span v-if="streaming" class="streaming-cursor">▊</span>
</div>
<!-- 工具调用展示 -->
<ToolCallDisplay v-if="message.toolCalls" :tool-calls="message.toolCalls" />
</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue';
import { User, ChatDotRound } from '@element-plus/icons-vue';
import MarkdownIt from 'markdown-it';
import hljs from 'highlight.js';
import 'highlight.js/styles/github.css';
import ToolCallDisplay from './ToolCallDisplay.vue';
interface Props {
message: {
id: number;
role: string;
content: string;
toolCalls?: any;
createdAt: string;
};
streaming?: boolean;
}
const props = defineProps<Props>();
// Markdown 渲染器
const md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
highlight: (str, lang) => {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value;
} catch {}
}
return '';
},
});
const roleLabel = computed(() => {
const labels: Record<string, string> = {
user: '你',
assistant: 'AI 助手',
system: '系统',
tool: '工具',
};
return labels[props.message.role] || props.message.role;
});
const formattedTime = computed(() => {
const date = new Date(props.message.createdAt);
return date.toLocaleTimeString('zh-CN', {
hour: '2-digit',
minute: '2-digit',
});
});
const renderedContent = computed(() => {
return md.render(props.message.content);
});
</script>
<style scoped>
.message-item {
display: flex;
gap: 12px;
margin-bottom: 24px;
animation: fadeIn 0.3s ease-in;
}
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.message-avatar {
flex-shrink: 0;
}
.message-content-wrapper {
flex: 1;
min-width: 0;
}
.message-meta {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 8px;
font-size: 12px;
color: #909399;
}
.message-role {
font-weight: 600;
color: #303133;
}
.message-content {
position: relative;
padding: 12px 16px;
border-radius: 8px;
background-color: #f5f7fa;
word-wrap: break-word;
}
.message-item.user .message-content {
background-color: #409eff;
color: white;
}
.user-message {
white-space: pre-wrap;
}
.markdown-body {
font-size: 14px;
line-height: 1.6;
}
.markdown-body :deep(h1),
.markdown-body :deep(h2),
.markdown-body :deep(h3) {
margin-top: 16px;
margin-bottom: 8px;
font-weight: 600;
}
.markdown-body :deep(p) {
margin-bottom: 8px;
}
.markdown-body :deep(code) {
padding: 2px 6px;
background-color: rgba(0, 0, 0, 0.06);
border-radius: 3px;
font-family: 'Courier New', monospace;
font-size: 13px;
}
.markdown-body :deep(pre) {
padding: 12px;
background-color: #f6f8fa;
border-radius: 6px;
overflow-x: auto;
margin: 8px 0;
}
.markdown-body :deep(pre code) {
padding: 0;
background-color: transparent;
}
.markdown-body :deep(ul),
.markdown-body :deep(ol) {
padding-left: 24px;
margin-bottom: 8px;
}
.markdown-body :deep(blockquote) {
padding-left: 12px;
border-left: 4px solid #dfe2e5;
color: #6a737d;
margin: 8px 0;
}
.streaming-cursor {
display: inline-block;
animation: blink 1s infinite;
margin-left: 2px;
}
@keyframes blink {
0%, 50% {
opacity: 1;
}
51%, 100% {
opacity: 0;
}
}
</style>
```
---
### 1.2 工具调用展示组件
```vue
<!-- frontend/src/components/agent/ToolCallDisplay.vue -->
<template>
<div class="tool-call-display">
<el-collapse v-model="activeNames">
<el-collapse-item
v-for="(call, index) in toolCalls"
:key="index"
:name="index"
>
<template #title>
<div class="tool-call-header">
<el-icon><Tools /></el-icon>
<span class="tool-name">{{ getToolName(call.name) }}</span>
<el-tag size="small" type="info">工具调用</el-tag>
</div>
</template>
<div class="tool-call-content">
<div class="tool-section">
<div class="section-title">输入参数</div>
<pre class="code-block">{{ formatJson(call.arguments) }}</pre>
</div>
<div v-if="call.result" class="tool-section">
<div class="section-title">执行结果</div>
<pre class="code-block">{{ formatJson(call.result) }}</pre>
</div>
</div>
</el-collapse-item>
</el-collapse>
</div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { Tools } from '@element-plus/icons-vue';
interface Props {
toolCalls: Array<{
name: string;
arguments: any;
result?: any;
}>;
}
defineProps<Props>();
const activeNames = ref<number[]>([]);
const toolNameMap: Record<string, string> = {
searchArticles: '搜索资讯',
analyzeReport: '分析报告',
webSearch: '联网搜索',
};
function getToolName(name: string): string {
return toolNameMap[name] || name;
}
function formatJson(obj: any): string {
try {
return JSON.stringify(obj, null, 2);
} catch {
return String(obj);
}
}
</script>
<style scoped>
.tool-call-display {
margin-top: 12px;
border-top: 1px solid #e6e6e6;
padding-top: 12px;
}
.tool-call-header {
display: flex;
align-items: center;
gap: 8px;
}
.tool-name {
font-weight: 600;
color: #303133;
}
.tool-call-content {
padding: 12px;
background-color: #fafafa;
border-radius: 4px;
}
.tool-section {
margin-bottom: 16px;
}
.tool-section:last-child {
margin-bottom: 0;
}
.section-title {
font-size: 13px;
font-weight: 600;
color: #606266;
margin-bottom: 8px;
}
.code-block {
padding: 12px;
background-color: #f6f8fa;
border-radius: 4px;
font-family: 'Courier New', monospace;
font-size: 12px;
overflow-x: auto;
margin: 0;
}
</style>
```
---
### 1.3 对话列表组件
```vue
<!-- frontend/src/views/agent/ConversationList.vue -->
<template>
<div class="conversation-list">
<el-card>
<template #header>
<div class="header">
<h3>对话历史</h3>
<el-button type="primary" @click="handleNewConversation">
新建对话
</el-button>
</div>
</template>
<el-empty v-if="conversations.length === 0" description="暂无对话记录" />
<div v-else class="conversation-items">
<div
v-for="conversation in conversations"
:key="conversation.id"
class="conversation-item"
@click="handleOpenConversation(conversation)"
>
<div class="conversation-info">
<div class="conversation-title">{{ conversation.title }}</div>
<div class="conversation-meta">
<el-tag size="small">{{ conversation.topic?.name }}</el-tag>
<span class="conversation-time">
{{ formatTime(conversation.updatedAt) }}
</span>
</div>
<div v-if="conversation.messages?.[0]" class="conversation-preview">
{{ conversation.messages[0].content.substring(0, 100) }}...
</div>
</div>
<div class="conversation-actions">
<el-button
size="small"
type="danger"
text
@click.stop="handleDeleteConversation(conversation.id)"
>
删除
</el-button>
</div>
</div>
</div>
</el-card>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getConversations, deleteConversation } from '@/api/agent';
const router = useRouter();
const conversations = ref<any[]>([]);
onMounted(async () => {
await loadConversations();
});
async function loadConversations() {
try {
conversations.value = await getConversations('default-user'); // TODO: 从用户状态获取
} catch (error) {
ElMessage.error('加载对话列表失败');
}
}
function handleNewConversation() {
router.push({
path: '/agent/chat',
query: {
topicId: 1, // TODO: 让用户选择主题
llmConfigId: 1,
},
});
}
function handleOpenConversation(conversation: any) {
router.push({
path: '/agent/chat',
query: {
conversationId: conversation.id,
topicId: conversation.topicId,
reportId: conversation.reportId,
articleId: conversation.articleId,
llmConfigId: 1,
},
});
}
async function handleDeleteConversation(id: number) {
try {
await ElMessageBox.confirm('确定要删除这个对话吗?', '提示', {
type: 'warning',
});
await deleteConversation(id);
ElMessage.success('删除成功');
await loadConversations();
} catch (error) {
if (error !== 'cancel') {
ElMessage.error('删除失败');
}
}
}
function formatTime(time: string): string {
const date = new Date(time);
const now = new Date();
const diff = now.getTime() - date.getTime();
const minutes = Math.floor(diff / 60000);
const hours = Math.floor(diff / 3600000);
const days = Math.floor(diff / 86400000);
if (minutes < 1) return '刚刚';
if (minutes < 60) return `${minutes}分钟前`;
if (hours < 24) return `${hours}小时前`;
if (days < 7) return `${days}天前`;
return date.toLocaleDateString('zh-CN');
}
</script>
<style scoped>
.conversation-list {
padding: 20px;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
}
.header h3 {
margin: 0;
}
.conversation-items {
display: flex;
flex-direction: column;
gap: 12px;
}
.conversation-item {
display: flex;
justify-content: space-between;
align-items: flex-start;
padding: 16px;
border: 1px solid #e6e6e6;
border-radius: 8px;
cursor: pointer;
transition: all 0.3s;
}
.conversation-item:hover {
border-color: #409eff;
background-color: #f5f7fa;
}
.conversation-info {
flex: 1;
}
.conversation-title {
font-size: 16px;
font-weight: 600;
color: #303133;
margin-bottom: 8px;
}
.conversation-meta {
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 8px;
}
.conversation-time {
font-size: 12px;
color: #909399;
}
.conversation-preview {
font-size: 14px;
color: #606266;
line-height: 1.5;
}
.conversation-actions {
flex-shrink: 0;
}
</style>
```
---
## 二、数据库迁移
### 2.1 Prisma Schema 更新
```prisma
// backend/prisma/schema.prisma
// ... 其他模型 ...
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])
@@map("conversations")
}
model ConversationMessage {
id Int @id @default(autoincrement())
conversationId Int
role String
content String @db.Text
toolCalls Json?
createdAt DateTime @default(now())
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
@@index([conversationId])
@@map("conversation_messages")
}
// 更新其他模型,添加关联
model Topic {
// ... 现有字段 ...
conversations Conversation[]
}
model Report {
// ... 现有字段 ...
conversations Conversation[]
}
model Article {
// ... 现有字段 ...
conversations Conversation[]
}
```
### 2.2 执行迁移
```bash
# 生成迁移文件
npx prisma migrate dev --name add_agent_tables
# 生成 Prisma Client
npx prisma generate
```
---
## 三、路由配置
### 3.1 后端路由注册
```typescript
// backend/src/app.ts
import { agentRoutes } from './routes/agent.routes';
// ... 其他代码 ...
// 注册 Agent 路由
fastify.register(agentRoutes, { prefix: '/api/agent' });
```
### 3.2 前端路由配置
```typescript
// frontend/src/router/index.ts
import { createRouter, createWebHistory } from 'vue-router';
const routes = [
// ... 其他路由 ...
{
path: '/agent',
name: 'Agent',
children: [
{
path: 'conversations',
name: 'ConversationList',
component: () => import('@/views/agent/ConversationList.vue'),
meta: { title: '对话列表' },
},
{
path: 'chat',
name: 'AgentChat',
component: () => import('@/views/agent/AgentChat.vue'),
meta: { title: 'AI 对话' },
},
],
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
export default router;
```
---
## 四、依赖安装
### 4.1 后端依赖
```bash
cd backend
# 安装 Vercel AI SDK
npm install ai @ai-sdk/openai zod
# 如果使用其他 LLM 提供商
npm install @ai-sdk/anthropic # Anthropic Claude
npm install @ai-sdk/google # Google Gemini
```
### 4.2 前端依赖
```bash
cd frontend
# 安装 Markdown 渲染
npm install markdown-it @types/markdown-it
# 安装代码高亮
npm install highlight.js
# 安装 SSE 解析(如果需要)
npm install eventsource-parser
```
---
## 五、配置文件
### 5.1 环境变量配置
```env
# backend/.env
# 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
AGENT_MAX_CONTEXT_LENGTH=8000
# 搜索 API(可选)
GOOGLE_SEARCH_API_KEY=xxx
GOOGLE_SEARCH_ENGINE_ID=xxx
```
### 5.2 前端环境变量
```env
# frontend/.env
VITE_API_BASE_URL=http://localhost:3000
VITE_AGENT_STREAM_TIMEOUT=60000
```
---
## 六、测试示例
### 6.1 后端单元测试
```typescript
// backend/src/services/agent/__tests__/agent.service.test.ts
import { describe, it, expect, beforeEach } from 'vitest';
import { AgentService } from '../agent.service';
describe('AgentService', () => {
let agentService: AgentService;
beforeEach(() => {
agentService = new AgentService();
});
it('should create conversation', async () => {
// TODO: 实现测试
});
it('should stream chat response', async () => {
// TODO: 实现测试
});
it('should call tools correctly', async () => {
// TODO: 实现测试
});
});
```
### 6.2 API 测试
```bash
# 测试流式对话
curl -X POST http://localhost:3000/api/agent/chat \
-H "Content-Type: application/json" \
-d '{
"topicId": 1,
"message": "帮我搜索最新的 AI 新闻",
"llmConfigId": 1,
"userId": "test-user"
}'
```
---
## 七、下一步
继续创建部署和优化文档...