实现 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:
hughhuang(黄健铭)andClaude Sonnet 4.5 committed 2026-02-06 09:58:47 +08:00
1 parent cb54568b22
commit e6a434e516
27 files changed
+8734 -19

No files matched your search

+126 -5
View File
@@ -9,9 +9,11 @@
"version": "1.0.0",
"license": "ISC",
"dependencies": {
"@ai-sdk/openai": "^3.0.25",
"@fastify/cors": "^11.2.0",
"@fastify/static": "^9.0.0",
"@prisma/client": "^5.22.0",
"ai": "^6.0.71",
"dotenv": "^17.2.3",
"fastify": "^5.7.4",
"node-cron": "^4.2.1",
@@ -20,7 +22,8 @@
"playwright": "^1.58.1",
"prisma": "^5.22.0",
"rss-parser": "^3.13.0",
"winston": "^3.19.0"
"winston": "^3.19.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^25.2.0",
@@ -34,6 +37,68 @@
"vitest": "^4.0.18"
}
},
"node_modules/@ai-sdk/gateway": {
"version": "3.0.34",
"resolved": "https://registry.npmjs.org/@ai-sdk/gateway/-/gateway-3.0.34.tgz",
"integrity": "sha512-ZS1dWai5DINQOv3bpNi3ua9+yt3jnRaux3CwEr/ai9qETp6T+2wcpZyw+0jUHo1He/Lznw//AQh4zhdwHnTWrg==",
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/provider": "3.0.7",
"@ai-sdk/provider-utils": "4.0.13",
"@vercel/oidc": "3.1.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"zod": "^3.25.76 || ^4.1.8"
}
},
"node_modules/@ai-sdk/openai": {
"version": "3.0.25",
"resolved": "https://registry.npmjs.org/@ai-sdk/openai/-/openai-3.0.25.tgz",
"integrity": "sha512-DsaN46R98+D1W3lU3fKuPU3ofacboLaHlkAwxJPgJ8eup1AJHmPK1N1y10eJJbJcF6iby8Tf/vanoZxc9JPUfw==",
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/provider": "3.0.7",
"@ai-sdk/provider-utils": "4.0.13"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"zod": "^3.25.76 || ^4.1.8"
}
},
"node_modules/@ai-sdk/provider": {
"version": "3.0.7",
"resolved": "https://registry.npmjs.org/@ai-sdk/provider/-/provider-3.0.7.tgz",
"integrity": "sha512-VkPLrutM6VdA924/mG8OS+5frbVTcu6e046D2bgDo00tehBANR1QBJ/mPcZ9tXMFOsVcm6SQArOregxePzTFPw==",
"license": "Apache-2.0",
"dependencies": {
"json-schema": "^0.4.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@ai-sdk/provider-utils": {
"version": "4.0.13",
"resolved": "https://registry.npmjs.org/@ai-sdk/provider-utils/-/provider-utils-4.0.13.tgz",
"integrity": "sha512-HHG72BN4d+OWTcq2NwTxOm/2qvk1duYsnhCDtsbYwn/h/4zeqURu1S0+Cn0nY2Ysq9a9HGKvrYuMn9bgFhR2Og==",
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/provider": "3.0.7",
"@standard-schema/spec": "^1.1.0",
"eventsource-parser": "^3.0.6"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"zod": "^3.25.76 || ^4.1.8"
}
},
"node_modules/@colors/colors": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/@colors/colors/-/colors-1.6.0.tgz",
@@ -740,6 +805,15 @@
"url": "https://paulmillr.com/funding/"
}
},
"node_modules/@opentelemetry/api": {
"version": "1.9.0",
"resolved": "https://registry.npmjs.org/@opentelemetry/api/-/api-1.9.0.tgz",
"integrity": "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg==",
"license": "Apache-2.0",
"engines": {
"node": ">=8.0.0"
}
},
"node_modules/@paralleldrive/cuid2": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/@paralleldrive/cuid2/-/cuid2-2.3.1.tgz",
@@ -1183,7 +1257,6 @@
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/chai": {
@@ -1282,6 +1355,15 @@
"integrity": "sha512-6WaYesThRMCl19iryMYP7/x2OVgCtbIVflDGFpWnb9irXI3UjYE4AzmYuiUKY1AJstGijoY+MgUszMgRxIYTYw==",
"license": "MIT"
},
"node_modules/@vercel/oidc": {
"version": "3.1.0",
"resolved": "https://registry.npmjs.org/@vercel/oidc/-/oidc-3.1.0.tgz",
"integrity": "sha512-Fw28YZpRnA3cAHHDlkt7xQHiJ0fcL+NRcIqsocZQUSmbzeIKRpwttJjik5ZGanXP+vlA4SbTg+AbA3bP363l+w==",
"license": "Apache-2.0",
"engines": {
"node": ">= 20"
}
},
"node_modules/@vitest/expect": {
"version": "4.0.18",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.0.18.tgz",
@@ -1399,6 +1481,24 @@
"integrity": "sha512-2BjRTZxTPvheOvGbBslFSYOUkr+SjPtOnrLP33f+VIWLzezQpZcqVg7ja3L4dBXmzzgwT+a029jRx5PCi3JuiA==",
"license": "MIT"
},
"node_modules/ai": {
"version": "6.0.71",
"resolved": "https://registry.npmjs.org/ai/-/ai-6.0.71.tgz",
"integrity": "sha512-33/Qq0BhEG+SabYeE7ZlLL3DCubUQo04C8E9UdEHqh2DJuGdtxMXG/TSMkO2uF+ZmlGJpD4UY5Wij9/qal298w==",
"license": "Apache-2.0",
"dependencies": {
"@ai-sdk/gateway": "3.0.34",
"@ai-sdk/provider": "3.0.7",
"@ai-sdk/provider-utils": "4.0.13",
"@opentelemetry/api": "1.9.0"
},
"engines": {
"node": ">=18"
},
"peerDependencies": {
"zod": "^3.25.76 || ^4.1.8"
}
},
"node_modules/ajv": {
"version": "8.17.1",
"resolved": "https://registry.npmjs.org/ajv/-/ajv-8.17.1.tgz",
@@ -1937,6 +2037,15 @@
"@types/estree": "^1.0.0"
}
},
"node_modules/eventsource-parser": {
"version": "3.0.6",
"resolved": "https://registry.npmjs.org/eventsource-parser/-/eventsource-parser-3.0.6.tgz",
"integrity": "sha512-Vo1ab+QXPzZ4tCa8SwIHJFaSzy4R6SHf7BY79rFBDf0idraZWAkYrDjDj8uWaSm3S2TK+hJ7/t1CEmZ7jXw+pg==",
"license": "MIT",
"engines": {
"node": ">=18.0.0"
}
},
"node_modules/expect-type": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.3.0.tgz",
@@ -2418,6 +2527,12 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/json-schema": {
"version": "0.4.0",
"resolved": "https://registry.npmjs.org/json-schema/-/json-schema-0.4.0.tgz",
"integrity": "sha512-es94M3nTIfsEPisRafak+HDLfHXnKBhV3vU5eqPcS3flIWqcxJWgXHXiey3YrpaNsanY5ei1VoYEbOzijuq9BA==",
"license": "(AFL-2.1 OR BSD-3-Clause)"
},
"node_modules/json-schema-ref-resolver": {
"version": "3.0.0",
"resolved": "https://registry.npmjs.org/json-schema-ref-resolver/-/json-schema-ref-resolver-3.0.0.tgz",
@@ -2914,7 +3029,6 @@
"integrity": "sha512-vtpjW3XuYCSnMsNVBjLMNkTj6OZbudcPPTPYHqX0CJfpcdWciI1dM8uHETwmDxxiqEwCIE6WvXucWUetJgfu/A==",
"hasInstallScript": true,
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"@prisma/engines": "5.22.0"
},
@@ -3522,7 +3636,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -3773,7 +3886,6 @@
"integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -3953,6 +4065,15 @@
"engines": {
"node": ">=4.0"
}
},
"node_modules/zod": {
"version": "4.3.6",
"resolved": "https://registry.npmjs.org/zod/-/zod-4.3.6.tgz",
"integrity": "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg==",
"license": "MIT",
"funding": {
"url": "https://github.com/sponsors/colinhacks"
}
}
}
}
+4 -1
View File
@@ -19,9 +19,11 @@
"license": "ISC",
"type": "commonjs",
"dependencies": {
"@ai-sdk/openai": "^3.0.25",
"@fastify/cors": "^11.2.0",
"@fastify/static": "^9.0.0",
"@prisma/client": "^5.22.0",
"ai": "^6.0.71",
"dotenv": "^17.2.3",
"fastify": "^5.7.4",
"node-cron": "^4.2.1",
@@ -30,7 +32,8 @@
"playwright": "^1.58.1",
"prisma": "^5.22.0",
"rss-parser": "^3.13.0",
"winston": "^3.19.0"
"winston": "^3.19.0",
"zod": "^4.3.6"
},
"devDependencies": {
"@types/node": "^25.2.0",
+2
View File
@@ -13,6 +13,7 @@ import { topicRoutes } from './web/routes/topics';
import { reportRoutes } from './web/routes/reports';
import { articleRoutes } from './web/routes/articles';
import { collectionLogRoutes } from './web/routes/collection-logs';
import { agentRoutes } from './web/routes/agent';
import { SchedulerService } from './services/scheduler.service';
let schedulerService: SchedulerService | null = null;
@@ -61,6 +62,7 @@ async function registerRoutes(): Promise<void> {
await app.register(reportRoutes, { prefix: '/api/v1/reports' });
await app.register(articleRoutes, { prefix: '/api/v1/articles' });
await app.register(collectionLogRoutes, { prefix: '/api/v1/collection-logs' });
await app.register(agentRoutes, { prefix: '/api/v1/agent' });
logger.info('路由已注册');
}
+165
View File
@@ -0,0 +1,165 @@
import { streamText } from 'ai';
import { createOpenAI } from '@ai-sdk/openai';
import prisma from '../../config/database';
import logger from '../../utils/logger';
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?: number;
}
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 historyMessages = await this.conversationManager.getMessages(conversation.id);
// 6. 获取 LLM 配置
const llmConfig = await prisma.llmConfig.findUnique({
where: { id: params.llmConfigId },
});
if (!llmConfig) {
throw new Error('LLM 配置不存在');
}
// 7. 创建 LLM 实例
logger.info('创建 LLM 实例', { baseUrl: llmConfig.baseUrl, model: llmConfig.model });
const openai = createOpenAI({
baseURL: llmConfig.baseUrl,
apiKey: llmConfig.apiKey,
});
const model = openai.chat(llmConfig.model);
// 8. 构建消息列表
const messages = historyMessages.map(m => ({
role: m.role as 'user' | 'assistant',
content: m.content,
}));
logger.info('开始流式生成', { messagesCount: messages.length });
// 9. 流式生成(暂不使用工具,简化实现)
const result = streamText({
model,
system: systemPrompt,
messages,
});
// 11. 异步保存助手消息
this.saveAssistantMessage(conversation.id, result);
return {
conversationId: conversation.id,
stream: result,
};
} catch (error) {
logger.error('Agent 对话失败:', 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) {
if (msg.role === 'assistant' && msg.content) {
// 提取文本内容
let content = '';
if (typeof msg.content === 'string') {
content = msg.content;
} else if (Array.isArray(msg.content)) {
content = msg.content
.filter((c: any) => c.type === 'text')
.map((c: any) => c.text)
.join('');
}
if (content) {
await this.conversationManager.addMessage(conversationId, {
role: 'assistant',
content,
toolCalls: msg.toolCalls,
});
}
}
}
} catch (error) {
logger.error('保存助手消息失败:', error);
}
}
/**
* 获取对话详情
*/
async getConversation(conversationId: number) {
return this.conversationManager.getConversation(conversationId);
}
/**
* 获取对话列表
*/
async getConversations(userId?: number, topicId?: number) {
return this.conversationManager.getUserConversations(userId, topicId);
}
/**
* 删除对话
*/
async deleteConversation(conversationId: number) {
return this.conversationManager.deleteConversation(conversationId);
}
}
@@ -0,0 +1,190 @@
import prisma from '../../../config/database';
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 | null;
};
report?: {
id: number;
title: string;
content: string;
periodStart: Date;
periodEnd: Date;
};
article?: {
id: number;
title: string;
content: string | null;
summary: string | null;
url: string | null;
publishedAt: Date | null;
};
relatedArticles?: Array<{
id: number;
title: string;
summary: string | null;
}>;
}
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('主题不存在');
}
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,
periodStart: true,
periodEnd: true,
},
});
if (report) {
context.type = 'report';
context.report = report;
// 加载该时间段内的相关资讯
const relatedArticles = await this.loadReportArticles(
params.topicId,
report.periodStart,
report.periodEnd
);
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,
sourceId: true,
},
});
if (article) {
context.type = 'article';
context.article = article;
// 加载相关资讯
const relatedArticles = await this.loadRelatedArticles(
article.sourceId,
article.id,
article.publishedAt
);
context.relatedArticles = relatedArticles;
}
}
return context;
} catch (error) {
logger.error('上下文加载失败:', error);
throw error;
}
}
/**
* 加载报告时间段内的资讯
*/
private async loadReportArticles(
topicId: number,
periodStart: Date,
periodEnd: Date
) {
// 获取主题关联的数据源
const topicSources = await prisma.topicSource.findMany({
where: { topicId },
select: { sourceId: true },
});
const sourceIds = topicSources.map(ts => ts.sourceId);
const articles = await prisma.article.findMany({
where: {
sourceId: { in: sourceIds },
publishedAt: {
gte: periodStart,
lte: periodEnd,
},
},
take: 10,
orderBy: { publishedAt: 'desc' },
select: {
id: true,
title: true,
summary: true,
},
});
return articles;
}
/**
* 加载相关资讯(同数据源、相近时间)
*/
private async loadRelatedArticles(
sourceId: number,
excludeId: number,
publishedAt: Date | null
) {
const baseDate = publishedAt || new Date();
const sevenDaysAgo = new Date(baseDate.getTime() - 7 * 24 * 60 * 60 * 1000);
const articles = await prisma.article.findMany({
where: {
sourceId,
id: { not: excludeId },
publishedAt: { gte: sevenDaysAgo },
},
take: 10,
orderBy: { publishedAt: 'desc' },
select: {
id: true,
title: true,
summary: true,
},
});
return articles;
}
}
@@ -0,0 +1,150 @@
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.periodStart.toISOString()} 至 ${context.report.periodEnd.toISOString()}`);
parts.push(`\n报告内容:\n${this.truncateContent(context.report.content, 3000)}`);
}
// 资讯信息
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}`);
}
if (context.article.content) {
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. 格式化
- 使用 Markdown 格式
- 适当使用列表、标题等结构化元素
- 重要信息使用加粗或引用`;
}
/**
* 截断内容
*/
private truncateContent(content: string, maxLength: number): string {
if (content.length <= maxLength) {
return content;
}
return content.substring(0, maxLength) + '\n\n[内容过长,已截断...]';
}
}
@@ -0,0 +1,195 @@
import prisma from '../../../config/database';
import logger from '../../../utils/logger';
export interface CreateConversationParams {
conversationId?: number;
userId?: number;
topicId: number;
reportId?: number;
articleId?: number;
}
export interface MessageData {
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 conversation = await prisma.conversation.create({
data: {
userId: params.userId,
topicId: params.topicId,
reportId: params.reportId,
articleId: params.articleId,
messages: [],
},
});
logger.info(`创建对话: ${conversation.id}`);
return conversation;
} catch (error) {
logger.error('获取或创建对话失败:', error);
throw error;
}
}
/**
* 添加消息到对话
*/
async addMessage(conversationId: number, message: MessageData) {
try {
const conversation = await prisma.conversation.findUnique({
where: { id: conversationId },
});
if (!conversation) {
throw new Error('对话不存在');
}
const messages = conversation.messages as any[];
messages.push({
...message,
createdAt: new Date().toISOString(),
});
await prisma.conversation.update({
where: { id: conversationId },
data: {
messages,
updatedAt: new Date(),
},
});
return message;
} catch (error) {
logger.error('添加消息失败:', error);
throw error;
}
}
/**
* 获取对话消息
*/
async getMessages(conversationId: number): Promise<MessageData[]> {
try {
const conversation = await prisma.conversation.findUnique({
where: { id: conversationId },
});
if (!conversation) {
return [];
}
return (conversation.messages as unknown as MessageData[]) || [];
} catch (error) {
logger.error('获取消息失败:', error);
throw error;
}
}
/**
* 获取对话详情
*/
async getConversation(conversationId: number) {
try {
const conversation = await prisma.conversation.findUnique({
where: { id: conversationId },
include: {
topic: {
select: { id: true, name: true },
},
report: {
select: { id: true, title: true },
},
article: {
select: { id: true, title: true },
},
},
});
return conversation;
} catch (error) {
logger.error('获取对话详情失败:', error);
throw error;
}
}
/**
* 获取用户的对话列表
*/
async getUserConversations(userId?: number, topicId?: number) {
try {
const where: any = {};
if (userId) where.userId = userId;
if (topicId) where.topicId = topicId;
const conversations = await prisma.conversation.findMany({
where,
orderBy: { updatedAt: 'desc' },
include: {
topic: {
select: { id: true, name: true },
},
report: {
select: { id: true, title: true },
},
article: {
select: { id: true, title: true },
},
},
});
// 为每个对话添加消息预览
return conversations.map(conv => {
const messages = conv.messages as any[];
const lastMessage = messages[messages.length - 1];
return {
...conv,
messageCount: messages.length,
lastMessage: lastMessage ? {
role: lastMessage.role,
content: lastMessage.content?.substring(0, 100),
createdAt: lastMessage.createdAt,
} : null,
};
});
} catch (error) {
logger.error('获取对话列表失败:', error);
throw error;
}
}
/**
* 删除对话
*/
async deleteConversation(conversationId: number) {
try {
await prisma.conversation.delete({
where: { id: conversationId },
});
logger.info(`删除对话: ${conversationId}`);
} catch (error) {
logger.error('删除对话失败:', error);
throw error;
}
}
}
+144
View File
@@ -0,0 +1,144 @@
import { z } from 'zod';
import prisma from '../../../config/database';
// 定义工具类型
interface AgentTool<T extends z.ZodType> {
description: string;
parameters: T;
execute: (params: z.infer<T>) => Promise<any>;
}
// 资讯搜索工具
const searchArticlesSchema = z.object({
query: z.string().describe('搜索关键词'),
topicId: z.number().optional().describe('主题 ID'),
sourceId: z.number().optional().describe('数据源 ID'),
limit: z.number().default(10).describe('返回结果数量'),
});
// 报告分析工具
const analyzeReportSchema = z.object({
reportId: z.number().describe('报告 ID'),
analysisType: z.enum(['summary', 'full']).default('summary').describe('分析类型'),
});
// 联网搜索工具
const webSearchSchema = z.object({
query: z.string().describe('搜索查询'),
limit: z.number().default(5).describe('返回结果数量'),
});
export function createAgentTools() {
return {
searchArticles: {
description: '搜索资讯数据库,查找相关的新闻和文章',
parameters: searchArticlesSchema,
execute: async (params: z.infer<typeof searchArticlesSchema>) => {
const { query, topicId, sourceId, limit } = params;
try {
const whereConditions: any = {
OR: [
{ title: { contains: query } },
{ content: { contains: query } },
{ summary: { contains: query } },
],
};
if (sourceId) {
whereConditions.sourceId = sourceId;
}
if (topicId) {
const topicSources = await prisma.topicSource.findMany({
where: { topicId },
select: { sourceId: true },
});
const sourceIds = topicSources.map(ts => ts.sourceId);
whereConditions.sourceId = { in: sourceIds };
}
const articles = await prisma.article.findMany({
where: whereConditions,
take: limit,
orderBy: { publishedAt: 'desc' },
include: {
source: { select: { name: true } },
},
});
return {
success: true,
count: articles.length,
articles: articles.map(a => ({
id: a.id,
title: a.title,
summary: a.summary?.substring(0, 200),
url: a.url,
publishedAt: a.publishedAt,
source: a.source.name,
})),
};
} catch (error: any) {
return { success: false, error: error.message };
}
},
},
analyzeReport: {
description: '分析已生成的报告,提取关键信息和洞察',
parameters: analyzeReportSchema,
execute: async (params: z.infer<typeof analyzeReportSchema>) => {
const { reportId, analysisType } = params;
try {
const report = await prisma.report.findUnique({
where: { id: reportId },
include: { topic: { select: { name: true } } },
});
if (!report) {
return { success: false, error: '报告不存在' };
}
const analysis: any = {
id: report.id,
title: report.title,
topic: report.topic.name,
status: report.status,
periodStart: report.periodStart,
periodEnd: report.periodEnd,
articleCount: report.articleCount,
createdAt: report.createdAt,
};
if (analysisType === 'summary') {
analysis.content = report.content.substring(0, 1000);
if (report.content.length > 1000) {
analysis.content += '\n\n[内容已截断]';
}
} else {
analysis.content = report.content;
}
return { success: true, analysis };
} catch (error: any) {
return { success: false, error: error.message };
}
},
},
webSearch: {
description: '搜索互联网获取最新信息(当数据库中没有相关信息时使用)',
parameters: webSearchSchema,
execute: async (params: z.infer<typeof webSearchSchema>) => {
const { query, limit } = params;
return {
success: false,
message: '联网搜索功能暂未配置',
query,
requestedLimit: limit,
results: [],
};
},
},
};
}
+150
View File
@@ -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 });
}
});
}