实现 AI Agent 对话功能(Task 15)
后端实现: - 集成 Vercel AI SDK 实现流式对话 - 实现工具系统(文章搜索、报告分析、网络搜索) - 实现上下文加载和提示词构建 - 实现对话管理和消息存储 - 添加 Agent API 路由(流式对话、历史记录) 前端实现: - 实现聊天界面(配置选择、消息展示、历史记录) - 支持 Markdown 渲染和代码高亮 - 实现流式响应解析和展示 - 优化布局(单侧边栏 + 可折叠历史面板) - 修复 API 路径和 CORS 问题 Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb54568b22
commit
e6a434e516
27 files changed
+8734
-19
No files matched your search
@@ -0,0 +1,150 @@
|
||||
import { FastifyInstance, FastifyRequest, FastifyReply } from 'fastify';
|
||||
import { AgentService } from '../../services/agent/agent.service';
|
||||
import logger from '../../utils/logger';
|
||||
|
||||
const agentService = new AgentService();
|
||||
|
||||
interface ChatBody {
|
||||
conversationId?: number;
|
||||
reportId?: number;
|
||||
articleId?: number;
|
||||
topicId: number;
|
||||
message: string;
|
||||
llmConfigId: number;
|
||||
userId?: number;
|
||||
}
|
||||
|
||||
interface ConversationParams {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface ConversationQuery {
|
||||
userId?: string;
|
||||
topicId?: string;
|
||||
}
|
||||
|
||||
export async function agentRoutes(fastify: FastifyInstance) {
|
||||
/**
|
||||
* POST /api/v1/agent/chat
|
||||
* 流式对话
|
||||
*/
|
||||
fastify.post('/chat', async (request: FastifyRequest<{ Body: ChatBody }>, reply: FastifyReply) => {
|
||||
const { conversationId, reportId, articleId, topicId, message, llmConfigId, userId } = request.body;
|
||||
|
||||
// 参数验证
|
||||
if (!topicId) {
|
||||
return reply.status(400).send({ error: '缺少 topicId 参数' });
|
||||
}
|
||||
if (!message || !message.trim()) {
|
||||
return reply.status(400).send({ error: '消息不能为空' });
|
||||
}
|
||||
if (!llmConfigId) {
|
||||
return reply.status(400).send({ error: '缺少 llmConfigId 参数' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { conversationId: convId, stream } = await agentService.streamChat({
|
||||
conversationId,
|
||||
reportId,
|
||||
articleId,
|
||||
topicId,
|
||||
message: message.trim(),
|
||||
llmConfigId,
|
||||
userId,
|
||||
});
|
||||
|
||||
// 设置 SSE 响应头
|
||||
reply.raw.writeHead(200, {
|
||||
'Content-Type': 'text/event-stream',
|
||||
'Cache-Control': 'no-cache',
|
||||
'Connection': 'keep-alive',
|
||||
'X-Conversation-Id': convId.toString(),
|
||||
});
|
||||
|
||||
// 发送 conversationId
|
||||
reply.raw.write(`data: ${JSON.stringify({ type: 'conversation-id', conversationId: convId })}\n\n`);
|
||||
|
||||
// 流式传输
|
||||
try {
|
||||
for await (const chunk of stream.textStream) {
|
||||
reply.raw.write(`data: ${JSON.stringify({ type: 'text-delta', textDelta: chunk })}\n\n`);
|
||||
}
|
||||
} catch (streamError: any) {
|
||||
logger.error('Stream error:', streamError);
|
||||
reply.raw.write(`data: ${JSON.stringify({ type: 'error', error: streamError.message })}\n\n`);
|
||||
}
|
||||
|
||||
// 发送完成信号
|
||||
reply.raw.write(`data: ${JSON.stringify({ type: 'done' })}\n\n`);
|
||||
reply.raw.end();
|
||||
} catch (error: any) {
|
||||
logger.error('Agent chat error:', error);
|
||||
|
||||
// 如果还没有开始流式响应,返回 JSON 错误
|
||||
if (!reply.raw.headersSent) {
|
||||
return reply.status(500).send({ error: error.message || '对话失败' });
|
||||
}
|
||||
|
||||
// 如果已经开始流式响应,发送错误事件
|
||||
reply.raw.write(`data: ${JSON.stringify({ type: 'error', error: error.message })}\n\n`);
|
||||
reply.raw.end();
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/v1/agent/conversations/:id
|
||||
* 获取对话详情
|
||||
*/
|
||||
fastify.get('/conversations/:id', async (request: FastifyRequest<{ Params: ConversationParams }>, reply: FastifyReply) => {
|
||||
const { id } = request.params;
|
||||
|
||||
try {
|
||||
const conversation = await agentService.getConversation(Number(id));
|
||||
|
||||
if (!conversation) {
|
||||
return reply.status(404).send({ error: '对话不存在' });
|
||||
}
|
||||
|
||||
return conversation;
|
||||
} catch (error: any) {
|
||||
logger.error('获取对话详情失败:', error);
|
||||
return reply.status(500).send({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /api/v1/agent/conversations
|
||||
* 获取对话列表
|
||||
*/
|
||||
fastify.get('/conversations', async (request: FastifyRequest<{ Querystring: ConversationQuery }>, reply: FastifyReply) => {
|
||||
const { userId, topicId } = request.query;
|
||||
|
||||
try {
|
||||
const conversations = await agentService.getConversations(
|
||||
userId ? Number(userId) : undefined,
|
||||
topicId ? Number(topicId) : undefined
|
||||
);
|
||||
|
||||
return conversations;
|
||||
} catch (error: any) {
|
||||
logger.error('获取对话列表失败:', error);
|
||||
return reply.status(500).send({ error: error.message });
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /api/v1/agent/conversations/:id
|
||||
* 删除对话
|
||||
*/
|
||||
fastify.delete('/conversations/:id', async (request: FastifyRequest<{ Params: ConversationParams }>, reply: FastifyReply) => {
|
||||
const { id } = request.params;
|
||||
|
||||
try {
|
||||
await agentService.deleteConversation(Number(id));
|
||||
return { success: true };
|
||||
} catch (error: any) {
|
||||
logger.error('删除对话失败:', error);
|
||||
return reply.status(500).send({ error: error.message });
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in new issue
Block a user