后端实现: - 集成 Vercel AI SDK 实现流式对话 - 实现工具系统(文章搜索、报告分析、网络搜索) - 实现上下文加载和提示词构建 - 实现对话管理和消息存储 - 添加 Agent API 路由(流式对话、历史记录) 前端实现: - 实现聊天界面(配置选择、消息展示、历史记录) - 支持 Markdown 渲染和代码高亮 - 实现流式响应解析和展示 - 优化布局(单侧边栏 + 可折叠历史面板) - 修复 API 路径和 CORS 问题 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
676 lines
14 KiB
Markdown
676 lines
14 KiB
Markdown
# 任务 15:AI Agent 快速开始指南
|
||
|
||
## 一、快速开始(5 分钟)
|
||
|
||
### 1.1 安装依赖
|
||
|
||
```bash
|
||
# 后端依赖
|
||
cd backend
|
||
npm install ai @ai-sdk/openai zod
|
||
|
||
# 前端依赖
|
||
cd ../frontend
|
||
npm install markdown-it @types/markdown-it highlight.js
|
||
```
|
||
|
||
### 1.2 配置环境变量
|
||
|
||
```bash
|
||
# backend/.env
|
||
DEFAULT_LLM_API_KEY=sk-your-openai-api-key
|
||
DEFAULT_LLM_MODEL=gpt-4
|
||
DEFAULT_LLM_BASE_URL=https://api.openai.com/v1
|
||
```
|
||
|
||
### 1.3 数据库迁移
|
||
|
||
```bash
|
||
cd backend
|
||
npx prisma migrate dev --name add_agent_tables
|
||
npx prisma generate
|
||
```
|
||
|
||
### 1.4 启动服务
|
||
|
||
```bash
|
||
# 启动后端
|
||
cd backend
|
||
npm run dev
|
||
|
||
# 启动前端
|
||
cd frontend
|
||
npm run dev
|
||
```
|
||
|
||
### 1.5 访问应用
|
||
|
||
打开浏览器访问:`http://localhost:5173/agent/chat?topicId=1&llmConfigId=1`
|
||
|
||
---
|
||
|
||
## 二、核心文件清单
|
||
|
||
### 2.1 后端核心文件
|
||
|
||
```
|
||
backend/src/
|
||
├── services/agent/
|
||
│ ├── agent.service.ts # ⭐ 核心服务
|
||
│ ├── tools/
|
||
│ │ ├── article-search.tool.ts # 资讯检索工具
|
||
│ │ ├── report-analysis.tool.ts # 报告分析工具
|
||
│ │ └── web-search.tool.ts # 联网搜索工具
|
||
│ ├── context/
|
||
│ │ ├── context-loader.ts # 上下文加载器
|
||
│ │ └── prompt-builder.ts # Prompt 构建器
|
||
│ └── conversation/
|
||
│ └── conversation.manager.ts # 对话管理器
|
||
└── routes/
|
||
└── agent.routes.ts # ⭐ API 路由
|
||
```
|
||
|
||
### 2.2 前端核心文件
|
||
|
||
```
|
||
frontend/src/
|
||
├── views/agent/
|
||
│ ├── AgentChat.vue # ⭐ 对话界面
|
||
│ └── ConversationList.vue # 对话列表
|
||
├── components/agent/
|
||
│ ├── MessageItem.vue # 消息项组件
|
||
│ └── ToolCallDisplay.vue # 工具调用展示
|
||
├── composables/
|
||
│ └── useAgentChat.ts # ⭐ 对话 Hook
|
||
└── api/
|
||
└── agent.ts # API 封装
|
||
```
|
||
|
||
---
|
||
|
||
## 三、开发流程
|
||
|
||
### 3.1 添加新工具
|
||
|
||
**步骤 1:创建工具文件**
|
||
|
||
```typescript
|
||
// backend/src/services/agent/tools/my-tool.tool.ts
|
||
import { tool } from 'ai';
|
||
import { z } from 'zod';
|
||
|
||
export class MyTool {
|
||
static create() {
|
||
return tool({
|
||
description: '工具描述',
|
||
parameters: z.object({
|
||
param1: z.string().describe('参数描述'),
|
||
}),
|
||
execute: async ({ param1 }) => {
|
||
// 工具逻辑
|
||
return { success: true, result: 'xxx' };
|
||
},
|
||
});
|
||
}
|
||
}
|
||
```
|
||
|
||
**步骤 2:注册工具**
|
||
|
||
```typescript
|
||
// backend/src/services/agent/agent.service.ts
|
||
import { MyTool } from './tools/my-tool.tool';
|
||
|
||
const tools = {
|
||
searchArticles: ArticleSearchTool.create(),
|
||
analyzeReport: ReportAnalysisTool.create(),
|
||
webSearch: WebSearchTool.create(),
|
||
myTool: MyTool.create(), // 添加新工具
|
||
};
|
||
```
|
||
|
||
### 3.2 自定义 Prompt
|
||
|
||
编辑 `backend/src/services/agent/context/prompt-builder.ts`:
|
||
|
||
```typescript
|
||
private buildCapabilitiesPrompt(): string {
|
||
return `你可以使用以下工具:
|
||
|
||
1. searchArticles - 搜索资讯
|
||
2. analyzeReport - 分析报告
|
||
3. webSearch - 联网搜索
|
||
4. myTool - 我的自定义工具 // 添加说明
|
||
|
||
使用原则:
|
||
- 优先使用数据库信息
|
||
- 必要时使用联网搜索`;
|
||
}
|
||
```
|
||
|
||
### 3.3 修改 UI 样式
|
||
|
||
编辑 `frontend/src/components/agent/MessageItem.vue`:
|
||
|
||
```vue
|
||
<style scoped>
|
||
.message-content {
|
||
padding: 12px 16px;
|
||
border-radius: 8px;
|
||
background-color: #f5f7fa; /* 修改背景色 */
|
||
}
|
||
|
||
.message-item.user .message-content {
|
||
background-color: #409eff; /* 修改用户消息颜色 */
|
||
color: white;
|
||
}
|
||
</style>
|
||
```
|
||
|
||
---
|
||
|
||
## 四、常见使用场景
|
||
|
||
### 4.1 场景 1:基于报告的对话
|
||
|
||
```typescript
|
||
// 前端调用
|
||
const { sendMessage } = useAgentChat();
|
||
|
||
await sendMessage({
|
||
reportId: 123, // 指定报告 ID
|
||
topicId: 1,
|
||
message: '这份报告的核心观点是什么?',
|
||
llmConfigId: 1,
|
||
userId: 'user-123',
|
||
});
|
||
```
|
||
|
||
### 4.2 场景 2:基于资讯的对话
|
||
|
||
```typescript
|
||
await sendMessage({
|
||
articleId: 456, // 指定资讯 ID
|
||
topicId: 1,
|
||
message: '这篇文章提到的技术有哪些应用场景?',
|
||
llmConfigId: 1,
|
||
userId: 'user-123',
|
||
});
|
||
```
|
||
|
||
### 4.3 场景 3:主题探索
|
||
|
||
```typescript
|
||
await sendMessage({
|
||
topicId: 1, // 只指定主题
|
||
message: '最近 AI 领域有哪些重要进展?',
|
||
llmConfigId: 1,
|
||
userId: 'user-123',
|
||
});
|
||
```
|
||
|
||
### 4.4 场景 4:多轮对话
|
||
|
||
```typescript
|
||
// 第一轮
|
||
await sendMessage({
|
||
topicId: 1,
|
||
message: '介绍一下 GPT-4',
|
||
llmConfigId: 1,
|
||
userId: 'user-123',
|
||
});
|
||
|
||
// 第二轮(自动关联上下文)
|
||
await sendMessage({
|
||
conversationId: 789, // 使用同一个对话 ID
|
||
topicId: 1,
|
||
message: '它和 GPT-3 有什么区别?',
|
||
llmConfigId: 1,
|
||
userId: 'user-123',
|
||
});
|
||
```
|
||
|
||
---
|
||
|
||
## 五、配置选项
|
||
|
||
### 5.1 LLM 配置
|
||
|
||
```typescript
|
||
// 支持的 LLM 提供商
|
||
const providers = {
|
||
openai: {
|
||
baseUrl: 'https://api.openai.com/v1',
|
||
models: ['gpt-4', 'gpt-4-turbo', 'gpt-3.5-turbo'],
|
||
},
|
||
deepseek: {
|
||
baseUrl: 'https://api.deepseek.com/v1',
|
||
models: ['deepseek-chat', 'deepseek-coder'],
|
||
},
|
||
qwen: {
|
||
baseUrl: 'https://dashscope.aliyuncs.com/compatible-mode/v1',
|
||
models: ['qwen-turbo', 'qwen-plus', 'qwen-max'],
|
||
},
|
||
};
|
||
```
|
||
|
||
### 5.2 Agent 配置
|
||
|
||
```typescript
|
||
// backend/src/services/agent/agent.service.ts
|
||
|
||
const result = streamText({
|
||
model,
|
||
system: systemPrompt,
|
||
messages,
|
||
tools,
|
||
maxSteps: 5, // 最大工具调用步数
|
||
temperature: 0.7, // 温度(0-1)
|
||
maxTokens: 2000, // 最大 token 数
|
||
topP: 0.9, // Top-p 采样
|
||
});
|
||
```
|
||
|
||
### 5.3 上下文配置
|
||
|
||
```typescript
|
||
// backend/src/services/agent/context/context-loader.ts
|
||
|
||
export class ContextLoader {
|
||
private maxContextLength = 8000; // 最大上下文长度
|
||
private maxRelatedArticles = 10; // 最大相关资讯数
|
||
private relatedArticlesDays = 7; // 相关资讯时间范围(天)
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 六、API 参考
|
||
|
||
### 6.1 POST /api/agent/chat
|
||
|
||
**请求体:**
|
||
|
||
```json
|
||
{
|
||
"conversationId": 123, // 可选,对话 ID
|
||
"reportId": 456, // 可选,报告 ID
|
||
"articleId": 789, // 可选,资讯 ID
|
||
"topicId": 1, // 必需,主题 ID
|
||
"message": "你的问题", // 必需,用户消息
|
||
"llmConfigId": 1, // 必需,LLM 配置 ID
|
||
"userId": "user-123" // 可选,用户 ID
|
||
}
|
||
```
|
||
|
||
**响应:** Server-Sent Events (SSE) 流
|
||
|
||
```
|
||
data: {"type":"text-delta","textDelta":"你好"}
|
||
data: {"type":"text-delta","textDelta":","}
|
||
data: {"type":"tool-call","toolName":"searchArticles","args":{...}}
|
||
data: {"type":"tool-result","result":{...}}
|
||
data: [DONE]
|
||
```
|
||
|
||
### 6.2 GET /api/agent/conversations/:id
|
||
|
||
**响应:**
|
||
|
||
```json
|
||
{
|
||
"id": 123,
|
||
"title": "对话标题",
|
||
"topicId": 1,
|
||
"reportId": 456,
|
||
"articleId": null,
|
||
"createdAt": "2026-02-05T10:00:00Z",
|
||
"updatedAt": "2026-02-05T10:30:00Z",
|
||
"messages": [
|
||
{
|
||
"id": 1,
|
||
"role": "user",
|
||
"content": "你好",
|
||
"createdAt": "2026-02-05T10:00:00Z"
|
||
},
|
||
{
|
||
"id": 2,
|
||
"role": "assistant",
|
||
"content": "你好!有什么可以帮助你的吗?",
|
||
"createdAt": "2026-02-05T10:00:05Z"
|
||
}
|
||
]
|
||
}
|
||
```
|
||
|
||
### 6.3 GET /api/agent/conversations
|
||
|
||
**查询参数:**
|
||
- `userId`: 用户 ID
|
||
|
||
**响应:**
|
||
|
||
```json
|
||
[
|
||
{
|
||
"id": 123,
|
||
"title": "对话标题",
|
||
"topicId": 1,
|
||
"createdAt": "2026-02-05T10:00:00Z",
|
||
"updatedAt": "2026-02-05T10:30:00Z",
|
||
"topic": { "name": "AI 技术" },
|
||
"messages": [
|
||
{
|
||
"content": "最后一条消息内容",
|
||
"createdAt": "2026-02-05T10:30:00Z"
|
||
}
|
||
]
|
||
}
|
||
]
|
||
```
|
||
|
||
### 6.4 DELETE /api/agent/conversations/:id
|
||
|
||
**响应:**
|
||
|
||
```json
|
||
{
|
||
"success": true
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 七、故障排查
|
||
|
||
### 7.1 问题:流式响应不工作
|
||
|
||
**检查项:**
|
||
1. 确认后端返回了正确的 SSE 头
|
||
2. 检查前端是否正确处理流
|
||
3. 查看浏览器控制台错误
|
||
|
||
**解决方案:**
|
||
|
||
```typescript
|
||
// 后端确保设置正确的响应头
|
||
reply.raw.setHeader('Content-Type', 'text/event-stream');
|
||
reply.raw.setHeader('Cache-Control', 'no-cache');
|
||
reply.raw.setHeader('Connection', 'keep-alive');
|
||
```
|
||
|
||
### 7.2 问题:工具调用失败
|
||
|
||
**检查项:**
|
||
1. 工具参数验证是否通过
|
||
2. 数据库连接是否正常
|
||
3. 查看后端日志
|
||
|
||
**解决方案:**
|
||
|
||
```typescript
|
||
// 添加详细的错误日志
|
||
execute: async (params) => {
|
||
try {
|
||
logger.info('Tool execution started', { params });
|
||
const result = await doSomething(params);
|
||
logger.info('Tool execution completed', { result });
|
||
return result;
|
||
} catch (error) {
|
||
logger.error('Tool execution failed', { error, params });
|
||
throw error;
|
||
}
|
||
}
|
||
```
|
||
|
||
### 7.3 问题:上下文过长
|
||
|
||
**检查项:**
|
||
1. 报告/资讯内容是否过长
|
||
2. 历史消息数量是否过多
|
||
|
||
**解决方案:**
|
||
|
||
```typescript
|
||
// 限制上下文长度
|
||
const context = await this.contextLoader.load(params);
|
||
const compressed = this.contextCompressor.compress(context, 8000);
|
||
|
||
// 限制历史消息数量
|
||
const messages = await this.conversationManager.getRecentMessages(
|
||
conversationId,
|
||
10 // 只获取最近 10 条
|
||
);
|
||
```
|
||
|
||
### 7.4 问题:响应速度慢
|
||
|
||
**优化建议:**
|
||
|
||
1. **使用更快的模型**
|
||
```typescript
|
||
model: 'gpt-3.5-turbo' // 而不是 gpt-4
|
||
```
|
||
|
||
2. **减少上下文长度**
|
||
```typescript
|
||
maxContextLength: 4000 // 而不是 8000
|
||
```
|
||
|
||
3. **限制工具调用步数**
|
||
```typescript
|
||
maxSteps: 3 // 而不是 5
|
||
```
|
||
|
||
4. **启用缓存**
|
||
```typescript
|
||
// 缓存 LLM 配置
|
||
private llmConfigCache = new Map();
|
||
```
|
||
|
||
---
|
||
|
||
## 八、最佳实践
|
||
|
||
### 8.1 Prompt 设计
|
||
|
||
✅ **好的 Prompt:**
|
||
```typescript
|
||
`你是一个专业的资讯分析助手。
|
||
|
||
当前上下文:
|
||
- 主题:AI 技术
|
||
- 报告:《2024 AI 发展报告》
|
||
|
||
你的任务:
|
||
1. 基于提供的上下文回答问题
|
||
2. 必要时使用工具获取更多信息
|
||
3. 引用具体来源
|
||
|
||
回答要求:
|
||
- 使用中文
|
||
- 结构清晰
|
||
- 引用来源`
|
||
```
|
||
|
||
❌ **不好的 Prompt:**
|
||
```typescript
|
||
`你是 AI 助手,回答用户问题。`
|
||
```
|
||
|
||
### 8.2 工具设计
|
||
|
||
✅ **好的工具:**
|
||
```typescript
|
||
tool({
|
||
description: '搜索资讯数据库,查找相关的新闻和文章。适用于用户询问特定主题或关键词的资讯时。',
|
||
parameters: z.object({
|
||
query: z.string().describe('搜索关键词,例如:"人工智能"、"GPT-4"'),
|
||
limit: z.number().default(10).describe('返回结果数量,默认 10 条'),
|
||
}),
|
||
execute: async ({ query, limit }) => {
|
||
// 清晰的返回结构
|
||
return {
|
||
success: true,
|
||
count: results.length,
|
||
articles: results.map(a => ({
|
||
id: a.id,
|
||
title: a.title,
|
||
summary: a.summary,
|
||
})),
|
||
};
|
||
},
|
||
});
|
||
```
|
||
|
||
❌ **不好的工具:**
|
||
```typescript
|
||
tool({
|
||
description: '搜索',
|
||
parameters: z.object({
|
||
q: z.string(),
|
||
}),
|
||
execute: async ({ q }) => {
|
||
return results; // 返回结构不清晰
|
||
},
|
||
});
|
||
```
|
||
|
||
### 8.3 错误处理
|
||
|
||
✅ **好的错误处理:**
|
||
```typescript
|
||
try {
|
||
const result = await agentService.streamChat(params);
|
||
return result;
|
||
} catch (error) {
|
||
logger.error('Chat error:', {
|
||
error: error.message,
|
||
stack: error.stack,
|
||
params,
|
||
});
|
||
|
||
reply.status(500).send({
|
||
error: 'Chat failed',
|
||
message: '对话失败,请稍后重试',
|
||
requestId: generateRequestId(),
|
||
});
|
||
}
|
||
```
|
||
|
||
❌ **不好的错误处理:**
|
||
```typescript
|
||
try {
|
||
return await agentService.streamChat(params);
|
||
} catch (error) {
|
||
throw error; // 没有日志,没有友好提示
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 九、性能优化建议
|
||
|
||
### 9.1 数据库优化
|
||
|
||
```sql
|
||
-- 添加全文索引
|
||
ALTER TABLE articles ADD FULLTEXT INDEX ft_search (title, content, summary);
|
||
|
||
-- 添加复合索引
|
||
CREATE INDEX idx_topic_published ON articles(topicId, publishedAt DESC);
|
||
|
||
-- 定期清理旧数据
|
||
DELETE FROM conversation_messages
|
||
WHERE createdAt < DATE_SUB(NOW(), INTERVAL 90 DAY);
|
||
```
|
||
|
||
### 9.2 缓存策略
|
||
|
||
```typescript
|
||
// 1. LLM 配置缓存
|
||
private llmConfigCache = new Map();
|
||
|
||
// 2. 上下文缓存(短期)
|
||
private contextCache = new Map();
|
||
|
||
// 3. 工具结果缓存
|
||
private toolResultCache = new Map();
|
||
```
|
||
|
||
### 9.3 并发控制
|
||
|
||
```typescript
|
||
// 限制并发对话数
|
||
const maxConcurrentChats = 10;
|
||
const activeChatSemaphore = new Semaphore(maxConcurrentChats);
|
||
|
||
async streamChat(params) {
|
||
await activeChatSemaphore.acquire();
|
||
try {
|
||
return await this.doStreamChat(params);
|
||
} finally {
|
||
activeChatSemaphore.release();
|
||
}
|
||
}
|
||
```
|
||
|
||
---
|
||
|
||
## 十、下一步
|
||
|
||
### 10.1 功能增强
|
||
|
||
- [ ] 添加向量数据库支持(RAG 增强)
|
||
- [ ] 支持多模态输入(图片、文件)
|
||
- [ ] 实现 Agent 记忆系统
|
||
- [ ] 添加更多专业工具
|
||
- [ ] 支持多 Agent 协作
|
||
|
||
### 10.2 体验优化
|
||
|
||
- [ ] 添加打字机效果
|
||
- [ ] 支持消息编辑和重新生成
|
||
- [ ] 添加对话分享功能
|
||
- [ ] 支持语音输入/输出
|
||
- [ ] 添加快捷指令
|
||
|
||
### 10.3 运维增强
|
||
|
||
- [ ] 集成 LangSmith 监控
|
||
- [ ] 添加成本追踪
|
||
- [ ] 实现 A/B 测试
|
||
- [ ] 添加用户反馈收集
|
||
- [ ] 优化日志和告警
|
||
|
||
---
|
||
|
||
## 十一、参考资源
|
||
|
||
### 11.1 官方文档
|
||
|
||
- [Vercel AI SDK 文档](https://sdk.vercel.ai/docs)
|
||
- [OpenAI API 文档](https://platform.openai.com/docs)
|
||
- [Prisma 文档](https://www.prisma.io/docs)
|
||
|
||
### 11.2 示例项目
|
||
|
||
- [AI SDK Examples](https://github.com/vercel/ai/tree/main/examples)
|
||
- [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)
|
||
|
||
### 11.3 社区资源
|
||
|
||
- [Vercel AI SDK Discord](https://discord.gg/vercel)
|
||
- [AI SDK GitHub Discussions](https://github.com/vercel/ai/discussions)
|
||
|
||
---
|
||
|
||
**文档版本**: v1.0
|
||
**最后更新**: 2026-02-05
|
||
**维护者**: Claude Code
|
||
|
||
**快速链接**:
|
||
- [完整架构设计](./task-15-agent-architecture.md)
|
||
- [详细实现指南](./task-15-agent-implementation-part2.md)
|
||
- [部署和优化](./task-15-agent-deployment.md)
|