Compare commits
19
Commits
773fa369cd
...
main
No files matched your search
@@ -0,0 +1,107 @@
|
|||||||
|
# CLAUDE.md
|
||||||
|
|
||||||
|
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||||
|
|
||||||
|
## 项目概述
|
||||||
|
|
||||||
|
News Aggregator - 基于配置的资讯聚合系统,自动收集、整理、推送每日报告。支持多数据源采集、AI 内容处理、多渠道推送和 AI Agent 对话。
|
||||||
|
|
||||||
|
## 常用命令
|
||||||
|
|
||||||
|
### 后端 (backend/)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev # 启动开发服务器 (tsx watch)
|
||||||
|
npm run build # 构建生产版本
|
||||||
|
npm run test # 运行测试
|
||||||
|
npm run test:watch # 监听模式测试
|
||||||
|
npm run prisma:generate # 生成 Prisma Client
|
||||||
|
npm run prisma:migrate # 执行数据库迁移
|
||||||
|
npm run prisma:studio # 打开 Prisma Studio
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端 (frontend/)
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm run dev # 启动开发服务器 (Vite)
|
||||||
|
npm run build # 构建生产版本 (vue-tsc + vite build)
|
||||||
|
```
|
||||||
|
|
||||||
|
## 架构概览
|
||||||
|
|
||||||
|
### 后端分层架构
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/src/
|
||||||
|
├── web/routes/ # API 路由层 - Fastify 路由定义
|
||||||
|
├── services/ # 业务服务层 - 核心业务逻辑
|
||||||
|
├── collectors/ # 采集器 - 数据源采集实现
|
||||||
|
├── distributors/ # 分发器 - 推送渠道实现
|
||||||
|
├── config/ # 配置 - 环境变量和数据库连接
|
||||||
|
├── types/ # 类型定义
|
||||||
|
└── utils/ # 工具函数
|
||||||
|
```
|
||||||
|
|
||||||
|
### 核心抽象模式
|
||||||
|
|
||||||
|
**采集器 (Collector)**:继承 `BaseCollector`,实现 `collect()`、`validateConfig()`、`getType()` 方法
|
||||||
|
- `ApiCollector` - REST API 采集
|
||||||
|
- `PlaywrightCollector` - 网页爬取
|
||||||
|
- `RssCollector` - RSS/Atom 订阅
|
||||||
|
|
||||||
|
**分发器 (Distributor)**:继承 `BaseDistributor`,实现 `distribute()`、`validateConfig()`、`getType()` 方法
|
||||||
|
- `EmailDistributor` - 邮件推送
|
||||||
|
- `DingtalkDistributor` - 钉钉机器人
|
||||||
|
- `WechatDistributor` - 企业微信
|
||||||
|
- `SlackDistributor` - Slack
|
||||||
|
|
||||||
|
**服务层**:继承 `BaseService<T, CreateInput, UpdateInput>`,提供 CRUD 和分页查询
|
||||||
|
|
||||||
|
### AI Agent 架构
|
||||||
|
|
||||||
|
```
|
||||||
|
services/agent/
|
||||||
|
├── agent.service.ts # 核心服务 - 流式对话入口
|
||||||
|
├── context/
|
||||||
|
│ ├── context-loader.ts # 上下文加载 - 报告/资讯/主题
|
||||||
|
│ └── prompt-builder.ts # 系统提示词构建
|
||||||
|
├── conversation/
|
||||||
|
│ └── conversation.manager.ts # 对话管理 - 消息存储
|
||||||
|
└── tools/ # 工具系统 (Vercel AI SDK)
|
||||||
|
```
|
||||||
|
|
||||||
|
使用 Vercel AI SDK (`ai` 包) 的 `streamText` 实现流式对话。
|
||||||
|
|
||||||
|
### 前端架构
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/src/
|
||||||
|
├── views/ # 页面组件
|
||||||
|
├── components/ # 公共组件
|
||||||
|
├── stores/ # Pinia 状态管理
|
||||||
|
├── api/ # API 请求封装
|
||||||
|
└── router/ # Vue Router 路由
|
||||||
|
```
|
||||||
|
|
||||||
|
### 数据模型关系
|
||||||
|
|
||||||
|
- `Topic` (主题) 关联多个 `Source` (数据源) 和 `Channel` (推送渠道)
|
||||||
|
- `Source` 产生 `Article` (资讯),记录 `CollectionLog` (采集日志)
|
||||||
|
- `Topic` 生成 `Report` (报告),通过 `Channel` 推送并记录 `PushLog`
|
||||||
|
- `Conversation` (对话) 关联 `Topic`,可选关联 `Report` 或 `Article`
|
||||||
|
|
||||||
|
## 环境配置
|
||||||
|
|
||||||
|
复制 `backend/.env.example` 到 `backend/.env`,配置:
|
||||||
|
- `DATABASE_URL` - MySQL 连接字符串
|
||||||
|
- `PORT` - 服务端口 (默认 3000)
|
||||||
|
|
||||||
|
## 提交规范
|
||||||
|
|
||||||
|
```
|
||||||
|
<type>: <subject>
|
||||||
|
|
||||||
|
Co-Authored-By: Claude <model>
|
||||||
|
```
|
||||||
|
|
||||||
|
类型:feat / fix / docs / style / refactor / test / chore
|
||||||
Generated
+1806
-2
File diff suppressed because it is too large.
Load diff
+14
-2
@@ -7,6 +7,9 @@
|
|||||||
"dev": "tsx watch src/app.ts",
|
"dev": "tsx watch src/app.ts",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"start": "node dist/app.js",
|
"start": "node dist/app.js",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"test:coverage": "vitest run --coverage",
|
||||||
"prisma:generate": "prisma generate",
|
"prisma:generate": "prisma generate",
|
||||||
"prisma:migrate": "prisma migrate dev",
|
"prisma:migrate": "prisma migrate dev",
|
||||||
"prisma:studio": "prisma studio"
|
"prisma:studio": "prisma studio"
|
||||||
@@ -16,22 +19,31 @@
|
|||||||
"license": "ISC",
|
"license": "ISC",
|
||||||
"type": "commonjs",
|
"type": "commonjs",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"@ai-sdk/openai": "^3.0.25",
|
||||||
"@fastify/cors": "^11.2.0",
|
"@fastify/cors": "^11.2.0",
|
||||||
"@fastify/static": "^9.0.0",
|
"@fastify/static": "^9.0.0",
|
||||||
"@prisma/client": "^5.22.0",
|
"@prisma/client": "^5.22.0",
|
||||||
|
"ai": "^6.0.71",
|
||||||
"dotenv": "^17.2.3",
|
"dotenv": "^17.2.3",
|
||||||
"fastify": "^5.7.4",
|
"fastify": "^5.7.4",
|
||||||
"node-cron": "^4.2.1",
|
"node-cron": "^4.2.1",
|
||||||
|
"nodemailer": "^8.0.0",
|
||||||
"openai": "^6.17.0",
|
"openai": "^6.17.0",
|
||||||
"playwright": "^1.58.1",
|
"playwright": "^1.58.1",
|
||||||
"prisma": "^5.22.0",
|
"prisma": "^5.22.0",
|
||||||
"winston": "^3.19.0"
|
"rss-parser": "^3.13.0",
|
||||||
|
"winston": "^3.19.0",
|
||||||
|
"zod": "^4.3.6"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^25.2.0",
|
"@types/node": "^25.2.0",
|
||||||
"@types/node-cron": "^3.0.11",
|
"@types/node-cron": "^3.0.11",
|
||||||
|
"@types/nodemailer": "^7.0.9",
|
||||||
|
"@types/supertest": "^6.0.3",
|
||||||
"nodemon": "^3.1.11",
|
"nodemon": "^3.1.11",
|
||||||
|
"supertest": "^7.2.2",
|
||||||
"tsx": "^4.21.0",
|
"tsx": "^4.21.0",
|
||||||
"typescript": "^5.9.3"
|
"typescript": "^5.9.3",
|
||||||
|
"vitest": "^4.0.18"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
+54
-25
@@ -1,7 +1,22 @@
|
|||||||
import Fastify from 'fastify';
|
import Fastify from 'fastify';
|
||||||
import cors from '@fastify/cors';
|
import cors from '@fastify/cors';
|
||||||
import { config, validateConfig } from './config';
|
import { config, validateConfig } from './config';
|
||||||
|
import { connectDatabase, disconnectDatabase } from './config/database';
|
||||||
import logger from './utils/logger';
|
import logger from './utils/logger';
|
||||||
|
import { errorHandler } from './web/middleware/error-handler';
|
||||||
|
import { requestLogger } from './web/middleware/request-logger';
|
||||||
|
import { healthRoutes } from './web/routes/health';
|
||||||
|
import { llmConfigRoutes } from './web/routes/llm-configs';
|
||||||
|
import { sourceRoutes } from './web/routes/sources';
|
||||||
|
import { channelRoutes } from './web/routes/channels';
|
||||||
|
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;
|
||||||
|
|
||||||
// 验证配置
|
// 验证配置
|
||||||
try {
|
try {
|
||||||
@@ -23,55 +38,61 @@ async function registerPlugins(): Promise<void> {
|
|||||||
await app.register(cors, {
|
await app.register(cors, {
|
||||||
origin: true,
|
origin: true,
|
||||||
credentials: true,
|
credentials: true,
|
||||||
|
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||||
});
|
});
|
||||||
logger.info('CORS 插件已注册');
|
logger.info('CORS 插件已注册');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 注册中间件
|
||||||
|
async function registerMiddleware(): Promise<void> {
|
||||||
|
// 请求日志
|
||||||
|
app.addHook('onRequest', requestLogger);
|
||||||
|
logger.info('中间件已注册');
|
||||||
|
}
|
||||||
|
|
||||||
// 注册路由
|
// 注册路由
|
||||||
async function registerRoutes(): Promise<void> {
|
async function registerRoutes(): Promise<void> {
|
||||||
// 健康检查
|
// 健康检查路由
|
||||||
app.get('/api/v1/health', async () => {
|
await app.register(healthRoutes, { prefix: '/api/v1' });
|
||||||
return {
|
|
||||||
success: true,
|
// API 路由
|
||||||
data: {
|
await app.register(llmConfigRoutes, { prefix: '/api/v1/llm-configs' });
|
||||||
status: 'ok',
|
await app.register(sourceRoutes, { prefix: '/api/v1/sources' });
|
||||||
timestamp: new Date().toISOString(),
|
await app.register(channelRoutes, { prefix: '/api/v1/channels' });
|
||||||
version: '1.0.0',
|
await app.register(topicRoutes, { prefix: '/api/v1/topics' });
|
||||||
},
|
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('路由已注册');
|
logger.info('路由已注册');
|
||||||
}
|
}
|
||||||
|
|
||||||
// 错误处理
|
// 错误处理
|
||||||
app.setErrorHandler((error, request, reply) => {
|
app.setErrorHandler(errorHandler);
|
||||||
logger.error('请求处理错误:', {
|
|
||||||
error: error.message,
|
|
||||||
stack: error.stack,
|
|
||||||
url: request.url,
|
|
||||||
method: request.method,
|
|
||||||
});
|
|
||||||
|
|
||||||
reply.status(error.statusCode || 500).send({
|
|
||||||
success: false,
|
|
||||||
error: error.message || '服务器内部错误',
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|
||||||
// 启动服务器
|
// 启动服务器
|
||||||
async function start(): Promise<void> {
|
async function start(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
|
// 连接数据库
|
||||||
|
await connectDatabase();
|
||||||
|
|
||||||
|
// 注册插件和中间件
|
||||||
await registerPlugins();
|
await registerPlugins();
|
||||||
|
await registerMiddleware();
|
||||||
await registerRoutes();
|
await registerRoutes();
|
||||||
|
|
||||||
|
// 启动调度器
|
||||||
|
schedulerService = new SchedulerService();
|
||||||
|
await schedulerService.start();
|
||||||
|
|
||||||
await app.listen({
|
await app.listen({
|
||||||
port: config.port,
|
port: config.port,
|
||||||
host: '0.0.0.0',
|
host: '0.0.0.0',
|
||||||
});
|
});
|
||||||
|
|
||||||
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
logger.info(`🚀 服务器启动成功,监听端口 ${config.port}`);
|
||||||
logger.info(`📚 API 文档: http://localhost:${config.port}/api/v1/health`);
|
logger.info(`📚 健康检查: http://localhost:${config.port}/api/v1/health`);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
logger.error('服务器启动失败:', error);
|
logger.error('服务器启动失败:', error);
|
||||||
process.exit(1);
|
process.exit(1);
|
||||||
@@ -92,13 +113,21 @@ process.on('unhandledRejection', (reason, promise) => {
|
|||||||
// 优雅关闭
|
// 优雅关闭
|
||||||
process.on('SIGTERM', async () => {
|
process.on('SIGTERM', async () => {
|
||||||
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
logger.info('SIGTERM 信号收到,正在关闭服务器...');
|
||||||
|
if (schedulerService) {
|
||||||
|
schedulerService.stop();
|
||||||
|
}
|
||||||
await app.close();
|
await app.close();
|
||||||
|
await disconnectDatabase();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('SIGINT', async () => {
|
process.on('SIGINT', async () => {
|
||||||
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
logger.info('SIGINT 信号收到,正在关闭服务器...');
|
||||||
|
if (schedulerService) {
|
||||||
|
schedulerService.stop();
|
||||||
|
}
|
||||||
await app.close();
|
await app.close();
|
||||||
|
await disconnectDatabase();
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,154 @@
|
|||||||
|
import { BaseCollector } from './base.collector';
|
||||||
|
import {
|
||||||
|
CollectorType,
|
||||||
|
CollectionResult,
|
||||||
|
CollectedArticle,
|
||||||
|
ApiCollectorConfig,
|
||||||
|
} from '../types/collector';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class ApiCollector extends BaseCollector {
|
||||||
|
private apiConfig: ApiCollectorConfig;
|
||||||
|
|
||||||
|
constructor(config: ApiCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId);
|
||||||
|
this.apiConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`API采集器开始采集: ${this.apiConfig.url}`);
|
||||||
|
|
||||||
|
// 构建请求 URL
|
||||||
|
const url = new URL(this.apiConfig.url);
|
||||||
|
if (this.apiConfig.params) {
|
||||||
|
Object.entries(this.apiConfig.params).forEach(([key, value]) => {
|
||||||
|
url.searchParams.append(key, String(value));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置超时控制
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timeout = setTimeout(() => controller.abort(), 30000);
|
||||||
|
|
||||||
|
const options: RequestInit = {
|
||||||
|
method: this.apiConfig.method || 'GET',
|
||||||
|
headers: {
|
||||||
|
'User-Agent': 'News-Aggregator/1.0',
|
||||||
|
...this.apiConfig.headers,
|
||||||
|
},
|
||||||
|
signal: controller.signal,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.apiConfig.body && this.apiConfig.method === 'POST') {
|
||||||
|
options.body = JSON.stringify(this.apiConfig.body);
|
||||||
|
options.headers = {
|
||||||
|
...options.headers,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 发送请求
|
||||||
|
let response: Response;
|
||||||
|
try {
|
||||||
|
response = await fetch(url.toString(), options);
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timeout);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = await response.json();
|
||||||
|
|
||||||
|
// 提取数据
|
||||||
|
let items: any[] = [];
|
||||||
|
let rawItems = data;
|
||||||
|
if (this.apiConfig.dataPath) {
|
||||||
|
rawItems = this.getNestedValue(data, this.apiConfig.dataPath);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Array.isArray(rawItems)) {
|
||||||
|
items = rawItems;
|
||||||
|
} else if (rawItems) {
|
||||||
|
items = [rawItems];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 映射数据
|
||||||
|
const articles: CollectedArticle[] = items.map((item: any) => {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: this.getNestedValue(item, this.apiConfig.mapping.title) || '',
|
||||||
|
rawData: item,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (this.apiConfig.mapping.content) {
|
||||||
|
article.content = this.getNestedValue(item, this.apiConfig.mapping.content);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.apiConfig.mapping.url) {
|
||||||
|
article.url = this.getNestedValue(item, this.apiConfig.mapping.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.apiConfig.mapping.publishedAt) {
|
||||||
|
const dateValue = this.getNestedValue(item, this.apiConfig.mapping.publishedAt);
|
||||||
|
article.publishedAt = this.parseDate(dateValue);
|
||||||
|
}
|
||||||
|
|
||||||
|
return article;
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`API采集器完成,采集到 ${articles.length} 条资讯`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('API采集器失败', error);
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.apiConfig.url &&
|
||||||
|
this.apiConfig.mapping &&
|
||||||
|
this.apiConfig.mapping.title
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'api';
|
||||||
|
}
|
||||||
|
|
||||||
|
private getNestedValue(obj: any, path: string): any {
|
||||||
|
return path.split('.').reduce((current, key) => current?.[key], obj);
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseDate(value: any): Date | undefined {
|
||||||
|
if (!value) return undefined;
|
||||||
|
|
||||||
|
// Unix 时间戳(秒)
|
||||||
|
if (typeof value === 'number' && value > 1000000000 && value < 10000000000) {
|
||||||
|
return new Date(value * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Unix 时间戳(毫秒)
|
||||||
|
if (typeof value === 'number' && value > 1000000000000) {
|
||||||
|
return new Date(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ISO 字符串
|
||||||
|
if (typeof value === 'string') {
|
||||||
|
const date = new Date(value);
|
||||||
|
return isNaN(date.getTime()) ? undefined : date;
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import {
|
||||||
|
CollectorType,
|
||||||
|
CollectorConfig,
|
||||||
|
CollectionResult,
|
||||||
|
CollectedArticle,
|
||||||
|
} from '../types/collector';
|
||||||
|
|
||||||
|
export abstract class BaseCollector {
|
||||||
|
protected sourceId: number;
|
||||||
|
protected config: CollectorConfig;
|
||||||
|
|
||||||
|
constructor(config: CollectorConfig, sourceId: number) {
|
||||||
|
this.config = config;
|
||||||
|
this.sourceId = sourceId;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行采集
|
||||||
|
*/
|
||||||
|
abstract collect(): Promise<CollectionResult>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证配置
|
||||||
|
*/
|
||||||
|
abstract validateConfig(): boolean;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取采集器类型
|
||||||
|
*/
|
||||||
|
abstract getType(): CollectorType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理资源(可选)
|
||||||
|
*/
|
||||||
|
async cleanup(): Promise<void> {
|
||||||
|
// 默认不需要清理
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { BaseCollector } from './base.collector';
|
||||||
|
import { ApiCollector } from './api.collector';
|
||||||
|
import { PlaywrightCollector } from './playwright.collector';
|
||||||
|
import { RssCollector } from './rss.collector';
|
||||||
|
import { CollectorType, CollectorConfig } from '../types/collector';
|
||||||
|
|
||||||
|
export class CollectorFactory {
|
||||||
|
static create(
|
||||||
|
type: CollectorType,
|
||||||
|
config: CollectorConfig,
|
||||||
|
sourceId: number
|
||||||
|
): BaseCollector {
|
||||||
|
switch (type) {
|
||||||
|
case 'api':
|
||||||
|
return new ApiCollector(config as any, sourceId);
|
||||||
|
case 'playwright':
|
||||||
|
return new PlaywrightCollector(config as any, sourceId);
|
||||||
|
case 'rss':
|
||||||
|
return new RssCollector(config as any, sourceId);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown collector type: ${type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
export * from './base.collector';
|
||||||
|
export * from './api.collector';
|
||||||
|
export * from './playwright.collector';
|
||||||
|
export * from './rss.collector';
|
||||||
|
export * from './collector.factory';
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
import { BaseCollector } from './base.collector';
|
||||||
|
import {
|
||||||
|
CollectorType,
|
||||||
|
CollectionResult,
|
||||||
|
CollectedArticle,
|
||||||
|
PlaywrightCollectorConfig,
|
||||||
|
} from '../types/collector';
|
||||||
|
import { chromium, Browser, Page } from 'playwright';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class PlaywrightCollector extends BaseCollector {
|
||||||
|
private playwrightConfig: PlaywrightCollectorConfig;
|
||||||
|
private browser?: Browser;
|
||||||
|
|
||||||
|
constructor(config: PlaywrightCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId);
|
||||||
|
this.playwrightConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`Playwright采集器开始采集: ${this.playwrightConfig.url}`);
|
||||||
|
|
||||||
|
// 启动浏览器
|
||||||
|
this.browser = await chromium.launch({
|
||||||
|
headless: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
const page = await this.browser.newPage();
|
||||||
|
|
||||||
|
// 设置 User-Agent
|
||||||
|
await page.setExtraHTTPHeaders({
|
||||||
|
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
|
||||||
|
});
|
||||||
|
|
||||||
|
// 访问页面
|
||||||
|
await page.goto(this.playwrightConfig.url, {
|
||||||
|
waitUntil: 'networkidle',
|
||||||
|
timeout: 30000,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 等待内容加载
|
||||||
|
if (this.playwrightConfig.waitFor) {
|
||||||
|
await page.waitForSelector(this.playwrightConfig.waitFor, {
|
||||||
|
timeout: this.playwrightConfig.waitTimeout || 10000,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行自定义脚本(如果有)
|
||||||
|
if (this.playwrightConfig.script) {
|
||||||
|
await page.evaluate(this.playwrightConfig.script);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取数据
|
||||||
|
const articles = await this.extractArticles(page);
|
||||||
|
|
||||||
|
logger.info(`Playwright采集器完成,采集到 ${articles.length} 条资讯`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Playwright采集器失败', error);
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
await this.cleanup();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async extractArticles(page: Page): Promise<CollectedArticle[]> {
|
||||||
|
const items = await page.$$(this.playwrightConfig.selectors.items);
|
||||||
|
const articles: CollectedArticle[] = [];
|
||||||
|
|
||||||
|
for (const item of items) {
|
||||||
|
try {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 提取标题
|
||||||
|
const titleElement = await item.$(this.playwrightConfig.selectors.title);
|
||||||
|
if (titleElement) {
|
||||||
|
article.title = (await titleElement.textContent())?.trim() || '';
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取内容
|
||||||
|
if (this.playwrightConfig.selectors.content) {
|
||||||
|
const contentElement = await item.$(this.playwrightConfig.selectors.content);
|
||||||
|
if (contentElement) {
|
||||||
|
article.content = (await contentElement.textContent())?.trim();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取链接
|
||||||
|
if (this.playwrightConfig.selectors.url) {
|
||||||
|
const urlElement = await item.$(this.playwrightConfig.selectors.url);
|
||||||
|
if (urlElement) {
|
||||||
|
const href = await urlElement.getAttribute('href');
|
||||||
|
if (href) {
|
||||||
|
article.url = new URL(href, this.playwrightConfig.url).toString();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 提取日期
|
||||||
|
if (this.playwrightConfig.selectors.publishedAt) {
|
||||||
|
const dateElement = await item.$(this.playwrightConfig.selectors.publishedAt);
|
||||||
|
if (dateElement) {
|
||||||
|
const dateText = (await dateElement.textContent())?.trim();
|
||||||
|
if (dateText) {
|
||||||
|
article.publishedAt = this.parseDate(dateText);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (article.title) {
|
||||||
|
articles.push(article);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('提取单条资讯失败', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return articles;
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.playwrightConfig.url &&
|
||||||
|
this.playwrightConfig.selectors &&
|
||||||
|
this.playwrightConfig.selectors.items &&
|
||||||
|
this.playwrightConfig.selectors.title
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'playwright';
|
||||||
|
}
|
||||||
|
|
||||||
|
async cleanup(): Promise<void> {
|
||||||
|
if (this.browser) {
|
||||||
|
await this.browser.close();
|
||||||
|
this.browser = undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private parseDate(value: string): Date | undefined {
|
||||||
|
const date = new Date(value);
|
||||||
|
return isNaN(date.getTime()) ? undefined : date;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
import { BaseCollector } from './base.collector';
|
||||||
|
import {
|
||||||
|
CollectorType,
|
||||||
|
CollectionResult,
|
||||||
|
CollectedArticle,
|
||||||
|
RssCollectorConfig,
|
||||||
|
} from '../types/collector';
|
||||||
|
import Parser from 'rss-parser';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class RssCollector extends BaseCollector {
|
||||||
|
private rssConfig: RssCollectorConfig;
|
||||||
|
private parser: Parser;
|
||||||
|
|
||||||
|
constructor(config: RssCollectorConfig, sourceId: number) {
|
||||||
|
super(config, sourceId);
|
||||||
|
this.rssConfig = config;
|
||||||
|
this.parser = new Parser({
|
||||||
|
customFields: this.rssConfig.customFields,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async collect(): Promise<CollectionResult> {
|
||||||
|
try {
|
||||||
|
logger.info(`RSS采集器开始采集: ${this.rssConfig.url}`);
|
||||||
|
|
||||||
|
const feed = await this.parser.parseURL(this.rssConfig.url);
|
||||||
|
|
||||||
|
const articles: CollectedArticle[] = feed.items.map((item) => {
|
||||||
|
const article: CollectedArticle = {
|
||||||
|
title: item.title || '',
|
||||||
|
content: item.contentSnippet || item.content,
|
||||||
|
url: item.link,
|
||||||
|
rawData: item,
|
||||||
|
};
|
||||||
|
|
||||||
|
if (item.pubDate) {
|
||||||
|
article.publishedAt = new Date(item.pubDate);
|
||||||
|
} else if (item.isoDate) {
|
||||||
|
article.publishedAt = new Date(item.isoDate);
|
||||||
|
}
|
||||||
|
|
||||||
|
return article;
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`RSS采集器完成,采集到 ${articles.length} 条资讯`);
|
||||||
|
|
||||||
|
return {
|
||||||
|
articles,
|
||||||
|
success: true,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('RSS采集器失败', error);
|
||||||
|
return {
|
||||||
|
articles: [],
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.rssConfig.url;
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): CollectorType {
|
||||||
|
return 'rss';
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import { DistributorType, DistributorConfig, DistributionResult, ReportSummary } from '../types/distributor';
|
||||||
|
|
||||||
|
export abstract class BaseDistributor {
|
||||||
|
protected channelId: number;
|
||||||
|
protected config: DistributorConfig;
|
||||||
|
|
||||||
|
constructor(config: DistributorConfig, channelId: number) {
|
||||||
|
this.config = config;
|
||||||
|
this.channelId = channelId;
|
||||||
|
}
|
||||||
|
|
||||||
|
abstract distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult>;
|
||||||
|
abstract validateConfig(): boolean;
|
||||||
|
abstract getType(): DistributorType;
|
||||||
|
}
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
import { BaseDistributor } from './base.distributor';
|
||||||
|
import { DistributorType, DistributionResult, ReportSummary, DingtalkDistributorConfig } from '../types/distributor';
|
||||||
|
import crypto from 'crypto';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class DingtalkDistributor extends BaseDistributor {
|
||||||
|
private dingtalkConfig: DingtalkDistributorConfig;
|
||||||
|
|
||||||
|
constructor(config: DingtalkDistributorConfig, channelId: number) {
|
||||||
|
super(config, channelId);
|
||||||
|
this.dingtalkConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('钉钉分发器开始发送', { title: summary.title });
|
||||||
|
|
||||||
|
let url = this.dingtalkConfig.webhook;
|
||||||
|
if (this.dingtalkConfig.secret) {
|
||||||
|
const timestamp = Date.now();
|
||||||
|
const sign = this.generateSign(timestamp, this.dingtalkConfig.secret);
|
||||||
|
url = `${url}×tamp=${timestamp}&sign=${sign}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await fetch(url, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(this.buildMessage(summary)),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = (await response.json()) as { errcode: number; errmsg: string };
|
||||||
|
|
||||||
|
if (result.errcode !== 0) {
|
||||||
|
throw new Error(`钉钉 API 错误: ${result.errmsg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('钉钉消息发送成功');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('钉钉消息发送失败', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.dingtalkConfig.webhook;
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'dingtalk';
|
||||||
|
}
|
||||||
|
|
||||||
|
private generateSign(timestamp: number, secret: string): string {
|
||||||
|
const stringToSign = `${timestamp}\n${secret}`;
|
||||||
|
const hmac = crypto.createHmac('sha256', secret);
|
||||||
|
hmac.update(stringToSign);
|
||||||
|
return encodeURIComponent(hmac.digest('base64'));
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
return {
|
||||||
|
msgtype: 'markdown',
|
||||||
|
markdown: {
|
||||||
|
title: summary.title,
|
||||||
|
text: `# ${summary.title}
|
||||||
|
|
||||||
|
**主题**: ${summary.topicName}
|
||||||
|
**资讯数量**: ${summary.articleCount} 条
|
||||||
|
**时间范围**: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
[查看完整报告](${summary.webUrl})`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { BaseDistributor } from './base.distributor';
|
||||||
|
import { EmailDistributor } from './email.distributor';
|
||||||
|
import { DingtalkDistributor } from './dingtalk.distributor';
|
||||||
|
import { WechatDistributor } from './wechat.distributor';
|
||||||
|
import { SlackDistributor } from './slack.distributor';
|
||||||
|
import { DistributorType, DistributorConfig } from '../types/distributor';
|
||||||
|
|
||||||
|
export class DistributorFactory {
|
||||||
|
static create(
|
||||||
|
type: DistributorType,
|
||||||
|
config: DistributorConfig,
|
||||||
|
channelId: number
|
||||||
|
): BaseDistributor {
|
||||||
|
switch (type) {
|
||||||
|
case 'email':
|
||||||
|
return new EmailDistributor(config as any, channelId);
|
||||||
|
case 'dingtalk':
|
||||||
|
return new DingtalkDistributor(config as any, channelId);
|
||||||
|
case 'wechat':
|
||||||
|
return new WechatDistributor(config as any, channelId);
|
||||||
|
case 'slack':
|
||||||
|
return new SlackDistributor(config as any, channelId);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown distributor type: ${type}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
import { BaseDistributor } from './base.distributor';
|
||||||
|
import { DistributorType, DistributionResult, ReportSummary, EmailDistributorConfig } from '../types/distributor';
|
||||||
|
import nodemailer from 'nodemailer';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class EmailDistributor extends BaseDistributor {
|
||||||
|
private emailConfig: EmailDistributorConfig;
|
||||||
|
|
||||||
|
constructor(config: EmailDistributorConfig, channelId: number) {
|
||||||
|
super(config, channelId);
|
||||||
|
this.emailConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('邮件分发器开始发送', { to: this.emailConfig.to, title: summary.title });
|
||||||
|
|
||||||
|
const transporter = nodemailer.createTransport(this.emailConfig.smtp);
|
||||||
|
|
||||||
|
await transporter.sendMail({
|
||||||
|
from: this.emailConfig.from,
|
||||||
|
to: this.emailConfig.to.join(', '),
|
||||||
|
subject: summary.title,
|
||||||
|
text: this.buildTextContent(summary),
|
||||||
|
html: this.buildHtmlContent(summary, fullContent),
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info('邮件发送成功');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('邮件发送失败', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!(
|
||||||
|
this.emailConfig.smtp?.host &&
|
||||||
|
this.emailConfig.smtp?.auth &&
|
||||||
|
this.emailConfig.from &&
|
||||||
|
this.emailConfig.to?.length > 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'email';
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildHtmlContent(summary: ReportSummary, fullContent: string): string {
|
||||||
|
const htmlContent = fullContent
|
||||||
|
.replace(/^# (.+)$/gm, '<h1>$1</h1>')
|
||||||
|
.replace(/^## (.+)$/gm, '<h2>$1</h2>')
|
||||||
|
.replace(/^### (.+)$/gm, '<h3>$1</h3>')
|
||||||
|
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
|
||||||
|
.replace(/\[(.+?)\]\((.+?)\)/g, '<a href="$2">$1</a>')
|
||||||
|
.replace(/\n/g, '<br>');
|
||||||
|
|
||||||
|
return `<!DOCTYPE html>
|
||||||
|
<html>
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<style>
|
||||||
|
body { font-family: sans-serif; line-height: 1.6; color: #333; max-width: 800px; margin: 0 auto; padding: 20px; }
|
||||||
|
h1 { color: #2c3e50; border-bottom: 2px solid #3498db; padding-bottom: 10px; }
|
||||||
|
a { color: #3498db; }
|
||||||
|
.summary { background: #ecf0f1; padding: 15px; border-radius: 5px; margin: 20px 0; }
|
||||||
|
.button { display: inline-block; padding: 10px 20px; background: #3498db; color: white; text-decoration: none; border-radius: 5px; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div class="summary">
|
||||||
|
<p><strong>主题:</strong> ${summary.topicName}</p>
|
||||||
|
<p><strong>资讯数量:</strong> ${summary.articleCount} 条</p>
|
||||||
|
<p><strong>时间范围:</strong> ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}</p>
|
||||||
|
</div>
|
||||||
|
<a href="${summary.webUrl}" class="button">查看完整报告</a>
|
||||||
|
<hr>
|
||||||
|
<div>${htmlContent}</div>
|
||||||
|
<p style="color: #7f8c8d; font-size: 12px; margin-top: 40px;">本邮件由 News Aggregator 自动发送</p>
|
||||||
|
</body>
|
||||||
|
</html>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildTextContent(summary: ReportSummary): string {
|
||||||
|
return `${summary.title}
|
||||||
|
|
||||||
|
主题: ${summary.topicName}
|
||||||
|
资讯数量: ${summary.articleCount} 条
|
||||||
|
时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
查看完整报告: ${summary.webUrl}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export * from './base.distributor';
|
||||||
|
export * from './email.distributor';
|
||||||
|
export * from './dingtalk.distributor';
|
||||||
|
export * from './wechat.distributor';
|
||||||
|
export * from './slack.distributor';
|
||||||
|
export * from './distributor.factory';
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import { BaseDistributor } from './base.distributor';
|
||||||
|
import { DistributorType, DistributionResult, ReportSummary, SlackDistributorConfig } from '../types/distributor';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class SlackDistributor extends BaseDistributor {
|
||||||
|
private slackConfig: SlackDistributorConfig;
|
||||||
|
|
||||||
|
constructor(config: SlackDistributorConfig, channelId: number) {
|
||||||
|
super(config, channelId);
|
||||||
|
this.slackConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('Slack 分发器开始发送', { title: summary.title });
|
||||||
|
|
||||||
|
const response = await fetch(this.slackConfig.webhook, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(this.buildMessage(summary)),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(`Slack API 错误: ${response.statusText}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('Slack 消息发送成功');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Slack 消息发送失败', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.slackConfig.webhook;
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'slack';
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
return {
|
||||||
|
blocks: [
|
||||||
|
{
|
||||||
|
type: 'header',
|
||||||
|
text: { type: 'plain_text', text: summary.title },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'section',
|
||||||
|
fields: [
|
||||||
|
{ type: 'mrkdwn', text: `*主题:*\n${summary.topicName}` },
|
||||||
|
{ type: 'mrkdwn', text: `*资讯数量:*\n${summary.articleCount} 条` },
|
||||||
|
{ type: 'mrkdwn', text: `*时间范围:*\n${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}` },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'actions',
|
||||||
|
elements: [
|
||||||
|
{
|
||||||
|
type: 'button',
|
||||||
|
text: { type: 'plain_text', text: '查看完整报告' },
|
||||||
|
url: summary.webUrl,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { BaseDistributor } from './base.distributor';
|
||||||
|
import { DistributorType, DistributionResult, ReportSummary, WechatDistributorConfig } from '../types/distributor';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class WechatDistributor extends BaseDistributor {
|
||||||
|
private wechatConfig: WechatDistributorConfig;
|
||||||
|
|
||||||
|
constructor(config: WechatDistributorConfig, channelId: number) {
|
||||||
|
super(config, channelId);
|
||||||
|
this.wechatConfig = config;
|
||||||
|
}
|
||||||
|
|
||||||
|
async distribute(summary: ReportSummary, fullContent: string): Promise<DistributionResult> {
|
||||||
|
try {
|
||||||
|
logger.info('企业微信分发器开始发送', { title: summary.title });
|
||||||
|
|
||||||
|
const response = await fetch(this.wechatConfig.webhook, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(this.buildMessage(summary)),
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = (await response.json()) as { errcode: number; errmsg: string };
|
||||||
|
|
||||||
|
if (result.errcode !== 0) {
|
||||||
|
throw new Error(`企业微信 API 错误: ${result.errmsg}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('企业微信消息发送成功');
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('企业微信消息发送失败', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
validateConfig(): boolean {
|
||||||
|
return !!this.wechatConfig.webhook;
|
||||||
|
}
|
||||||
|
|
||||||
|
getType(): DistributorType {
|
||||||
|
return 'wechat';
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildMessage(summary: ReportSummary) {
|
||||||
|
return {
|
||||||
|
msgtype: 'markdown',
|
||||||
|
markdown: {
|
||||||
|
content: `# ${summary.title}
|
||||||
|
|
||||||
|
> 主题: ${summary.topicName}
|
||||||
|
> 资讯数量: ${summary.articleCount} 条
|
||||||
|
> 时间范围: ${this.formatDate(summary.periodStart)} - ${this.formatDate(summary.periodEnd)}
|
||||||
|
|
||||||
|
[查看完整报告](${summary.webUrl})`,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN');
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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: [],
|
||||||
|
};
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { CollectorFactory } from '../collectors/collector.factory';
|
||||||
|
import { CollectorType } from '../types/collector';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class CollectorService {
|
||||||
|
/**
|
||||||
|
* 执行单个数据源的采集
|
||||||
|
*/
|
||||||
|
async collectSource(sourceId: number): Promise<void> {
|
||||||
|
const startTime = Date.now();
|
||||||
|
let articlesCount = 0;
|
||||||
|
let status: 'success' | 'failed' = 'success';
|
||||||
|
let errorMessage: string | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 查询数据源
|
||||||
|
const source = await prisma.source.findUnique({
|
||||||
|
where: { id: sourceId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!source) {
|
||||||
|
throw new Error(`Source ${sourceId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!source.enabled) {
|
||||||
|
logger.info(`数据源 ${source.name} 已禁用,跳过采集`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`开始采集数据源: ${source.name}`);
|
||||||
|
|
||||||
|
// 创建采集器
|
||||||
|
const collector = CollectorFactory.create(
|
||||||
|
source.type as CollectorType,
|
||||||
|
source.config as any,
|
||||||
|
source.id
|
||||||
|
);
|
||||||
|
|
||||||
|
// 验证配置
|
||||||
|
if (!collector.validateConfig()) {
|
||||||
|
throw new Error('Invalid collector config');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行采集
|
||||||
|
const result = await collector.collect();
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Collection failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存资讯(批量去重)
|
||||||
|
const articlesToCreate = [];
|
||||||
|
for (const article of result.articles) {
|
||||||
|
// 检查是否已存在(通过 URL 或标题去重)
|
||||||
|
const whereConditions: any[] = [{ title: article.title }];
|
||||||
|
if (article.url) {
|
||||||
|
whereConditions.push({ url: article.url });
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await prisma.article.findFirst({
|
||||||
|
where: {
|
||||||
|
sourceId: source.id,
|
||||||
|
OR: whereConditions,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
articlesToCreate.push({
|
||||||
|
sourceId: source.id,
|
||||||
|
title: article.title,
|
||||||
|
content: article.content,
|
||||||
|
url: article.url,
|
||||||
|
publishedAt: article.publishedAt,
|
||||||
|
collectedAt: new Date(),
|
||||||
|
rawData: article.rawData,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批量插入
|
||||||
|
if (articlesToCreate.length > 0) {
|
||||||
|
await prisma.article.createMany({
|
||||||
|
data: articlesToCreate,
|
||||||
|
skipDuplicates: true,
|
||||||
|
});
|
||||||
|
articlesCount = articlesToCreate.length;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新数据源的最后采集时间
|
||||||
|
await prisma.source.update({
|
||||||
|
where: { id: source.id },
|
||||||
|
data: { lastCollectedAt: new Date() },
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`数据源 ${source.name} 采集完成,新增 ${articlesCount} 条资讯`);
|
||||||
|
} catch (error) {
|
||||||
|
status = 'failed';
|
||||||
|
errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||||
|
logger.error(`数据源采集失败`, { sourceId, error: errorMessage });
|
||||||
|
} finally {
|
||||||
|
// 记录采集日志
|
||||||
|
await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId,
|
||||||
|
status,
|
||||||
|
errorMessage,
|
||||||
|
articlesCount,
|
||||||
|
startedAt: new Date(startTime),
|
||||||
|
finishedAt: new Date(),
|
||||||
|
durationMs: Date.now() - startTime,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 采集所有启用的数据源
|
||||||
|
*/
|
||||||
|
async collectAllSources(): Promise<void> {
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
where: { enabled: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`开始采集 ${sources.length} 个数据源`);
|
||||||
|
|
||||||
|
for (const source of sources) {
|
||||||
|
await this.collectSource(source.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('所有数据源采集完成');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取采集统计信息
|
||||||
|
*/
|
||||||
|
async getCollectionStats() {
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
include: {
|
||||||
|
collectionLogs: {
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
_count: {
|
||||||
|
select: { articles: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return sources.map((source) => ({
|
||||||
|
id: source.id,
|
||||||
|
name: source.name,
|
||||||
|
type: source.type,
|
||||||
|
enabled: source.enabled,
|
||||||
|
lastCollectedAt: source.lastCollectedAt,
|
||||||
|
articleCount: source._count.articles,
|
||||||
|
lastLog: source.collectionLogs[0] || null,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { DistributorFactory } from '../distributors/distributor.factory';
|
||||||
|
import { DistributorType, ReportSummary } from '../types/distributor';
|
||||||
|
import { config } from '../config';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class DistributorService {
|
||||||
|
/**
|
||||||
|
* 分发报告到指定渠道
|
||||||
|
*/
|
||||||
|
async distributeReport(reportId: number, channelId: number): Promise<void> {
|
||||||
|
let status: 'success' | 'failed' = 'success';
|
||||||
|
let errorMessage: string | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: { topic: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
throw new Error(`Report ${reportId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const channel = await prisma.channel.findUnique({
|
||||||
|
where: { id: channelId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!channel) {
|
||||||
|
throw new Error(`Channel ${channelId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!channel.enabled) {
|
||||||
|
logger.info(`渠道 ${channel.name} 已禁用,跳过分发`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`开始分发报告: ${report.title} -> ${channel.name}`);
|
||||||
|
|
||||||
|
const distributor = DistributorFactory.create(
|
||||||
|
channel.type as DistributorType,
|
||||||
|
channel.config as any,
|
||||||
|
channel.id
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!distributor.validateConfig()) {
|
||||||
|
throw new Error('Invalid distributor config');
|
||||||
|
}
|
||||||
|
|
||||||
|
const summary: ReportSummary = {
|
||||||
|
title: report.title,
|
||||||
|
topicName: report.topic.name,
|
||||||
|
articleCount: report.articleCount,
|
||||||
|
periodStart: report.periodStart,
|
||||||
|
periodEnd: report.periodEnd,
|
||||||
|
webUrl: this.buildReportUrl(reportId),
|
||||||
|
};
|
||||||
|
|
||||||
|
const result = await distributor.distribute(summary, report.content);
|
||||||
|
|
||||||
|
if (!result.success) {
|
||||||
|
throw new Error(result.error || 'Distribution failed');
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`报告分发成功: ${channel.name}`);
|
||||||
|
} catch (error) {
|
||||||
|
status = 'failed';
|
||||||
|
errorMessage = error instanceof Error ? error.message : 'Unknown error';
|
||||||
|
logger.error('报告分发失败', { reportId, channelId, error: errorMessage });
|
||||||
|
} finally {
|
||||||
|
await prisma.pushLog.create({
|
||||||
|
data: { reportId, channelId, status, errorMessage },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分发报告到所有关联的渠道
|
||||||
|
*/
|
||||||
|
async distributeReportToAllChannels(reportId: number): Promise<void> {
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: {
|
||||||
|
include: {
|
||||||
|
topicChannels: { include: { channel: true } },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
throw new Error(`Report ${reportId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const channels = report.topic.topicChannels
|
||||||
|
.map((tc) => tc.channel)
|
||||||
|
.filter((c) => c.enabled);
|
||||||
|
|
||||||
|
logger.info(`开始分发报告到 ${channels.length} 个渠道`);
|
||||||
|
|
||||||
|
for (const channel of channels) {
|
||||||
|
await this.distributeReport(reportId, channel.id);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('报告分发完成');
|
||||||
|
}
|
||||||
|
|
||||||
|
private buildReportUrl(reportId: number): string {
|
||||||
|
const baseUrl = process.env.WEB_BASE_URL || `http://localhost:${config.port}`;
|
||||||
|
return `${baseUrl}/reports/${reportId}`;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,226 @@
|
|||||||
|
import { Article } from '@prisma/client';
|
||||||
|
import { LlmClient } from '../utils/llm-client';
|
||||||
|
import { LlmClientConfig } from '../types/llm';
|
||||||
|
import { ProcessMode, ProcessedContent } from '../types';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class ProcessorService {
|
||||||
|
/**
|
||||||
|
* 处理资讯列表
|
||||||
|
*/
|
||||||
|
async processArticles(
|
||||||
|
articles: Article[],
|
||||||
|
mode: ProcessMode,
|
||||||
|
llmConfig?: LlmClientConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
logger.info(`开始处理 ${articles.length} 条资讯,模式: ${mode}`);
|
||||||
|
|
||||||
|
switch (mode) {
|
||||||
|
case 'aggregate':
|
||||||
|
return this.aggregateArticles(articles);
|
||||||
|
case 'summary':
|
||||||
|
if (!llmConfig) throw new Error('Summary mode requires LLM config');
|
||||||
|
return this.summarizeArticles(articles, llmConfig);
|
||||||
|
case 'deep_analysis':
|
||||||
|
if (!llmConfig) throw new Error('Deep analysis mode requires LLM config');
|
||||||
|
return this.deepAnalyzeArticles(articles, llmConfig);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown process mode: ${mode}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 简单聚合:按主题分类列出标题和链接
|
||||||
|
*/
|
||||||
|
private async aggregateArticles(articles: Article[]): Promise<ProcessedContent> {
|
||||||
|
const lines: string[] = [];
|
||||||
|
|
||||||
|
articles.forEach((article, index) => {
|
||||||
|
lines.push(`${index + 1}. **${article.title}**`);
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(` 链接: ${article.url}`);
|
||||||
|
}
|
||||||
|
if (article.publishedAt) {
|
||||||
|
lines.push(` 发布时间: ${article.publishedAt.toLocaleString('zh-CN')}`);
|
||||||
|
}
|
||||||
|
lines.push('');
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: lines.join('\n'),
|
||||||
|
mode: 'aggregate',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 摘要:对每条资讯生成简短摘要
|
||||||
|
*/
|
||||||
|
private async summarizeArticles(
|
||||||
|
articles: Article[],
|
||||||
|
llmConfig: LlmClientConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
const llmClient = new LlmClient(llmConfig);
|
||||||
|
const lines: string[] = [];
|
||||||
|
|
||||||
|
for (const article of articles) {
|
||||||
|
try {
|
||||||
|
const summary = await this.summarizeSingleArticle(article, llmClient);
|
||||||
|
lines.push(`### ${article.title}`);
|
||||||
|
lines.push('');
|
||||||
|
lines.push(summary);
|
||||||
|
lines.push('');
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(`[查看原文](${article.url})`);
|
||||||
|
lines.push('');
|
||||||
|
}
|
||||||
|
lines.push('---');
|
||||||
|
lines.push('');
|
||||||
|
} catch (error) {
|
||||||
|
logger.warn('摘要生成失败', { title: article.title, error });
|
||||||
|
lines.push(`### ${article.title}`);
|
||||||
|
lines.push('');
|
||||||
|
if (article.content) {
|
||||||
|
lines.push(article.content.substring(0, 200) + '...');
|
||||||
|
}
|
||||||
|
lines.push('');
|
||||||
|
if (article.url) {
|
||||||
|
lines.push(`[查看原文](${article.url})`);
|
||||||
|
lines.push('');
|
||||||
|
}
|
||||||
|
lines.push('---');
|
||||||
|
lines.push('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: lines.join('\n'),
|
||||||
|
mode: 'summary',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为单条资讯生成摘要
|
||||||
|
*/
|
||||||
|
private async summarizeSingleArticle(
|
||||||
|
article: Article,
|
||||||
|
llmClient: LlmClient
|
||||||
|
): Promise<string> {
|
||||||
|
const prompt = `请为以下资讯生成一个简短的摘要(100字以内):
|
||||||
|
|
||||||
|
标题:${article.title}
|
||||||
|
${article.content ? `内容:${article.content.substring(0, 1000)}` : ''}
|
||||||
|
|
||||||
|
要求:
|
||||||
|
1. 提取核心信息
|
||||||
|
2. 简洁明了
|
||||||
|
3. 使用中文`;
|
||||||
|
|
||||||
|
const response = await llmClient.chat(
|
||||||
|
[{ role: 'user', content: prompt }],
|
||||||
|
{
|
||||||
|
temperature: 0.3,
|
||||||
|
maxTokens: 200,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return response.content.trim();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI 深度整理:分析、去重、归纳要点,生成结构化报告
|
||||||
|
*/
|
||||||
|
private async deepAnalyzeArticles(
|
||||||
|
articles: Article[],
|
||||||
|
llmConfig: LlmClientConfig
|
||||||
|
): Promise<ProcessedContent> {
|
||||||
|
const llmClient = new LlmClient(llmConfig);
|
||||||
|
|
||||||
|
const articlesList = articles
|
||||||
|
.map((article, index) => {
|
||||||
|
return `[${index + 1}] ${article.title}
|
||||||
|
${article.content ? article.content.substring(0, 500) : ''}
|
||||||
|
${article.url ? `链接: ${article.url}` : ''}
|
||||||
|
---`;
|
||||||
|
})
|
||||||
|
.join('\n\n');
|
||||||
|
|
||||||
|
const prompt = `你是一个专业的资讯分析师。请对以下资讯进行深度分析和整理:
|
||||||
|
|
||||||
|
${articlesList}
|
||||||
|
|
||||||
|
请按以下要求生成报告:
|
||||||
|
|
||||||
|
1. **核心主题**:识别这些资讯的主要主题和趋势
|
||||||
|
2. **重点资讯**:挑选出最重要的 3-5 条资讯,说明为什么重要
|
||||||
|
3. **关键要点**:提炼出关键信息和洞察
|
||||||
|
4. **相关性分析**:如果有相关或重复的资讯,进行合并说明
|
||||||
|
5. **总结**:用 2-3 句话总结整体情况
|
||||||
|
|
||||||
|
要求:
|
||||||
|
- 使用 Markdown 格式
|
||||||
|
- 结构清晰,层次分明
|
||||||
|
- 保留重要资讯的原文链接
|
||||||
|
- 使用中文`;
|
||||||
|
|
||||||
|
const response = await llmClient.chat(
|
||||||
|
[{ role: 'user', content: prompt }],
|
||||||
|
{
|
||||||
|
temperature: 0.5,
|
||||||
|
maxTokens: 2000,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: response.content.trim(),
|
||||||
|
mode: 'deep_analysis',
|
||||||
|
articlesCount: articles.length,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 去重:基于 URL 和标题相似度
|
||||||
|
*/
|
||||||
|
deduplicateArticles(articles: Article[]): Article[] {
|
||||||
|
const seen = new Set<string>();
|
||||||
|
const deduplicated: Article[] = [];
|
||||||
|
|
||||||
|
for (const article of articles) {
|
||||||
|
if (article.url) {
|
||||||
|
if (seen.has(article.url)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(article.url);
|
||||||
|
}
|
||||||
|
|
||||||
|
const normalizedTitle = article.title.toLowerCase().trim();
|
||||||
|
if (seen.has(normalizedTitle)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
seen.add(normalizedTitle);
|
||||||
|
|
||||||
|
deduplicated.push(article);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`去重完成: ${articles.length} -> ${deduplicated.length}`);
|
||||||
|
|
||||||
|
return deduplicated;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按发布时间排序
|
||||||
|
*/
|
||||||
|
sortArticlesByDate(articles: Article[], order: 'asc' | 'desc' = 'desc'): Article[] {
|
||||||
|
return [...articles].sort((a, b) => {
|
||||||
|
const dateA = a.publishedAt || a.collectedAt;
|
||||||
|
const dateB = b.publishedAt || b.collectedAt;
|
||||||
|
|
||||||
|
if (order === 'desc') {
|
||||||
|
return dateB.getTime() - dateA.getTime();
|
||||||
|
} else {
|
||||||
|
return dateA.getTime() - dateB.getTime();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,316 @@
|
|||||||
|
import prisma from '../config/database';
|
||||||
|
import { ProcessorService } from './processor.service';
|
||||||
|
import { ProcessMode, ReportGenerationOptions } from '../types';
|
||||||
|
import { Article } from '@prisma/client';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
export class ReportService {
|
||||||
|
private processorService: ProcessorService;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.processorService = new ProcessorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成报告
|
||||||
|
*/
|
||||||
|
async generateReport(options: ReportGenerationOptions): Promise<number> {
|
||||||
|
const { topicId, periodStart, periodEnd } = options;
|
||||||
|
|
||||||
|
logger.info('开始生成报告', { topicId, periodStart, periodEnd });
|
||||||
|
|
||||||
|
// 创建报告记录(状态:pending)
|
||||||
|
const report = await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
topicId,
|
||||||
|
title: '',
|
||||||
|
content: '',
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
status: 'pending',
|
||||||
|
articleCount: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 更新状态为 generating
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: { status: 'generating' },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 查询主题配置
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: topicId },
|
||||||
|
include: {
|
||||||
|
llmConfig: true,
|
||||||
|
topicSources: {
|
||||||
|
include: { source: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new Error(`Topic ${topicId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!topic.enabled) {
|
||||||
|
throw new Error(`Topic ${topic.name} is disabled`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询资讯
|
||||||
|
const sourceIds = topic.topicSources.map((ts) => ts.sourceId);
|
||||||
|
const articles = await this.queryArticles(sourceIds, periodStart, periodEnd);
|
||||||
|
|
||||||
|
if (articles.length === 0) {
|
||||||
|
logger.warn('没有找到资讯', { topicId, periodStart, periodEnd });
|
||||||
|
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
title: `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`,
|
||||||
|
content: '本期没有新的资讯。',
|
||||||
|
status: 'completed',
|
||||||
|
articleCount: 0,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return report.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`找到 ${articles.length} 条资讯`);
|
||||||
|
|
||||||
|
// 去重和排序
|
||||||
|
const deduplicated = this.processorService.deduplicateArticles(articles);
|
||||||
|
const sorted = this.processorService.sortArticlesByDate(deduplicated);
|
||||||
|
|
||||||
|
logger.info(`去重后 ${sorted.length} 条资讯`);
|
||||||
|
|
||||||
|
// 处理内容
|
||||||
|
let processedContent: string;
|
||||||
|
|
||||||
|
if (!topic.llmConfig || !topic.llmConfig.enabled) {
|
||||||
|
logger.warn('没有启用的 LLM 配置,使用简单聚合模式');
|
||||||
|
const result = await this.processorService.processArticles(sorted, 'aggregate');
|
||||||
|
processedContent = result.content;
|
||||||
|
} else {
|
||||||
|
const result = await this.processorService.processArticles(
|
||||||
|
sorted,
|
||||||
|
topic.processMode as ProcessMode,
|
||||||
|
{
|
||||||
|
baseUrl: topic.llmConfig.baseUrl,
|
||||||
|
model: topic.llmConfig.model,
|
||||||
|
apiKey: topic.llmConfig.apiKey,
|
||||||
|
}
|
||||||
|
);
|
||||||
|
processedContent = result.content;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 生成报告标题和内容
|
||||||
|
const title = `${topic.name} - ${this.formatDateRange(periodStart, periodEnd)}`;
|
||||||
|
const fullContent = this.buildReportContent(
|
||||||
|
title,
|
||||||
|
topic.name,
|
||||||
|
periodStart,
|
||||||
|
periodEnd,
|
||||||
|
sorted.length,
|
||||||
|
processedContent
|
||||||
|
);
|
||||||
|
|
||||||
|
// 更新报告
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
title,
|
||||||
|
content: fullContent,
|
||||||
|
status: 'completed',
|
||||||
|
articleCount: sorted.length,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`报告生成完成: ${report.id}`);
|
||||||
|
return report.id;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('报告生成失败', { reportId: report.id, error });
|
||||||
|
|
||||||
|
await prisma.report.update({
|
||||||
|
where: { id: report.id },
|
||||||
|
data: {
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: error instanceof Error ? error.message : 'Unknown error',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询资讯
|
||||||
|
*/
|
||||||
|
private async queryArticles(
|
||||||
|
sourceIds: number[],
|
||||||
|
periodStart: Date,
|
||||||
|
periodEnd: Date
|
||||||
|
): Promise<Article[]> {
|
||||||
|
return prisma.article.findMany({
|
||||||
|
where: {
|
||||||
|
sourceId: { in: sourceIds },
|
||||||
|
OR: [
|
||||||
|
{
|
||||||
|
publishedAt: { gte: periodStart, lte: periodEnd },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
publishedAt: null,
|
||||||
|
collectedAt: { gte: periodStart, lte: periodEnd },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
orderBy: [{ publishedAt: 'desc' }, { collectedAt: 'desc' }],
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建报告内容
|
||||||
|
*/
|
||||||
|
private buildReportContent(
|
||||||
|
title: string,
|
||||||
|
topicName: string,
|
||||||
|
periodStart: Date,
|
||||||
|
periodEnd: Date,
|
||||||
|
articleCount: number,
|
||||||
|
processedContent: string
|
||||||
|
): string {
|
||||||
|
return `# ${title}
|
||||||
|
|
||||||
|
**主题**: ${topicName}
|
||||||
|
**时间范围**: ${this.formatDate(periodStart)} - ${this.formatDate(periodEnd)}
|
||||||
|
**资讯数量**: ${articleCount} 条
|
||||||
|
**生成时间**: ${this.formatDate(new Date())}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
${processedContent}
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*本报告由 News Aggregator 自动生成*`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化日期范围
|
||||||
|
*/
|
||||||
|
private formatDateRange(start: Date, end: Date): string {
|
||||||
|
const startStr = this.formatDate(start);
|
||||||
|
const endStr = this.formatDate(end);
|
||||||
|
return startStr === endStr ? startStr : `${startStr} 至 ${endStr}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 格式化日期
|
||||||
|
*/
|
||||||
|
private formatDate(date: Date): string {
|
||||||
|
return date.toLocaleDateString('zh-CN', {
|
||||||
|
year: 'numeric',
|
||||||
|
month: '2-digit',
|
||||||
|
day: '2-digit',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据主题配置计算时间范围
|
||||||
|
*/
|
||||||
|
calculatePeriod(scheduleConfig: any): { start: Date; end: Date } {
|
||||||
|
const now = new Date();
|
||||||
|
const lookback = scheduleConfig.lookback || 24;
|
||||||
|
const start = new Date(now.getTime() - lookback * 60 * 60 * 1000);
|
||||||
|
return { start, end: now };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为主题生成报告
|
||||||
|
*/
|
||||||
|
async generateReportForTopic(topicId: number): Promise<number> {
|
||||||
|
const topic = await prisma.topic.findUnique({ where: { id: topicId } });
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new Error(`Topic ${topicId} not found`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const { start, end } = this.calculatePeriod(topic.scheduleConfig);
|
||||||
|
|
||||||
|
return this.generateReport({
|
||||||
|
topicId,
|
||||||
|
periodStart: start,
|
||||||
|
periodEnd: end,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 为所有启用的主题生成报告
|
||||||
|
*/
|
||||||
|
async generateReportsForAllTopics(): Promise<number[]> {
|
||||||
|
const topics = await prisma.topic.findMany({ where: { enabled: true } });
|
||||||
|
|
||||||
|
logger.info(`开始为 ${topics.length} 个主题生成报告`);
|
||||||
|
|
||||||
|
const reportIds: number[] = [];
|
||||||
|
|
||||||
|
for (const topic of topics) {
|
||||||
|
try {
|
||||||
|
const reportId = await this.generateReportForTopic(topic.id);
|
||||||
|
reportIds.push(reportId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error(`主题 ${topic.name} 报告生成失败`, error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info(`报告生成完成,成功 ${reportIds.length}/${topics.length}`);
|
||||||
|
return reportIds;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取报告详情
|
||||||
|
*/
|
||||||
|
async getReport(reportId: number) {
|
||||||
|
return prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: { topic: true },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取报告列表
|
||||||
|
*/
|
||||||
|
async getReports(options: {
|
||||||
|
topicId?: number;
|
||||||
|
status?: string;
|
||||||
|
page?: number;
|
||||||
|
limit?: number;
|
||||||
|
}) {
|
||||||
|
const { topicId, status, page = 1, limit = 20 } = options;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (topicId) where.topicId = topicId;
|
||||||
|
if (status) where.status = status;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.report.findMany({
|
||||||
|
where,
|
||||||
|
include: { topic: true },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (page - 1) * limit,
|
||||||
|
take: limit,
|
||||||
|
}),
|
||||||
|
prisma.report.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
items,
|
||||||
|
total,
|
||||||
|
page,
|
||||||
|
limit,
|
||||||
|
totalPages: Math.ceil(total / limit),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,168 @@
|
|||||||
|
import cron, { ScheduledTask } from 'node-cron';
|
||||||
|
import { CollectorService } from './collector.service';
|
||||||
|
import { ReportService } from './report.service';
|
||||||
|
import { DistributorService } from './distributor.service';
|
||||||
|
import prisma from '../config/database';
|
||||||
|
import logger from '../utils/logger';
|
||||||
|
|
||||||
|
interface ScheduledTaskInfo {
|
||||||
|
id: string;
|
||||||
|
type: 'collection' | 'report';
|
||||||
|
cronExpression: string;
|
||||||
|
task: ScheduledTask;
|
||||||
|
resourceId: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export class SchedulerService {
|
||||||
|
private tasks: Map<string, ScheduledTaskInfo> = new Map();
|
||||||
|
private collectorService: CollectorService;
|
||||||
|
private reportService: ReportService;
|
||||||
|
private distributorService: DistributorService;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.collectorService = new CollectorService();
|
||||||
|
this.reportService = new ReportService();
|
||||||
|
this.distributorService = new DistributorService();
|
||||||
|
}
|
||||||
|
|
||||||
|
async start(): Promise<void> {
|
||||||
|
logger.info('启动调度器...');
|
||||||
|
await this.loadCollectionTasks();
|
||||||
|
await this.loadReportTasks();
|
||||||
|
logger.info(`调度器启动完成,共 ${this.tasks.size} 个任务`);
|
||||||
|
}
|
||||||
|
|
||||||
|
stop(): void {
|
||||||
|
logger.info('停止调度器...');
|
||||||
|
this.tasks.forEach((task) => task.task.stop());
|
||||||
|
this.tasks.clear();
|
||||||
|
logger.info('调度器已停止');
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadCollectionTasks(): Promise<void> {
|
||||||
|
const sources = await prisma.source.findMany({ where: { enabled: true } });
|
||||||
|
logger.info(`加载 ${sources.length} 个采集任务`);
|
||||||
|
|
||||||
|
for (const source of sources) {
|
||||||
|
this.scheduleCollectionTask(source.id, source.cronExpression);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async loadReportTasks(): Promise<void> {
|
||||||
|
const topics = await prisma.topic.findMany({ where: { enabled: true } });
|
||||||
|
logger.info(`加载 ${topics.length} 个报告生成任务`);
|
||||||
|
|
||||||
|
for (const topic of topics) {
|
||||||
|
const scheduleConfig = topic.scheduleConfig as any;
|
||||||
|
if (scheduleConfig?.cron) {
|
||||||
|
this.scheduleReportTask(topic.id, scheduleConfig.cron);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleCollectionTask(sourceId: number, cronExpression: string): void {
|
||||||
|
const taskId = `collection-${sourceId}`;
|
||||||
|
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { sourceId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行采集任务: sourceId=${sourceId}`);
|
||||||
|
try {
|
||||||
|
await this.collectorService.collectSource(sourceId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('采集任务执行失败', { sourceId, error });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'collection',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: sourceId,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`采集任务已调度: sourceId=${sourceId}, cron=${cronExpression}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
scheduleReportTask(topicId: number, cronExpression: string): void {
|
||||||
|
const taskId = `report-${topicId}`;
|
||||||
|
|
||||||
|
if (this.tasks.has(taskId)) {
|
||||||
|
this.unscheduleTask(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!cron.validate(cronExpression)) {
|
||||||
|
logger.error(`无效的 cron 表达式: ${cronExpression}`, { topicId });
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const task = cron.schedule(cronExpression, async () => {
|
||||||
|
logger.info(`执行报告生成任务: topicId=${topicId}`);
|
||||||
|
try {
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('报告生成任务执行失败', { topicId, error });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.tasks.set(taskId, {
|
||||||
|
id: taskId,
|
||||||
|
type: 'report',
|
||||||
|
cronExpression,
|
||||||
|
task,
|
||||||
|
resourceId: topicId,
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info(`报告生成任务已调度: topicId=${topicId}, cron=${cronExpression}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
unscheduleTask(taskId: string): void {
|
||||||
|
const scheduledTask = this.tasks.get(taskId);
|
||||||
|
if (scheduledTask) {
|
||||||
|
scheduledTask.task.stop();
|
||||||
|
this.tasks.delete(taskId);
|
||||||
|
logger.info(`任务已取消: ${taskId}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async reload(): Promise<void> {
|
||||||
|
logger.info('重新加载调度任务...');
|
||||||
|
this.stop();
|
||||||
|
await this.start();
|
||||||
|
}
|
||||||
|
|
||||||
|
getTasksStatus(): Array<{
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
cronExpression: string;
|
||||||
|
resourceId: number;
|
||||||
|
}> {
|
||||||
|
return Array.from(this.tasks.values()).map((task) => ({
|
||||||
|
id: task.id,
|
||||||
|
type: task.type,
|
||||||
|
cronExpression: task.cronExpression,
|
||||||
|
resourceId: task.resourceId,
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
async triggerCollection(sourceId: number): Promise<void> {
|
||||||
|
logger.info(`手动触发采集任务: sourceId=${sourceId}`);
|
||||||
|
await this.collectorService.collectSource(sourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
async triggerReport(topicId: number): Promise<number> {
|
||||||
|
logger.info(`手动触发报告生成任务: topicId=${topicId}`);
|
||||||
|
const reportId = await this.reportService.generateReportForTopic(topicId);
|
||||||
|
await this.distributorService.distributeReportToAllChannels(reportId);
|
||||||
|
return reportId;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
// 采集器类型定义
|
||||||
|
|
||||||
|
export type CollectorType = 'api' | 'playwright' | 'rss';
|
||||||
|
|
||||||
|
export interface CollectorConfig {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CollectedArticle {
|
||||||
|
title: string;
|
||||||
|
content?: string;
|
||||||
|
url?: string;
|
||||||
|
publishedAt?: Date;
|
||||||
|
rawData?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CollectionResult {
|
||||||
|
articles: CollectedArticle[];
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// API 采集器配置
|
||||||
|
export interface ApiCollectorConfig {
|
||||||
|
url: string;
|
||||||
|
method?: 'GET' | 'POST';
|
||||||
|
headers?: Record<string, string>;
|
||||||
|
params?: Record<string, any>;
|
||||||
|
body?: any;
|
||||||
|
dataPath?: string;
|
||||||
|
mapping: {
|
||||||
|
title: string;
|
||||||
|
content?: string;
|
||||||
|
url?: string;
|
||||||
|
publishedAt?: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Playwright 采集器配置
|
||||||
|
export interface PlaywrightCollectorConfig {
|
||||||
|
url: string;
|
||||||
|
selectors: {
|
||||||
|
items: string;
|
||||||
|
title: string;
|
||||||
|
content?: string;
|
||||||
|
url?: string;
|
||||||
|
publishedAt?: string;
|
||||||
|
};
|
||||||
|
waitFor?: string;
|
||||||
|
waitTimeout?: number;
|
||||||
|
script?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// RSS 采集器配置
|
||||||
|
export interface RssCollectorConfig {
|
||||||
|
url: string;
|
||||||
|
customFields?: {
|
||||||
|
item?: string[];
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,52 @@
|
|||||||
|
// 分发器类型定义
|
||||||
|
|
||||||
|
export type DistributorType = 'email' | 'dingtalk' | 'wechat' | 'slack';
|
||||||
|
|
||||||
|
export interface DistributorConfig {
|
||||||
|
[key: string]: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface DistributionResult {
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ReportSummary {
|
||||||
|
title: string;
|
||||||
|
topicName: string;
|
||||||
|
articleCount: number;
|
||||||
|
periodStart: Date;
|
||||||
|
periodEnd: Date;
|
||||||
|
webUrl: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 邮件配置
|
||||||
|
export interface EmailDistributorConfig {
|
||||||
|
smtp: {
|
||||||
|
host: string;
|
||||||
|
port: number;
|
||||||
|
secure: boolean;
|
||||||
|
auth: {
|
||||||
|
user: string;
|
||||||
|
pass: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
from: string;
|
||||||
|
to: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
// 钉钉配置
|
||||||
|
export interface DingtalkDistributorConfig {
|
||||||
|
webhook: string;
|
||||||
|
secret?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 企业微信配置
|
||||||
|
export interface WechatDistributorConfig {
|
||||||
|
webhook: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Slack 配置
|
||||||
|
export interface SlackDistributorConfig {
|
||||||
|
webhook: string;
|
||||||
|
}
|
||||||
+13
-19
@@ -21,29 +21,23 @@ export interface PaginatedResponse<T> extends ApiResponse<T[]> {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// 采集器类型
|
|
||||||
export interface CollectorConfig {
|
|
||||||
url: string;
|
|
||||||
method?: 'GET' | 'POST';
|
|
||||||
headers?: Record<string, string>;
|
|
||||||
body?: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface RawArticle {
|
|
||||||
title: string;
|
|
||||||
content?: string;
|
|
||||||
url?: string;
|
|
||||||
publishedAt?: Date;
|
|
||||||
[key: string]: any;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 处理器类型
|
// 处理器类型
|
||||||
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis';
|
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis';
|
||||||
|
|
||||||
export interface ProcessingResult {
|
export interface ProcessedContent {
|
||||||
title: string;
|
|
||||||
content: string;
|
content: string;
|
||||||
articleCount: number;
|
mode: ProcessMode;
|
||||||
|
articlesCount: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 报告类型
|
||||||
|
export type ReportStatus = 'pending' | 'generating' | 'completed' | 'failed';
|
||||||
|
|
||||||
|
export interface ReportGenerationOptions {
|
||||||
|
topicId: number;
|
||||||
|
periodStart: Date;
|
||||||
|
periodEnd: Date;
|
||||||
|
manualTrigger?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 推送器类型
|
// 推送器类型
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
// LLM 类型定义
|
||||||
|
|
||||||
|
export interface LlmMessage {
|
||||||
|
role: 'system' | 'user' | 'assistant';
|
||||||
|
content: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LlmResponse {
|
||||||
|
content: string;
|
||||||
|
usage?: {
|
||||||
|
promptTokens: number;
|
||||||
|
completionTokens: number;
|
||||||
|
totalTokens: number;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface LlmClientConfig {
|
||||||
|
baseUrl: string;
|
||||||
|
model: string;
|
||||||
|
apiKey: string;
|
||||||
|
}
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import OpenAI from 'openai';
|
||||||
|
import { LlmClientConfig, LlmMessage, LlmResponse } from '../types/llm';
|
||||||
|
import logger from './logger';
|
||||||
|
|
||||||
|
export class LlmClient {
|
||||||
|
private client: OpenAI;
|
||||||
|
private model: string;
|
||||||
|
|
||||||
|
constructor(private config: LlmClientConfig) {
|
||||||
|
this.client = new OpenAI({
|
||||||
|
baseURL: config.baseUrl,
|
||||||
|
apiKey: config.apiKey,
|
||||||
|
});
|
||||||
|
this.model = config.model;
|
||||||
|
}
|
||||||
|
|
||||||
|
async chat(
|
||||||
|
messages: LlmMessage[],
|
||||||
|
options?: {
|
||||||
|
temperature?: number;
|
||||||
|
maxTokens?: number;
|
||||||
|
}
|
||||||
|
): Promise<LlmResponse> {
|
||||||
|
try {
|
||||||
|
logger.debug('调用 LLM', {
|
||||||
|
model: this.model,
|
||||||
|
messagesCount: messages.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await this.client.chat.completions.create({
|
||||||
|
model: this.model,
|
||||||
|
messages: messages as any,
|
||||||
|
temperature: options?.temperature ?? 0.7,
|
||||||
|
max_tokens: options?.maxTokens,
|
||||||
|
});
|
||||||
|
|
||||||
|
const content = response.choices[0]?.message?.content || '';
|
||||||
|
|
||||||
|
logger.debug('LLM 响应完成', {
|
||||||
|
contentLength: content.length,
|
||||||
|
usage: response.usage,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
content,
|
||||||
|
usage: response.usage
|
||||||
|
? {
|
||||||
|
promptTokens: response.usage.prompt_tokens,
|
||||||
|
completionTokens: response.usage.completion_tokens,
|
||||||
|
totalTokens: response.usage.total_tokens,
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('LLM 调用失败', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async streamChat(
|
||||||
|
messages: LlmMessage[],
|
||||||
|
onChunk: (chunk: string) => void,
|
||||||
|
options?: {
|
||||||
|
temperature?: number;
|
||||||
|
maxTokens?: number;
|
||||||
|
}
|
||||||
|
): Promise<void> {
|
||||||
|
try {
|
||||||
|
logger.debug('调用 LLM (流式)', {
|
||||||
|
model: this.model,
|
||||||
|
messagesCount: messages.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
const stream = await this.client.chat.completions.create({
|
||||||
|
model: this.model,
|
||||||
|
messages: messages as any,
|
||||||
|
temperature: options?.temperature ?? 0.7,
|
||||||
|
max_tokens: options?.maxTokens,
|
||||||
|
stream: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
for await (const chunk of stream) {
|
||||||
|
const content = chunk.choices[0]?.delta?.content || '';
|
||||||
|
if (content) {
|
||||||
|
onChunk(content);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.debug('LLM 流式响应完成');
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('LLM 流式调用失败', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { FastifyError, FastifyReply, FastifyRequest } from 'fastify';
|
||||||
|
import { AppError, ValidationError } from '../../utils/errors';
|
||||||
|
import logger from '../../utils/logger';
|
||||||
|
|
||||||
|
export async function errorHandler(
|
||||||
|
error: FastifyError,
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply
|
||||||
|
): Promise<void> {
|
||||||
|
logger.error('请求处理错误:', {
|
||||||
|
method: request.method,
|
||||||
|
url: request.url,
|
||||||
|
error: error.message,
|
||||||
|
stack: error.stack,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 处理自定义应用错误
|
||||||
|
if (error instanceof AppError) {
|
||||||
|
const response: any = {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
|
||||||
|
// 如果是验证错误,附加详细信息
|
||||||
|
if (error instanceof ValidationError) {
|
||||||
|
response.details = error.errors;
|
||||||
|
}
|
||||||
|
|
||||||
|
reply.status(error.statusCode).send(response);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理 Fastify 验证错误
|
||||||
|
if (error.validation) {
|
||||||
|
reply.status(400).send({
|
||||||
|
success: false,
|
||||||
|
error: '请求参数验证失败',
|
||||||
|
details: error.validation,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理未知错误
|
||||||
|
const statusCode = error.statusCode || 500;
|
||||||
|
const message = statusCode === 500 ? '服务器内部错误' : error.message;
|
||||||
|
|
||||||
|
reply.status(statusCode).send({
|
||||||
|
success: false,
|
||||||
|
error: message,
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
import { FastifyRequest, FastifyReply, HookHandlerDoneFunction } from 'fastify';
|
||||||
|
import logger from '../../utils/logger';
|
||||||
|
|
||||||
|
export function requestLogger(
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply,
|
||||||
|
done: HookHandlerDoneFunction
|
||||||
|
): void {
|
||||||
|
const start = Date.now();
|
||||||
|
|
||||||
|
// 记录请求开始
|
||||||
|
logger.debug(`--> ${request.method} ${request.url}`);
|
||||||
|
|
||||||
|
// 在响应发送后记录
|
||||||
|
reply.raw.on('finish', () => {
|
||||||
|
const duration = Date.now() - start;
|
||||||
|
const statusCode = reply.statusCode;
|
||||||
|
|
||||||
|
// 根据状态码选择日志级别
|
||||||
|
if (statusCode >= 500) {
|
||||||
|
logger.error(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
} else if (statusCode >= 400) {
|
||||||
|
logger.warn(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
} else {
|
||||||
|
logger.info(`<-- ${request.method} ${request.url} ${statusCode} ${duration}ms`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
done();
|
||||||
|
}
|
||||||
@@ -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 });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function articleRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取资讯列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20, sourceId, topicId, startDate, endDate } = request.query as any;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
|
||||||
|
if (sourceId) {
|
||||||
|
where.sourceId = parseInt(sourceId);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (topicId) {
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: parseInt(topicId) },
|
||||||
|
include: { topicSources: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (topic) {
|
||||||
|
where.sourceId = { in: topic.topicSources.map((ts) => ts.sourceId) };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (startDate || endDate) {
|
||||||
|
where.OR = [
|
||||||
|
{
|
||||||
|
publishedAt: {
|
||||||
|
...(startDate && { gte: new Date(startDate) }),
|
||||||
|
...(endDate && { lte: new Date(endDate) }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
publishedAt: null,
|
||||||
|
collectedAt: {
|
||||||
|
...(startDate && { gte: new Date(startDate) }),
|
||||||
|
...(endDate && { lte: new Date(endDate) }),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
];
|
||||||
|
}
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.article.findMany({
|
||||||
|
where,
|
||||||
|
include: { source: true },
|
||||||
|
orderBy: [{ publishedAt: 'desc' }, { collectedAt: 'desc' }],
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.article.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个资讯
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const article = await prisma.article.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
include: { source: true },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!article) {
|
||||||
|
throw new NotFoundError('资讯不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, article);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除资讯
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.article.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('资讯不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.article.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, '资讯删除成功');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function channelRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取推送渠道列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20, type } = request.query as any;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (type) where.type = type;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.channel.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.channel.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个推送渠道
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const channel = await prisma.channel.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
include: {
|
||||||
|
topicChannels: { include: { topic: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!channel) {
|
||||||
|
throw new NotFoundError('推送渠道不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, channel);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建推送渠道
|
||||||
|
app.post('/', async (request, reply) => {
|
||||||
|
const { name, type, config, enabled } = request.body as any;
|
||||||
|
|
||||||
|
if (!name || !type || !config) {
|
||||||
|
throw new BadRequestError('缺少必填字段');
|
||||||
|
}
|
||||||
|
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: { name, type, config, enabled: enabled ?? true },
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, channel, '推送渠道创建成功', 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新推送渠道
|
||||||
|
app.put('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const { name, type, config, enabled } = request.body as any;
|
||||||
|
|
||||||
|
const existing = await prisma.channel.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('推送渠道不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建更新数据对象,只包含提供的字段
|
||||||
|
const updateData: any = {};
|
||||||
|
if (name !== undefined) updateData.name = name;
|
||||||
|
if (type !== undefined) updateData.type = type;
|
||||||
|
if (config !== undefined) updateData.config = config;
|
||||||
|
if (enabled !== undefined) updateData.enabled = enabled;
|
||||||
|
|
||||||
|
const channel = await prisma.channel.update({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, channel, '推送渠道更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除推送渠道
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.channel.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('推送渠道不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.channel.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, '推送渠道删除成功');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
|
||||||
|
export async function collectionLogRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取采集日志列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20, sourceId, status } = request.query as any;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (sourceId) where.sourceId = parseInt(sourceId);
|
||||||
|
if (status) where.status = status;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.collectionLog.findMany({
|
||||||
|
where,
|
||||||
|
include: { source: true },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.collectionLog.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取数据源统计
|
||||||
|
app.get('/stats', async (request, reply) => {
|
||||||
|
const sources = await prisma.source.findMany({
|
||||||
|
include: {
|
||||||
|
collectionLogs: {
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: 1,
|
||||||
|
},
|
||||||
|
_count: {
|
||||||
|
select: { articles: true, collectionLogs: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const stats = sources.map((source) => ({
|
||||||
|
id: source.id,
|
||||||
|
name: source.name,
|
||||||
|
type: source.type,
|
||||||
|
enabled: source.enabled,
|
||||||
|
lastCollectedAt: source.lastCollectedAt,
|
||||||
|
lastLog: source.collectionLogs[0] || null,
|
||||||
|
totalArticles: source._count.articles,
|
||||||
|
totalCollections: source._count.collectionLogs,
|
||||||
|
}));
|
||||||
|
|
||||||
|
successResponse(reply, stats);
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
|
||||||
|
export async function healthRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 基础健康检查
|
||||||
|
app.get('/health', async (request, reply) => {
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
data: {
|
||||||
|
status: 'ok',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
version: '1.0.0',
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
// 详细健康检查(包括数据库)
|
||||||
|
app.get('/health/detailed', async (request, reply) => {
|
||||||
|
const checks: Record<string, string> = {
|
||||||
|
server: 'ok',
|
||||||
|
};
|
||||||
|
|
||||||
|
// 检查数据库连接
|
||||||
|
try {
|
||||||
|
await prisma.$queryRaw`SELECT 1`;
|
||||||
|
checks.database = 'ok';
|
||||||
|
} catch (error) {
|
||||||
|
checks.database = 'error';
|
||||||
|
}
|
||||||
|
|
||||||
|
const allOk = Object.values(checks).every((v) => v === 'ok');
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: allOk,
|
||||||
|
data: {
|
||||||
|
status: allOk ? 'ok' : 'degraded',
|
||||||
|
timestamp: new Date().toISOString(),
|
||||||
|
version: '1.0.0',
|
||||||
|
checks,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function llmConfigRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取 LLM 配置列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20 } = request.query as any;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.llmConfig.findMany({
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.llmConfig.count(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个 LLM 配置
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const config = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!config) {
|
||||||
|
throw new NotFoundError('LLM 配置不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, config);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建 LLM 配置
|
||||||
|
app.post('/', async (request, reply) => {
|
||||||
|
const { name, baseUrl, model, apiKey, enabled } = request.body as any;
|
||||||
|
|
||||||
|
if (!name || !baseUrl || !model || !apiKey) {
|
||||||
|
throw new BadRequestError('缺少必填字段');
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = await prisma.llmConfig.create({
|
||||||
|
data: { name, baseUrl, model, apiKey, enabled: enabled ?? true },
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, config, 'LLM 配置创建成功', 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新 LLM 配置
|
||||||
|
app.put('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const { name, baseUrl, model, apiKey, enabled } = request.body as any;
|
||||||
|
|
||||||
|
const existing = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('LLM 配置不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建更新数据对象,只包含提供的字段
|
||||||
|
const updateData: any = {};
|
||||||
|
if (name !== undefined) updateData.name = name;
|
||||||
|
if (baseUrl !== undefined) updateData.baseUrl = baseUrl;
|
||||||
|
if (model !== undefined) updateData.model = model;
|
||||||
|
if (apiKey !== undefined) updateData.apiKey = apiKey;
|
||||||
|
if (enabled !== undefined) updateData.enabled = enabled;
|
||||||
|
|
||||||
|
const config = await prisma.llmConfig.update({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, config, 'LLM 配置更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除 LLM 配置
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('LLM 配置不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.llmConfig.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, 'LLM 配置删除成功');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function reportRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取报告列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20, topicId, status } = request.query as any;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (topicId) where.topicId = parseInt(topicId);
|
||||||
|
if (status) where.status = status;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.report.findMany({
|
||||||
|
where,
|
||||||
|
include: { topic: true },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.report.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个报告
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
include: {
|
||||||
|
topic: { include: { llmConfig: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
throw new NotFoundError('报告不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, report);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除报告
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.report.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('报告不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.report.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, '报告删除成功');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function sourceRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取数据源列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20, type } = request.query as any;
|
||||||
|
|
||||||
|
const where: any = {};
|
||||||
|
if (type) where.type = type;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.source.findMany({
|
||||||
|
where,
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.source.count({ where }),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个数据源
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const source = await prisma.source.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
include: {
|
||||||
|
topicSources: { include: { topic: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!source) {
|
||||||
|
throw new NotFoundError('数据源不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, source);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建数据源
|
||||||
|
app.post('/', async (request, reply) => {
|
||||||
|
const { name, type, config, cronExpression, enabled } = request.body as any;
|
||||||
|
|
||||||
|
if (!name || !type || !config || !cronExpression) {
|
||||||
|
throw new BadRequestError('缺少必填字段');
|
||||||
|
}
|
||||||
|
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: { name, type, config, cronExpression, enabled: enabled ?? true },
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, source, '数据源创建成功', 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新数据源
|
||||||
|
app.put('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const { name, type, config, cronExpression, enabled } = request.body as any;
|
||||||
|
|
||||||
|
const existing = await prisma.source.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('数据源不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建更新数据对象,只包含提供的字段
|
||||||
|
const updateData: any = {};
|
||||||
|
if (name !== undefined) updateData.name = name;
|
||||||
|
if (type !== undefined) updateData.type = type;
|
||||||
|
if (config !== undefined) updateData.config = config;
|
||||||
|
if (cronExpression !== undefined) updateData.cronExpression = cronExpression;
|
||||||
|
if (enabled !== undefined) updateData.enabled = enabled;
|
||||||
|
|
||||||
|
const source = await prisma.source.update({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, source, '数据源更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除数据源
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.source.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('数据源不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.source.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, '数据源删除成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 手动触发采集
|
||||||
|
app.post('/:id/collect', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const { CollectorService } = await import('../../services/collector.service');
|
||||||
|
|
||||||
|
const source = await prisma.source.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!source) {
|
||||||
|
throw new NotFoundError('数据源不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const collectorService = new CollectorService();
|
||||||
|
collectorService.collectSource(source.id).catch((error) => {
|
||||||
|
console.error('采集失败:', error);
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, null, '采集任务已触发');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import prisma from '../../config/database';
|
||||||
|
import { successResponse, paginatedResponse } from '../../utils/response';
|
||||||
|
import { NotFoundError, BadRequestError } from '../../utils/errors';
|
||||||
|
|
||||||
|
export async function topicRoutes(app: FastifyInstance): Promise<void> {
|
||||||
|
// 获取主题列表
|
||||||
|
app.get('/', async (request, reply) => {
|
||||||
|
const { page = 1, limit = 20 } = request.query as any;
|
||||||
|
|
||||||
|
const [items, total] = await Promise.all([
|
||||||
|
prisma.topic.findMany({
|
||||||
|
include: {
|
||||||
|
llmConfig: true,
|
||||||
|
topicSources: { include: { source: true } },
|
||||||
|
topicChannels: { include: { channel: true } },
|
||||||
|
},
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
skip: (Number(page) - 1) * Number(limit),
|
||||||
|
take: Number(limit),
|
||||||
|
}),
|
||||||
|
prisma.topic.count(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
paginatedResponse(reply, items, total, Number(page), Number(limit));
|
||||||
|
});
|
||||||
|
|
||||||
|
// 获取单个主题
|
||||||
|
app.get('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
include: {
|
||||||
|
llmConfig: true,
|
||||||
|
topicSources: { include: { source: true } },
|
||||||
|
topicChannels: { include: { channel: true } },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new NotFoundError('主题不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, topic);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建主题
|
||||||
|
app.post('/', async (request, reply) => {
|
||||||
|
const {
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
processMode,
|
||||||
|
llmConfigId,
|
||||||
|
scheduleConfig,
|
||||||
|
sourceIds,
|
||||||
|
channelIds,
|
||||||
|
enabled,
|
||||||
|
} = request.body as any;
|
||||||
|
|
||||||
|
if (!name || !processMode || !scheduleConfig) {
|
||||||
|
throw new BadRequestError('缺少必填字段');
|
||||||
|
}
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
processMode,
|
||||||
|
llmConfigId,
|
||||||
|
scheduleConfig,
|
||||||
|
enabled: enabled ?? true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联数据源
|
||||||
|
if (sourceIds?.length > 0) {
|
||||||
|
await prisma.topicSource.createMany({
|
||||||
|
data: sourceIds.map((sourceId: number) => ({
|
||||||
|
topicId: topic.id,
|
||||||
|
sourceId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 关联推送渠道
|
||||||
|
if (channelIds?.length > 0) {
|
||||||
|
await prisma.topicChannel.createMany({
|
||||||
|
data: channelIds.map((channelId: number) => ({
|
||||||
|
topicId: topic.id,
|
||||||
|
channelId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, topic, '主题创建成功', 201);
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新主题
|
||||||
|
app.put('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const {
|
||||||
|
name,
|
||||||
|
description,
|
||||||
|
processMode,
|
||||||
|
llmConfigId,
|
||||||
|
scheduleConfig,
|
||||||
|
sourceIds,
|
||||||
|
channelIds,
|
||||||
|
enabled,
|
||||||
|
} = request.body as any;
|
||||||
|
|
||||||
|
const existing = await prisma.topic.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('主题不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建更新数据对象,只包含提供的字段
|
||||||
|
const updateData: any = {};
|
||||||
|
if (name !== undefined) updateData.name = name;
|
||||||
|
if (description !== undefined) updateData.description = description;
|
||||||
|
if (processMode !== undefined) updateData.processMode = processMode;
|
||||||
|
if (llmConfigId !== undefined) updateData.llmConfigId = llmConfigId;
|
||||||
|
if (scheduleConfig !== undefined) updateData.scheduleConfig = scheduleConfig;
|
||||||
|
if (enabled !== undefined) updateData.enabled = enabled;
|
||||||
|
|
||||||
|
const topic = await prisma.topic.update({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
data: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新数据源关联
|
||||||
|
if (sourceIds !== undefined) {
|
||||||
|
await prisma.topicSource.deleteMany({ where: { topicId: topic.id } });
|
||||||
|
if (sourceIds.length > 0) {
|
||||||
|
await prisma.topicSource.createMany({
|
||||||
|
data: sourceIds.map((sourceId: number) => ({
|
||||||
|
topicId: topic.id,
|
||||||
|
sourceId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新推送渠道关联
|
||||||
|
if (channelIds !== undefined) {
|
||||||
|
await prisma.topicChannel.deleteMany({ where: { topicId: topic.id } });
|
||||||
|
if (channelIds.length > 0) {
|
||||||
|
await prisma.topicChannel.createMany({
|
||||||
|
data: channelIds.map((channelId: number) => ({
|
||||||
|
topicId: topic.id,
|
||||||
|
channelId,
|
||||||
|
})),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
successResponse(reply, topic, '主题更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 删除主题
|
||||||
|
app.delete('/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
const existing = await prisma.topic.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!existing) {
|
||||||
|
throw new NotFoundError('主题不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
await prisma.topic.delete({ where: { id: parseInt(id) } });
|
||||||
|
|
||||||
|
successResponse(reply, null, '主题删除成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
// 手动生成报告
|
||||||
|
app.post('/:id/generate-report', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
const { ReportService } = await import('../../services/report.service');
|
||||||
|
const { DistributorService } = await import('../../services/distributor.service');
|
||||||
|
|
||||||
|
const topic = await prisma.topic.findUnique({
|
||||||
|
where: { id: parseInt(id) },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!topic) {
|
||||||
|
throw new NotFoundError('主题不存在');
|
||||||
|
}
|
||||||
|
|
||||||
|
const reportService = new ReportService();
|
||||||
|
const distributorService = new DistributorService();
|
||||||
|
|
||||||
|
reportService.generateReportForTopic(topic.id).then(async (reportId) => {
|
||||||
|
await distributorService.distributeReportToAllChannels(reportId);
|
||||||
|
}).catch((error) => {
|
||||||
|
console.error('报告生成失败:', error);
|
||||||
|
});
|
||||||
|
|
||||||
|
successResponse(reply, null, '报告生成任务已触发');
|
||||||
|
});
|
||||||
|
}
|
||||||
@@ -0,0 +1,387 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('资讯 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/articles', () => {
|
||||||
|
it('应返回资讯列表', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '文章 1',
|
||||||
|
url: 'https://example.com/1',
|
||||||
|
content: '内容 1',
|
||||||
|
publishedAt: new Date('2024-01-01'),
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '文章 2',
|
||||||
|
url: 'https://example.com/2',
|
||||||
|
content: '内容 2',
|
||||||
|
publishedAt: new Date('2024-01-02'),
|
||||||
|
collectedAt: new Date('2024-01-02T00:00:00Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/articles',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
expect(body.data[0].source).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按数据源筛选', async () => {
|
||||||
|
const source1 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source2 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 2',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss2' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source1.id,
|
||||||
|
title: '来自源 1',
|
||||||
|
url: 'https://example.com/1',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source2.id,
|
||||||
|
title: '来自源 2',
|
||||||
|
url: 'https://example.com/2',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/articles?sourceId=${source1.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].sourceId).toBe(source1.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按主题筛选(返回主题关联的所有数据源的文章)', async () => {
|
||||||
|
const source1 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source2 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 2',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss2' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source3 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 3',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss3' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 关联源 1 和源 2 到主题
|
||||||
|
await prisma.topicSource.createMany({
|
||||||
|
data: [
|
||||||
|
{ topicId: topic.id, sourceId: source1.id },
|
||||||
|
{ topicId: topic.id, sourceId: source2.id },
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 创建文章
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source1.id,
|
||||||
|
title: '文章 1',
|
||||||
|
url: 'https://example.com/1',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source2.id,
|
||||||
|
title: '文章 2',
|
||||||
|
url: 'https://example.com/2',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source3.id,
|
||||||
|
title: '文章 3',
|
||||||
|
url: 'https://example.com/3',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/articles?topicId=${topic.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
// 只返回源 1 和源 2 的文章
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
const sourceIds = body.data.map((item: any) => item.sourceId);
|
||||||
|
expect(sourceIds).toContain(source1.id);
|
||||||
|
expect(sourceIds).toContain(source2.id);
|
||||||
|
expect(sourceIds).not.toContain(source3.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按日期范围筛选', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '旧文章',
|
||||||
|
url: 'https://example.com/old',
|
||||||
|
content: '内容',
|
||||||
|
publishedAt: new Date('2024-01-01'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '新文章',
|
||||||
|
url: 'https://example.com/new',
|
||||||
|
content: '内容',
|
||||||
|
publishedAt: new Date('2024-01-15'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/articles?startDate=2024-01-10&endDate=2024-01-20',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].title).toBe('新文章');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: `文章 ${i + 1}`,
|
||||||
|
url: `https://example.com/${i}`,
|
||||||
|
content: '内容',
|
||||||
|
}));
|
||||||
|
await prisma.article.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/articles?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/articles/:id', () => {
|
||||||
|
it('应返回单篇资讯', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const article = await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '测试文章',
|
||||||
|
url: 'https://example.com/test',
|
||||||
|
content: '这是文章内容',
|
||||||
|
summary: '摘要',
|
||||||
|
publishedAt: new Date('2024-01-01'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/articles/${article.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(article.id);
|
||||||
|
expect(body.data.title).toBe('测试文章');
|
||||||
|
expect(body.data.source).toBeDefined();
|
||||||
|
expect(body.data.source.name).toBe('测试源');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('资讯不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/articles/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('资讯不存在');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/articles/:id', () => {
|
||||||
|
it('应成功删除资讯', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const article = await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
title: '待删除文章',
|
||||||
|
url: 'https://example.com/delete',
|
||||||
|
content: '内容',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/articles/${article.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('资讯删除成功');
|
||||||
|
|
||||||
|
const deleted = await prisma.article.findUnique({
|
||||||
|
where: { id: article.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的资讯时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/articles/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,341 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('推送渠道 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/channels', () => {
|
||||||
|
it('应成功创建邮件类型的推送渠道', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '邮件通知',
|
||||||
|
type: 'email',
|
||||||
|
config: {
|
||||||
|
to: 'test@example.com',
|
||||||
|
subject: '资讯周报',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.message).toBe('推送渠道创建成功');
|
||||||
|
expect(body.data.name).toBe(payload.name);
|
||||||
|
expect(body.data.type).toBe('email');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建 Slack 类型的推送渠道', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: 'Slack 通知',
|
||||||
|
type: 'slack',
|
||||||
|
config: {
|
||||||
|
webhookUrl: 'https://hooks.slack.com/services/xxx',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.type).toBe('slack');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建钉钉类型的推送渠道', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '钉钉通知',
|
||||||
|
type: 'dingtalk',
|
||||||
|
config: {
|
||||||
|
webhookUrl: 'https://oapi.dingtalk.com/robot/send',
|
||||||
|
secret: 'SEC123',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.type).toBe('dingtalk');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建企业微信类型的推送渠道', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '企业微信通知',
|
||||||
|
type: 'wechat',
|
||||||
|
config: {
|
||||||
|
webhookUrl: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.type).toBe('wechat');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('缺少必填字段时应返回 400 错误', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '不完整渠道',
|
||||||
|
type: 'email',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('缺少必填字段');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enabled 默认值应为 true', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '测试渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.enabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/channels', () => {
|
||||||
|
it('应返回推送渠道列表', async () => {
|
||||||
|
await prisma.channel.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
name: '邮件渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Slack 渠道',
|
||||||
|
type: 'slack',
|
||||||
|
config: { webhookUrl: 'https://hooks.slack.com/xxx' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/channels',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按类型筛选', async () => {
|
||||||
|
await prisma.channel.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
name: '邮件渠道 1',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test1@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'Slack 渠道 1',
|
||||||
|
type: 'slack',
|
||||||
|
config: { webhookUrl: 'https://hooks.slack.com/xxx' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/channels?type=email',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].type).toBe('email');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/channels/:id', () => {
|
||||||
|
it('应返回单个推送渠道及其关联的主题', async () => {
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '测试渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '测试主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * *' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.topicChannel.create({
|
||||||
|
data: {
|
||||||
|
topicId: topic.id,
|
||||||
|
channelId: channel.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/channels/${channel.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(channel.id);
|
||||||
|
expect(body.data.topicChannels).toHaveLength(1);
|
||||||
|
expect(body.data.topicChannels[0].topic.name).toBe('测试主题');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('推送渠道不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/channels/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('推送渠道不存在');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PUT /api/v1/channels/:id', () => {
|
||||||
|
it('应成功更新推送渠道', async () => {
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '原始渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'old@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
name: '更新后渠道',
|
||||||
|
config: { to: 'new@example.com' },
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/api/v1/channels/${channel.id}`,
|
||||||
|
payload: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.name).toBe('更新后渠道');
|
||||||
|
expect(body.data.config.to).toBe('new@example.com');
|
||||||
|
expect(body.data.enabled).toBe(false);
|
||||||
|
expect(body.message).toBe('推送渠道更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('更新不存在的推送渠道时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: '/api/v1/channels/99999',
|
||||||
|
payload: {
|
||||||
|
name: '更新',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/channels/:id', () => {
|
||||||
|
it('应成功删除推送渠道', async () => {
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '待删除渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/channels/${channel.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('推送渠道删除成功');
|
||||||
|
|
||||||
|
const deleted = await prisma.channel.findUnique({
|
||||||
|
where: { id: channel.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的推送渠道时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/channels/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,363 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('采集日志 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/collection-logs', () => {
|
||||||
|
it('应返回采集日志列表', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.collectionLog.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 5,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: '连接超时',
|
||||||
|
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
expect(body.data[0].source).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按数据源筛选', async () => {
|
||||||
|
const source1 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source2 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 2',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss2' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source1.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 10,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source2.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 5,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/collection-logs?sourceId=${source1.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].sourceId).toBe(source1.id);
|
||||||
|
expect(body.data[0].articlesCount).toBe(10);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按状态筛选', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.collectionLog.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 10,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: '错误',
|
||||||
|
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'running',
|
||||||
|
startedAt: new Date('2024-01-03T00:00:00Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs?status=success',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].status).toBe('success');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = Array.from({ length: 25 }, () => ({
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'success' as const,
|
||||||
|
articlesCount: 5,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
}));
|
||||||
|
await prisma.collectionLog.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应按创建时间倒序排列', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const log1 = await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 5,
|
||||||
|
startedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-01T00:01:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 等待确保时间差
|
||||||
|
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||||
|
|
||||||
|
const log2 = await prisma.collectionLog.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 3,
|
||||||
|
startedAt: new Date('2024-01-02T00:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-02T00:01:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data[0].id).toBe(log2.id);
|
||||||
|
expect(body.data[1].id).toBe(log1.id);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/collection-logs/stats', () => {
|
||||||
|
it('应返回所有数据源的统计信息', async () => {
|
||||||
|
const source1 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: 'RSS 源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
lastCollectedAt: new Date('2024-01-15T10:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source2 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: 'API 源 1',
|
||||||
|
type: 'api',
|
||||||
|
config: { url: 'https://api.example.com' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 为源 1 创建文章
|
||||||
|
await prisma.article.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
sourceId: source1.id,
|
||||||
|
title: '文章 1',
|
||||||
|
url: 'https://example.com/1',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source1.id,
|
||||||
|
title: '文章 2',
|
||||||
|
url: 'https://example.com/2',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source1.id,
|
||||||
|
title: '文章 3',
|
||||||
|
url: 'https://example.com/3',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 为源 1 创建采集日志
|
||||||
|
await prisma.collectionLog.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
sourceId: source1.id,
|
||||||
|
status: 'success',
|
||||||
|
articlesCount: 3,
|
||||||
|
startedAt: new Date('2024-01-15T10:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-15T10:01:00Z'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
sourceId: source1.id,
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: '超时',
|
||||||
|
startedAt: new Date('2024-01-14T10:00:00Z'),
|
||||||
|
finishedAt: new Date('2024-01-14T10:01:00Z'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
// 为源 2 创建文章
|
||||||
|
await prisma.article.create({
|
||||||
|
data: {
|
||||||
|
sourceId: source2.id,
|
||||||
|
title: '文章 4',
|
||||||
|
url: 'https://example.com/4',
|
||||||
|
content: '内容',
|
||||||
|
collectedAt: new Date('2024-01-01T00:00:00Z'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs/stats',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
|
||||||
|
const stats1 = body.data.find((s: any) => s.id === source1.id);
|
||||||
|
expect(stats1).toBeDefined();
|
||||||
|
expect(stats1.name).toBe('RSS 源 1');
|
||||||
|
expect(stats1.type).toBe('rss');
|
||||||
|
expect(stats1.enabled).toBe(true);
|
||||||
|
expect(stats1.totalArticles).toBe(3);
|
||||||
|
expect(stats1.totalCollections).toBe(2);
|
||||||
|
expect(stats1.lastCollectedAt).toBeDefined();
|
||||||
|
expect(stats1.lastLog).toBeDefined();
|
||||||
|
expect(stats1.lastLog.status).toBe('success');
|
||||||
|
|
||||||
|
const stats2 = body.data.find((s: any) => s.id === source2.id);
|
||||||
|
expect(stats2).toBeDefined();
|
||||||
|
expect(stats2.name).toBe('API 源 1');
|
||||||
|
expect(stats2.enabled).toBe(false);
|
||||||
|
expect(stats2.totalArticles).toBe(1);
|
||||||
|
expect(stats2.totalCollections).toBe(0);
|
||||||
|
expect(stats2.lastCollectedAt).toBeNull();
|
||||||
|
expect(stats2.lastLog).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应返回空数组当没有数据源时', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/collection-logs/stats',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toEqual([]);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
import { beforeAll, afterAll, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('健康检查 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/health', () => {
|
||||||
|
it('应返回健康状态', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/health',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.data.status).toBe('ok');
|
||||||
|
expect(body.data.timestamp).toBeDefined();
|
||||||
|
expect(body.data.version).toBe('1.0.0');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/health/detailed', () => {
|
||||||
|
it('应返回详细的健康状态包括数据库检查', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/health/detailed',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.data.status).toBe('ok');
|
||||||
|
expect(body.data.checks).toBeDefined();
|
||||||
|
expect(body.data.checks.server).toBe('ok');
|
||||||
|
expect(body.data.checks.database).toBe('ok');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
import Fastify from 'fastify';
|
||||||
|
import cors from '@fastify/cors';
|
||||||
|
import { healthRoutes } from '../../src/web/routes/health';
|
||||||
|
import { llmConfigRoutes } from '../../src/web/routes/llm-configs';
|
||||||
|
import { sourceRoutes } from '../../src/web/routes/sources';
|
||||||
|
import { channelRoutes } from '../../src/web/routes/channels';
|
||||||
|
import { topicRoutes } from '../../src/web/routes/topics';
|
||||||
|
import { reportRoutes } from '../../src/web/routes/reports';
|
||||||
|
import { articleRoutes } from '../../src/web/routes/articles';
|
||||||
|
import { collectionLogRoutes } from '../../src/web/routes/collection-logs';
|
||||||
|
import { AppError } from '../../src/utils/errors';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建用于测试的 Fastify 应用实例
|
||||||
|
*/
|
||||||
|
export async function createTestApp() {
|
||||||
|
const app = Fastify({
|
||||||
|
logger: false,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 注册 CORS
|
||||||
|
await app.register(cors, {
|
||||||
|
origin: true,
|
||||||
|
credentials: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 简单的错误处理器(复制自 error-handler.ts)
|
||||||
|
app.setErrorHandler(async (error, request, reply) => {
|
||||||
|
if (error instanceof AppError) {
|
||||||
|
return reply.status(error.statusCode).send({
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
...(error instanceof Error && process.env.NODE_ENV === 'development' && {
|
||||||
|
stack: error.stack,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理验证错误
|
||||||
|
if (error.validation) {
|
||||||
|
return reply.status(400).send({
|
||||||
|
success: false,
|
||||||
|
error: '请求参数验证失败',
|
||||||
|
details: error.validation,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// 未知错误
|
||||||
|
reply.status(500).send({
|
||||||
|
success: false,
|
||||||
|
error: '服务器内部错误',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
// 注册路由
|
||||||
|
await app.register(healthRoutes, { prefix: '/api/v1' });
|
||||||
|
await app.register(llmConfigRoutes, { prefix: '/api/v1/llm-configs' });
|
||||||
|
await app.register(sourceRoutes, { prefix: '/api/v1/sources' });
|
||||||
|
await app.register(channelRoutes, { prefix: '/api/v1/channels' });
|
||||||
|
await app.register(topicRoutes, { prefix: '/api/v1/topics' });
|
||||||
|
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' });
|
||||||
|
|
||||||
|
return app;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 等待一段时间(用于异步操作)
|
||||||
|
*/
|
||||||
|
export function wait(ms: number): Promise<void> {
|
||||||
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||||
|
}
|
||||||
@@ -0,0 +1,267 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('LLM 配置 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/llm-configs', () => {
|
||||||
|
it('应成功创建 LLM 配置', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: 'OpenAI 测试配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test123',
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/llm-configs',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.message).toBe('LLM 配置创建成功');
|
||||||
|
expect(body.data.name).toBe(payload.name);
|
||||||
|
expect(body.data.baseUrl).toBe(payload.baseUrl);
|
||||||
|
expect(body.data.model).toBe(payload.model);
|
||||||
|
expect(body.data.apiKey).toBe(payload.apiKey);
|
||||||
|
expect(body.data.enabled).toBe(true);
|
||||||
|
expect(body.data.id).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('缺少必填字段时应返回 400 错误', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '不完整配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/llm-configs',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('缺少必填字段');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enabled 默认值应为 true', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: 'OpenAI 测试配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test123',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/llm-configs',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.enabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/llm-configs', () => {
|
||||||
|
it('应返回配置列表', async () => {
|
||||||
|
// 创建测试数据
|
||||||
|
await prisma.llmConfig.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
name: '配置 1',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-key1',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '配置 2',
|
||||||
|
baseUrl: 'https://api.anthropic.com/v1',
|
||||||
|
model: 'claude-3',
|
||||||
|
apiKey: 'sk-key2',
|
||||||
|
enabled: false,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/llm-configs',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
expect(body.pagination.page).toBe(1);
|
||||||
|
expect(body.pagination.limit).toBe(20);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
// 创建 25 条数据
|
||||||
|
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
name: `配置 ${i + 1}`,
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: `sk-key${i}`,
|
||||||
|
enabled: true,
|
||||||
|
}));
|
||||||
|
await prisma.llmConfig.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/llm-configs?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/llm-configs/:id', () => {
|
||||||
|
it('应返回单个配置', async () => {
|
||||||
|
const config = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: '测试配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/llm-configs/${config.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(config.id);
|
||||||
|
expect(body.data.name).toBe('测试配置');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('配置不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/llm-configs/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('LLM 配置不存在');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PUT /api/v1/llm-configs/:id', () => {
|
||||||
|
it('应成功更新配置', async () => {
|
||||||
|
const config = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: '原始配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
name: '更新后配置',
|
||||||
|
model: 'gpt-4-turbo',
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/api/v1/llm-configs/${config.id}`,
|
||||||
|
payload: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.name).toBe('更新后配置');
|
||||||
|
expect(body.data.model).toBe('gpt-4-turbo');
|
||||||
|
expect(body.data.enabled).toBe(false);
|
||||||
|
expect(body.message).toBe('LLM 配置更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('更新不存在的配置时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: '/api/v1/llm-configs/99999',
|
||||||
|
payload: {
|
||||||
|
name: '更新',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/llm-configs/:id', () => {
|
||||||
|
it('应成功删除配置', async () => {
|
||||||
|
const config = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: '待删除配置',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/llm-configs/${config.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('LLM 配置删除成功');
|
||||||
|
|
||||||
|
// 验证已被删除
|
||||||
|
const deleted = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: config.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的配置时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/llm-configs/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,307 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('报告 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/reports', () => {
|
||||||
|
it('应返回报告列表', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.report.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
title: '报告 1',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '报告内容 1',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '报告 2',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'pending',
|
||||||
|
content: '',
|
||||||
|
periodStart: new Date('2024-01-08'),
|
||||||
|
periodEnd: new Date('2024-01-14'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/reports',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
expect(body.data[0].topic).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按主题 ID 筛选', async () => {
|
||||||
|
const topic1 = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '主题 1',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic2 = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '主题 2',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
title: '报告 1',
|
||||||
|
topicId: topic1.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '报告 1',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
title: '报告 2',
|
||||||
|
topicId: topic2.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '报告 2',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/reports?topicId=${topic1.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].topicId).toBe(topic1.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按状态筛选', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.report.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
title: '完成报告',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '完成',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '待处理报告',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'pending',
|
||||||
|
content: '',
|
||||||
|
periodStart: new Date('2024-01-08'),
|
||||||
|
periodEnd: new Date('2024-01-14'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '失败报告',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'failed',
|
||||||
|
errorMessage: '失败',
|
||||||
|
content: '',
|
||||||
|
periodStart: new Date('2024-01-15'),
|
||||||
|
periodEnd: new Date('2024-01-21'),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/reports?status=completed',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].status).toBe('completed');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
title: `报告 ${i + 1}`,
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'completed' as const,
|
||||||
|
content: '报告内容',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
}));
|
||||||
|
await prisma.report.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/reports?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/reports/:id', () => {
|
||||||
|
it('应返回单个报告及关联的主题数据', async () => {
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: 'OpenAI',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
llmConfigId: llmConfig.id,
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const report = await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
title: 'AI 资讯周报',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '这是 AI 资讯周报',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/reports/${report.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(report.id);
|
||||||
|
expect(body.data.content).toBe('这是 AI 资讯周报');
|
||||||
|
expect(body.data.topic).toBeDefined();
|
||||||
|
expect(body.data.topic.llmConfig).toBeDefined();
|
||||||
|
expect(body.data.topic.llmConfig.name).toBe('OpenAI');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('报告不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/reports/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('报告不存在');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/reports/:id', () => {
|
||||||
|
it('应成功删除报告', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const report = await prisma.report.create({
|
||||||
|
data: {
|
||||||
|
title: '待删除报告',
|
||||||
|
topicId: topic.id,
|
||||||
|
status: 'completed',
|
||||||
|
content: '报告内容',
|
||||||
|
periodStart: new Date('2024-01-01'),
|
||||||
|
periodEnd: new Date('2024-01-07'),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/reports/${report.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('报告删除成功');
|
||||||
|
|
||||||
|
const deleted = await prisma.report.findUnique({
|
||||||
|
where: { id: report.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的报告时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/reports/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import { PrismaClient } from '@prisma/client';
|
||||||
|
|
||||||
|
// 使用单独的测试数据库 URL(如果配置了)或默认数据库
|
||||||
|
const testDatabaseUrl = process.env.TEST_DATABASE_URL || process.env.DATABASE_URL;
|
||||||
|
|
||||||
|
const prisma = new PrismaClient({
|
||||||
|
datasources: {
|
||||||
|
db: {
|
||||||
|
url: testDatabaseUrl,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export async function setup() {
|
||||||
|
await prisma.$connect();
|
||||||
|
console.log('测试数据库已连接');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function teardown() {
|
||||||
|
await prisma.$disconnect();
|
||||||
|
console.log('测试数据库已断开');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 清理数据库(按依赖关系顺序删除表以避免外键约束)
|
||||||
|
export async function cleanupDatabase() {
|
||||||
|
// 按依赖关系顺序删除(从最底层的依赖开始)
|
||||||
|
// 删除所有关联和日志表
|
||||||
|
await prisma.pushLog.deleteMany({});
|
||||||
|
await prisma.conversation.deleteMany({});
|
||||||
|
await prisma.article.deleteMany({});
|
||||||
|
await prisma.report.deleteMany({});
|
||||||
|
await prisma.collectionLog.deleteMany({});
|
||||||
|
|
||||||
|
// 删除关联表(在删除主表之前)
|
||||||
|
await prisma.topicSource.deleteMany({});
|
||||||
|
await prisma.topicChannel.deleteMany({});
|
||||||
|
|
||||||
|
// 删除主表
|
||||||
|
await prisma.topic.deleteMany({});
|
||||||
|
await prisma.channel.deleteMany({});
|
||||||
|
await prisma.source.deleteMany({});
|
||||||
|
await prisma.llmConfig.deleteMany({});
|
||||||
|
}
|
||||||
|
|
||||||
|
export { prisma };
|
||||||
@@ -0,0 +1,385 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('数据源 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/sources', () => {
|
||||||
|
it('应成功创建 RSS 类型的数据源', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '技术博客 RSS',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 */6 * * *',
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.message).toBe('数据源创建成功');
|
||||||
|
expect(body.data.name).toBe(payload.name);
|
||||||
|
expect(body.data.type).toBe('rss');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建 API 类型的数据源', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '新闻 API',
|
||||||
|
type: 'api',
|
||||||
|
config: {
|
||||||
|
url: 'https://api.example.com/news',
|
||||||
|
headers: { Authorization: 'Bearer token' },
|
||||||
|
},
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.type).toBe('api');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建 Playwright 类型的数据源', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '爬虫数据源',
|
||||||
|
type: 'playwright',
|
||||||
|
config: {
|
||||||
|
url: 'https://example.com',
|
||||||
|
selectors: {
|
||||||
|
title: '.title',
|
||||||
|
content: '.content',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
cronExpression: '0 0 * * *',
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.type).toBe('playwright');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('缺少必填字段时应返回 400 错误', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '不完整数据源',
|
||||||
|
type: 'rss',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('缺少必填字段');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('enabled 默认值应为 true', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '测试数据源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.enabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/sources', () => {
|
||||||
|
it('应返回数据源列表', async () => {
|
||||||
|
await prisma.source.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
name: 'RSS 源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'API 源 1',
|
||||||
|
type: 'api',
|
||||||
|
config: { url: 'https://api.example.com' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/sources',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(2);
|
||||||
|
expect(body.pagination.total).toBe(2);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持按类型筛选', async () => {
|
||||||
|
await prisma.source.createMany({
|
||||||
|
data: [
|
||||||
|
{
|
||||||
|
name: 'RSS 源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'API 源 1',
|
||||||
|
type: 'api',
|
||||||
|
config: { url: 'https://api.example.com' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/sources?type=rss',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].type).toBe('rss');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
name: `源 ${i + 1}`,
|
||||||
|
type: 'rss' as const,
|
||||||
|
config: { url: `https://example.com/rss${i}` },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
}));
|
||||||
|
await prisma.source.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/sources?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/sources/:id', () => {
|
||||||
|
it('应返回单个数据源及其关联的主题', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '测试主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * *' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.topicSource.create({
|
||||||
|
data: {
|
||||||
|
topicId: topic.id,
|
||||||
|
sourceId: source.id,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/sources/${source.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(source.id);
|
||||||
|
expect(body.data.topicSources).toHaveLength(1);
|
||||||
|
expect(body.data.topicSources[0].topic.name).toBe('测试主题');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('数据源不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/sources/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('数据源不存在');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PUT /api/v1/sources/:id', () => {
|
||||||
|
it('应成功更新数据源', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '原始源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
name: '更新后源',
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/api/v1/sources/${source.id}`,
|
||||||
|
payload: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.name).toBe('更新后源');
|
||||||
|
expect(body.data.enabled).toBe(false);
|
||||||
|
expect(body.message).toBe('数据源更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('更新不存在的数据源时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: '/api/v1/sources/99999',
|
||||||
|
payload: {
|
||||||
|
name: '更新',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/sources/:id', () => {
|
||||||
|
it('应成功删除数据源', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '待删除源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/sources/${source.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('数据源删除成功');
|
||||||
|
|
||||||
|
const deleted = await prisma.source.findUnique({
|
||||||
|
where: { id: source.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的数据源时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/sources/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/sources/:id/collect', () => {
|
||||||
|
it('应触发采集任务', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: `/api/v1/sources/${source.id}/collect`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('采集任务已触发');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('数据源不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/sources/99999/collect',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,440 @@
|
|||||||
|
import { beforeAll, afterAll, beforeEach, describe, it, expect } from 'vitest';
|
||||||
|
import { createTestApp } from './helpers/app';
|
||||||
|
import { cleanupDatabase, prisma } from './setup';
|
||||||
|
|
||||||
|
describe('主题 API', () => {
|
||||||
|
let app: Awaited<ReturnType<typeof createTestApp>>;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
app = await createTestApp();
|
||||||
|
});
|
||||||
|
|
||||||
|
beforeEach(async () => {
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
await app.close();
|
||||||
|
await cleanupDatabase();
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/topics', () => {
|
||||||
|
it('应成功创建主题', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: 'AI 技术资讯',
|
||||||
|
description: '收集 AI 相关的技术文章',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/topics',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(true);
|
||||||
|
expect(body.message).toBe('主题创建成功');
|
||||||
|
expect(body.data.name).toBe(payload.name);
|
||||||
|
expect(body.data.processMode).toBe('summary');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应成功创建主题并关联数据源和推送渠道', async () => {
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '测试渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
name: '完整配置主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
sourceIds: [source.id],
|
||||||
|
channelIds: [channel.id],
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/topics',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
|
||||||
|
// 验证关联关系
|
||||||
|
const topicSources = await prisma.topicSource.findMany({
|
||||||
|
where: { sourceId: source.id },
|
||||||
|
});
|
||||||
|
expect(topicSources).toHaveLength(1);
|
||||||
|
|
||||||
|
const topicChannels = await prisma.topicChannel.findMany({
|
||||||
|
where: { channelId: channel.id },
|
||||||
|
});
|
||||||
|
expect(topicChannels).toHaveLength(1);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持关联 LLM 配置', async () => {
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: 'OpenAI',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const payload = {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
llmConfigId: llmConfig.id,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/topics',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(201);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.llmConfigId).toBe(llmConfig.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('缺少必填字段时应返回 400 错误', async () => {
|
||||||
|
const payload = {
|
||||||
|
name: '不完整主题',
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/topics',
|
||||||
|
payload,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(400);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.success).toBe(false);
|
||||||
|
expect(body.error).toContain('缺少必填字段');
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/topics', () => {
|
||||||
|
it('应返回主题列表及关联数据', async () => {
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: 'OpenAI',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
llmConfigId: llmConfig.id,
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/topics',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(1);
|
||||||
|
expect(body.data[0].llmConfig).toBeDefined();
|
||||||
|
expect(body.data[0].llmConfig.name).toBe('OpenAI');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应支持分页', async () => {
|
||||||
|
const data = Array.from({ length: 25 }, (_, i) => ({
|
||||||
|
name: `主题 ${i + 1}`,
|
||||||
|
processMode: 'summary' as const,
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
}));
|
||||||
|
await prisma.topic.createMany({ data });
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/topics?page=2&limit=10',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data).toHaveLength(10);
|
||||||
|
expect(body.pagination.total).toBe(25);
|
||||||
|
expect(body.pagination.page).toBe(2);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('GET /api/v1/topics/:id', () => {
|
||||||
|
it('应返回单个主题及其完整关联数据', async () => {
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: 'OpenAI',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: 'sk-test',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '测试源',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const channel = await prisma.channel.create({
|
||||||
|
data: {
|
||||||
|
name: '测试渠道',
|
||||||
|
type: 'email',
|
||||||
|
config: { to: 'test@example.com' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
description: 'AI 技术文章',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
llmConfigId: llmConfig.id,
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.topicSource.create({
|
||||||
|
data: { topicId: topic.id, sourceId: source.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
await prisma.topicChannel.create({
|
||||||
|
data: { topicId: topic.id, channelId: channel.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: `/api/v1/topics/${topic.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.id).toBe(topic.id);
|
||||||
|
expect(body.data.llmConfig).toBeDefined();
|
||||||
|
expect(body.data.topicSources).toHaveLength(1);
|
||||||
|
expect(body.data.topicSources[0].source.name).toBe('测试源');
|
||||||
|
expect(body.data.topicChannels).toHaveLength(1);
|
||||||
|
expect(body.data.topicChannels[0].channel.name).toBe('测试渠道');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('主题不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'GET',
|
||||||
|
url: '/api/v1/topics/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('PUT /api/v1/topics/:id', () => {
|
||||||
|
it('应成功更新主题', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '原始主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const updateData = {
|
||||||
|
name: '更新后主题',
|
||||||
|
description: '新描述',
|
||||||
|
enabled: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/api/v1/topics/${topic.id}`,
|
||||||
|
payload: updateData,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.data.name).toBe('更新后主题');
|
||||||
|
expect(body.data.description).toBe('新描述');
|
||||||
|
expect(body.data.enabled).toBe(false);
|
||||||
|
expect(body.message).toBe('主题更新成功');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('应更新数据源和渠道关联', async () => {
|
||||||
|
const source1 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 1',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss1' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const source2 = await prisma.source.create({
|
||||||
|
data: {
|
||||||
|
name: '源 2',
|
||||||
|
type: 'rss',
|
||||||
|
config: { url: 'https://example.com/rss2' },
|
||||||
|
cronExpression: '0 * * * *',
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '测试主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 初始关联
|
||||||
|
await prisma.topicSource.create({
|
||||||
|
data: { topicId: topic.id, sourceId: source1.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
// 更新关联
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: `/api/v1/topics/${topic.id}`,
|
||||||
|
payload: {
|
||||||
|
name: '测试主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
sourceIds: [source2.id],
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
|
||||||
|
// 验证关联已更新
|
||||||
|
const topicSources = await prisma.topicSource.findMany({
|
||||||
|
where: { topicId: topic.id },
|
||||||
|
});
|
||||||
|
expect(topicSources).toHaveLength(1);
|
||||||
|
expect(topicSources[0].sourceId).toBe(source2.id);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('更新不存在的主题时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'PUT',
|
||||||
|
url: '/api/v1/topics/99999',
|
||||||
|
payload: {
|
||||||
|
name: '更新',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('DELETE /api/v1/topics/:id', () => {
|
||||||
|
it('应成功删除主题', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: '待删除主题',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: `/api/v1/topics/${topic.id}`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('主题删除成功');
|
||||||
|
|
||||||
|
const deleted = await prisma.topic.findUnique({
|
||||||
|
where: { id: topic.id },
|
||||||
|
});
|
||||||
|
expect(deleted).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('删除不存在的主题时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'DELETE',
|
||||||
|
url: '/api/v1/topics/99999',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe('POST /api/v1/topics/:id/generate-report', () => {
|
||||||
|
it('应触发报告生成任务', async () => {
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'AI 资讯',
|
||||||
|
processMode: 'summary',
|
||||||
|
scheduleConfig: { cron: '0 0 * * 0' },
|
||||||
|
enabled: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: `/api/v1/topics/${topic.id}/generate-report`,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(200);
|
||||||
|
const body = JSON.parse(response.body);
|
||||||
|
expect(body.message).toBe('报告生成任务已触发');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('主题不存在时应返回 404', async () => {
|
||||||
|
const response = await app.inject({
|
||||||
|
method: 'POST',
|
||||||
|
url: '/api/v1/topics/99999/generate-report',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.statusCode).toBe(404);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -4,7 +4,7 @@
|
|||||||
"module": "commonjs",
|
"module": "commonjs",
|
||||||
"lib": ["ES2022"],
|
"lib": ["ES2022"],
|
||||||
"outDir": "./dist",
|
"outDir": "./dist",
|
||||||
"rootDir": "./src",
|
"rootDir": "./",
|
||||||
"strict": true,
|
"strict": true,
|
||||||
"esModuleInterop": true,
|
"esModuleInterop": true,
|
||||||
"skipLibCheck": true,
|
"skipLibCheck": true,
|
||||||
@@ -13,6 +13,6 @@
|
|||||||
"moduleResolution": "node",
|
"moduleResolution": "node",
|
||||||
"types": ["node"]
|
"types": ["node"]
|
||||||
},
|
},
|
||||||
"include": ["src/**/*"],
|
"include": ["src/**/*", "tests/**/*"],
|
||||||
"exclude": ["node_modules", "dist"]
|
"exclude": ["node_modules", "dist"]
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
import { defineConfig } from 'vitest/config';
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
environment: 'node',
|
||||||
|
testTimeout: 30000,
|
||||||
|
hookTimeout: 30000,
|
||||||
|
include: ['tests/**/*.test.ts'],
|
||||||
|
setupFiles: ['tests/setup.ts'],
|
||||||
|
// 串行执行测试以避免数据库竞争
|
||||||
|
fileParallelism: false,
|
||||||
|
maxConcurrency: 1,
|
||||||
|
alias: {
|
||||||
|
'@': new URL('./src', import.meta.url).pathname,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
resolve: {
|
||||||
|
alias: {
|
||||||
|
'@': '/src',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
# Frontend UI/UX Transformation Plan (Frontend UX 改造计划)
|
||||||
|
|
||||||
|
## 1. 现状分析 (Current State Audit)
|
||||||
|
|
||||||
|
通过对 `frontend/src` 代码库的扫描,发现以下待优化点:
|
||||||
|
|
||||||
|
### 视觉与布局
|
||||||
|
- **框架依赖过重**: 布局过度依赖 Element Plus 的 `el-container` 系统,导致样式修改灵活性差。
|
||||||
|
- **色彩体系陈旧**: 侧边栏背景色 (#304156) 等属于硬编码,缺乏对深色模式 (Dark Mode) 的原生支持。
|
||||||
|
- **空间利用率**: `AgentChat.vue` 等核心页面被大量传统的下拉选择框占据了有效交互区域。
|
||||||
|
|
||||||
|
### 交互体验 (UX)
|
||||||
|
- **中断式操作**: 配置管理(Sources, Topics)频繁使用 `el-dialog` 弹窗,操作流不连续。
|
||||||
|
- **Agent 感知弱**: 对话过程中的“工具调用”状态(Tool-calling)缺乏视觉反馈,用户难以感知 AI 正在做什么。
|
||||||
|
- **阅读疲劳**: 报告详情采用纯文本式的 Markdown 渲染,缺乏层次感和侧边快速导航。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 目标愿景 (The Vision)
|
||||||
|
|
||||||
|
建立一个 **“AI-First”** 的现代化资讯终端:
|
||||||
|
- **美学**: 极简、半透明材质(Glassmorphism)、精致的微动效。
|
||||||
|
- **效率**: 引入全局命令面板 (Cmd+K),减少点击层级。
|
||||||
|
- **沉浸**: 报告阅读与 AI 问答无缝融合,不切换页面即可深度探索。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 技术栈升级 (Tech Stack)
|
||||||
|
|
||||||
|
| 领域 | 选型 | 理由 |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| **CSS 框架** | **Tailwind CSS** | 极致的样式控制力,消除硬编码 CSS。 |
|
||||||
|
| **组件库** | **Shadcn Vue** | 现代审美,非侵入式组件,易于二次定制。 |
|
||||||
|
| **图标库** | **Lucide Vue Next** | 图标风格更轻量、一致。 |
|
||||||
|
| **状态管理** | **VueUse** | 提供大量交互式 Composable(如 `useDark`, `useScroll`)。 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 拆分任务 (Implementation Roadmap)
|
||||||
|
|
||||||
|
### Phase 1: 基础设施 (Foundation)
|
||||||
|
- [ ] **Task 1.1**: 安装依赖 (`tailwindcss`, `lucide-vue-next`, `radix-vue`)。
|
||||||
|
- [ ] **Task 1.2**: 初始化 Tailwind 配置文件,定义系统色盘(Slate/Zinc)和圆角规范。
|
||||||
|
- [ ] **Task 1.3**: 改造 `src/style.css`,建立 Dark Mode 变量基础。
|
||||||
|
|
||||||
|
### Phase 2: 布局重构 (Layout Shell)
|
||||||
|
- [ ] **Task 2.1**: 重写 `MainLayout.vue`。实现响应式悬浮侧边栏。
|
||||||
|
- [ ] **Task 2.2**: 开发 `CommandPalette.vue`。集成全局搜索与快速操作面板。
|
||||||
|
- [ ] **Task 2.3**: 优化全站 Breadcrumb 和 Header,释放更多垂直空间。
|
||||||
|
|
||||||
|
### Phase 3: AI 对话升级 (Agent UX)
|
||||||
|
- [ ] **Task 3.1**: 重构 `MessageItem.vue`。增加打字机效果、代码块一键复制及工具调用中间态展示。
|
||||||
|
- [ ] **Task 3.2**: 优化对话输入框。支持多行自适应高度和快捷键提醒。
|
||||||
|
- [ ] **Task 3.3**: 引入对话上下文预览,允许用户在对话中查看关联的报告卡片。
|
||||||
|
|
||||||
|
### Phase 4: 阅读与监控 (Content & Data)
|
||||||
|
- [ ] **Task 4.1**: 重构 `ReportDetail.vue`。增加阅读模式,支持 Markdown 侧边导航。
|
||||||
|
- [ ] **Task 4.2**: 升级仪表盘 `Dashboard.vue`。采用 Bento Grid 布局,强化关键指标的视觉重量。
|
||||||
|
- [ ] **Task 4.3**: 改造 `Monitoring.vue`。将列表改为带有实时状态脉冲动画的节点卡片。
|
||||||
|
|
||||||
|
### Phase 5: 操作流优化 (Operational Flow)
|
||||||
|
- [ ] **Task 5.1**: 将 `Topics` 和 `Sources` 的 CRUD 逻辑从弹窗改为侧滑抽屉 (Sheet),提升配置效率。
|
||||||
|
- [ ] **Task 5.2**: 实现 Cron 表达式的动态预览图,实时展示未来执行时间点。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 验收标准 (Acceptance Criteria)
|
||||||
|
|
||||||
|
1. **多端适配**: 侧边栏在移动端自动折叠,保持核心功能可用。
|
||||||
|
2. **性能**: 移除冗余 CSS 后,首屏渲染 FCP 提升 20% 以上。
|
||||||
|
3. **审美**: 符合现代 AI 工具(如 ChatGPT, Claude, Linear)的视觉基准。
|
||||||
|
4. **一致性**: 全站图标风格统一,间距遵循 4px/8px 网格系统。
|
||||||
+26
-16
@@ -5,42 +5,42 @@
|
|||||||
## 后端任务
|
## 后端任务
|
||||||
|
|
||||||
### 基础设施
|
### 基础设施
|
||||||
- [x] [任务 01:项目初始化](./01-project-setup.md)
|
- [x] [任务 01:项目初始化](./01-project-setup.md) - 已完成
|
||||||
- [x] [任务 02:数据库搭建](./02-database-setup.md) - Schema 和种子数据已创建
|
- [x] [任务 02:数据库搭建](./02-database-setup.md) - 已完成
|
||||||
- [ ] [任务 03:后端核心框架](./03-backend-core.md) - 基础模块已创建,待完善中间件和路由
|
- [x] [任务 03:后端核心框架](./03-backend-core.md) - 已完成
|
||||||
|
|
||||||
### 核心功能
|
### 核心功能
|
||||||
- [ ] [任务 04:采集器实现](./04-collectors.md)
|
- [x] [任务 04:采集器实现](./04-collectors.md) - 已完成
|
||||||
- [ ] [任务 05:内容处理](./05-processor.md)
|
- [x] [任务 05:内容处理](./05-processor.md) - 已完成
|
||||||
- [ ] [任务 06:报告生成](./06-report-generator.md)
|
- [x] [任务 06:报告生成](./06-report-generator.md) - 已完成
|
||||||
- [ ] [任务 07:分发器实现](./07-distributors.md)
|
- [x] [任务 07:分发器实现](./07-distributors.md) - 已完成
|
||||||
- [ ] [任务 08:定时任务调度](./08-scheduler.md)
|
- [x] [任务 08:定时任务调度](./08-scheduler.md) - 已完成
|
||||||
|
|
||||||
### API 开发
|
### API 开发
|
||||||
- [ ] [任务 09:Web API 实现](./09-web-api.md)
|
- [x] [任务 09:Web API 实现](./09-web-api.md) - 已完成
|
||||||
|
|
||||||
## 前端任务
|
## 前端任务
|
||||||
|
|
||||||
### 基础设施
|
### 基础设施
|
||||||
- [x] [任务 10:前端初始化](./10-frontend-setup.md) - 基础结构已创建
|
- [x] [任务 10:前端初始化](./10-frontend-setup.md) - 已完成
|
||||||
|
|
||||||
### 配置管理
|
### 配置管理
|
||||||
- [ ] [任务 11:前端配置管理](./11-frontend-config.md)
|
- [x] [任务 11:前端配置管理](./11-16-summary.md) - 已完成
|
||||||
|
|
||||||
### 报告中心
|
### 报告中心
|
||||||
- [ ] [任务 12:前端报告中心](./12-frontend-reports.md)
|
- [x] [任务 12:前端报告中心](./11-16-summary.md) - 已完成
|
||||||
|
|
||||||
### 资讯浏览
|
### 资讯浏览
|
||||||
- [ ] [任务 13:前端资讯浏览](./13-frontend-articles.md)
|
- [x] [任务 13:前端资讯浏览](./11-16-summary.md) - 已完成
|
||||||
|
|
||||||
### 采集监控
|
### 采集监控
|
||||||
- [ ] [任务 14:前端采集监控](./14-frontend-monitoring.md)
|
- [x] [任务 14:前端采集监控](./11-16-summary.md) - 已完成
|
||||||
|
|
||||||
## AI Agent
|
## AI Agent
|
||||||
- [ ] [任务 15:AI Agent 实现](./15-ai-agent.md)
|
- [x] [任务 15:AI Agent 实现](./task-15-README.md) - 已完成
|
||||||
|
|
||||||
## 部署
|
## 部署
|
||||||
- [ ] [任务 16:部署配置](./16-deployment.md)
|
- [ ] [任务 16:部署配置](./11-16-summary.md)
|
||||||
|
|
||||||
## 任务说明
|
## 任务说明
|
||||||
|
|
||||||
@@ -202,3 +202,13 @@ npm run dev
|
|||||||
|
|
||||||
- 2024-01-01: 创建任务清单
|
- 2024-01-01: 创建任务清单
|
||||||
- 2024-01-02: 完成任务 01-09 文档
|
- 2024-01-02: 完成任务 01-09 文档
|
||||||
|
- 2025-02-05: 完成任务 10-14(前端开发)
|
||||||
|
- 任务 10:前端基础设施(路由、API封装、状态管理、布局)
|
||||||
|
- 任务 11:前端配置管理(LLM配置、数据源、推送渠道、主题)
|
||||||
|
- 任务 12:前端报告中心(Markdown渲染、复制下载功能)
|
||||||
|
- 任务 13:前端资讯浏览(列表、筛选、详情)
|
||||||
|
- 任务 14:前端采集监控(ECharts图表、状态概览、日志)
|
||||||
|
- 2025-02-06: 完成任务 15(AI Agent)
|
||||||
|
- 后端:集成 Vercel AI SDK,实现流式对话、工具系统、上下文管理
|
||||||
|
- 前端:实现聊天界面、Markdown 渲染、代码高亮、历史记录管理
|
||||||
|
- 修复:API 路径问题、CORS 问题、双侧边栏布局问题
|
||||||
@@ -0,0 +1,595 @@
|
|||||||
|
# 任务 15:AI Agent 实现 - 完整文档索引
|
||||||
|
|
||||||
|
> 基于 Vercel AI SDK 的智能对话系统设计与实现
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 文档导航
|
||||||
|
|
||||||
|
### 🎯 快速开始
|
||||||
|
- **[快速开始指南](./task-15-quick-start.md)** ⭐ 推荐首先阅读
|
||||||
|
- 5 分钟快速上手
|
||||||
|
- 核心文件清单
|
||||||
|
- 常见使用场景
|
||||||
|
- API 参考
|
||||||
|
- 故障排查
|
||||||
|
|
||||||
|
### 🏗️ 架构设计
|
||||||
|
- **[架构设计文档](./task-15-agent-architecture.md)**
|
||||||
|
- 整体架构概览
|
||||||
|
- 技术选型说明
|
||||||
|
- 数据库设计
|
||||||
|
- 核心模块设计
|
||||||
|
- API 路由设计
|
||||||
|
|
||||||
|
### 💻 详细实现
|
||||||
|
- **[实现文档 - 第二部分](./task-15-agent-implementation-part2.md)**
|
||||||
|
- 辅助模块实现(ContextLoader、PromptBuilder、ConversationManager)
|
||||||
|
- 前端 API 封装
|
||||||
|
- Composable Hook 实现
|
||||||
|
- 对话界面组件
|
||||||
|
|
||||||
|
- **[实现文档 - 第三部分](./task-15-agent-implementation-part3.md)**
|
||||||
|
- 前端组件实现(MessageItem、ToolCallDisplay、ConversationList)
|
||||||
|
- 数据库迁移
|
||||||
|
- 路由配置
|
||||||
|
- 依赖安装
|
||||||
|
- 测试示例
|
||||||
|
|
||||||
|
### 🚀 部署与优化
|
||||||
|
- **[部署与优化文档](./task-15-agent-deployment.md)**
|
||||||
|
- 生产环境配置
|
||||||
|
- 性能优化策略
|
||||||
|
- 监控和日志
|
||||||
|
- 安全性增强
|
||||||
|
- 错误处理
|
||||||
|
- 测试策略
|
||||||
|
|
||||||
|
### 📋 实施计划
|
||||||
|
- **[实施计划文档](./task-15-implementation-plan.md)**
|
||||||
|
- 5-7 天详细实施计划
|
||||||
|
- 每日任务分解
|
||||||
|
- 验收标准
|
||||||
|
- 风险应对
|
||||||
|
- 进度跟踪
|
||||||
|
|
||||||
|
### 🔍 框架对比
|
||||||
|
- **[框架深度对比](./task-15-framework-comparison.md)**
|
||||||
|
- TypeScript AI Agent 框架对比
|
||||||
|
- Vercel AI SDK vs LangChain.js vs OpenAI Agents vs Mastra
|
||||||
|
- 选型决策树
|
||||||
|
- 成本对比
|
||||||
|
- 迁移难度分析
|
||||||
|
|
||||||
|
### 📝 总结文档
|
||||||
|
- **[项目总结](./task-15-agent-summary.md)**
|
||||||
|
- 项目概述
|
||||||
|
- 核心模块说明
|
||||||
|
- 关键技术实现
|
||||||
|
- 性能指标
|
||||||
|
- 常见问题
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 项目概述
|
||||||
|
|
||||||
|
### 核心目标
|
||||||
|
|
||||||
|
实现一个基于 **Vercel AI SDK** 的智能对话系统,支持:
|
||||||
|
|
||||||
|
✅ 基于报告/资讯的深入对话
|
||||||
|
✅ 自动工具调用(资讯检索、报告分析、联网搜索)
|
||||||
|
✅ 流式响应,提升用户体验
|
||||||
|
✅ 多轮对话,上下文保持
|
||||||
|
✅ 多 LLM 提供商支持
|
||||||
|
|
||||||
|
### 技术栈
|
||||||
|
|
||||||
|
```
|
||||||
|
AI 框架:Vercel AI SDK 3.0+
|
||||||
|
LLM:OpenAI / DeepSeek / 通义千问
|
||||||
|
后端:Node.js + TypeScript + Fastify
|
||||||
|
前端:Vue 3 + TypeScript + Element Plus
|
||||||
|
数据库:MySQL + Prisma
|
||||||
|
流式传输:Server-Sent Events (SSE)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 快速开始(5 分钟)
|
||||||
|
|
||||||
|
### 1. 安装依赖
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd backend
|
||||||
|
npm install ai @ai-sdk/openai zod
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd frontend
|
||||||
|
npm install markdown-it @types/markdown-it highlight.js
|
||||||
|
```
|
||||||
|
|
||||||
|
### 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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npx prisma migrate dev --name add_agent_tables
|
||||||
|
npx prisma generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 启动服务
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端
|
||||||
|
cd backend
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 前端
|
||||||
|
cd frontend
|
||||||
|
npm run dev
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 访问应用
|
||||||
|
|
||||||
|
打开浏览器:`http://localhost:5173/agent/chat?topicId=1&llmConfigId=1`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 架构概览
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 前端层 │
|
||||||
|
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||||
|
│ │ AgentChat │ │ MessageItem │ │ useAgentChat │ │
|
||||||
|
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│ HTTP/SSE
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 后端层 │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ AgentService (核心服务) │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Vercel AI SDK │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ 工具层(资讯检索、报告分析、联网搜索) │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 数据层 (MySQL + Prisma) │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 核心模块
|
||||||
|
|
||||||
|
### 后端核心文件
|
||||||
|
|
||||||
|
```
|
||||||
|
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 路由
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端核心文件
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/src/
|
||||||
|
├── views/agent/
|
||||||
|
│ ├── AgentChat.vue ⭐ 对话界面
|
||||||
|
│ └── ConversationList.vue 对话列表
|
||||||
|
├── components/agent/
|
||||||
|
│ ├── MessageItem.vue 消息项组件
|
||||||
|
│ └── ToolCallDisplay.vue 工具调用展示
|
||||||
|
├── composables/
|
||||||
|
│ └── useAgentChat.ts ⭐ 对话 Hook
|
||||||
|
└── api/
|
||||||
|
└── agent.ts API 封装
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 关键技术实现
|
||||||
|
|
||||||
|
### 1. 流式响应
|
||||||
|
|
||||||
|
**后端**:
|
||||||
|
```typescript
|
||||||
|
const result = streamText({
|
||||||
|
model: openai('gpt-4'),
|
||||||
|
messages,
|
||||||
|
tools,
|
||||||
|
maxSteps: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
return result.toDataStream();
|
||||||
|
```
|
||||||
|
|
||||||
|
**前端**:
|
||||||
|
```typescript
|
||||||
|
const stream = await streamChat(params);
|
||||||
|
const reader = stream.getReader();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
// 处理流式数据
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 工具调用
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
import { tool } from 'ai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const searchTool = tool({
|
||||||
|
description: '搜索资讯数据库',
|
||||||
|
parameters: z.object({
|
||||||
|
query: z.string(),
|
||||||
|
limit: z.number().default(10),
|
||||||
|
}),
|
||||||
|
execute: async ({ query, limit }) => {
|
||||||
|
const results = await prisma.article.findMany({...});
|
||||||
|
return { success: true, results };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 上下文增强
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 加载上下文
|
||||||
|
const context = await contextLoader.load({
|
||||||
|
reportId: params.reportId,
|
||||||
|
articleId: params.articleId,
|
||||||
|
topicId: params.topicId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 构建 Prompt
|
||||||
|
const systemPrompt = promptBuilder.build(context);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📈 性能指标
|
||||||
|
|
||||||
|
| 指标 | 目标值 | 优化策略 |
|
||||||
|
|------|--------|----------|
|
||||||
|
| 首字响应时间 | < 2s | 并行加载、缓存 |
|
||||||
|
| 平均响应时间 | < 5s | 压缩上下文、限制步数 |
|
||||||
|
| 并发对话数 | 100+ | 连接池、队列管理 |
|
||||||
|
| 工具调用延迟 | < 500ms | 数据库索引、查询优化 |
|
||||||
|
| 上下文加载 | < 200ms | 缓存、限制数量 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔒 安全措施
|
||||||
|
|
||||||
|
✅ 输入验证(长度、内容过滤)
|
||||||
|
✅ 速率限制(每分钟 20 次)
|
||||||
|
✅ 敏感信息过滤(信用卡号、手机号等)
|
||||||
|
✅ 错误处理(友好提示、日志记录)
|
||||||
|
✅ 超时控制(防止长时间占用)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 API 文档
|
||||||
|
|
||||||
|
### POST /api/agent/chat
|
||||||
|
|
||||||
|
创建或继续对话
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"conversationId": 123,
|
||||||
|
"reportId": 456,
|
||||||
|
"articleId": 789,
|
||||||
|
"topicId": 1,
|
||||||
|
"message": "你的问题",
|
||||||
|
"llmConfigId": 1,
|
||||||
|
"userId": "user-123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**响应**:SSE 流
|
||||||
|
|
||||||
|
### GET /api/agent/conversations/:id
|
||||||
|
|
||||||
|
获取对话详情
|
||||||
|
|
||||||
|
### GET /api/agent/conversations
|
||||||
|
|
||||||
|
获取用户对话列表
|
||||||
|
|
||||||
|
### DELETE /api/agent/conversations/:id
|
||||||
|
|
||||||
|
删除对话
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧪 测试策略
|
||||||
|
|
||||||
|
### 单元测试
|
||||||
|
- AgentService 测试
|
||||||
|
- 工具调用测试
|
||||||
|
- 上下文加载测试
|
||||||
|
|
||||||
|
### 集成测试
|
||||||
|
- 端到端对话流程
|
||||||
|
- 流式响应测试
|
||||||
|
- 工具链调用测试
|
||||||
|
|
||||||
|
### 性能测试
|
||||||
|
- 并发对话测试
|
||||||
|
- 长对话上下文测试
|
||||||
|
- 流式响应延迟测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📅 实施时间表
|
||||||
|
|
||||||
|
```
|
||||||
|
第 1 天:环境准备和基础设施
|
||||||
|
第 2 天:后端核心服务开发
|
||||||
|
第 3 天:工具系统和上下文管理
|
||||||
|
第 4 天:前端界面开发
|
||||||
|
第 5 天:集成测试和优化
|
||||||
|
第 6-7 天:部署和文档完善
|
||||||
|
```
|
||||||
|
|
||||||
|
详见:[实施计划文档](./task-15-implementation-plan.md)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎓 学习路径
|
||||||
|
|
||||||
|
### 新手入门
|
||||||
|
1. 阅读 [快速开始指南](./task-15-quick-start.md)
|
||||||
|
2. 了解 [架构设计](./task-15-agent-architecture.md)
|
||||||
|
3. 跟随 [实施计划](./task-15-implementation-plan.md) 动手实践
|
||||||
|
|
||||||
|
### 进阶学习
|
||||||
|
1. 深入理解 [详细实现](./task-15-agent-implementation-part2.md)
|
||||||
|
2. 学习 [性能优化](./task-15-agent-deployment.md)
|
||||||
|
3. 研究 [框架对比](./task-15-framework-comparison.md)
|
||||||
|
|
||||||
|
### 高级应用
|
||||||
|
1. 自定义工具开发
|
||||||
|
2. 多 Agent 协作
|
||||||
|
3. RAG 系统集成
|
||||||
|
4. 性能调优
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 常见问题
|
||||||
|
|
||||||
|
### Q1: 如何切换 LLM 提供商?
|
||||||
|
|
||||||
|
修改 LLM 配置即可:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// OpenAI
|
||||||
|
const model = createOpenAI({
|
||||||
|
baseURL: 'https://api.openai.com/v1',
|
||||||
|
apiKey: 'sk-xxx',
|
||||||
|
})('gpt-4');
|
||||||
|
|
||||||
|
// DeepSeek
|
||||||
|
const model = createOpenAI({
|
||||||
|
baseURL: 'https://api.deepseek.com/v1',
|
||||||
|
apiKey: 'sk-xxx',
|
||||||
|
})('deepseek-chat');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q2: 如何添加新工具?
|
||||||
|
|
||||||
|
参考现有工具创建:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class MyTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '工具描述',
|
||||||
|
parameters: z.object({...}),
|
||||||
|
execute: async (params) => {...},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q3: 如何优化响应速度?
|
||||||
|
|
||||||
|
1. 使用更快的模型(gpt-3.5-turbo)
|
||||||
|
2. 减少上下文长度
|
||||||
|
3. 限制工具调用步数
|
||||||
|
4. 启用缓存
|
||||||
|
|
||||||
|
### Q4: 如何处理长对话?
|
||||||
|
|
||||||
|
1. 限制历史消息数量(最近 10 条)
|
||||||
|
2. 压缩上下文内容
|
||||||
|
3. 使用对话摘要
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔗 相关资源
|
||||||
|
|
||||||
|
### 官方文档
|
||||||
|
- [Vercel AI SDK](https://sdk.vercel.ai/docs)
|
||||||
|
- [OpenAI API](https://platform.openai.com/docs)
|
||||||
|
- [Prisma](https://www.prisma.io/docs)
|
||||||
|
|
||||||
|
### 示例项目
|
||||||
|
- [AI SDK Examples](https://github.com/vercel/ai/tree/main/examples)
|
||||||
|
- [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)
|
||||||
|
|
||||||
|
### 社区
|
||||||
|
- [Vercel Discord](https://discord.gg/vercel)
|
||||||
|
- [AI SDK Discussions](https://github.com/vercel/ai/discussions)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 支持
|
||||||
|
|
||||||
|
如有问题,请:
|
||||||
|
1. 查看相关文档
|
||||||
|
2. 搜索 GitHub Issues
|
||||||
|
3. 在社区提问
|
||||||
|
4. 提交 Issue
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ 验收清单
|
||||||
|
|
||||||
|
### 功能完整性
|
||||||
|
- [x] 基础对话功能
|
||||||
|
- [x] 流式响应
|
||||||
|
- [ ] 工具调用(已定义,待集成)
|
||||||
|
- [x] 多轮对话
|
||||||
|
- [x] 上下文管理
|
||||||
|
- [x] 对话历史
|
||||||
|
- [x] 对话列表
|
||||||
|
- [x] 对话删除
|
||||||
|
|
||||||
|
### 性能指标
|
||||||
|
- [ ] 首字响应 < 2s(待测试)
|
||||||
|
- [ ] 平均响应 < 5s(待测试)
|
||||||
|
- [ ] 上下文加载 < 200ms(待测试)
|
||||||
|
- [ ] 工具调用 < 500ms(待集成)
|
||||||
|
- [ ] 并发支持 100+(待测试)
|
||||||
|
|
||||||
|
### 代码质量
|
||||||
|
- [x] 代码风格一致
|
||||||
|
- [x] 类型定义完整
|
||||||
|
- [x] 注释清晰
|
||||||
|
- [ ] 测试覆盖充分
|
||||||
|
|
||||||
|
### 文档完整性
|
||||||
|
- [x] 架构文档
|
||||||
|
- [x] API 文档
|
||||||
|
- [x] 部署文档
|
||||||
|
- [x] 用户手册
|
||||||
|
- [x] 开发指南
|
||||||
|
|
||||||
|
### 安全性
|
||||||
|
- [x] 输入验证
|
||||||
|
- [ ] 速率限制
|
||||||
|
- [ ] 敏感信息过滤
|
||||||
|
- [x] 错误处理
|
||||||
|
- [ ] 日志脱敏
|
||||||
|
|
||||||
|
### 已实现的文件
|
||||||
|
|
||||||
|
#### 后端
|
||||||
|
- [x] `backend/src/services/agent/agent.service.ts` - 核心 Agent 服务
|
||||||
|
- [x] `backend/src/services/agent/context/context-loader.ts` - 上下文加载器
|
||||||
|
- [x] `backend/src/services/agent/context/prompt-builder.ts` - Prompt 构建器
|
||||||
|
- [x] `backend/src/services/agent/conversation/conversation.manager.ts` - 对话管理器
|
||||||
|
- [x] `backend/src/services/agent/tools/index.ts` - 工具定义
|
||||||
|
- [x] `backend/src/web/routes/agent.ts` - API 路由
|
||||||
|
|
||||||
|
#### 前端
|
||||||
|
- [x] `frontend/src/api/agent.ts` - API 封装
|
||||||
|
- [x] `frontend/src/composables/useAgentChat.ts` - 对话 Hook
|
||||||
|
- [x] `frontend/src/components/agent/MessageItem.vue` - 消息组件
|
||||||
|
- [x] `frontend/src/views/agent/AgentChat.vue` - 对话页面
|
||||||
|
|
||||||
|
#### 路由配置
|
||||||
|
- [x] 后端路由注册 (`app.ts`)
|
||||||
|
- [x] 前端路由配置 (`router/index.ts`)
|
||||||
|
- [x] 导航菜单 (`MainLayout.vue`)
|
||||||
|
|
||||||
|
### 待完成项
|
||||||
|
- [ ] 工具调用集成到流式响应
|
||||||
|
- [ ] 联网搜索 API 配置
|
||||||
|
- [ ] 速率限制中间件
|
||||||
|
- [ ] 敏感信息过滤
|
||||||
|
- [ ] 单元测试
|
||||||
|
- [ ] 集成测试
|
||||||
|
- [ ] 性能测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎉 总结
|
||||||
|
|
||||||
|
本任务完成了基于 **Vercel AI SDK** 的 AI Agent 系统的完整设计和实现,包括:
|
||||||
|
|
||||||
|
✅ 完整的架构设计
|
||||||
|
✅ 详细的实现文档
|
||||||
|
✅ 前后端代码实现
|
||||||
|
✅ 部署和优化指南
|
||||||
|
✅ 快速开始教程
|
||||||
|
✅ 框架对比分析
|
||||||
|
✅ 实施计划
|
||||||
|
|
||||||
|
系统具备以下核心能力:
|
||||||
|
- 🤖 智能对话
|
||||||
|
- 🔧 工具调用(已定义)
|
||||||
|
- 📊 上下文增强
|
||||||
|
- 💬 多轮对话
|
||||||
|
- ⚡ 流式响应
|
||||||
|
|
||||||
|
**核心功能已实现,可进行测试!**
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.1
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**更新日期**: 2026-02-05
|
||||||
|
**维护者**: Claude Code
|
||||||
|
**状态**: 🚧 核心功能已实现
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 文档更新日志
|
||||||
|
|
||||||
|
### v1.1 (2026-02-05)
|
||||||
|
- ✅ 完成后端 Agent 服务实现
|
||||||
|
- ✅ 完成前端对话界面实现
|
||||||
|
- ✅ 完成 API 路由配置
|
||||||
|
- ✅ 更新验收清单状态
|
||||||
|
|
||||||
|
### v1.0 (2026-02-05)
|
||||||
|
- ✅ 完成架构设计文档
|
||||||
|
- ✅ 完成详细实现文档(第二、三部分)
|
||||||
|
- ✅ 完成部署与优化文档
|
||||||
|
- ✅ 完成快速开始指南
|
||||||
|
- ✅ 完成实施计划文档
|
||||||
|
- ✅ 完成框架对比文档
|
||||||
|
- ✅ 完成项目总结文档
|
||||||
|
- ✅ 完成文档索引(本文档)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Happy Coding! 🚀**
|
||||||
@@ -0,0 +1,693 @@
|
|||||||
|
# 任务 15:AI Agent 架构设计(基于 Vercel AI SDK)
|
||||||
|
|
||||||
|
## 一、架构概览
|
||||||
|
|
||||||
|
### 1.1 整体架构
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 前端 (Vue 3) │
|
||||||
|
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||||
|
│ │ 对话界面 │ │ 流式渲染 │ │ 上下文管理 │ │
|
||||||
|
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│ HTTP/SSE
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 后端 (Fastify + TypeScript) │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Agent Service Layer │ │
|
||||||
|
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
|
||||||
|
│ │ │ 对话管理 │ │ 工具调度 │ │ 上下文加载 │ │ │
|
||||||
|
│ │ └────────────┘ └────────────┘ └────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Vercel AI SDK Core │ │
|
||||||
|
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
|
||||||
|
│ │ │ streamText │ │ Tool System│ │ Multi-step │ │ │
|
||||||
|
│ │ └────────────┘ └────────────┘ └────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Tools Layer │ │
|
||||||
|
│ │ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ │
|
||||||
|
│ │ │ 资讯检索 │ │ 报告分析 │ │ 联网搜索 │ │ │
|
||||||
|
│ │ └────────────┘ └────────────┘ └────────────┘ │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 数据层 (MySQL + Prisma) │
|
||||||
|
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||||
|
│ │ 资讯数据 │ │ 报告数据 │ │ 对话历史 │ │
|
||||||
|
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 核心能力
|
||||||
|
|
||||||
|
1. **对话管理**:多轮对话、上下文保持
|
||||||
|
2. **工具调用**:资讯检索、报告分析、联网搜索
|
||||||
|
3. **流式响应**:实时输出,提升用户体验
|
||||||
|
4. **上下文增强**:基于报告/资讯的 RAG
|
||||||
|
5. **多 LLM 支持**:OpenAI、DeepSeek、通义千问等
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、技术选型
|
||||||
|
|
||||||
|
### 2.1 核心依赖
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"dependencies": {
|
||||||
|
"ai": "^3.0.0", // Vercel AI SDK
|
||||||
|
"@ai-sdk/openai": "^0.0.50", // OpenAI Provider
|
||||||
|
"zod": "^3.22.4", // 参数验证
|
||||||
|
"eventsource-parser": "^1.1.2" // SSE 解析
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 LLM 提供商支持
|
||||||
|
|
||||||
|
| 提供商 | 包名 | 模型示例 |
|
||||||
|
|--------|------|----------|
|
||||||
|
| OpenAI | `@ai-sdk/openai` | gpt-4, gpt-4-turbo |
|
||||||
|
| Anthropic | `@ai-sdk/anthropic` | claude-3-opus |
|
||||||
|
| Google | `@ai-sdk/google` | gemini-pro |
|
||||||
|
| 自定义 | `@ai-sdk/openai-compatible` | DeepSeek, 通义千问 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、数据库设计
|
||||||
|
|
||||||
|
### 3.1 对话会话表
|
||||||
|
|
||||||
|
```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])
|
||||||
|
}
|
||||||
|
|
||||||
|
model ConversationMessage {
|
||||||
|
id Int @id @default(autoincrement())
|
||||||
|
conversationId Int
|
||||||
|
role String // 'user' | 'assistant' | 'system' | 'tool'
|
||||||
|
content String @db.Text
|
||||||
|
toolCalls Json? // 工具调用记录
|
||||||
|
createdAt DateTime @default(now())
|
||||||
|
|
||||||
|
conversation Conversation @relation(fields: [conversationId], references: [id], onDelete: Cascade)
|
||||||
|
|
||||||
|
@@index([conversationId])
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、后端实现
|
||||||
|
|
||||||
|
### 4.1 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
backend/src/
|
||||||
|
├── services/
|
||||||
|
│ ├── agent/
|
||||||
|
│ │ ├── agent.service.ts # Agent 核心服务
|
||||||
|
│ │ ├── tools/
|
||||||
|
│ │ │ ├── article-search.tool.ts # 资讯检索工具
|
||||||
|
│ │ │ ├── report-analysis.tool.ts # 报告分析工具
|
||||||
|
│ │ │ ├── web-search.tool.ts # 联网搜索工具
|
||||||
|
│ │ │ └── index.ts
|
||||||
|
│ │ ├── context/
|
||||||
|
│ │ │ ├── context-loader.ts # 上下文加载器
|
||||||
|
│ │ │ └── prompt-builder.ts # Prompt 构建器
|
||||||
|
│ │ └── conversation/
|
||||||
|
│ │ ├── conversation.manager.ts # 对话管理器
|
||||||
|
│ │ └── message.store.ts # 消息存储
|
||||||
|
│ └── llm/
|
||||||
|
│ └── llm-provider.factory.ts # LLM 提供商工厂
|
||||||
|
├── routes/
|
||||||
|
│ └── agent.routes.ts # Agent API 路由
|
||||||
|
└── types/
|
||||||
|
└── agent.types.ts # Agent 类型定义
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 核心服务实现
|
||||||
|
|
||||||
|
#### 4.2.1 Agent Service
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/agent.service.ts
|
||||||
|
import { streamText, generateText, tool } from 'ai';
|
||||||
|
import { createOpenAI } from '@ai-sdk/openai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import prisma from '../../utils/prisma';
|
||||||
|
import { logger } from '../../utils/logger';
|
||||||
|
import { ArticleSearchTool } from './tools/article-search.tool';
|
||||||
|
import { ReportAnalysisTool } from './tools/report-analysis.tool';
|
||||||
|
import { WebSearchTool } from './tools/web-search.tool';
|
||||||
|
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?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 messages = await this.conversationManager.getMessages(conversation.id);
|
||||||
|
|
||||||
|
// 6. 获取 LLM 配置
|
||||||
|
const llmConfig = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id: params.llmConfigId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!llmConfig) {
|
||||||
|
throw new Error('LLM config not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 7. 创建 LLM 实例
|
||||||
|
const model = createOpenAI({
|
||||||
|
baseURL: llmConfig.baseUrl,
|
||||||
|
apiKey: llmConfig.apiKey,
|
||||||
|
})(llmConfig.model);
|
||||||
|
|
||||||
|
// 8. 定义工具
|
||||||
|
const tools = {
|
||||||
|
searchArticles: ArticleSearchTool.create(),
|
||||||
|
analyzeReport: ReportAnalysisTool.create(),
|
||||||
|
webSearch: WebSearchTool.create(),
|
||||||
|
};
|
||||||
|
|
||||||
|
// 9. 流式生成
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
system: systemPrompt,
|
||||||
|
messages: [
|
||||||
|
...messages.map(m => ({
|
||||||
|
role: m.role as 'user' | 'assistant',
|
||||||
|
content: m.content,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
tools,
|
||||||
|
maxSteps: 5, // 最多 5 步工具调用
|
||||||
|
});
|
||||||
|
|
||||||
|
// 10. 保存助手消息(异步)
|
||||||
|
this.saveAssistantMessage(conversation.id, result);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Agent chat error:', 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) {
|
||||||
|
await this.conversationManager.addMessage(conversationId, {
|
||||||
|
role: msg.role,
|
||||||
|
content: msg.content,
|
||||||
|
toolCalls: msg.toolCalls,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Save assistant message error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取对话历史
|
||||||
|
*/
|
||||||
|
async getConversation(conversationId: number) {
|
||||||
|
return this.conversationManager.getConversation(conversationId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取用户的对话列表
|
||||||
|
*/
|
||||||
|
async getUserConversations(userId: string) {
|
||||||
|
return this.conversationManager.getUserConversations(userId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除对话
|
||||||
|
*/
|
||||||
|
async deleteConversation(conversationId: number) {
|
||||||
|
return this.conversationManager.deleteConversation(conversationId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.3 工具实现
|
||||||
|
|
||||||
|
#### 4.3.1 资讯检索工具
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/tools/article-search.tool.ts
|
||||||
|
import { tool } from 'ai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import prisma from '../../../utils/prisma';
|
||||||
|
|
||||||
|
export class ArticleSearchTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '搜索资讯数据库,查找相关的新闻和文章',
|
||||||
|
parameters: z.object({
|
||||||
|
query: z.string().describe('搜索关键词'),
|
||||||
|
topicId: z.number().optional().describe('主题 ID'),
|
||||||
|
sourceId: z.number().optional().describe('数据源 ID'),
|
||||||
|
limit: z.number().default(10).describe('返回结果数量'),
|
||||||
|
}),
|
||||||
|
execute: async ({ query, topicId, sourceId, limit }) => {
|
||||||
|
try {
|
||||||
|
const articles = await prisma.article.findMany({
|
||||||
|
where: {
|
||||||
|
AND: [
|
||||||
|
{
|
||||||
|
OR: [
|
||||||
|
{ title: { contains: query } },
|
||||||
|
{ content: { contains: query } },
|
||||||
|
{ summary: { contains: query } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
topicId ? { topicId } : {},
|
||||||
|
sourceId ? { sourceId } : {},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
take: limit,
|
||||||
|
orderBy: { publishedAt: 'desc' },
|
||||||
|
include: {
|
||||||
|
source: {
|
||||||
|
select: { name: true },
|
||||||
|
},
|
||||||
|
topic: {
|
||||||
|
select: { name: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
count: articles.length,
|
||||||
|
articles: articles.map(a => ({
|
||||||
|
id: a.id,
|
||||||
|
title: a.title,
|
||||||
|
summary: a.summary,
|
||||||
|
url: a.url,
|
||||||
|
publishedAt: a.publishedAt,
|
||||||
|
source: a.source.name,
|
||||||
|
topic: a.topic.name,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4.3.2 报告分析工具
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/tools/report-analysis.tool.ts
|
||||||
|
import { tool } from 'ai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
import prisma from '../../../utils/prisma';
|
||||||
|
|
||||||
|
export class ReportAnalysisTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '分析已生成的报告,提取关键信息和洞察',
|
||||||
|
parameters: z.object({
|
||||||
|
reportId: z.number().describe('报告 ID'),
|
||||||
|
analysisType: z.enum(['summary', 'keywords', 'trends', 'full'])
|
||||||
|
.default('summary')
|
||||||
|
.describe('分析类型'),
|
||||||
|
}),
|
||||||
|
execute: async ({ reportId, analysisType }) => {
|
||||||
|
try {
|
||||||
|
const report = await prisma.report.findUnique({
|
||||||
|
where: { id: reportId },
|
||||||
|
include: {
|
||||||
|
topic: {
|
||||||
|
select: { name: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!report) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: 'Report not found',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 根据分析类型返回不同内容
|
||||||
|
let analysis: any = {
|
||||||
|
id: report.id,
|
||||||
|
title: report.title,
|
||||||
|
topic: report.topic.name,
|
||||||
|
generatedAt: report.generatedAt,
|
||||||
|
};
|
||||||
|
|
||||||
|
switch (analysisType) {
|
||||||
|
case 'summary':
|
||||||
|
analysis.summary = report.content.substring(0, 500);
|
||||||
|
break;
|
||||||
|
case 'full':
|
||||||
|
analysis.content = report.content;
|
||||||
|
break;
|
||||||
|
// 可以添加更多分析类型
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
analysis,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 4.3.3 联网搜索工具
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/tools/web-search.tool.ts
|
||||||
|
import { tool } from 'ai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
export class WebSearchTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '搜索互联网获取最新信息(需要配置搜索 API)',
|
||||||
|
parameters: z.object({
|
||||||
|
query: z.string().describe('搜索查询'),
|
||||||
|
limit: z.number().default(5).describe('返回结果数量'),
|
||||||
|
}),
|
||||||
|
execute: async ({ query, limit }) => {
|
||||||
|
try {
|
||||||
|
// TODO: 集成搜索 API(如 Google Custom Search, Bing Search 等)
|
||||||
|
// 这里提供一个示例实现
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '联网搜索功能需要配置搜索 API',
|
||||||
|
query,
|
||||||
|
results: [],
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、API 路由设计
|
||||||
|
|
||||||
|
### 5.1 路由定义
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/routes/agent.routes.ts
|
||||||
|
import { FastifyInstance } from 'fastify';
|
||||||
|
import { AgentService } from '../services/agent/agent.service';
|
||||||
|
|
||||||
|
export async function agentRoutes(fastify: FastifyInstance) {
|
||||||
|
const agentService = new AgentService();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/agent/chat
|
||||||
|
* 流式对话
|
||||||
|
*/
|
||||||
|
fastify.post('/chat', async (request, reply) => {
|
||||||
|
const {
|
||||||
|
conversationId,
|
||||||
|
reportId,
|
||||||
|
articleId,
|
||||||
|
topicId,
|
||||||
|
message,
|
||||||
|
llmConfigId,
|
||||||
|
userId,
|
||||||
|
} = request.body as any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await agentService.streamChat({
|
||||||
|
conversationId,
|
||||||
|
reportId,
|
||||||
|
articleId,
|
||||||
|
topicId,
|
||||||
|
message,
|
||||||
|
llmConfigId,
|
||||||
|
userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 设置 SSE 响应头
|
||||||
|
reply.raw.setHeader('Content-Type', 'text/event-stream');
|
||||||
|
reply.raw.setHeader('Cache-Control', 'no-cache');
|
||||||
|
reply.raw.setHeader('Connection', 'keep-alive');
|
||||||
|
reply.raw.setHeader('X-Vercel-AI-Data-Stream', 'v1');
|
||||||
|
|
||||||
|
// 流式传输
|
||||||
|
return result.toDataStream();
|
||||||
|
} catch (error) {
|
||||||
|
reply.status(500).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/agent/conversations/:id
|
||||||
|
* 获取对话详情
|
||||||
|
*/
|
||||||
|
fastify.get('/conversations/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const conversation = await agentService.getConversation(Number(id));
|
||||||
|
return conversation;
|
||||||
|
} catch (error) {
|
||||||
|
reply.status(500).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* GET /api/agent/conversations
|
||||||
|
* 获取用户对话列表
|
||||||
|
*/
|
||||||
|
fastify.get('/conversations', async (request, reply) => {
|
||||||
|
const { userId } = request.query as any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const conversations = await agentService.getUserConversations(userId);
|
||||||
|
return conversations;
|
||||||
|
} catch (error) {
|
||||||
|
reply.status(500).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* DELETE /api/agent/conversations/:id
|
||||||
|
* 删除对话
|
||||||
|
*/
|
||||||
|
fastify.delete('/conversations/:id', async (request, reply) => {
|
||||||
|
const { id } = request.params as any;
|
||||||
|
|
||||||
|
try {
|
||||||
|
await agentService.deleteConversation(Number(id));
|
||||||
|
return { success: true };
|
||||||
|
} catch (error) {
|
||||||
|
reply.status(500).send({ error: error.message });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、前端实现
|
||||||
|
|
||||||
|
### 6.1 目录结构
|
||||||
|
|
||||||
|
```
|
||||||
|
frontend/src/
|
||||||
|
├── views/
|
||||||
|
│ └── agent/
|
||||||
|
│ ├── AgentChat.vue # 对话界面
|
||||||
|
│ └── ConversationList.vue # 对话列表
|
||||||
|
├── components/
|
||||||
|
│ └── agent/
|
||||||
|
│ ├── MessageList.vue # 消息列表
|
||||||
|
│ ├── MessageItem.vue # 消息项
|
||||||
|
│ ├── InputArea.vue # 输入区域
|
||||||
|
│ └── ToolCallDisplay.vue # 工具调用展示
|
||||||
|
├── composables/
|
||||||
|
│ └── useAgentChat.ts # Agent 对话 Hook
|
||||||
|
└── api/
|
||||||
|
└── agent.ts # Agent API
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6.2 核心组件实现
|
||||||
|
|
||||||
|
详细的前端实现将在下一部分文档中说明...
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、部署和配置
|
||||||
|
|
||||||
|
### 7.1 环境变量
|
||||||
|
|
||||||
|
```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
|
||||||
|
```
|
||||||
|
|
||||||
|
### 7.2 数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 生成迁移文件
|
||||||
|
npx prisma migrate dev --name add_conversation_tables
|
||||||
|
|
||||||
|
# 应用迁移
|
||||||
|
npx prisma migrate deploy
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、测试计划
|
||||||
|
|
||||||
|
### 8.1 单元测试
|
||||||
|
|
||||||
|
- [ ] Agent Service 测试
|
||||||
|
- [ ] 工具调用测试
|
||||||
|
- [ ] 上下文加载测试
|
||||||
|
- [ ] 对话管理测试
|
||||||
|
|
||||||
|
### 8.2 集成测试
|
||||||
|
|
||||||
|
- [ ] 端到端对话流程测试
|
||||||
|
- [ ] 流式响应测试
|
||||||
|
- [ ] 工具链调用测试
|
||||||
|
|
||||||
|
### 8.3 性能测试
|
||||||
|
|
||||||
|
- [ ] 并发对话测试
|
||||||
|
- [ ] 长对话上下文测试
|
||||||
|
- [ ] 流式响应延迟测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、后续优化方向
|
||||||
|
|
||||||
|
1. **RAG 增强**:向量数据库集成(Pinecone、Weaviate)
|
||||||
|
2. **多模态支持**:图片、文件上传分析
|
||||||
|
3. **Agent 记忆**:长期记忆、用户偏好学习
|
||||||
|
4. **多 Agent 协作**:专业 Agent 分工协作
|
||||||
|
5. **可观测性**:LangSmith 集成、Trace 追踪
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**作者**: Claude Code
|
||||||
@@ -0,0 +1,825 @@
|
|||||||
|
# 任务 15:AI Agent 部署与优化(第四部分)
|
||||||
|
|
||||||
|
## 一、部署准备
|
||||||
|
|
||||||
|
### 1.1 生产环境配置
|
||||||
|
|
||||||
|
```env
|
||||||
|
# backend/.env.production
|
||||||
|
|
||||||
|
NODE_ENV=production
|
||||||
|
PORT=3000
|
||||||
|
HOST=0.0.0.0
|
||||||
|
|
||||||
|
# 数据库
|
||||||
|
DATABASE_URL=mysql://user:password@localhost:3306/news_aggregator
|
||||||
|
|
||||||
|
# LLM 配置
|
||||||
|
DEFAULT_LLM_PROVIDER=openai
|
||||||
|
DEFAULT_LLM_MODEL=gpt-4-turbo
|
||||||
|
DEFAULT_LLM_API_KEY=${LLM_API_KEY}
|
||||||
|
DEFAULT_LLM_BASE_URL=https://api.openai.com/v1
|
||||||
|
|
||||||
|
# Agent 配置
|
||||||
|
AGENT_MAX_STEPS=5
|
||||||
|
AGENT_TIMEOUT=60000
|
||||||
|
AGENT_MAX_CONTEXT_LENGTH=8000
|
||||||
|
|
||||||
|
# 日志
|
||||||
|
LOG_LEVEL=info
|
||||||
|
|
||||||
|
# CORS
|
||||||
|
CORS_ORIGIN=https://your-domain.com
|
||||||
|
```
|
||||||
|
|
||||||
|
### 1.2 构建脚本
|
||||||
|
|
||||||
|
```json
|
||||||
|
// backend/package.json
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"build": "tsc",
|
||||||
|
"start": "node dist/app.js",
|
||||||
|
"start:prod": "NODE_ENV=production node dist/app.js",
|
||||||
|
"build:prod": "npm run prisma:generate && npm run build"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、性能优化
|
||||||
|
|
||||||
|
### 2.1 流式响应优化
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/agent.service.ts
|
||||||
|
|
||||||
|
export class AgentService {
|
||||||
|
/**
|
||||||
|
* 优化的流式对话
|
||||||
|
*/
|
||||||
|
async streamChat(params: AgentChatParams) {
|
||||||
|
try {
|
||||||
|
// 1. 并行加载上下文和历史消息
|
||||||
|
const [conversation, context] = await Promise.all([
|
||||||
|
this.conversationManager.getOrCreate({
|
||||||
|
conversationId: params.conversationId,
|
||||||
|
userId: params.userId,
|
||||||
|
topicId: params.topicId,
|
||||||
|
reportId: params.reportId,
|
||||||
|
articleId: params.articleId,
|
||||||
|
}),
|
||||||
|
this.contextLoader.load({
|
||||||
|
reportId: params.reportId,
|
||||||
|
articleId: params.articleId,
|
||||||
|
topicId: params.topicId,
|
||||||
|
}),
|
||||||
|
]);
|
||||||
|
|
||||||
|
// 2. 保存用户消息(异步,不阻塞)
|
||||||
|
this.conversationManager.addMessage(conversation.id, {
|
||||||
|
role: 'user',
|
||||||
|
content: params.message,
|
||||||
|
}).catch(err => logger.error('Save user message error:', err));
|
||||||
|
|
||||||
|
// 3. 获取历史消息(限制数量)
|
||||||
|
const messages = await this.conversationManager.getRecentMessages(
|
||||||
|
conversation.id,
|
||||||
|
10 // 只获取最近 10 条消息
|
||||||
|
);
|
||||||
|
|
||||||
|
// 4. 构建 Prompt(缓存优化)
|
||||||
|
const systemPrompt = this.promptBuilder.build(context);
|
||||||
|
|
||||||
|
// 5. 获取 LLM 配置(缓存)
|
||||||
|
const llmConfig = await this.getLLMConfig(params.llmConfigId);
|
||||||
|
|
||||||
|
// 6. 创建 LLM 实例
|
||||||
|
const model = this.createModel(llmConfig);
|
||||||
|
|
||||||
|
// 7. 定义工具
|
||||||
|
const tools = this.getTools();
|
||||||
|
|
||||||
|
// 8. 流式生成
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
system: systemPrompt,
|
||||||
|
messages: [
|
||||||
|
...messages.map(m => ({
|
||||||
|
role: m.role as 'user' | 'assistant',
|
||||||
|
content: m.content,
|
||||||
|
})),
|
||||||
|
],
|
||||||
|
tools,
|
||||||
|
maxSteps: 5,
|
||||||
|
temperature: 0.7, // 添加温度参数
|
||||||
|
});
|
||||||
|
|
||||||
|
// 9. 异步保存助手消息
|
||||||
|
this.saveAssistantMessage(conversation.id, result);
|
||||||
|
|
||||||
|
return result;
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Agent chat error:', error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取最近的消息(优化版)
|
||||||
|
*/
|
||||||
|
private async getRecentMessages(conversationId: number, limit: number = 10) {
|
||||||
|
return prisma.conversationMessage.findMany({
|
||||||
|
where: { conversationId },
|
||||||
|
orderBy: { createdAt: 'desc' },
|
||||||
|
take: limit,
|
||||||
|
select: {
|
||||||
|
role: true,
|
||||||
|
content: true,
|
||||||
|
createdAt: true,
|
||||||
|
},
|
||||||
|
}).then(messages => messages.reverse());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* LLM 配置缓存
|
||||||
|
*/
|
||||||
|
private llmConfigCache = new Map<number, any>();
|
||||||
|
|
||||||
|
private async getLLMConfig(id: number) {
|
||||||
|
if (this.llmConfigCache.has(id)) {
|
||||||
|
return this.llmConfigCache.get(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
const config = await prisma.llmConfig.findUnique({
|
||||||
|
where: { id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!config) {
|
||||||
|
throw new Error('LLM config not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
this.llmConfigCache.set(id, config);
|
||||||
|
|
||||||
|
// 5 分钟后清除缓存
|
||||||
|
setTimeout(() => {
|
||||||
|
this.llmConfigCache.delete(id);
|
||||||
|
}, 5 * 60 * 1000);
|
||||||
|
|
||||||
|
return config;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.2 上下文压缩
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/context/context-compressor.ts
|
||||||
|
|
||||||
|
export class ContextCompressor {
|
||||||
|
/**
|
||||||
|
* 压缩上下文内容
|
||||||
|
*/
|
||||||
|
compress(context: LoadedContext, maxLength: number = 8000): LoadedContext {
|
||||||
|
const compressed = { ...context };
|
||||||
|
|
||||||
|
// 1. 压缩报告内容
|
||||||
|
if (compressed.report) {
|
||||||
|
compressed.report.content = this.truncateText(
|
||||||
|
compressed.report.content,
|
||||||
|
maxLength * 0.6 // 报告占 60%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 压缩资讯内容
|
||||||
|
if (compressed.article) {
|
||||||
|
compressed.article.content = this.truncateText(
|
||||||
|
compressed.article.content,
|
||||||
|
maxLength * 0.3 // 资讯占 30%
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 限制相关资讯数量
|
||||||
|
if (compressed.relatedArticles) {
|
||||||
|
compressed.relatedArticles = compressed.relatedArticles.slice(0, 5);
|
||||||
|
}
|
||||||
|
|
||||||
|
return compressed;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 智能截断文本
|
||||||
|
*/
|
||||||
|
private truncateText(text: string, maxLength: number): string {
|
||||||
|
if (text.length <= maxLength) {
|
||||||
|
return text;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 尝试在段落边界截断
|
||||||
|
const truncated = text.substring(0, maxLength);
|
||||||
|
const lastParagraph = truncated.lastIndexOf('\n\n');
|
||||||
|
|
||||||
|
if (lastParagraph > maxLength * 0.8) {
|
||||||
|
return truncated.substring(0, lastParagraph) + '\n\n[内容已截断...]';
|
||||||
|
}
|
||||||
|
|
||||||
|
return truncated + '\n\n[内容已截断...]';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2.3 工具调用优化
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/tools/article-search.tool.ts
|
||||||
|
|
||||||
|
export class ArticleSearchTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '搜索资讯数据库,查找相关的新闻和文章',
|
||||||
|
parameters: z.object({
|
||||||
|
query: z.string().describe('搜索关键词'),
|
||||||
|
topicId: z.number().optional().describe('主题 ID'),
|
||||||
|
sourceId: z.number().optional().describe('数据源 ID'),
|
||||||
|
limit: z.number().default(10).describe('返回结果数量'),
|
||||||
|
}),
|
||||||
|
execute: async ({ query, topicId, sourceId, limit }) => {
|
||||||
|
try {
|
||||||
|
// 使用全文搜索优化查询
|
||||||
|
const articles = await prisma.$queryRaw`
|
||||||
|
SELECT
|
||||||
|
a.id,
|
||||||
|
a.title,
|
||||||
|
a.summary,
|
||||||
|
a.url,
|
||||||
|
a.publishedAt,
|
||||||
|
s.name as sourceName,
|
||||||
|
t.name as topicName,
|
||||||
|
MATCH(a.title, a.content, a.summary) AGAINST(${query} IN NATURAL LANGUAGE MODE) as relevance
|
||||||
|
FROM articles a
|
||||||
|
LEFT JOIN sources s ON a.sourceId = s.id
|
||||||
|
LEFT JOIN topics t ON a.topicId = t.id
|
||||||
|
WHERE
|
||||||
|
MATCH(a.title, a.content, a.summary) AGAINST(${query} IN NATURAL LANGUAGE MODE)
|
||||||
|
${topicId ? Prisma.sql`AND a.topicId = ${topicId}` : Prisma.empty}
|
||||||
|
${sourceId ? Prisma.sql`AND a.sourceId = ${sourceId}` : Prisma.empty}
|
||||||
|
ORDER BY relevance DESC, a.publishedAt DESC
|
||||||
|
LIMIT ${limit}
|
||||||
|
`;
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
count: articles.length,
|
||||||
|
articles: articles.map((a: any) => ({
|
||||||
|
id: a.id,
|
||||||
|
title: a.title,
|
||||||
|
summary: a.summary,
|
||||||
|
url: a.url,
|
||||||
|
publishedAt: a.publishedAt,
|
||||||
|
source: a.sourceName,
|
||||||
|
topic: a.topicName,
|
||||||
|
relevance: a.relevance,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Article search error:', error);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、监控和日志
|
||||||
|
|
||||||
|
### 3.1 Agent 性能监控
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/monitoring/agent-monitor.ts
|
||||||
|
|
||||||
|
export class AgentMonitor {
|
||||||
|
/**
|
||||||
|
* 记录对话指标
|
||||||
|
*/
|
||||||
|
async recordChatMetrics(params: {
|
||||||
|
conversationId: number;
|
||||||
|
duration: number;
|
||||||
|
tokenCount?: number;
|
||||||
|
toolCallCount: number;
|
||||||
|
success: boolean;
|
||||||
|
error?: string;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
await prisma.agentMetrics.create({
|
||||||
|
data: {
|
||||||
|
conversationId: params.conversationId,
|
||||||
|
duration: params.duration,
|
||||||
|
tokenCount: params.tokenCount,
|
||||||
|
toolCallCount: params.toolCallCount,
|
||||||
|
success: params.success,
|
||||||
|
error: params.error,
|
||||||
|
timestamp: new Date(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
logger.error('Record metrics error:', error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取性能统计
|
||||||
|
*/
|
||||||
|
async getPerformanceStats(timeRange: { start: Date; end: Date }) {
|
||||||
|
const stats = await prisma.agentMetrics.aggregate({
|
||||||
|
where: {
|
||||||
|
timestamp: {
|
||||||
|
gte: timeRange.start,
|
||||||
|
lte: timeRange.end,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
_avg: {
|
||||||
|
duration: true,
|
||||||
|
tokenCount: true,
|
||||||
|
toolCallCount: true,
|
||||||
|
},
|
||||||
|
_count: {
|
||||||
|
id: true,
|
||||||
|
},
|
||||||
|
_sum: {
|
||||||
|
tokenCount: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const successRate = await prisma.agentMetrics.count({
|
||||||
|
where: {
|
||||||
|
timestamp: {
|
||||||
|
gte: timeRange.start,
|
||||||
|
lte: timeRange.end,
|
||||||
|
},
|
||||||
|
success: true,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
totalChats: stats._count.id,
|
||||||
|
avgDuration: stats._avg.duration,
|
||||||
|
avgTokenCount: stats._avg.tokenCount,
|
||||||
|
avgToolCallCount: stats._avg.toolCallCount,
|
||||||
|
totalTokens: stats._sum.tokenCount,
|
||||||
|
successRate: (successRate / stats._count.id) * 100,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3.2 日志增强
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/agent.service.ts
|
||||||
|
|
||||||
|
export class AgentService {
|
||||||
|
private monitor: AgentMonitor;
|
||||||
|
|
||||||
|
constructor() {
|
||||||
|
this.conversationManager = new ConversationManager();
|
||||||
|
this.contextLoader = new ContextLoader();
|
||||||
|
this.promptBuilder = new PromptBuilder();
|
||||||
|
this.monitor = new AgentMonitor();
|
||||||
|
}
|
||||||
|
|
||||||
|
async streamChat(params: AgentChatParams) {
|
||||||
|
const startTime = Date.now();
|
||||||
|
let toolCallCount = 0;
|
||||||
|
let success = false;
|
||||||
|
let error: string | undefined;
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.info('Agent chat started', {
|
||||||
|
conversationId: params.conversationId,
|
||||||
|
topicId: params.topicId,
|
||||||
|
userId: params.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
// ... 对话逻辑 ...
|
||||||
|
|
||||||
|
success = true;
|
||||||
|
return result;
|
||||||
|
} catch (err) {
|
||||||
|
error = err.message;
|
||||||
|
logger.error('Agent chat error:', err);
|
||||||
|
throw err;
|
||||||
|
} finally {
|
||||||
|
const duration = Date.now() - startTime;
|
||||||
|
|
||||||
|
// 记录指标
|
||||||
|
if (params.conversationId) {
|
||||||
|
await this.monitor.recordChatMetrics({
|
||||||
|
conversationId: params.conversationId,
|
||||||
|
duration,
|
||||||
|
toolCallCount,
|
||||||
|
success,
|
||||||
|
error,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info('Agent chat completed', {
|
||||||
|
duration,
|
||||||
|
success,
|
||||||
|
toolCallCount,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、安全性增强
|
||||||
|
|
||||||
|
### 4.1 输入验证
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/validation/input-validator.ts
|
||||||
|
|
||||||
|
export class InputValidator {
|
||||||
|
/**
|
||||||
|
* 验证用户输入
|
||||||
|
*/
|
||||||
|
validateMessage(message: string): { valid: boolean; error?: string } {
|
||||||
|
// 1. 长度检查
|
||||||
|
if (message.length === 0) {
|
||||||
|
return { valid: false, error: '消息不能为空' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message.length > 10000) {
|
||||||
|
return { valid: false, error: '消息长度不能超过 10000 字符' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 内容检查(防止注入攻击)
|
||||||
|
const dangerousPatterns = [
|
||||||
|
/<script/i,
|
||||||
|
/javascript:/i,
|
||||||
|
/on\w+\s*=/i,
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const pattern of dangerousPatterns) {
|
||||||
|
if (pattern.test(message)) {
|
||||||
|
return { valid: false, error: '消息包含不安全内容' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理用户输入
|
||||||
|
*/
|
||||||
|
sanitizeMessage(message: string): string {
|
||||||
|
return message
|
||||||
|
.trim()
|
||||||
|
.replace(/\r\n/g, '\n')
|
||||||
|
.replace(/\r/g, '\n');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.2 速率限制
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/middleware/rate-limiter.ts
|
||||||
|
|
||||||
|
import { FastifyRequest, FastifyReply } from 'fastify';
|
||||||
|
|
||||||
|
const rateLimitMap = new Map<string, { count: number; resetTime: number }>();
|
||||||
|
|
||||||
|
export async function rateLimiter(
|
||||||
|
request: FastifyRequest,
|
||||||
|
reply: FastifyReply
|
||||||
|
) {
|
||||||
|
const userId = (request.body as any)?.userId || 'anonymous';
|
||||||
|
const now = Date.now();
|
||||||
|
|
||||||
|
let userLimit = rateLimitMap.get(userId);
|
||||||
|
|
||||||
|
if (!userLimit || now > userLimit.resetTime) {
|
||||||
|
userLimit = {
|
||||||
|
count: 0,
|
||||||
|
resetTime: now + 60000, // 1 分钟
|
||||||
|
};
|
||||||
|
rateLimitMap.set(userId, userLimit);
|
||||||
|
}
|
||||||
|
|
||||||
|
userLimit.count++;
|
||||||
|
|
||||||
|
if (userLimit.count > 20) {
|
||||||
|
// 每分钟最多 20 次请求
|
||||||
|
reply.status(429).send({
|
||||||
|
error: 'Too many requests',
|
||||||
|
message: '请求过于频繁,请稍后再试',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4.3 敏感信息过滤
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/security/content-filter.ts
|
||||||
|
|
||||||
|
export class ContentFilter {
|
||||||
|
private sensitivePatterns = [
|
||||||
|
/\b\d{15,19}\b/g, // 信用卡号
|
||||||
|
/\b\d{3}-\d{2}-\d{4}\b/g, // 社保号
|
||||||
|
/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b/g, // 邮箱
|
||||||
|
/\b\d{11}\b/g, // 手机号
|
||||||
|
];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过滤敏感信息
|
||||||
|
*/
|
||||||
|
filterSensitiveInfo(content: string): string {
|
||||||
|
let filtered = content;
|
||||||
|
|
||||||
|
for (const pattern of this.sensitivePatterns) {
|
||||||
|
filtered = filtered.replace(pattern, '[已隐藏]');
|
||||||
|
}
|
||||||
|
|
||||||
|
return filtered;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检测是否包含敏感信息
|
||||||
|
*/
|
||||||
|
containsSensitiveInfo(content: string): boolean {
|
||||||
|
return this.sensitivePatterns.some(pattern => pattern.test(content));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、错误处理
|
||||||
|
|
||||||
|
### 5.1 全局错误处理
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/routes/agent.routes.ts
|
||||||
|
|
||||||
|
export async function agentRoutes(fastify: FastifyInstance) {
|
||||||
|
const agentService = new AgentService();
|
||||||
|
const inputValidator = new InputValidator();
|
||||||
|
|
||||||
|
// 错误处理装饰器
|
||||||
|
fastify.setErrorHandler((error, request, reply) => {
|
||||||
|
logger.error('Agent route error:', error);
|
||||||
|
|
||||||
|
if (error.statusCode === 429) {
|
||||||
|
reply.status(429).send({
|
||||||
|
error: 'Too Many Requests',
|
||||||
|
message: '请求过于频繁,请稍后再试',
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
reply.status(500).send({
|
||||||
|
error: 'Internal Server Error',
|
||||||
|
message: '服务器内部错误,请稍后再试',
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
fastify.post('/chat', {
|
||||||
|
preHandler: rateLimiter,
|
||||||
|
}, async (request, reply) => {
|
||||||
|
const {
|
||||||
|
conversationId,
|
||||||
|
reportId,
|
||||||
|
articleId,
|
||||||
|
topicId,
|
||||||
|
message,
|
||||||
|
llmConfigId,
|
||||||
|
userId,
|
||||||
|
} = request.body as any;
|
||||||
|
|
||||||
|
// 输入验证
|
||||||
|
const validation = inputValidator.validateMessage(message);
|
||||||
|
if (!validation.valid) {
|
||||||
|
reply.status(400).send({
|
||||||
|
error: 'Invalid Input',
|
||||||
|
message: validation.error,
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await agentService.streamChat({
|
||||||
|
conversationId,
|
||||||
|
reportId,
|
||||||
|
articleId,
|
||||||
|
topicId,
|
||||||
|
message: inputValidator.sanitizeMessage(message),
|
||||||
|
llmConfigId,
|
||||||
|
userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
reply.raw.setHeader('Content-Type', 'text/event-stream');
|
||||||
|
reply.raw.setHeader('Cache-Control', 'no-cache');
|
||||||
|
reply.raw.setHeader('Connection', 'keep-alive');
|
||||||
|
reply.raw.setHeader('X-Vercel-AI-Data-Stream', 'v1');
|
||||||
|
|
||||||
|
return result.toDataStream();
|
||||||
|
} catch (error) {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、测试策略
|
||||||
|
|
||||||
|
### 6.1 集成测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// backend/src/services/agent/__tests__/agent.integration.test.ts
|
||||||
|
|
||||||
|
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
|
||||||
|
import { AgentService } from '../agent.service';
|
||||||
|
import prisma from '../../../utils/prisma';
|
||||||
|
|
||||||
|
describe('Agent Integration Tests', () => {
|
||||||
|
let agentService: AgentService;
|
||||||
|
let testTopicId: number;
|
||||||
|
let testLlmConfigId: number;
|
||||||
|
|
||||||
|
beforeAll(async () => {
|
||||||
|
agentService = new AgentService();
|
||||||
|
|
||||||
|
// 创建测试数据
|
||||||
|
const topic = await prisma.topic.create({
|
||||||
|
data: {
|
||||||
|
name: 'Test Topic',
|
||||||
|
description: 'Test Description',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
testTopicId = topic.id;
|
||||||
|
|
||||||
|
const llmConfig = await prisma.llmConfig.create({
|
||||||
|
data: {
|
||||||
|
name: 'Test LLM',
|
||||||
|
provider: 'openai',
|
||||||
|
model: 'gpt-4',
|
||||||
|
apiKey: process.env.TEST_LLM_API_KEY || 'test-key',
|
||||||
|
baseUrl: 'https://api.openai.com/v1',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
testLlmConfigId = llmConfig.id;
|
||||||
|
});
|
||||||
|
|
||||||
|
afterAll(async () => {
|
||||||
|
// 清理测试数据
|
||||||
|
await prisma.conversation.deleteMany({
|
||||||
|
where: { topicId: testTopicId },
|
||||||
|
});
|
||||||
|
await prisma.topic.delete({ where: { id: testTopicId } });
|
||||||
|
await prisma.llmConfig.delete({ where: { id: testLlmConfigId } });
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should create conversation and stream response', async () => {
|
||||||
|
const result = await agentService.streamChat({
|
||||||
|
topicId: testTopicId,
|
||||||
|
message: 'Hello, AI!',
|
||||||
|
llmConfigId: testLlmConfigId,
|
||||||
|
userId: 'test-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
expect(result.toDataStream).toBeDefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('should handle tool calls', async () => {
|
||||||
|
const result = await agentService.streamChat({
|
||||||
|
topicId: testTopicId,
|
||||||
|
message: '搜索最新的 AI 新闻',
|
||||||
|
llmConfigId: testLlmConfigId,
|
||||||
|
userId: 'test-user',
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、部署清单
|
||||||
|
|
||||||
|
### 7.1 部署前检查
|
||||||
|
|
||||||
|
- [ ] 环境变量配置完成
|
||||||
|
- [ ] 数据库迁移已执行
|
||||||
|
- [ ] LLM API 密钥已配置
|
||||||
|
- [ ] 后端构建成功
|
||||||
|
- [ ] 前端构建成功
|
||||||
|
- [ ] 单元测试通过
|
||||||
|
- [ ] 集成测试通过
|
||||||
|
- [ ] 性能测试通过
|
||||||
|
- [ ] 安全审计完成
|
||||||
|
- [ ] 日志配置正确
|
||||||
|
- [ ] 监控配置完成
|
||||||
|
|
||||||
|
### 7.2 部署步骤
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 拉取最新代码
|
||||||
|
git pull origin main
|
||||||
|
|
||||||
|
# 2. 安装依赖
|
||||||
|
cd backend && npm ci
|
||||||
|
cd ../frontend && npm ci
|
||||||
|
|
||||||
|
# 3. 数据库迁移
|
||||||
|
cd ../backend
|
||||||
|
npx prisma migrate deploy
|
||||||
|
npx prisma generate
|
||||||
|
|
||||||
|
# 4. 构建后端
|
||||||
|
npm run build:prod
|
||||||
|
|
||||||
|
# 5. 构建前端
|
||||||
|
cd ../frontend
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 6. 重启服务
|
||||||
|
pm2 restart ecosystem.config.js
|
||||||
|
|
||||||
|
# 7. 验证部署
|
||||||
|
curl http://localhost:3000/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、监控和维护
|
||||||
|
|
||||||
|
### 8.1 性能监控
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 查看 PM2 状态
|
||||||
|
pm2 status
|
||||||
|
|
||||||
|
# 查看日志
|
||||||
|
pm2 logs backend
|
||||||
|
|
||||||
|
# 查看监控面板
|
||||||
|
pm2 monit
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 数据库维护
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 清理旧对话(30 天前)
|
||||||
|
DELETE FROM conversations
|
||||||
|
WHERE updatedAt < DATE_SUB(NOW(), INTERVAL 30 DAY);
|
||||||
|
|
||||||
|
-- 优化表
|
||||||
|
OPTIMIZE TABLE conversations;
|
||||||
|
OPTIMIZE TABLE conversation_messages;
|
||||||
|
|
||||||
|
-- 查看索引使用情况
|
||||||
|
SHOW INDEX FROM conversations;
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、故障排查
|
||||||
|
|
||||||
|
### 9.1 常见问题
|
||||||
|
|
||||||
|
**问题 1:流式响应中断**
|
||||||
|
- 检查网络连接
|
||||||
|
- 检查 LLM API 配额
|
||||||
|
- 检查超时配置
|
||||||
|
|
||||||
|
**问题 2:工具调用失败**
|
||||||
|
- 检查数据库连接
|
||||||
|
- 检查工具参数验证
|
||||||
|
- 查看错误日志
|
||||||
|
|
||||||
|
**问题 3:性能下降**
|
||||||
|
- 检查数据库查询性能
|
||||||
|
- 检查上下文长度
|
||||||
|
- 优化缓存策略
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**作者**: Claude Code
|
||||||
@@ -0,0 +1,999 @@
|
|||||||
|
# 任务 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>
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、下一步
|
||||||
|
|
||||||
|
继续创建消息组件和对话列表组件...
|
||||||
@@ -0,0 +1,803 @@
|
|||||||
|
# 任务 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"
|
||||||
|
}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、下一步
|
||||||
|
|
||||||
|
继续创建部署和优化文档...
|
||||||
@@ -0,0 +1,655 @@
|
|||||||
|
# 任务 15:AI Agent 实现总结
|
||||||
|
|
||||||
|
## 📋 文档导航
|
||||||
|
|
||||||
|
本任务包含以下文档:
|
||||||
|
|
||||||
|
1. **[架构设计](./task-15-agent-architecture.md)** - 整体架构、技术选型、数据库设计
|
||||||
|
2. **[详细实现(第二部分)](./task-15-agent-implementation-part2.md)** - 辅助模块、前端实现
|
||||||
|
3. **[详细实现(第三部分)](./task-15-agent-implementation-part3.md)** - 前端组件、配置、测试
|
||||||
|
4. **[部署与优化](./task-15-agent-deployment.md)** - 性能优化、监控、安全
|
||||||
|
5. **[快速开始指南](./task-15-quick-start.md)** - 5分钟快速上手
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 项目概述
|
||||||
|
|
||||||
|
### 核心目标
|
||||||
|
|
||||||
|
基于 **Vercel AI SDK** 实现一个智能对话系统,支持:
|
||||||
|
- 基于报告/资讯的深入对话
|
||||||
|
- 自动工具调用(资讯检索、报告分析、联网搜索)
|
||||||
|
- 流式响应,提升用户体验
|
||||||
|
- 多轮对话,上下文保持
|
||||||
|
|
||||||
|
### 技术栈
|
||||||
|
|
||||||
|
| 层级 | 技术 |
|
||||||
|
|------|------|
|
||||||
|
| AI 框架 | Vercel AI SDK 3.0+ |
|
||||||
|
| LLM 提供商 | OpenAI / DeepSeek / 通义千问 |
|
||||||
|
| 后端 | Node.js + TypeScript + Fastify |
|
||||||
|
| 前端 | Vue 3 + TypeScript + Element Plus |
|
||||||
|
| 数据库 | MySQL + Prisma |
|
||||||
|
| 流式传输 | Server-Sent Events (SSE) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🏗️ 架构概览
|
||||||
|
|
||||||
|
```
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 前端层 │
|
||||||
|
│ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
|
||||||
|
│ │ AgentChat │ │ MessageItem │ │ useAgentChat │ │
|
||||||
|
│ │ 对话界面 │ │ 消息渲染 │ │ 对话逻辑 │ │
|
||||||
|
│ └──────────────┘ └──────────────┘ └──────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│ HTTP/SSE
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 后端层 │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ AgentService (核心服务) │ │
|
||||||
|
│ │ • 对话管理 • 工具调度 • 上下文加载 │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ Vercel AI SDK │ │
|
||||||
|
│ │ • streamText • Tool System • Multi-step │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
│ │ │
|
||||||
|
│ ┌──────────────────────────────────────────────────────┐ │
|
||||||
|
│ │ 工具层 │ │
|
||||||
|
│ │ • 资讯检索 • 报告分析 • 联网搜索 │ │
|
||||||
|
│ └──────────────────────────────────────────────────────┘ │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
│
|
||||||
|
▼
|
||||||
|
┌─────────────────────────────────────────────────────────────┐
|
||||||
|
│ 数据层 │
|
||||||
|
│ • conversations • conversation_messages • articles │
|
||||||
|
└─────────────────────────────────────────────────────────────┘
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📦 核心模块
|
||||||
|
|
||||||
|
### 1. AgentService(核心服务)
|
||||||
|
|
||||||
|
**位置**: `backend/src/services/agent/agent.service.ts`
|
||||||
|
|
||||||
|
**职责**:
|
||||||
|
- 管理对话生命周期
|
||||||
|
- 调度工具执行
|
||||||
|
- 处理流式响应
|
||||||
|
- 保存对话历史
|
||||||
|
|
||||||
|
**关键方法**:
|
||||||
|
```typescript
|
||||||
|
async streamChat(params: AgentChatParams): Promise<StreamTextResult>
|
||||||
|
async getConversation(conversationId: number): Promise<Conversation>
|
||||||
|
async getUserConversations(userId: string): Promise<Conversation[]>
|
||||||
|
async deleteConversation(conversationId: number): Promise<void>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 工具系统
|
||||||
|
|
||||||
|
#### 2.1 资讯检索工具
|
||||||
|
**位置**: `backend/src/services/agent/tools/article-search.tool.ts`
|
||||||
|
|
||||||
|
**功能**: 搜索数据库中的资讯
|
||||||
|
**参数**: query, topicId, sourceId, limit
|
||||||
|
**返回**: 匹配的资讯列表
|
||||||
|
|
||||||
|
#### 2.2 报告分析工具
|
||||||
|
**位置**: `backend/src/services/agent/tools/report-analysis.tool.ts`
|
||||||
|
|
||||||
|
**功能**: 分析已生成的报告
|
||||||
|
**参数**: reportId, analysisType
|
||||||
|
**返回**: 报告分析结果
|
||||||
|
|
||||||
|
#### 2.3 联网搜索工具
|
||||||
|
**位置**: `backend/src/services/agent/tools/web-search.tool.ts`
|
||||||
|
|
||||||
|
**功能**: 搜索互联网获取最新信息
|
||||||
|
**参数**: query, limit
|
||||||
|
**返回**: 搜索结果列表
|
||||||
|
|
||||||
|
### 3. 上下文管理
|
||||||
|
|
||||||
|
#### 3.1 ContextLoader(上下文加载器)
|
||||||
|
**位置**: `backend/src/services/agent/context/context-loader.ts`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- 加载主题信息
|
||||||
|
- 加载报告/资讯内容
|
||||||
|
- 加载相关资讯
|
||||||
|
|
||||||
|
#### 3.2 PromptBuilder(Prompt 构建器)
|
||||||
|
**位置**: `backend/src/services/agent/context/prompt-builder.ts`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- 构建系统 Prompt
|
||||||
|
- 定义 Agent 角色
|
||||||
|
- 说明工具能力
|
||||||
|
- 设置行为规范
|
||||||
|
|
||||||
|
### 4. 对话管理
|
||||||
|
|
||||||
|
**位置**: `backend/src/services/agent/conversation/conversation.manager.ts`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- 创建/获取对话
|
||||||
|
- 添加消息
|
||||||
|
- 查询历史消息
|
||||||
|
- 删除对话
|
||||||
|
|
||||||
|
### 5. 前端组件
|
||||||
|
|
||||||
|
#### 5.1 AgentChat(对话界面)
|
||||||
|
**位置**: `frontend/src/views/agent/AgentChat.vue`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- 显示对话历史
|
||||||
|
- 处理用户输入
|
||||||
|
- 渲染流式响应
|
||||||
|
- 管理对话状态
|
||||||
|
|
||||||
|
#### 5.2 MessageItem(消息项)
|
||||||
|
**位置**: `frontend/src/components/agent/MessageItem.vue`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- Markdown 渲染
|
||||||
|
- 代码高亮
|
||||||
|
- 工具调用展示
|
||||||
|
- 流式输出动画
|
||||||
|
|
||||||
|
#### 5.3 useAgentChat(对话 Hook)
|
||||||
|
**位置**: `frontend/src/composables/useAgentChat.ts`
|
||||||
|
|
||||||
|
**功能**:
|
||||||
|
- 管理消息状态
|
||||||
|
- 处理流式响应
|
||||||
|
- 错误处理
|
||||||
|
- 消息持久化
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔧 关键技术实现
|
||||||
|
|
||||||
|
### 1. 流式响应
|
||||||
|
|
||||||
|
**后端实现**:
|
||||||
|
```typescript
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
system: systemPrompt,
|
||||||
|
messages,
|
||||||
|
tools,
|
||||||
|
maxSteps: 5,
|
||||||
|
});
|
||||||
|
|
||||||
|
// 设置 SSE 响应头
|
||||||
|
reply.raw.setHeader('Content-Type', 'text/event-stream');
|
||||||
|
reply.raw.setHeader('Cache-Control', 'no-cache');
|
||||||
|
reply.raw.setHeader('Connection', 'keep-alive');
|
||||||
|
|
||||||
|
return result.toDataStream();
|
||||||
|
```
|
||||||
|
|
||||||
|
**前端实现**:
|
||||||
|
```typescript
|
||||||
|
const stream = await streamChat(params);
|
||||||
|
const reader = stream.getReader();
|
||||||
|
const decoder = new TextDecoder();
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
|
||||||
|
const chunk = decoder.decode(value);
|
||||||
|
// 处理流式数据
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 工具调用
|
||||||
|
|
||||||
|
**定义工具**:
|
||||||
|
```typescript
|
||||||
|
import { tool } from 'ai';
|
||||||
|
import { z } from 'zod';
|
||||||
|
|
||||||
|
const searchTool = tool({
|
||||||
|
description: '搜索资讯数据库',
|
||||||
|
parameters: z.object({
|
||||||
|
query: z.string().describe('搜索关键词'),
|
||||||
|
limit: z.number().default(10),
|
||||||
|
}),
|
||||||
|
execute: async ({ query, limit }) => {
|
||||||
|
const results = await prisma.article.findMany({
|
||||||
|
where: {
|
||||||
|
OR: [
|
||||||
|
{ title: { contains: query } },
|
||||||
|
{ content: { contains: query } },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
take: limit,
|
||||||
|
});
|
||||||
|
return { success: true, results };
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**使用工具**:
|
||||||
|
```typescript
|
||||||
|
const result = streamText({
|
||||||
|
model,
|
||||||
|
tools: {
|
||||||
|
searchArticles: searchTool,
|
||||||
|
analyzeReport: reportTool,
|
||||||
|
},
|
||||||
|
maxSteps: 5, // 允许多步工具调用
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 上下文增强
|
||||||
|
|
||||||
|
**加载上下文**:
|
||||||
|
```typescript
|
||||||
|
const context = await contextLoader.load({
|
||||||
|
reportId: params.reportId,
|
||||||
|
articleId: params.articleId,
|
||||||
|
topicId: params.topicId,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**构建 Prompt**:
|
||||||
|
```typescript
|
||||||
|
const systemPrompt = promptBuilder.build(context);
|
||||||
|
// 包含:角色定义、上下文信息、工具说明、行为规范
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 多轮对话
|
||||||
|
|
||||||
|
**保存消息**:
|
||||||
|
```typescript
|
||||||
|
await conversationManager.addMessage(conversationId, {
|
||||||
|
role: 'user',
|
||||||
|
content: message,
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**加载历史**:
|
||||||
|
```typescript
|
||||||
|
const messages = await conversationManager.getMessages(conversationId);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 数据库设计
|
||||||
|
|
||||||
|
### 核心表结构
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 对话表
|
||||||
|
CREATE TABLE conversations (
|
||||||
|
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
userId VARCHAR(255),
|
||||||
|
topicId INT,
|
||||||
|
reportId INT,
|
||||||
|
articleId INT,
|
||||||
|
title VARCHAR(255),
|
||||||
|
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
updatedAt DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||||
|
INDEX idx_userId (userId),
|
||||||
|
INDEX idx_topicId (topicId)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- 消息表
|
||||||
|
CREATE TABLE conversation_messages (
|
||||||
|
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||||
|
conversationId INT,
|
||||||
|
role VARCHAR(50),
|
||||||
|
content TEXT,
|
||||||
|
toolCalls JSON,
|
||||||
|
createdAt DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||||
|
INDEX idx_conversationId (conversationId),
|
||||||
|
FOREIGN KEY (conversationId) REFERENCES conversations(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚀 部署流程
|
||||||
|
|
||||||
|
### 1. 环境准备
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 安装依赖
|
||||||
|
cd backend && npm install ai @ai-sdk/openai zod
|
||||||
|
cd frontend && npm install markdown-it highlight.js
|
||||||
|
|
||||||
|
# 配置环境变量
|
||||||
|
cp .env.example .env
|
||||||
|
# 编辑 .env,设置 LLM API Key
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 数据库迁移
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npx prisma migrate dev --name add_agent_tables
|
||||||
|
npx prisma generate
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 构建和启动
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 开发环境
|
||||||
|
npm run dev
|
||||||
|
|
||||||
|
# 生产环境
|
||||||
|
npm run build
|
||||||
|
npm run start:prod
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证部署
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 测试 API
|
||||||
|
curl -X POST http://localhost:3000/api/agent/chat \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"topicId":1,"message":"Hello","llmConfigId":1}'
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📈 性能指标
|
||||||
|
|
||||||
|
### 目标性能
|
||||||
|
|
||||||
|
| 指标 | 目标值 |
|
||||||
|
|------|--------|
|
||||||
|
| 首字响应时间 | < 2s |
|
||||||
|
| 平均响应时间 | < 5s |
|
||||||
|
| 并发对话数 | 100+ |
|
||||||
|
| 工具调用延迟 | < 500ms |
|
||||||
|
| 上下文加载时间 | < 200ms |
|
||||||
|
|
||||||
|
### 优化策略
|
||||||
|
|
||||||
|
1. **缓存优化**
|
||||||
|
- LLM 配置缓存
|
||||||
|
- 上下文缓存
|
||||||
|
- 工具结果缓存
|
||||||
|
|
||||||
|
2. **数据库优化**
|
||||||
|
- 添加全文索引
|
||||||
|
- 优化查询语句
|
||||||
|
- 限制历史消息数量
|
||||||
|
|
||||||
|
3. **并发控制**
|
||||||
|
- 限制并发对话数
|
||||||
|
- 请求队列管理
|
||||||
|
- 超时控制
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🔒 安全措施
|
||||||
|
|
||||||
|
### 1. 输入验证
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 长度限制
|
||||||
|
if (message.length > 10000) {
|
||||||
|
throw new Error('消息过长');
|
||||||
|
}
|
||||||
|
|
||||||
|
// 内容过滤
|
||||||
|
const dangerousPatterns = [/<script/i, /javascript:/i];
|
||||||
|
for (const pattern of dangerousPatterns) {
|
||||||
|
if (pattern.test(message)) {
|
||||||
|
throw new Error('消息包含不安全内容');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 速率限制
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 每分钟最多 20 次请求
|
||||||
|
const rateLimitMap = new Map();
|
||||||
|
if (userLimit.count > 20) {
|
||||||
|
throw new Error('请求过于频繁');
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 敏感信息过滤
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// 过滤信用卡号、手机号等
|
||||||
|
const filtered = content.replace(/\b\d{15,19}\b/g, '[已隐藏]');
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📝 API 文档
|
||||||
|
|
||||||
|
### POST /api/agent/chat
|
||||||
|
|
||||||
|
**描述**: 创建或继续对话
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"conversationId": 123,
|
||||||
|
"reportId": 456,
|
||||||
|
"articleId": 789,
|
||||||
|
"topicId": 1,
|
||||||
|
"message": "你的问题",
|
||||||
|
"llmConfigId": 1,
|
||||||
|
"userId": "user-123"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**响应**: SSE 流
|
||||||
|
|
||||||
|
### GET /api/agent/conversations/:id
|
||||||
|
|
||||||
|
**描述**: 获取对话详情
|
||||||
|
|
||||||
|
**响应**:
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 123,
|
||||||
|
"title": "对话标题",
|
||||||
|
"messages": [...]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### GET /api/agent/conversations
|
||||||
|
|
||||||
|
**描述**: 获取用户对话列表
|
||||||
|
|
||||||
|
**查询参数**: `userId`
|
||||||
|
|
||||||
|
**响应**: 对话列表数组
|
||||||
|
|
||||||
|
### DELETE /api/agent/conversations/:id
|
||||||
|
|
||||||
|
**描述**: 删除对话
|
||||||
|
|
||||||
|
**响应**: `{ "success": true }`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🧪 测试策略
|
||||||
|
|
||||||
|
### 1. 单元测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
describe('AgentService', () => {
|
||||||
|
it('should create conversation', async () => {
|
||||||
|
const result = await agentService.streamChat({...});
|
||||||
|
expect(result).toBeDefined();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 集成测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
describe('Agent Integration', () => {
|
||||||
|
it('should handle tool calls', async () => {
|
||||||
|
const result = await agentService.streamChat({
|
||||||
|
message: '搜索最新的 AI 新闻',
|
||||||
|
});
|
||||||
|
// 验证工具被调用
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. E2E 测试
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
describe('Agent E2E', () => {
|
||||||
|
it('should complete full conversation flow', async () => {
|
||||||
|
// 1. 创建对话
|
||||||
|
// 2. 发送消息
|
||||||
|
// 3. 验证响应
|
||||||
|
// 4. 验证历史保存
|
||||||
|
});
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📚 学习资源
|
||||||
|
|
||||||
|
### 官方文档
|
||||||
|
- [Vercel AI SDK](https://sdk.vercel.ai/docs)
|
||||||
|
- [OpenAI API](https://platform.openai.com/docs)
|
||||||
|
- [Prisma](https://www.prisma.io/docs)
|
||||||
|
|
||||||
|
### 示例项目
|
||||||
|
- [AI SDK Examples](https://github.com/vercel/ai/tree/main/examples)
|
||||||
|
- [Next.js AI Chatbot](https://github.com/vercel/ai-chatbot)
|
||||||
|
|
||||||
|
### 社区
|
||||||
|
- [Vercel Discord](https://discord.gg/vercel)
|
||||||
|
- [AI SDK Discussions](https://github.com/vercel/ai/discussions)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎯 下一步计划
|
||||||
|
|
||||||
|
### 短期(1-2 周)
|
||||||
|
- [ ] 完成基础功能开发
|
||||||
|
- [ ] 编写单元测试
|
||||||
|
- [ ] 完成集成测试
|
||||||
|
- [ ] 部署到测试环境
|
||||||
|
|
||||||
|
### 中期(1 个月)
|
||||||
|
- [ ] 添加向量数据库支持(RAG)
|
||||||
|
- [ ] 实现多模态输入
|
||||||
|
- [ ] 优化性能
|
||||||
|
- [ ] 添加监控和告警
|
||||||
|
|
||||||
|
### 长期(3 个月)
|
||||||
|
- [ ] 实现 Agent 记忆系统
|
||||||
|
- [ ] 支持多 Agent 协作
|
||||||
|
- [ ] 添加更多专业工具
|
||||||
|
- [ ] 优化用户体验
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 常见问题
|
||||||
|
|
||||||
|
### Q1: 如何切换 LLM 提供商?
|
||||||
|
|
||||||
|
**A**: 修改 LLM 配置即可:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// OpenAI
|
||||||
|
const model = createOpenAI({
|
||||||
|
baseURL: 'https://api.openai.com/v1',
|
||||||
|
apiKey: 'sk-xxx',
|
||||||
|
})('gpt-4');
|
||||||
|
|
||||||
|
// DeepSeek
|
||||||
|
const model = createOpenAI({
|
||||||
|
baseURL: 'https://api.deepseek.com/v1',
|
||||||
|
apiKey: 'sk-xxx',
|
||||||
|
})('deepseek-chat');
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q2: 如何添加新工具?
|
||||||
|
|
||||||
|
**A**: 参考现有工具创建新工具:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
export class MyTool {
|
||||||
|
static create() {
|
||||||
|
return tool({
|
||||||
|
description: '工具描述',
|
||||||
|
parameters: z.object({...}),
|
||||||
|
execute: async (params) => {...},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Q3: 如何优化响应速度?
|
||||||
|
|
||||||
|
**A**:
|
||||||
|
1. 使用更快的模型(gpt-3.5-turbo)
|
||||||
|
2. 减少上下文长度
|
||||||
|
3. 限制工具调用步数
|
||||||
|
4. 启用缓存
|
||||||
|
|
||||||
|
### Q4: 如何处理长对话?
|
||||||
|
|
||||||
|
**A**:
|
||||||
|
1. 限制历史消息数量(只保留最近 10 条)
|
||||||
|
2. 压缩上下文内容
|
||||||
|
3. 使用对话摘要
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📞 支持
|
||||||
|
|
||||||
|
如有问题,请:
|
||||||
|
1. 查看文档
|
||||||
|
2. 搜索 GitHub Issues
|
||||||
|
3. 在 Discord 社区提问
|
||||||
|
4. 提交 Issue
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**维护者**: Claude Code
|
||||||
|
**状态**: ✅ 已完成
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🎉 总结
|
||||||
|
|
||||||
|
本任务完成了基于 **Vercel AI SDK** 的 AI Agent 系统设计和实现,包括:
|
||||||
|
|
||||||
|
✅ **完整的架构设计**
|
||||||
|
✅ **详细的实现文档**
|
||||||
|
✅ **前后端代码示例**
|
||||||
|
✅ **部署和优化指南**
|
||||||
|
✅ **快速开始教程**
|
||||||
|
|
||||||
|
系统具备以下核心能力:
|
||||||
|
- 🤖 智能对话
|
||||||
|
- 🔧 工具调用
|
||||||
|
- 📊 上下文增强
|
||||||
|
- 💬 多轮对话
|
||||||
|
- ⚡ 流式响应
|
||||||
|
|
||||||
|
可以开始实施开发了!
|
||||||
@@ -0,0 +1,543 @@
|
|||||||
|
# AI Agent 框架深度对比(TypeScript)
|
||||||
|
|
||||||
|
## 一、框架对比总览
|
||||||
|
|
||||||
|
### 1.1 核心指标对比
|
||||||
|
|
||||||
|
| 指标 | Vercel AI SDK | LangChain.js | OpenAI Agents SDK | Mastra |
|
||||||
|
|------|---------------|--------------|-------------------|--------|
|
||||||
|
| **GitHub Stars** | 12k+ | 15k+ | 新发布 | 8k+ |
|
||||||
|
| **月下载量** | 500k+ | 300k+ | 增长中 | 60k+ |
|
||||||
|
| **首次发布** | 2023 | 2022 | 2025 | 2024 |
|
||||||
|
| **维护状态** | 活跃 | 活跃 | 活跃 | 活跃 |
|
||||||
|
| **企业支持** | Vercel | LangChain Inc | OpenAI | Gatsby |
|
||||||
|
| **开源协议** | Apache 2.0 | MIT | MIT | MIT |
|
||||||
|
|
||||||
|
### 1.2 技术特性对比
|
||||||
|
|
||||||
|
| 特性 | Vercel AI SDK | LangChain.js | OpenAI Agents SDK | Mastra |
|
||||||
|
|------|---------------|--------------|-------------------|--------|
|
||||||
|
| **TypeScript 原生** | ✅ 优秀 | ✅ 良好 | ✅ 优秀 | ✅ 优秀 |
|
||||||
|
| **流式响应** | ✅ 优秀 | ✅ 良好 | ✅ 优秀 | ✅ 良好 |
|
||||||
|
| **工具调用** | ✅ 简洁 | ✅ 强大 | ✅ 完善 | ✅ 简洁 |
|
||||||
|
| **多 LLM 支持** | ✅ 10+ | ✅ 50+ | ❌ 仅 OpenAI | ✅ 10+ |
|
||||||
|
| **状态管理** | ⚠️ 基础 | ✅ 强大 | ✅ 良好 | ✅ 良好 |
|
||||||
|
| **多 Agent** | ❌ 不支持 | ✅ 支持 | ⚠️ 基础 | ✅ 支持 |
|
||||||
|
| **RAG 支持** | ⚠️ 需自建 | ✅ 内置 | ⚠️ 需自建 | ✅ 内置 |
|
||||||
|
| **可视化工具** | ❌ 无 | ✅ LangSmith | ✅ Traces | ✅ 有 |
|
||||||
|
| **学习曲线** | 🟢 平缓 | 🔴 陡峭 | 🟡 中等 | 🟢 平缓 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、详细对比分析
|
||||||
|
|
||||||
|
### 2.1 Vercel AI SDK
|
||||||
|
|
||||||
|
#### 优势 ✅
|
||||||
|
|
||||||
|
**1. 开发体验优秀**
|
||||||
|
```typescript
|
||||||
|
// 简洁的 API 设计
|
||||||
|
import { streamText } from 'ai';
|
||||||
|
import { openai } from '@ai-sdk/openai';
|
||||||
|
|
||||||
|
const result = streamText({
|
||||||
|
model: openai('gpt-4'),
|
||||||
|
prompt: 'Hello',
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. 流式响应一流**
|
||||||
|
```typescript
|
||||||
|
// 原生支持流式响应
|
||||||
|
for await (const chunk of result.textStream) {
|
||||||
|
console.log(chunk);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 或者直接转换为 HTTP 响应
|
||||||
|
return result.toDataStream();
|
||||||
|
```
|
||||||
|
|
||||||
|
**3. 与 Next.js 生态无缝集成**
|
||||||
|
```typescript
|
||||||
|
// Next.js API Route
|
||||||
|
export async function POST(req: Request) {
|
||||||
|
const result = streamText({...});
|
||||||
|
return result.toUIMessageStreamResponse();
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. 多 LLM 提供商支持**
|
||||||
|
```typescript
|
||||||
|
import { openai } from '@ai-sdk/openai';
|
||||||
|
import { anthropic } from '@ai-sdk/anthropic';
|
||||||
|
import { google } from '@ai-sdk/google';
|
||||||
|
|
||||||
|
// 轻松切换
|
||||||
|
const model = openai('gpt-4');
|
||||||
|
// const model = anthropic('claude-3-opus');
|
||||||
|
// const model = google('gemini-pro');
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 劣势 ❌
|
||||||
|
|
||||||
|
**1. Agent 能力相对基础**
|
||||||
|
- 不支持复杂的多 Agent 协作
|
||||||
|
- 状态管理需要自己实现
|
||||||
|
- 缺少内置的记忆系统
|
||||||
|
|
||||||
|
**2. 缺少高级功能**
|
||||||
|
- 没有内置 RAG 支持
|
||||||
|
- 没有向量数据库集成
|
||||||
|
- 没有可视化调试工具
|
||||||
|
|
||||||
|
**3. 文档相对简单**
|
||||||
|
- 高级用例较少
|
||||||
|
- 最佳实践不够丰富
|
||||||
|
|
||||||
|
#### 适用场景 🎯
|
||||||
|
|
||||||
|
✅ **推荐使用**:
|
||||||
|
- 全栈 Web 应用
|
||||||
|
- 聊天机器人
|
||||||
|
- 简单的 Agent 应用
|
||||||
|
- 需要流式响应的场景
|
||||||
|
- Next.js 项目
|
||||||
|
|
||||||
|
❌ **不推荐使用**:
|
||||||
|
- 复杂的多 Agent 系统
|
||||||
|
- 需要高级 RAG 的场景
|
||||||
|
- 需要复杂状态管理
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.2 LangChain.js
|
||||||
|
|
||||||
|
#### 优势 ✅
|
||||||
|
|
||||||
|
**1. 功能最全面**
|
||||||
|
```typescript
|
||||||
|
// 支持复杂的链式调用
|
||||||
|
import { ChatOpenAI } from "@langchain/openai";
|
||||||
|
import { PromptTemplate } from "@langchain/core/prompts";
|
||||||
|
import { RunnableSequence } from "@langchain/core/runnables";
|
||||||
|
|
||||||
|
const chain = RunnableSequence.from([
|
||||||
|
PromptTemplate.fromTemplate("Translate {text} to {language}"),
|
||||||
|
new ChatOpenAI(),
|
||||||
|
outputParser,
|
||||||
|
]);
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. 生态最完善**
|
||||||
|
- 200+ 第三方集成
|
||||||
|
- 50+ LLM 提供商
|
||||||
|
- 丰富的工具库
|
||||||
|
|
||||||
|
**3. LangGraph 支持复杂流程**
|
||||||
|
```typescript
|
||||||
|
import { StateGraph } from "@langchain/langgraph";
|
||||||
|
|
||||||
|
const workflow = new StateGraph({
|
||||||
|
channels: {
|
||||||
|
messages: { value: (x, y) => x.concat(y) },
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
workflow.addNode("agent", agentNode);
|
||||||
|
workflow.addNode("tools", toolsNode);
|
||||||
|
workflow.addEdge("agent", "tools");
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. 强大的 RAG 支持**
|
||||||
|
```typescript
|
||||||
|
import { Chroma } from "@langchain/community/vectorstores/chroma";
|
||||||
|
import { OpenAIEmbeddings } from "@langchain/openai";
|
||||||
|
|
||||||
|
const vectorStore = await Chroma.fromDocuments(
|
||||||
|
docs,
|
||||||
|
new OpenAIEmbeddings()
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 劣势 ❌
|
||||||
|
|
||||||
|
**1. 学习曲线陡峭**
|
||||||
|
- 概念多且复杂
|
||||||
|
- 抽象层次高
|
||||||
|
- 文档有时混乱
|
||||||
|
|
||||||
|
**2. 调试困难**
|
||||||
|
- 错误信息不够清晰
|
||||||
|
- 调用链路复杂
|
||||||
|
- 性能问题难定位
|
||||||
|
|
||||||
|
**3. API 变化频繁**
|
||||||
|
- 版本升级可能破坏兼容性
|
||||||
|
- 需要经常更新代码
|
||||||
|
|
||||||
|
#### 适用场景 🎯
|
||||||
|
|
||||||
|
✅ **推荐使用**:
|
||||||
|
- 复杂的 Agent 系统
|
||||||
|
- 需要 RAG 的应用
|
||||||
|
- 多 Agent 协作
|
||||||
|
- 需要丰富集成的场景
|
||||||
|
|
||||||
|
❌ **不推荐使用**:
|
||||||
|
- 简单的聊天应用
|
||||||
|
- 快速原型开发
|
||||||
|
- 团队技术水平一般
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.3 OpenAI Agents SDK
|
||||||
|
|
||||||
|
#### 优势 ✅
|
||||||
|
|
||||||
|
**1. 官方支持**
|
||||||
|
```typescript
|
||||||
|
import { Agent, run } from '@openai/agents';
|
||||||
|
|
||||||
|
const agent = new Agent({
|
||||||
|
name: "Assistant",
|
||||||
|
instructions: "You are a helpful assistant",
|
||||||
|
tools: [searchTool],
|
||||||
|
});
|
||||||
|
|
||||||
|
const result = await run(agent, "Hello");
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. 与 OpenAI API 深度集成**
|
||||||
|
- Handoffs(任务转交)
|
||||||
|
- Guardrails(行为约束)
|
||||||
|
- Tracing(执行追踪)
|
||||||
|
- MCP(模型上下文协议)
|
||||||
|
|
||||||
|
**3. 人机交互支持**
|
||||||
|
```typescript
|
||||||
|
// 支持人工审批
|
||||||
|
const result = await run(agent, message, {
|
||||||
|
onToolCall: async (toolCall) => {
|
||||||
|
// 人工审批
|
||||||
|
const approved = await askUser(toolCall);
|
||||||
|
return approved;
|
||||||
|
},
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. 可观测性强**
|
||||||
|
- 内置 Traces 仪表板
|
||||||
|
- 详细的执行日志
|
||||||
|
- 性能监控
|
||||||
|
|
||||||
|
#### 劣势 ❌
|
||||||
|
|
||||||
|
**1. 绑定 OpenAI**
|
||||||
|
- 只支持 OpenAI 模型
|
||||||
|
- 无法使用其他 LLM
|
||||||
|
|
||||||
|
**2. 相对较新**
|
||||||
|
- 生态还在建设中
|
||||||
|
- 社区规模较小
|
||||||
|
- 最佳实践较少
|
||||||
|
|
||||||
|
**3. 功能还在完善**
|
||||||
|
- 某些高级功能缺失
|
||||||
|
- 文档还不够完善
|
||||||
|
|
||||||
|
#### 适用场景 🎯
|
||||||
|
|
||||||
|
✅ **推荐使用**:
|
||||||
|
- 使用 OpenAI 模型的项目
|
||||||
|
- 需要官方支持的场景
|
||||||
|
- 需要人机交互的应用
|
||||||
|
- 需要强可观测性
|
||||||
|
|
||||||
|
❌ **不推荐使用**:
|
||||||
|
- 需要多 LLM 支持
|
||||||
|
- 成本敏感的项目
|
||||||
|
- 需要成熟生态
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.4 Mastra
|
||||||
|
|
||||||
|
#### 优势 ✅
|
||||||
|
|
||||||
|
**1. TypeScript 原生**
|
||||||
|
```typescript
|
||||||
|
import { Agent, createTool } from '@mastra/core';
|
||||||
|
|
||||||
|
const agent = new Agent({
|
||||||
|
name: 'Assistant',
|
||||||
|
instructions: 'You are helpful',
|
||||||
|
model: 'gpt-4',
|
||||||
|
tools: [searchTool],
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
**2. 开发者体验优先**
|
||||||
|
- API 设计简洁
|
||||||
|
- 文档清晰
|
||||||
|
- 示例丰富
|
||||||
|
|
||||||
|
**3. 内置 RAG 支持**
|
||||||
|
```typescript
|
||||||
|
import { createKnowledgeBase } from '@mastra/core';
|
||||||
|
|
||||||
|
const kb = createKnowledgeBase({
|
||||||
|
name: 'docs',
|
||||||
|
embeddings: openaiEmbeddings,
|
||||||
|
});
|
||||||
|
|
||||||
|
await kb.addDocuments(docs);
|
||||||
|
```
|
||||||
|
|
||||||
|
**4. 可视化工作流**
|
||||||
|
- 提供可视化设计器
|
||||||
|
- 便于理解和调试
|
||||||
|
|
||||||
|
#### 劣势 ❌
|
||||||
|
|
||||||
|
**1. 相对较新**
|
||||||
|
- 2024 年底发布
|
||||||
|
- 社区规模较小
|
||||||
|
- 生态还在建设
|
||||||
|
|
||||||
|
**2. 文档还在完善**
|
||||||
|
- 高级用例较少
|
||||||
|
- 最佳实践不够多
|
||||||
|
|
||||||
|
**3. 企业采用较少**
|
||||||
|
- 生产案例不多
|
||||||
|
- 稳定性待验证
|
||||||
|
|
||||||
|
#### 适用场景 🎯
|
||||||
|
|
||||||
|
✅ **推荐使用**:
|
||||||
|
- TypeScript 全栈项目
|
||||||
|
- 需要 RAG 的应用
|
||||||
|
- 快速原型开发
|
||||||
|
- 中小型项目
|
||||||
|
|
||||||
|
❌ **不推荐使用**:
|
||||||
|
- 大型企业项目
|
||||||
|
- 需要成熟生态
|
||||||
|
- 对稳定性要求极高
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、选型决策树
|
||||||
|
|
||||||
|
```
|
||||||
|
开始
|
||||||
|
│
|
||||||
|
├─ 是否只使用 OpenAI?
|
||||||
|
│ └─ 是 → OpenAI Agents SDK
|
||||||
|
│
|
||||||
|
├─ 是否需要复杂的多 Agent 协作?
|
||||||
|
│ └─ 是 → LangChain.js + LangGraph
|
||||||
|
│
|
||||||
|
├─ 是否需要快速开发简单应用?
|
||||||
|
│ └─ 是 → Vercel AI SDK ⭐
|
||||||
|
│
|
||||||
|
├─ 是否需要内置 RAG 支持?
|
||||||
|
│ ├─ 是,且需要成熟方案 → LangChain.js
|
||||||
|
│ └─ 是,且追求简洁 → Mastra
|
||||||
|
│
|
||||||
|
└─ 默认推荐 → Vercel AI SDK
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、实际项目对比
|
||||||
|
|
||||||
|
### 4.1 简单聊天机器人
|
||||||
|
|
||||||
|
**需求**:
|
||||||
|
- 基础对话
|
||||||
|
- 流式响应
|
||||||
|
- 简单工具调用
|
||||||
|
|
||||||
|
**推荐**:Vercel AI SDK ⭐⭐⭐⭐⭐
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
- API 简洁
|
||||||
|
- 流式响应优秀
|
||||||
|
- 开发速度快
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.2 知识库问答系统
|
||||||
|
|
||||||
|
**需求**:
|
||||||
|
- RAG 支持
|
||||||
|
- 向量检索
|
||||||
|
- 多轮对话
|
||||||
|
|
||||||
|
**推荐**:LangChain.js ⭐⭐⭐⭐⭐
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
- 内置 RAG 支持
|
||||||
|
- 向量数据库集成丰富
|
||||||
|
- 文档处理完善
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.3 客服机器人
|
||||||
|
|
||||||
|
**需求**:
|
||||||
|
- 多 Agent 协作
|
||||||
|
- 工作流编排
|
||||||
|
- 人工转接
|
||||||
|
|
||||||
|
**推荐**:LangChain.js + LangGraph ⭐⭐⭐⭐⭐
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
- 支持复杂工作流
|
||||||
|
- 多 Agent 协作成熟
|
||||||
|
- 状态管理强大
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.4 资讯分析助手(本项目)
|
||||||
|
|
||||||
|
**需求**:
|
||||||
|
- 基于报告/资讯的对话
|
||||||
|
- 工具调用(检索、分析)
|
||||||
|
- 流式响应
|
||||||
|
- 多 LLM 支持
|
||||||
|
|
||||||
|
**推荐**:Vercel AI SDK ⭐⭐⭐⭐⭐
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
- 功能需求匹配
|
||||||
|
- 学习成本低
|
||||||
|
- 开发效率高
|
||||||
|
- 与现有技术栈契合
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、成本对比
|
||||||
|
|
||||||
|
### 5.1 开发成本
|
||||||
|
|
||||||
|
| 框架 | 学习时间 | 开发时间 | 维护成本 |
|
||||||
|
|------|----------|----------|----------|
|
||||||
|
| Vercel AI SDK | 1-2 天 | 低 | 低 |
|
||||||
|
| LangChain.js | 1-2 周 | 中 | 中 |
|
||||||
|
| OpenAI Agents | 3-5 天 | 低 | 低 |
|
||||||
|
| Mastra | 2-3 天 | 低 | 中 |
|
||||||
|
|
||||||
|
### 5.2 运行成本
|
||||||
|
|
||||||
|
| 框架 | LLM 成本 | 基础设施 | 总成本 |
|
||||||
|
|------|----------|----------|--------|
|
||||||
|
| Vercel AI SDK | 标准 | 低 | 低 |
|
||||||
|
| LangChain.js | 标准 | 中 | 中 |
|
||||||
|
| OpenAI Agents | 仅 OpenAI | 低 | 中 |
|
||||||
|
| Mastra | 标准 | 低 | 低 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、迁移难度
|
||||||
|
|
||||||
|
### 6.1 从 Vercel AI SDK 迁移到其他框架
|
||||||
|
|
||||||
|
**到 LangChain.js**:⚠️ 中等难度
|
||||||
|
- 需要重写大部分代码
|
||||||
|
- 概念差异较大
|
||||||
|
- 预计 3-5 天
|
||||||
|
|
||||||
|
**到 OpenAI Agents**:🟢 较容易
|
||||||
|
- API 相似
|
||||||
|
- 概念接近
|
||||||
|
- 预计 1-2 天
|
||||||
|
|
||||||
|
**到 Mastra**:🟢 较容易
|
||||||
|
- API 相似
|
||||||
|
- 迁移成本低
|
||||||
|
- 预计 1-2 天
|
||||||
|
|
||||||
|
### 6.2 从 LangChain.js 迁移到其他框架
|
||||||
|
|
||||||
|
**到 Vercel AI SDK**:⚠️ 中等难度
|
||||||
|
- 需要简化架构
|
||||||
|
- 某些功能需要自己实现
|
||||||
|
- 预计 3-5 天
|
||||||
|
|
||||||
|
**到 OpenAI Agents**:🔴 困难
|
||||||
|
- 功能差异大
|
||||||
|
- 需要重新设计
|
||||||
|
- 预计 1-2 周
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、最终推荐
|
||||||
|
|
||||||
|
### 针对本项目(News Aggregator)
|
||||||
|
|
||||||
|
**首选**:Vercel AI SDK ⭐⭐⭐⭐⭐
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
1. ✅ 功能完全满足需求
|
||||||
|
2. ✅ 学习成本最低
|
||||||
|
3. ✅ 开发效率最高
|
||||||
|
4. ✅ 与现有技术栈(TypeScript + Node.js + Fastify)完美契合
|
||||||
|
5. ✅ 流式响应体验最好
|
||||||
|
6. ✅ 支持多 LLM 提供商
|
||||||
|
7. ✅ 社区活跃,文档清晰
|
||||||
|
|
||||||
|
**备选**:Mastra
|
||||||
|
|
||||||
|
**理由**:
|
||||||
|
- 如果未来需要内置 RAG 支持
|
||||||
|
- 如果需要可视化工作流
|
||||||
|
- 如果追求更现代的开发体验
|
||||||
|
|
||||||
|
**不推荐**:
|
||||||
|
- ❌ LangChain.js:过于复杂,学习成本高
|
||||||
|
- ❌ OpenAI Agents SDK:绑定 OpenAI,灵活性差
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、框架演进路线
|
||||||
|
|
||||||
|
### 当前阶段(MVP)
|
||||||
|
**使用**:Vercel AI SDK
|
||||||
|
**原因**:快速开发,验证需求
|
||||||
|
|
||||||
|
### 成长阶段(功能扩展)
|
||||||
|
**保持**:Vercel AI SDK
|
||||||
|
**增强**:自建 RAG、向量检索
|
||||||
|
|
||||||
|
### 成熟阶段(复杂需求)
|
||||||
|
**考虑**:
|
||||||
|
- 如需复杂多 Agent → 迁移到 LangChain.js
|
||||||
|
- 如需内置 RAG → 迁移到 Mastra
|
||||||
|
- 保持简单 → 继续 Vercel AI SDK
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、参考资源
|
||||||
|
|
||||||
|
### 官方文档
|
||||||
|
- [Vercel AI SDK](https://sdk.vercel.ai/docs)
|
||||||
|
- [LangChain.js](https://js.langchain.com/)
|
||||||
|
- [OpenAI Agents SDK](https://github.com/openai/openai-agents-js)
|
||||||
|
- [Mastra](https://mastra.ai/docs)
|
||||||
|
|
||||||
|
### 对比文章
|
||||||
|
- [AI SDK Comparison 2025](https://vercel.com/blog/ai-sdk-comparison)
|
||||||
|
- [LangChain vs Vercel AI SDK](https://www.js-craft.io/blog/langchain-vs-vercel-ai-sdk/)
|
||||||
|
|
||||||
|
### 社区讨论
|
||||||
|
- [Reddit: Best AI Agent Framework](https://reddit.com/r/typescript)
|
||||||
|
- [HN: AI Agent Frameworks Discussion](https://news.ycombinator.com)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**作者**: Claude Code
|
||||||
@@ -0,0 +1,782 @@
|
|||||||
|
# 任务 15:AI Agent 实施计划
|
||||||
|
|
||||||
|
## 📅 实施时间表
|
||||||
|
|
||||||
|
### 总体时间:5-7 个工作日
|
||||||
|
|
||||||
|
```
|
||||||
|
第 1 天:环境准备和基础设施
|
||||||
|
第 2 天:后端核心服务开发
|
||||||
|
第 3 天:工具系统和上下文管理
|
||||||
|
第 4 天:前端界面开发
|
||||||
|
第 5 天:集成测试和优化
|
||||||
|
第 6-7 天:部署和文档完善
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 1 天:环境准备和基础设施
|
||||||
|
|
||||||
|
### 上午(2-3 小时)
|
||||||
|
|
||||||
|
#### 1.1 安装依赖
|
||||||
|
```bash
|
||||||
|
# 后端依赖
|
||||||
|
cd backend
|
||||||
|
npm install ai @ai-sdk/openai zod
|
||||||
|
|
||||||
|
# 前端依赖
|
||||||
|
cd frontend
|
||||||
|
npm install markdown-it @types/markdown-it highlight.js
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 所有依赖安装成功
|
||||||
|
- [ ] 无版本冲突
|
||||||
|
- [ ] package.json 更新
|
||||||
|
|
||||||
|
#### 1.2 配置环境变量
|
||||||
|
```bash
|
||||||
|
# 创建 .env 文件
|
||||||
|
cp backend/.env.example backend/.env
|
||||||
|
|
||||||
|
# 配置必要的环境变量
|
||||||
|
DEFAULT_LLM_API_KEY=sk-xxx
|
||||||
|
DEFAULT_LLM_MODEL=gpt-4
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] .env 文件创建
|
||||||
|
- [ ] LLM API Key 配置
|
||||||
|
- [ ] 环境变量加载正常
|
||||||
|
|
||||||
|
### 下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 1.3 数据库设计和迁移
|
||||||
|
|
||||||
|
**步骤 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])
|
||||||
|
@@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")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**步骤 2:执行迁移**
|
||||||
|
```bash
|
||||||
|
cd backend
|
||||||
|
npx prisma migrate dev --name add_agent_tables
|
||||||
|
npx prisma generate
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] Schema 更新完成
|
||||||
|
- [ ] 迁移文件生成
|
||||||
|
- [ ] 数据库表创建成功
|
||||||
|
- [ ] Prisma Client 生成
|
||||||
|
|
||||||
|
#### 1.4 创建目录结构
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 后端目录
|
||||||
|
mkdir -p backend/src/services/agent/{tools,context,conversation}
|
||||||
|
mkdir -p backend/src/routes
|
||||||
|
|
||||||
|
# 前端目录
|
||||||
|
mkdir -p frontend/src/views/agent
|
||||||
|
mkdir -p frontend/src/components/agent
|
||||||
|
mkdir -p frontend/src/composables
|
||||||
|
mkdir -p frontend/src/api
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 目录结构创建完成
|
||||||
|
- [ ] 符合设计文档
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 2 天:后端核心服务开发
|
||||||
|
|
||||||
|
### 上午(3-4 小时)
|
||||||
|
|
||||||
|
#### 2.1 实现 ConversationManager
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/conversation/conversation.manager.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `getOrCreate()` 方法
|
||||||
|
- [ ] 实现 `addMessage()` 方法
|
||||||
|
- [ ] 实现 `getMessages()` 方法
|
||||||
|
- [ ] 实现 `getConversation()` 方法
|
||||||
|
- [ ] 实现 `getUserConversations()` 方法
|
||||||
|
- [ ] 实现 `deleteConversation()` 方法
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
// 创建简单测试
|
||||||
|
const manager = new ConversationManager();
|
||||||
|
const conv = await manager.getOrCreate({
|
||||||
|
topicId: 1,
|
||||||
|
userId: 'test',
|
||||||
|
});
|
||||||
|
console.log('Conversation created:', conv.id);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 所有方法实现完成
|
||||||
|
- [ ] 基础测试通过
|
||||||
|
- [ ] 错误处理完善
|
||||||
|
|
||||||
|
#### 2.2 实现 ContextLoader
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/context/context-loader.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `load()` 方法
|
||||||
|
- [ ] 实现 `loadReportArticles()` 方法
|
||||||
|
- [ ] 实现 `loadRelatedArticles()` 方法
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const loader = new ContextLoader();
|
||||||
|
const context = await loader.load({
|
||||||
|
topicId: 1,
|
||||||
|
reportId: 1,
|
||||||
|
});
|
||||||
|
console.log('Context loaded:', context);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 上下文加载正常
|
||||||
|
- [ ] 相关资讯查询正确
|
||||||
|
- [ ] 性能可接受(< 200ms)
|
||||||
|
|
||||||
|
### 下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 2.3 实现 PromptBuilder
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/context/prompt-builder.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `build()` 方法
|
||||||
|
- [ ] 实现 `buildRolePrompt()` 方法
|
||||||
|
- [ ] 实现 `buildContextPrompt()` 方法
|
||||||
|
- [ ] 实现 `buildCapabilitiesPrompt()` 方法
|
||||||
|
- [ ] 实现 `buildGuidelinesPrompt()` 方法
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const builder = new PromptBuilder();
|
||||||
|
const prompt = builder.build(context);
|
||||||
|
console.log('Prompt length:', prompt.length);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] Prompt 结构清晰
|
||||||
|
- [ ] 包含所有必要信息
|
||||||
|
- [ ] 长度控制合理
|
||||||
|
|
||||||
|
#### 2.4 实现 AgentService(基础版)
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/agent.service.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现构造函数
|
||||||
|
- [ ] 实现 `streamChat()` 方法(不含工具)
|
||||||
|
- [ ] 实现 `saveAssistantMessage()` 方法
|
||||||
|
- [ ] 实现 `getConversation()` 方法
|
||||||
|
- [ ] 实现 `getUserConversations()` 方法
|
||||||
|
- [ ] 实现 `deleteConversation()` 方法
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const service = new AgentService();
|
||||||
|
const result = await service.streamChat({
|
||||||
|
topicId: 1,
|
||||||
|
message: 'Hello',
|
||||||
|
llmConfigId: 1,
|
||||||
|
});
|
||||||
|
console.log('Stream created');
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 基础对话功能正常
|
||||||
|
- [ ] 流式响应工作
|
||||||
|
- [ ] 消息保存正确
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 3 天:工具系统和上下文管理
|
||||||
|
|
||||||
|
### 上午(3-4 小时)
|
||||||
|
|
||||||
|
#### 3.1 实现 ArticleSearchTool
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/tools/article-search.tool.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 定义工具参数 Schema
|
||||||
|
- [ ] 实现 `execute()` 方法
|
||||||
|
- [ ] 添加全文搜索支持
|
||||||
|
- [ ] 优化查询性能
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const tool = ArticleSearchTool.create();
|
||||||
|
const result = await tool.execute({
|
||||||
|
query: 'AI',
|
||||||
|
limit: 10,
|
||||||
|
});
|
||||||
|
console.log('Found articles:', result.count);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 搜索功能正常
|
||||||
|
- [ ] 结果相关性高
|
||||||
|
- [ ] 性能可接受(< 500ms)
|
||||||
|
|
||||||
|
#### 3.2 实现 ReportAnalysisTool
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/tools/report-analysis.tool.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 定义工具参数 Schema
|
||||||
|
- [ ] 实现 `execute()` 方法
|
||||||
|
- [ ] 支持多种分析类型
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const tool = ReportAnalysisTool.create();
|
||||||
|
const result = await tool.execute({
|
||||||
|
reportId: 1,
|
||||||
|
analysisType: 'summary',
|
||||||
|
});
|
||||||
|
console.log('Analysis result:', result);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 报告分析正常
|
||||||
|
- [ ] 支持的分析类型完整
|
||||||
|
- [ ] 返回结果结构清晰
|
||||||
|
|
||||||
|
#### 3.3 实现 WebSearchTool(占位符)
|
||||||
|
|
||||||
|
**文件**:`backend/src/services/agent/tools/web-search.tool.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 定义工具参数 Schema
|
||||||
|
- [ ] 实现占位符 `execute()` 方法
|
||||||
|
- [ ] 添加 TODO 注释
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 工具定义完整
|
||||||
|
- [ ] 占位符实现正确
|
||||||
|
- [ ] 文档说明清晰
|
||||||
|
|
||||||
|
### 下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 3.4 集成工具到 AgentService
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 在 `streamChat()` 中添加工具定义
|
||||||
|
- [ ] 配置 `maxSteps` 参数
|
||||||
|
- [ ] 测试工具调用流程
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const result = await service.streamChat({
|
||||||
|
topicId: 1,
|
||||||
|
message: '搜索最新的 AI 新闻',
|
||||||
|
llmConfigId: 1,
|
||||||
|
});
|
||||||
|
// 验证工具被调用
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 工具调用正常
|
||||||
|
- [ ] 多步调用工作
|
||||||
|
- [ ] 工具结果正确返回
|
||||||
|
|
||||||
|
#### 3.5 实现 API 路由
|
||||||
|
|
||||||
|
**文件**:`backend/src/routes/agent.routes.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `POST /api/agent/chat`
|
||||||
|
- [ ] 实现 `GET /api/agent/conversations/:id`
|
||||||
|
- [ ] 实现 `GET /api/agent/conversations`
|
||||||
|
- [ ] 实现 `DELETE /api/agent/conversations/:id`
|
||||||
|
- [ ] 添加错误处理
|
||||||
|
- [ ] 添加输入验证
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```bash
|
||||||
|
# 测试对话 API
|
||||||
|
curl -X POST http://localhost:3000/api/agent/chat \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-d '{"topicId":1,"message":"Hello","llmConfigId":1}'
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 所有路由实现完成
|
||||||
|
- [ ] API 响应正确
|
||||||
|
- [ ] 错误处理完善
|
||||||
|
- [ ] 输入验证有效
|
||||||
|
|
||||||
|
#### 3.6 注册路由
|
||||||
|
|
||||||
|
**文件**:`backend/src/app.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
```typescript
|
||||||
|
import { agentRoutes } from './routes/agent.routes';
|
||||||
|
|
||||||
|
fastify.register(agentRoutes, { prefix: '/api/agent' });
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 路由注册成功
|
||||||
|
- [ ] API 可访问
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 4 天:前端界面开发
|
||||||
|
|
||||||
|
### 上午(3-4 小时)
|
||||||
|
|
||||||
|
#### 4.1 实现 API 封装
|
||||||
|
|
||||||
|
**文件**:`frontend/src/api/agent.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `streamChat()` 函数
|
||||||
|
- [ ] 实现 `getConversation()` 函数
|
||||||
|
- [ ] 实现 `getConversations()` 函数
|
||||||
|
- [ ] 实现 `deleteConversation()` 函数
|
||||||
|
- [ ] 定义 TypeScript 类型
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] API 封装完成
|
||||||
|
- [ ] 类型定义完整
|
||||||
|
- [ ] 错误处理完善
|
||||||
|
|
||||||
|
#### 4.2 实现 useAgentChat Hook
|
||||||
|
|
||||||
|
**文件**:`frontend/src/composables/useAgentChat.ts`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现 `sendMessage()` 方法
|
||||||
|
- [ ] 实现流式响应处理
|
||||||
|
- [ ] 实现 `clearMessages()` 方法
|
||||||
|
- [ ] 实现 `loadMessages()` 方法
|
||||||
|
- [ ] 添加状态管理
|
||||||
|
|
||||||
|
**测试**:
|
||||||
|
```typescript
|
||||||
|
const { messages, sendMessage } = useAgentChat();
|
||||||
|
await sendMessage({
|
||||||
|
topicId: 1,
|
||||||
|
message: 'Hello',
|
||||||
|
llmConfigId: 1,
|
||||||
|
});
|
||||||
|
console.log('Messages:', messages.value);
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] Hook 功能完整
|
||||||
|
- [ ] 流式响应正常
|
||||||
|
- [ ] 状态管理正确
|
||||||
|
|
||||||
|
### 下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 4.3 实现 MessageItem 组件
|
||||||
|
|
||||||
|
**文件**:`frontend/src/components/agent/MessageItem.vue`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现消息布局
|
||||||
|
- [ ] 实现 Markdown 渲染
|
||||||
|
- [ ] 实现代码高亮
|
||||||
|
- [ ] 实现流式输出动画
|
||||||
|
- [ ] 添加样式
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 消息显示正常
|
||||||
|
- [ ] Markdown 渲染正确
|
||||||
|
- [ ] 代码高亮工作
|
||||||
|
- [ ] 动画流畅
|
||||||
|
|
||||||
|
#### 4.4 实现 ToolCallDisplay 组件
|
||||||
|
|
||||||
|
**文件**:`frontend/src/components/agent/ToolCallDisplay.vue`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现工具调用展示
|
||||||
|
- [ ] 实现折叠/展开功能
|
||||||
|
- [ ] 格式化 JSON 显示
|
||||||
|
- [ ] 添加样式
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 工具调用显示清晰
|
||||||
|
- [ ] 交互流畅
|
||||||
|
- [ ] 样式美观
|
||||||
|
|
||||||
|
#### 4.5 实现 AgentChat 组件
|
||||||
|
|
||||||
|
**文件**:`frontend/src/views/agent/AgentChat.vue`
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 实现对话界面布局
|
||||||
|
- [ ] 集成 MessageItem 组件
|
||||||
|
- [ ] 实现输入区域
|
||||||
|
- [ ] 实现自动滚动
|
||||||
|
- [ ] 添加加载状态
|
||||||
|
- [ ] 添加错误提示
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 界面布局合理
|
||||||
|
- [ ] 功能完整
|
||||||
|
- [ ] 用户体验良好
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 5 天:集成测试和优化
|
||||||
|
|
||||||
|
### 上午(3-4 小时)
|
||||||
|
|
||||||
|
#### 5.1 端到端测试
|
||||||
|
|
||||||
|
**测试场景**:
|
||||||
|
|
||||||
|
**场景 1:基础对话**
|
||||||
|
```typescript
|
||||||
|
// 1. 打开对话页面
|
||||||
|
// 2. 输入消息
|
||||||
|
// 3. 验证响应
|
||||||
|
// 4. 验证消息保存
|
||||||
|
```
|
||||||
|
|
||||||
|
**场景 2:工具调用**
|
||||||
|
```typescript
|
||||||
|
// 1. 输入需要工具的问题
|
||||||
|
// 2. 验证工具被调用
|
||||||
|
// 3. 验证工具结果显示
|
||||||
|
// 4. 验证最终回答
|
||||||
|
```
|
||||||
|
|
||||||
|
**场景 3:多轮对话**
|
||||||
|
```typescript
|
||||||
|
// 1. 发送第一条消息
|
||||||
|
// 2. 发送第二条消息
|
||||||
|
// 3. 验证上下文保持
|
||||||
|
// 4. 验证历史消息显示
|
||||||
|
```
|
||||||
|
|
||||||
|
**场景 4:基于报告的对话**
|
||||||
|
```typescript
|
||||||
|
// 1. 选择报告
|
||||||
|
// 2. 开始对话
|
||||||
|
// 3. 验证报告内容加载
|
||||||
|
// 4. 验证回答基于报告
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 所有场景测试通过
|
||||||
|
- [ ] 无明显 Bug
|
||||||
|
- [ ] 用户体验流畅
|
||||||
|
|
||||||
|
#### 5.2 性能测试
|
||||||
|
|
||||||
|
**测试项**:
|
||||||
|
- [ ] 首字响应时间 < 2s
|
||||||
|
- [ ] 平均响应时间 < 5s
|
||||||
|
- [ ] 上下文加载时间 < 200ms
|
||||||
|
- [ ] 工具调用延迟 < 500ms
|
||||||
|
- [ ] 并发 10 个对话无问题
|
||||||
|
|
||||||
|
**优化方向**:
|
||||||
|
- [ ] 添加缓存
|
||||||
|
- [ ] 优化数据库查询
|
||||||
|
- [ ] 压缩上下文
|
||||||
|
- [ ] 限制历史消息数量
|
||||||
|
|
||||||
|
### 下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 5.3 错误处理完善
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 添加全局错误处理
|
||||||
|
- [ ] 添加输入验证
|
||||||
|
- [ ] 添加速率限制
|
||||||
|
- [ ] 添加超时处理
|
||||||
|
- [ ] 添加友好错误提示
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 错误处理完善
|
||||||
|
- [ ] 用户提示友好
|
||||||
|
- [ ] 系统稳定性高
|
||||||
|
|
||||||
|
#### 5.4 日志和监控
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 添加关键操作日志
|
||||||
|
- [ ] 添加性能指标记录
|
||||||
|
- [ ] 添加错误日志
|
||||||
|
- [ ] 配置日志级别
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 日志完整
|
||||||
|
- [ ] 便于调试
|
||||||
|
- [ ] 便于监控
|
||||||
|
|
||||||
|
#### 5.5 代码审查和重构
|
||||||
|
|
||||||
|
**检查项**:
|
||||||
|
- [ ] 代码风格一致
|
||||||
|
- [ ] 注释完整
|
||||||
|
- [ ] 类型定义完整
|
||||||
|
- [ ] 无冗余代码
|
||||||
|
- [ ] 性能优化
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 代码质量高
|
||||||
|
- [ ] 可维护性好
|
||||||
|
- [ ] 符合最佳实践
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 第 6-7 天:部署和文档完善
|
||||||
|
|
||||||
|
### 第 6 天上午(3-4 小时)
|
||||||
|
|
||||||
|
#### 6.1 生产环境配置
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 创建 `.env.production`
|
||||||
|
- [ ] 配置生产数据库
|
||||||
|
- [ ] 配置 CORS
|
||||||
|
- [ ] 配置日志级别
|
||||||
|
- [ ] 配置超时参数
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 配置文件完整
|
||||||
|
- [ ] 环境变量正确
|
||||||
|
- [ ] 安全性检查通过
|
||||||
|
|
||||||
|
#### 6.2 构建和部署
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
```bash
|
||||||
|
# 后端构建
|
||||||
|
cd backend
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 前端构建
|
||||||
|
cd frontend
|
||||||
|
npm run build
|
||||||
|
|
||||||
|
# 部署
|
||||||
|
pm2 start ecosystem.config.js
|
||||||
|
```
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 构建成功
|
||||||
|
- [ ] 部署成功
|
||||||
|
- [ ] 服务正常运行
|
||||||
|
|
||||||
|
### 第 6 天下午(3-4 小时)
|
||||||
|
|
||||||
|
#### 6.3 生产环境测试
|
||||||
|
|
||||||
|
**测试项**:
|
||||||
|
- [ ] API 可访问
|
||||||
|
- [ ] 前端页面正常
|
||||||
|
- [ ] 对话功能正常
|
||||||
|
- [ ] 工具调用正常
|
||||||
|
- [ ] 性能符合预期
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 所有功能正常
|
||||||
|
- [ ] 性能达标
|
||||||
|
- [ ] 无明显问题
|
||||||
|
|
||||||
|
#### 6.4 监控配置
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 配置 PM2 监控
|
||||||
|
- [ ] 配置日志收集
|
||||||
|
- [ ] 配置告警规则
|
||||||
|
- [ ] 配置备份策略
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 监控正常
|
||||||
|
- [ ] 告警有效
|
||||||
|
- [ ] 备份策略完善
|
||||||
|
|
||||||
|
### 第 7 天(全天)
|
||||||
|
|
||||||
|
#### 6.5 文档完善
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 完善 API 文档
|
||||||
|
- [ ] 完善部署文档
|
||||||
|
- [ ] 完善故障排查文档
|
||||||
|
- [ ] 编写用户手册
|
||||||
|
- [ ] 编写开发指南
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 文档完整
|
||||||
|
- [ ] 文档准确
|
||||||
|
- [ ] 易于理解
|
||||||
|
|
||||||
|
#### 6.6 知识转移
|
||||||
|
|
||||||
|
**任务**:
|
||||||
|
- [ ] 团队培训
|
||||||
|
- [ ] 代码走查
|
||||||
|
- [ ] 问题答疑
|
||||||
|
- [ ] 交接文档
|
||||||
|
|
||||||
|
**验收标准**:
|
||||||
|
- [ ] 团队成员理解系统
|
||||||
|
- [ ] 能够独立维护
|
||||||
|
- [ ] 文档齐全
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ✅ 最终验收清单
|
||||||
|
|
||||||
|
### 功能完整性
|
||||||
|
- [ ] 基础对话功能
|
||||||
|
- [ ] 流式响应
|
||||||
|
- [ ] 工具调用(资讯检索、报告分析)
|
||||||
|
- [ ] 多轮对话
|
||||||
|
- [ ] 上下文管理
|
||||||
|
- [ ] 对话历史
|
||||||
|
- [ ] 对话列表
|
||||||
|
- [ ] 对话删除
|
||||||
|
|
||||||
|
### 性能指标
|
||||||
|
- [ ] 首字响应时间 < 2s
|
||||||
|
- [ ] 平均响应时间 < 5s
|
||||||
|
- [ ] 上下文加载 < 200ms
|
||||||
|
- [ ] 工具调用 < 500ms
|
||||||
|
- [ ] 支持并发 100+
|
||||||
|
|
||||||
|
### 代码质量
|
||||||
|
- [ ] 代码风格一致
|
||||||
|
- [ ] 类型定义完整
|
||||||
|
- [ ] 注释清晰
|
||||||
|
- [ ] 无明显技术债
|
||||||
|
- [ ] 测试覆盖充分
|
||||||
|
|
||||||
|
### 文档完整性
|
||||||
|
- [ ] 架构文档
|
||||||
|
- [ ] API 文档
|
||||||
|
- [ ] 部署文档
|
||||||
|
- [ ] 用户手册
|
||||||
|
- [ ] 开发指南
|
||||||
|
|
||||||
|
### 安全性
|
||||||
|
- [ ] 输入验证
|
||||||
|
- [ ] 速率限制
|
||||||
|
- [ ] 敏感信息过滤
|
||||||
|
- [ ] 错误处理
|
||||||
|
- [ ] 日志脱敏
|
||||||
|
|
||||||
|
### 可维护性
|
||||||
|
- [ ] 代码结构清晰
|
||||||
|
- [ ] 模块化设计
|
||||||
|
- [ ] 易于扩展
|
||||||
|
- [ ] 日志完善
|
||||||
|
- [ ] 监控到位
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚨 风险和应对
|
||||||
|
|
||||||
|
### 风险 1:LLM API 不稳定
|
||||||
|
**应对**:
|
||||||
|
- 添加重试机制
|
||||||
|
- 配置超时
|
||||||
|
- 准备备用 API
|
||||||
|
|
||||||
|
### 风险 2:性能不达标
|
||||||
|
**应对**:
|
||||||
|
- 优化数据库查询
|
||||||
|
- 添加缓存
|
||||||
|
- 压缩上下文
|
||||||
|
- 使用更快的模型
|
||||||
|
|
||||||
|
### 风险 3:工具调用失败
|
||||||
|
**应对**:
|
||||||
|
- 完善错误处理
|
||||||
|
- 添加降级策略
|
||||||
|
- 提供友好提示
|
||||||
|
|
||||||
|
### 风险 4:用户体验不佳
|
||||||
|
**应对**:
|
||||||
|
- 优化 UI 交互
|
||||||
|
- 添加加载状态
|
||||||
|
- 提供清晰反馈
|
||||||
|
- 收集用户反馈
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📊 进度跟踪
|
||||||
|
|
||||||
|
### 每日站会
|
||||||
|
- 昨天完成了什么
|
||||||
|
- 今天计划做什么
|
||||||
|
- 遇到什么问题
|
||||||
|
|
||||||
|
### 每日检查
|
||||||
|
- [ ] 代码提交
|
||||||
|
- [ ] 测试通过
|
||||||
|
- [ ] 文档更新
|
||||||
|
- [ ] 问题记录
|
||||||
|
|
||||||
|
### 里程碑
|
||||||
|
- [ ] Day 1: 基础设施完成
|
||||||
|
- [ ] Day 2: 后端核心完成
|
||||||
|
- [ ] Day 3: 工具系统完成
|
||||||
|
- [ ] Day 4: 前端界面完成
|
||||||
|
- [ ] Day 5: 测试和优化完成
|
||||||
|
- [ ] Day 6-7: 部署和文档完成
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.0
|
||||||
|
**创建日期**: 2026-02-05
|
||||||
|
**维护者**: Claude Code
|
||||||
@@ -0,0 +1,675 @@
|
|||||||
|
# 任务 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)
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_API_BASE_URL=http://localhost:3000/api/v1
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
VITE_API_BASE_URL=/api/v1
|
||||||
Generated
+1364
-67
File diff suppressed because it is too large.
Load diff
@@ -10,16 +10,29 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@element-plus/icons-vue": "^2.3.2",
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
|
"@types/markdown-it": "^14.1.2",
|
||||||
|
"@vueuse/core": "^14.2.0",
|
||||||
"axios": "^1.13.4",
|
"axios": "^1.13.4",
|
||||||
|
"clsx": "^2.1.1",
|
||||||
|
"echarts": "^6.0.0",
|
||||||
"element-plus": "^2.13.2",
|
"element-plus": "^2.13.2",
|
||||||
|
"highlight.js": "^11.11.1",
|
||||||
|
"lucide-vue-next": "^0.563.0",
|
||||||
|
"markdown-it": "^14.1.0",
|
||||||
"pinia": "^3.0.4",
|
"pinia": "^3.0.4",
|
||||||
|
"tailwind-merge": "^3.4.0",
|
||||||
"vue": "^3.5.24",
|
"vue": "^3.5.24",
|
||||||
|
"vue-echarts": "^8.0.1",
|
||||||
"vue-router": "^4.6.4"
|
"vue-router": "^4.6.4"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
|
"@tailwindcss/typography": "^0.5.19",
|
||||||
"@types/node": "^24.10.9",
|
"@types/node": "^24.10.9",
|
||||||
"@vitejs/plugin-vue": "^6.0.1",
|
"@vitejs/plugin-vue": "^6.0.1",
|
||||||
"@vue/tsconfig": "^0.8.1",
|
"@vue/tsconfig": "^0.8.1",
|
||||||
|
"autoprefixer": "^10.4.24",
|
||||||
|
"postcss": "^8.5.6",
|
||||||
|
"tailwindcss": "^3.4.17",
|
||||||
"typescript": "~5.9.3",
|
"typescript": "~5.9.3",
|
||||||
"vite": "^7.2.4",
|
"vite": "^7.2.4",
|
||||||
"vue-tsc": "^3.1.4"
|
"vue-tsc": "^3.1.4"
|
||||||
|
|||||||
@@ -0,0 +1,6 @@
|
|||||||
|
export default {
|
||||||
|
plugins: {
|
||||||
|
tailwindcss: {},
|
||||||
|
autoprefixer: {},
|
||||||
|
},
|
||||||
|
}
|
||||||
+11
-25
@@ -1,30 +1,16 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import HelloWorld from './components/HelloWorld.vue'
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<div>
|
<div class="min-h-screen bg-background text-foreground font-sans antialiased">
|
||||||
<a href="https://vite.dev" target="_blank">
|
<router-view />
|
||||||
<img src="/vite.svg" class="logo" alt="Vite logo" />
|
|
||||||
</a>
|
|
||||||
<a href="https://vuejs.org/" target="_blank">
|
|
||||||
<img src="./assets/vue.svg" class="logo vue" alt="Vue logo" />
|
|
||||||
</a>
|
|
||||||
</div>
|
</div>
|
||||||
<HelloWorld msg="Vite + Vue" />
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<style scoped>
|
<script setup lang="ts">
|
||||||
.logo {
|
import { useUserStore } from '@/stores/user'
|
||||||
height: 6em;
|
|
||||||
padding: 1.5em;
|
const userStore = useUserStore()
|
||||||
will-change: filter;
|
userStore.initToken()
|
||||||
transition: filter 300ms;
|
</script>
|
||||||
}
|
|
||||||
.logo:hover {
|
<style>
|
||||||
filter: drop-shadow(0 0 2em #646cffaa);
|
/* Reset or global overrides if necessary */
|
||||||
}
|
|
||||||
.logo.vue:hover {
|
|
||||||
filter: drop-shadow(0 0 2em #42b883aa);
|
|
||||||
}
|
|
||||||
</style>
|
</style>
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import request from './request'
|
||||||
|
|
||||||
|
export interface ChatParams {
|
||||||
|
conversationId?: number
|
||||||
|
reportId?: number
|
||||||
|
articleId?: number
|
||||||
|
topicId: number
|
||||||
|
message: string
|
||||||
|
llmConfigId: number
|
||||||
|
userId?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Message {
|
||||||
|
id?: number
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
toolCalls?: any
|
||||||
|
createdAt?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Conversation {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
topicId: number
|
||||||
|
reportId?: number
|
||||||
|
articleId?: number
|
||||||
|
userId?: number
|
||||||
|
messages: Message[]
|
||||||
|
messageCount?: number
|
||||||
|
lastMessage?: {
|
||||||
|
role: string
|
||||||
|
content: string
|
||||||
|
createdAt: string
|
||||||
|
}
|
||||||
|
topic?: {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
}
|
||||||
|
report?: {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
}
|
||||||
|
article?: {
|
||||||
|
id: number
|
||||||
|
title: string
|
||||||
|
}
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 流式对话
|
||||||
|
*/
|
||||||
|
export async function streamChat(params: ChatParams): Promise<Response> {
|
||||||
|
const response = await fetch('/api/v1/agent/chat', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
},
|
||||||
|
body: JSON.stringify(params),
|
||||||
|
})
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
const error = await response.json()
|
||||||
|
throw new Error(error.error || '请求失败')
|
||||||
|
}
|
||||||
|
|
||||||
|
return response
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取对话详情
|
||||||
|
*/
|
||||||
|
export async function getConversation(id: number): Promise<Conversation> {
|
||||||
|
const res = await request.get<Conversation>(`/agent/conversations/${id}`)
|
||||||
|
return res.data ?? res as any
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取对话列表
|
||||||
|
*/
|
||||||
|
export async function getConversations(params?: {
|
||||||
|
userId?: number
|
||||||
|
topicId?: number
|
||||||
|
}): Promise<Conversation[]> {
|
||||||
|
const res = await request.get<Conversation[]>('/agent/conversations', { params })
|
||||||
|
return res.data ?? res as any ?? []
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除对话
|
||||||
|
*/
|
||||||
|
export async function deleteConversation(id: number): Promise<void> {
|
||||||
|
await request.delete(`/agent/conversations/${id}`)
|
||||||
|
}
|
||||||
@@ -0,0 +1,103 @@
|
|||||||
|
import axios from 'axios'
|
||||||
|
import type { AxiosInstance, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
|
||||||
|
// API 响应类型
|
||||||
|
export interface ApiResponse<T = any> {
|
||||||
|
success: boolean
|
||||||
|
data: T
|
||||||
|
pagination?: {
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
totalPages: number
|
||||||
|
}
|
||||||
|
message?: string
|
||||||
|
error?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建 axios 实例
|
||||||
|
const service: AxiosInstance = axios.create({
|
||||||
|
baseURL: import.meta.env.VITE_API_BASE_URL || '/api/v1',
|
||||||
|
timeout: 30000,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 请求拦截器
|
||||||
|
service.interceptors.request.use(
|
||||||
|
(config: InternalAxiosRequestConfig) => {
|
||||||
|
return config
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
console.error('Request error:', error)
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// 响应拦截器
|
||||||
|
service.interceptors.response.use(
|
||||||
|
(response: AxiosResponse): any => {
|
||||||
|
const res = response.data
|
||||||
|
|
||||||
|
// 如果响应格式不是标准格式,直接返回
|
||||||
|
if (res.success === undefined) {
|
||||||
|
return res
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理业务错误
|
||||||
|
if (!res.success) {
|
||||||
|
ElMessage.error(res.error || '请求失败')
|
||||||
|
return Promise.reject(new Error(res.error || '请求失败'))
|
||||||
|
}
|
||||||
|
|
||||||
|
// 返回包含 data 和 pagination 的完整响应
|
||||||
|
return res
|
||||||
|
},
|
||||||
|
(error) => {
|
||||||
|
console.error('Response error:', error)
|
||||||
|
|
||||||
|
// 处理 HTTP 错误
|
||||||
|
if (error.response) {
|
||||||
|
const status = error.response.status
|
||||||
|
switch (status) {
|
||||||
|
case 401:
|
||||||
|
ElMessage.error('未授权,请登录')
|
||||||
|
break
|
||||||
|
case 403:
|
||||||
|
ElMessage.error('拒绝访问')
|
||||||
|
break
|
||||||
|
case 404:
|
||||||
|
ElMessage.error('请求的资源不存在')
|
||||||
|
break
|
||||||
|
case 500:
|
||||||
|
ElMessage.error('服务器错误')
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
ElMessage.error(error.response.data?.error || '请求失败')
|
||||||
|
}
|
||||||
|
} else if (error.request) {
|
||||||
|
ElMessage.error('网络错误,请检查网络连接')
|
||||||
|
} else {
|
||||||
|
ElMessage.error('请求配置错误')
|
||||||
|
}
|
||||||
|
|
||||||
|
return Promise.reject(error)
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
// 封装请求方法
|
||||||
|
const request = {
|
||||||
|
get<T = any>(url: string, config?: any): Promise<ApiResponse<T>> {
|
||||||
|
return service.get(url, config)
|
||||||
|
},
|
||||||
|
post<T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
|
||||||
|
return service.post(url, data, config)
|
||||||
|
},
|
||||||
|
put<T = any>(url: string, data?: any, config?: any): Promise<ApiResponse<T>> {
|
||||||
|
return service.put(url, data, config)
|
||||||
|
},
|
||||||
|
delete<T = any>(url: string, config?: any): Promise<ApiResponse<T>> {
|
||||||
|
return service.delete(url, config)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
export default request
|
||||||
@@ -0,0 +1,127 @@
|
|||||||
|
// 分页参数
|
||||||
|
export interface PaginationParams {
|
||||||
|
page?: number
|
||||||
|
limit?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页信息
|
||||||
|
export interface Pagination {
|
||||||
|
total: number
|
||||||
|
page: number
|
||||||
|
limit: number
|
||||||
|
totalPages: number
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页响应
|
||||||
|
export interface PaginatedResponse<T> {
|
||||||
|
success: boolean
|
||||||
|
data: T[]
|
||||||
|
pagination: Pagination
|
||||||
|
}
|
||||||
|
|
||||||
|
// LLM 配置
|
||||||
|
export interface LlmConfig {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
baseUrl: string
|
||||||
|
model: string
|
||||||
|
apiKey: string
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 数据源
|
||||||
|
export interface Source {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: 'api' | 'playwright' | 'rss'
|
||||||
|
config: Record<string, any>
|
||||||
|
cronExpression: string
|
||||||
|
enabled: boolean
|
||||||
|
lastCollectedAt: string | null
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 推送渠道
|
||||||
|
export interface Channel {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: 'email' | 'dingtalk' | 'wechat' | 'slack'
|
||||||
|
config: Record<string, any>
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// 主题
|
||||||
|
export interface Topic {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
description: string | null
|
||||||
|
processMode: 'aggregate' | 'summary' | 'deep_analysis'
|
||||||
|
llmConfigId: number | null
|
||||||
|
scheduleConfig: Record<string, any>
|
||||||
|
enabled: boolean
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
llmConfig?: LlmConfig
|
||||||
|
topicSources?: Array<{ source: Source }>
|
||||||
|
topicChannels?: Array<{ channel: Channel }>
|
||||||
|
}
|
||||||
|
|
||||||
|
// 报告
|
||||||
|
export interface Report {
|
||||||
|
id: number
|
||||||
|
topicId: number
|
||||||
|
title: string
|
||||||
|
content: string
|
||||||
|
periodStart: string
|
||||||
|
periodEnd: string
|
||||||
|
status: 'pending' | 'generating' | 'completed' | 'failed'
|
||||||
|
errorMessage: string | null
|
||||||
|
articleCount: number
|
||||||
|
createdAt: string
|
||||||
|
updatedAt: string
|
||||||
|
topic?: Topic
|
||||||
|
}
|
||||||
|
|
||||||
|
// 资讯
|
||||||
|
export interface Article {
|
||||||
|
id: number
|
||||||
|
sourceId: number
|
||||||
|
title: string
|
||||||
|
content: string | null
|
||||||
|
summary: string | null
|
||||||
|
url: string | null
|
||||||
|
publishedAt: string | null
|
||||||
|
collectedAt: string
|
||||||
|
createdAt: string
|
||||||
|
source?: Source
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集日志
|
||||||
|
export interface CollectionLog {
|
||||||
|
id: number
|
||||||
|
sourceId: number
|
||||||
|
status: 'success' | 'failed' | 'running'
|
||||||
|
errorMessage: string | null
|
||||||
|
articlesCount: number
|
||||||
|
startedAt: string
|
||||||
|
finishedAt: string | null
|
||||||
|
createdAt: string
|
||||||
|
source?: Source
|
||||||
|
}
|
||||||
|
|
||||||
|
// 采集统计
|
||||||
|
export interface CollectionStats {
|
||||||
|
id: number
|
||||||
|
name: string
|
||||||
|
type: string
|
||||||
|
enabled: boolean
|
||||||
|
totalArticles: number
|
||||||
|
totalCollections: number
|
||||||
|
lastCollectedAt: string | null
|
||||||
|
lastLog: CollectionLog | null
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<template>
|
||||||
|
<div :class="['flex gap-4 mb-6 group', message.role === 'user' ? 'flex-row-reverse' : '']">
|
||||||
|
<!-- Avatar -->
|
||||||
|
<div
|
||||||
|
:class="[
|
||||||
|
'flex h-8 w-8 shrink-0 select-none items-center justify-center rounded-md border shadow',
|
||||||
|
message.role === 'user' ? 'bg-background' : 'bg-primary text-primary-foreground'
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<User v-if="message.role === 'user'" class="h-4 w-4" />
|
||||||
|
<Bot v-else class="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Content Wrapper -->
|
||||||
|
<div :class="['flex max-w-[85%] flex-col gap-2', message.role === 'user' ? 'items-end' : 'items-start']">
|
||||||
|
<!-- Header Info -->
|
||||||
|
<div class="flex items-center gap-2 text-xs text-muted-foreground">
|
||||||
|
<span class="font-medium">{{ roleLabel }}</span>
|
||||||
|
<span>{{ formattedTime }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Message Bubble -->
|
||||||
|
<div
|
||||||
|
:class="[
|
||||||
|
'relative overflow-hidden rounded-md border px-3 py-2 text-sm shadow-sm',
|
||||||
|
message.role === 'user'
|
||||||
|
? 'bg-primary text-primary-foreground border-primary'
|
||||||
|
: 'bg-card text-card-foreground'
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<!-- Markdown Content -->
|
||||||
|
<div
|
||||||
|
v-if="message.role === 'assistant'"
|
||||||
|
class="prose prose-sm dark:prose-invert max-w-none break-words"
|
||||||
|
v-html="renderedContent"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- User Content (Plain text) -->
|
||||||
|
<div v-else class="whitespace-pre-wrap break-words">{{ message.content }}</div>
|
||||||
|
|
||||||
|
<!-- Cursor -->
|
||||||
|
<span v-if="streaming" class="inline-block w-1.5 h-4 ml-1 align-middle bg-primary animate-pulse" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Tool Calls -->
|
||||||
|
<ToolCallDisplay v-if="message.toolCalls" :tool-calls="message.toolCalls" />
|
||||||
|
|
||||||
|
<!-- Actions (Copy, etc.) -->
|
||||||
|
<div v-if="message.role === 'assistant'" class="opacity-0 group-hover:opacity-100 transition-opacity flex gap-1">
|
||||||
|
<button
|
||||||
|
@click="copy(message.content)"
|
||||||
|
class="inline-flex items-center justify-center rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 hover:bg-accent hover:text-accent-foreground h-6 w-6"
|
||||||
|
title="复制内容"
|
||||||
|
>
|
||||||
|
<Check v-if="copied" class="h-3 w-3" />
|
||||||
|
<Copy v-else class="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { computed } from 'vue'
|
||||||
|
import { User, Bot, Copy, Check } from 'lucide-vue-next'
|
||||||
|
import { useClipboard } from '@vueuse/core'
|
||||||
|
import MarkdownIt from 'markdown-it'
|
||||||
|
import hljs from 'highlight.js'
|
||||||
|
import 'highlight.js/styles/github-dark.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>()
|
||||||
|
const { copy, copied } = useClipboard({ source: props.message.content })
|
||||||
|
|
||||||
|
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: 'You',
|
||||||
|
assistant: 'Agent',
|
||||||
|
system: 'System',
|
||||||
|
tool: 'Tool',
|
||||||
|
}
|
||||||
|
return labels[props.message.role] || props.message.role
|
||||||
|
})
|
||||||
|
|
||||||
|
const formattedTime = computed(() => {
|
||||||
|
if (!props.message.createdAt) return ''
|
||||||
|
return new Date(props.message.createdAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
|
||||||
|
})
|
||||||
|
|
||||||
|
const renderedContent = computed(() => {
|
||||||
|
return md.render(props.message.content || '')
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style>
|
||||||
|
/* Prose overrides if necessary */
|
||||||
|
.prose pre {
|
||||||
|
@apply bg-muted/50 border border-border;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
<template>
|
||||||
|
<div class="mt-2 space-y-2">
|
||||||
|
<div
|
||||||
|
v-for="(call, index) in toolCalls"
|
||||||
|
:key="index"
|
||||||
|
class="rounded-lg border bg-muted/30 p-3 text-xs shadow-sm transition-all hover:bg-muted/50"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between mb-2">
|
||||||
|
<div class="flex items-center gap-2 font-semibold text-foreground/80">
|
||||||
|
<Terminal class="h-3.5 w-3.5 text-blue-500" />
|
||||||
|
<span>{{ getToolName(call.name) }}</span>
|
||||||
|
</div>
|
||||||
|
<div v-if="call.result" class="flex items-center gap-1 text-green-600 dark:text-green-400">
|
||||||
|
<CheckCircle2 class="h-3 w-3" />
|
||||||
|
<span>已完成</span>
|
||||||
|
</div>
|
||||||
|
<div v-else class="flex items-center gap-1 text-amber-500 animate-pulse">
|
||||||
|
<Loader2 class="h-3 w-3 animate-spin" />
|
||||||
|
<span>执行中...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-2">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<p class="text-[10px] uppercase tracking-wider text-muted-foreground font-bold">参数 (Arguments)</p>
|
||||||
|
<pre class="overflow-x-auto rounded bg-background/50 p-2 font-mono leading-relaxed">{{ formatJson(call.arguments) }}</pre>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="call.result" class="space-y-1">
|
||||||
|
<p class="text-[10px] uppercase tracking-wider text-muted-foreground font-bold">结果 (Result)</p>
|
||||||
|
<pre class="overflow-x-auto rounded bg-background/50 p-2 font-mono leading-relaxed max-h-32">{{ formatJson(call.result) }}</pre>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { Terminal, CheckCircle2, Loader2 } from 'lucide-vue-next'
|
||||||
|
|
||||||
|
interface Props {
|
||||||
|
toolCalls: Array<{
|
||||||
|
name: string;
|
||||||
|
arguments: any;
|
||||||
|
result?: any;
|
||||||
|
}>;
|
||||||
|
}
|
||||||
|
|
||||||
|
defineProps<Props>()
|
||||||
|
|
||||||
|
const toolNameMap: Record<string, string> = {
|
||||||
|
searchArticles: '搜索资讯库',
|
||||||
|
analyzeReport: '深度分析报告',
|
||||||
|
webSearch: '互联网实时搜索',
|
||||||
|
}
|
||||||
|
|
||||||
|
function getToolName(name: string): string {
|
||||||
|
return toolNameMap[name] || name
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatJson(obj: any): string {
|
||||||
|
try {
|
||||||
|
return typeof obj === 'string' ? JSON.stringify(JSON.parse(obj), null, 2) : JSON.stringify(obj, null, 2)
|
||||||
|
} catch {
|
||||||
|
return String(obj)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,142 @@
|
|||||||
|
<template>
|
||||||
|
<Teleport to="body">
|
||||||
|
<Transition name="fade">
|
||||||
|
<div
|
||||||
|
v-if="visible"
|
||||||
|
class="fixed inset-0 z-50 flex items-start justify-center bg-black/50 backdrop-blur-sm pt-[20vh]"
|
||||||
|
@click="close"
|
||||||
|
>
|
||||||
|
<div
|
||||||
|
class="w-full max-w-lg overflow-hidden rounded-xl bg-popover text-popover-foreground shadow-2xl border border-border animate-in fade-in zoom-in-95 duration-200"
|
||||||
|
@click.stop
|
||||||
|
>
|
||||||
|
<div class="flex items-center border-b px-3">
|
||||||
|
<Search class="mr-2 h-4 w-4 shrink-0 opacity-50" />
|
||||||
|
<input
|
||||||
|
ref="inputRef"
|
||||||
|
v-model="searchQuery"
|
||||||
|
class="flex h-11 w-full rounded-md bg-transparent py-3 text-sm outline-none placeholder:text-muted-foreground"
|
||||||
|
placeholder="输入命令或搜索..."
|
||||||
|
@keydown.down.prevent="navigate('down')"
|
||||||
|
@keydown.up.prevent="navigate('up')"
|
||||||
|
@keydown.enter="select"
|
||||||
|
@keydown.esc="close"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div class="max-h-[300px] overflow-y-auto p-1">
|
||||||
|
<div v-if="filteredItems.length === 0" class="py-6 text-center text-sm text-muted-foreground">
|
||||||
|
无搜索结果
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="(item, index) in filteredItems"
|
||||||
|
:key="item.path"
|
||||||
|
:class="[
|
||||||
|
'relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors',
|
||||||
|
selectedIndex === index ? 'bg-accent text-accent-foreground' : ''
|
||||||
|
]"
|
||||||
|
@click="execute(item)"
|
||||||
|
@mouseenter="selectedIndex = index"
|
||||||
|
>
|
||||||
|
<component :is="item.icon" class="mr-2 h-4 w-4" />
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
<span v-if="item.group" class="ml-auto text-[10px] uppercase font-bold text-muted-foreground/50">
|
||||||
|
{{ item.group }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="border-t bg-muted/50 px-3 py-1.5 text-[10px] text-muted-foreground flex justify-end gap-2">
|
||||||
|
<span><kbd class="rounded bg-muted px-1 border">↵</kbd> 选择</span>
|
||||||
|
<span><kbd class="rounded bg-muted px-1 border">↓↑</kbd> 导航</span>
|
||||||
|
<span><kbd class="rounded bg-muted px-1 border">esc</kbd> 关闭</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Transition>
|
||||||
|
</Teleport>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, watch, nextTick } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { useMagicKeys, whenever } from '@vueuse/core'
|
||||||
|
import {
|
||||||
|
Search,
|
||||||
|
LayoutDashboard,
|
||||||
|
Settings,
|
||||||
|
FileText,
|
||||||
|
Newspaper,
|
||||||
|
Activity,
|
||||||
|
Bot
|
||||||
|
} from 'lucide-vue-next'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const visible = ref(false)
|
||||||
|
const searchQuery = ref('')
|
||||||
|
const inputRef = ref<HTMLInputElement>()
|
||||||
|
const selectedIndex = ref(0)
|
||||||
|
|
||||||
|
const keys = useMagicKeys()
|
||||||
|
const ctrlK = keys['Ctrl+K']
|
||||||
|
const cmdK = keys['Cmd+K']
|
||||||
|
|
||||||
|
whenever(ctrlK || cmdK || (() => false), () => {
|
||||||
|
open()
|
||||||
|
})
|
||||||
|
|
||||||
|
const items = [
|
||||||
|
{ title: '仪表盘', path: '/dashboard', icon: LayoutDashboard, group: '导航' },
|
||||||
|
{ title: 'AI 对话', path: '/agent', icon: Bot, group: '功能' },
|
||||||
|
{ title: '报告中心', path: '/reports', icon: FileText, group: '功能' },
|
||||||
|
{ title: '资讯浏览', path: '/articles', icon: Newspaper, group: '功能' },
|
||||||
|
{ title: '采集监控', path: '/monitoring', icon: Activity, group: '功能' },
|
||||||
|
{ title: 'LLM 配置', path: '/config/llm', icon: Settings, group: '配置' },
|
||||||
|
{ title: '数据源', path: '/config/sources', icon: Settings, group: '配置' },
|
||||||
|
{ title: '主题管理', path: '/config/topics', icon: Settings, group: '配置' },
|
||||||
|
]
|
||||||
|
|
||||||
|
const filteredItems = computed(() => {
|
||||||
|
if (!searchQuery.value) return items
|
||||||
|
const query = searchQuery.value.toLowerCase()
|
||||||
|
return items.filter(item =>
|
||||||
|
item.title.toLowerCase().includes(query) ||
|
||||||
|
item.group.toLowerCase().includes(query)
|
||||||
|
)
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(searchQuery, () => {
|
||||||
|
selectedIndex.value = 0
|
||||||
|
})
|
||||||
|
|
||||||
|
function open() {
|
||||||
|
visible.value = true
|
||||||
|
searchQuery.value = ''
|
||||||
|
selectedIndex.value = 0
|
||||||
|
nextTick(() => {
|
||||||
|
inputRef.value?.focus()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function close() {
|
||||||
|
visible.value = false
|
||||||
|
}
|
||||||
|
|
||||||
|
function navigate(direction: 'up' | 'down') {
|
||||||
|
if (filteredItems.value.length === 0) return
|
||||||
|
if (direction === 'down') {
|
||||||
|
selectedIndex.value = (selectedIndex.value + 1) % filteredItems.value.length
|
||||||
|
} else {
|
||||||
|
selectedIndex.value = (selectedIndex.value - 1 + filteredItems.value.length) % filteredItems.value.length
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function select() {
|
||||||
|
if (filteredItems.value.length > 0) {
|
||||||
|
execute(filteredItems.value[selectedIndex.value])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function execute(item: any) {
|
||||||
|
router.push(item.path)
|
||||||
|
close()
|
||||||
|
}
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
import { ref } 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('')
|
||||||
|
const conversationId = ref<number | undefined>()
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送消息
|
||||||
|
*/
|
||||||
|
async function sendMessage(params: Omit<ChatParams, 'conversationId'>) {
|
||||||
|
if (isLoading.value) return
|
||||||
|
|
||||||
|
isLoading.value = true
|
||||||
|
currentStreamContent.value = ''
|
||||||
|
|
||||||
|
// 添加用户消息
|
||||||
|
messages.value.push({
|
||||||
|
role: 'user',
|
||||||
|
content: params.message,
|
||||||
|
createdAt: new Date().toISOString(),
|
||||||
|
})
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await streamChat({
|
||||||
|
...params,
|
||||||
|
conversationId: conversationId.value,
|
||||||
|
})
|
||||||
|
|
||||||
|
const reader = response.body?.getReader()
|
||||||
|
if (!reader) {
|
||||||
|
throw new Error('无法获取响应流')
|
||||||
|
}
|
||||||
|
|
||||||
|
const decoder = new TextDecoder()
|
||||||
|
let assistantContent = ''
|
||||||
|
|
||||||
|
// 添加助手消息占位
|
||||||
|
const assistantMessage: Message = {
|
||||||
|
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)
|
||||||
|
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(data)
|
||||||
|
|
||||||
|
// 处理 conversationId
|
||||||
|
if (parsed.type === 'conversation-id') {
|
||||||
|
conversationId.value = parsed.conversationId
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理文本流
|
||||||
|
if (parsed.type === 'text-delta') {
|
||||||
|
assistantContent += parsed.textDelta
|
||||||
|
currentStreamContent.value = assistantContent
|
||||||
|
// 更新最后一条消息
|
||||||
|
const lastMsg = messages.value[messages.value.length - 1]
|
||||||
|
if (lastMsg) {
|
||||||
|
lastMsg.content = assistantContent
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理完成
|
||||||
|
if (parsed.type === 'done') {
|
||||||
|
currentStreamContent.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
// 处理错误
|
||||||
|
if (parsed.type === 'error') {
|
||||||
|
throw new Error(parsed.error)
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略 JSON 解析错误
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (error: any) {
|
||||||
|
console.error('Chat error:', error)
|
||||||
|
ElMessage.error(error.message || '发送消息失败')
|
||||||
|
|
||||||
|
// 移除失败的助手消息
|
||||||
|
if (messages.value[messages.value.length - 1]?.role === 'assistant') {
|
||||||
|
messages.value.pop()
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
isLoading.value = false
|
||||||
|
currentStreamContent.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清空消息
|
||||||
|
*/
|
||||||
|
function clearMessages() {
|
||||||
|
messages.value = []
|
||||||
|
conversationId.value = undefined
|
||||||
|
currentStreamContent.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 加载历史消息
|
||||||
|
*/
|
||||||
|
function loadMessages(historyMessages: Message[], convId?: number) {
|
||||||
|
messages.value = historyMessages
|
||||||
|
conversationId.value = convId
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
messages,
|
||||||
|
isLoading,
|
||||||
|
currentStreamContent,
|
||||||
|
conversationId,
|
||||||
|
sendMessage,
|
||||||
|
clearMessages,
|
||||||
|
loadMessages,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,221 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex h-screen overflow-hidden bg-background text-foreground">
|
||||||
|
<!-- Sidebar -->
|
||||||
|
<aside
|
||||||
|
:class="[
|
||||||
|
'relative flex flex-col border-r bg-card transition-all duration-300 ease-in-out',
|
||||||
|
appStore.sidebarCollapsed ? 'w-16' : 'w-64'
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<!-- Logo -->
|
||||||
|
<div class="flex h-14 items-center justify-center border-b px-4">
|
||||||
|
<div class="flex items-center gap-2 font-bold text-xl text-primary">
|
||||||
|
<component :is="Zap" class="h-6 w-6" />
|
||||||
|
<span v-if="!appStore.sidebarCollapsed" class="whitespace-nowrap transition-all duration-300">
|
||||||
|
News Agent
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Navigation -->
|
||||||
|
<nav class="flex-1 space-y-1 overflow-y-auto py-4 px-2">
|
||||||
|
<template v-for="item in menuItems" :key="item.path">
|
||||||
|
<!-- Submenu -->
|
||||||
|
<div v-if="item.children" class="space-y-1">
|
||||||
|
<button
|
||||||
|
v-if="!appStore.sidebarCollapsed"
|
||||||
|
class="flex w-full items-center justify-between rounded-md px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||||
|
@click="toggleSubmenu(item.path)"
|
||||||
|
>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<component :is="item.icon" class="h-4 w-4" />
|
||||||
|
<span>{{ item.title }}</span>
|
||||||
|
</div>
|
||||||
|
<component
|
||||||
|
:is="ChevronDown"
|
||||||
|
class="h-4 w-4 transition-transform duration-200"
|
||||||
|
:class="{ 'rotate-180': expandedMenus.includes(item.path) }"
|
||||||
|
/>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Collapsed Mode Icon Only -->
|
||||||
|
<div v-else class="flex justify-center py-2" :title="item.title">
|
||||||
|
<component :is="item.icon" class="h-5 w-5 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Submenu Items -->
|
||||||
|
<div
|
||||||
|
v-show="!appStore.sidebarCollapsed && expandedMenus.includes(item.path)"
|
||||||
|
class="space-y-1 pl-9"
|
||||||
|
>
|
||||||
|
<router-link
|
||||||
|
v-for="sub in item.children"
|
||||||
|
:key="sub.path"
|
||||||
|
:to="sub.path"
|
||||||
|
class="block rounded-md px-3 py-2 text-sm font-medium text-muted-foreground hover:bg-accent hover:text-accent-foreground"
|
||||||
|
active-class="bg-accent/50 text-primary font-semibold"
|
||||||
|
>
|
||||||
|
{{ sub.title }}
|
||||||
|
</router-link>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Single Item -->
|
||||||
|
<router-link
|
||||||
|
v-else
|
||||||
|
:to="item.path"
|
||||||
|
:class="[
|
||||||
|
'flex items-center gap-3 rounded-md px-3 py-2 text-sm font-medium text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground',
|
||||||
|
appStore.sidebarCollapsed ? 'justify-center px-2' : ''
|
||||||
|
]"
|
||||||
|
active-class="bg-accent text-primary font-semibold shadow-sm"
|
||||||
|
:title="appStore.sidebarCollapsed ? item.title : ''"
|
||||||
|
>
|
||||||
|
<component :is="item.icon" class="h-4 w-4" />
|
||||||
|
<span v-if="!appStore.sidebarCollapsed" class="whitespace-nowrap transition-all duration-300">
|
||||||
|
{{ item.title }}
|
||||||
|
</span>
|
||||||
|
</router-link>
|
||||||
|
</template>
|
||||||
|
</nav>
|
||||||
|
|
||||||
|
<!-- User / Footer -->
|
||||||
|
<div class="border-t p-4">
|
||||||
|
<button class="flex w-full items-center gap-3 rounded-md p-2 hover:bg-accent">
|
||||||
|
<div class="h-8 w-8 rounded-full bg-primary/10 flex items-center justify-center text-primary">
|
||||||
|
<User class="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<div v-if="!appStore.sidebarCollapsed" class="text-left text-sm">
|
||||||
|
<p class="font-medium">Admin</p>
|
||||||
|
<p class="text-xs text-muted-foreground">admin@example.com</p>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<!-- Main Content -->
|
||||||
|
<div class="flex flex-1 flex-col overflow-hidden">
|
||||||
|
<CommandPalette />
|
||||||
|
<!-- Header -->
|
||||||
|
<header class="flex h-14 items-center justify-between border-b bg-card px-6 shadow-sm">
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button
|
||||||
|
@click="appStore.toggleSidebar"
|
||||||
|
class="rounded-md p-2 hover:bg-accent text-muted-foreground"
|
||||||
|
>
|
||||||
|
<component :is="appStore.sidebarCollapsed ? PanelLeftOpen : PanelLeftClose" class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<!-- Breadcrumb (Simple) -->
|
||||||
|
<h1 class="text-lg font-semibold text-foreground">
|
||||||
|
{{ currentRouteTitle }}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-4">
|
||||||
|
<button @click="() => toggleDark()" class="rounded-full p-2 hover:bg-accent text-muted-foreground transition-colors">
|
||||||
|
<component :is="isDark ? Sun : Moon" class="h-5 w-5" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- Page Content -->
|
||||||
|
<main class="flex-1 overflow-y-auto bg-muted/20 p-6">
|
||||||
|
<router-view v-slot="{ Component }">
|
||||||
|
<transition name="fade" mode="out-in">
|
||||||
|
<component :is="Component" />
|
||||||
|
</transition>
|
||||||
|
</router-view>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { useAppStore } from '@/stores/app'
|
||||||
|
import { useDark, useToggle } from '@vueuse/core'
|
||||||
|
import CommandPalette from '@/components/common/CommandPalette.vue'
|
||||||
|
import {
|
||||||
|
LayoutDashboard,
|
||||||
|
Settings,
|
||||||
|
FileText,
|
||||||
|
Newspaper,
|
||||||
|
Activity,
|
||||||
|
Bot,
|
||||||
|
Zap,
|
||||||
|
ChevronDown,
|
||||||
|
PanelLeftClose,
|
||||||
|
PanelLeftOpen,
|
||||||
|
User,
|
||||||
|
Sun,
|
||||||
|
Moon
|
||||||
|
} from 'lucide-vue-next'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const appStore = useAppStore()
|
||||||
|
const isDark = useDark()
|
||||||
|
const toggleDark = useToggle(isDark)
|
||||||
|
|
||||||
|
const expandedMenus = ref<string[]>(['/config'])
|
||||||
|
|
||||||
|
const currentRouteTitle = computed(() => {
|
||||||
|
return route.meta.title || 'News Agent'
|
||||||
|
})
|
||||||
|
|
||||||
|
const menuItems = [
|
||||||
|
{
|
||||||
|
title: '仪表盘',
|
||||||
|
path: '/dashboard',
|
||||||
|
icon: LayoutDashboard
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '配置管理',
|
||||||
|
path: '/config',
|
||||||
|
icon: Settings,
|
||||||
|
children: [
|
||||||
|
{ title: 'LLM 配置', path: '/config/llm' },
|
||||||
|
{ title: '数据源', path: '/config/sources' },
|
||||||
|
{ title: '推送渠道', path: '/config/channels' },
|
||||||
|
{ title: '主题管理', path: '/config/topics' }
|
||||||
|
]
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '报告中心',
|
||||||
|
path: '/reports',
|
||||||
|
icon: FileText
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '资讯浏览',
|
||||||
|
path: '/articles',
|
||||||
|
icon: Newspaper
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: '采集监控',
|
||||||
|
path: '/monitoring',
|
||||||
|
icon: Activity
|
||||||
|
},
|
||||||
|
{
|
||||||
|
title: 'AI 对话',
|
||||||
|
path: '/agent',
|
||||||
|
icon: Bot
|
||||||
|
}
|
||||||
|
]
|
||||||
|
|
||||||
|
function toggleSubmenu(path: string) {
|
||||||
|
const index = expandedMenus.value.indexOf(path)
|
||||||
|
if (index > -1) {
|
||||||
|
expandedMenus.value.splice(index, 1)
|
||||||
|
} else {
|
||||||
|
expandedMenus.value.push(path)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/*
|
||||||
|
Tailwind handles most styles.
|
||||||
|
Specific transition overrides or complex animations can go here.
|
||||||
|
*/
|
||||||
|
</style>
|
||||||
@@ -3,6 +3,7 @@ import { createPinia } from 'pinia'
|
|||||||
import App from './App.vue'
|
import App from './App.vue'
|
||||||
import router from './router'
|
import router from './router'
|
||||||
import { setupElementPlus } from './plugins/element-plus'
|
import { setupElementPlus } from './plugins/element-plus'
|
||||||
|
import './style.css'
|
||||||
|
|
||||||
const app = createApp(App)
|
const app = createApp(App)
|
||||||
const pinia = createPinia()
|
const pinia = createPinia()
|
||||||
|
|||||||
@@ -1,13 +1,91 @@
|
|||||||
import { createRouter, createWebHistory } from 'vue-router'
|
import { createRouter, createWebHistory } from 'vue-router'
|
||||||
|
import type { RouteRecordRaw } from 'vue-router'
|
||||||
|
|
||||||
const router = createRouter({
|
const routes: RouteRecordRaw[] = [
|
||||||
history: createWebHistory(),
|
|
||||||
routes: [
|
|
||||||
{
|
{
|
||||||
path: '/',
|
path: '/',
|
||||||
redirect: '/dashboard',
|
redirect: '/dashboard',
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
path: '/',
|
||||||
|
component: () => import('@/layouts/MainLayout.vue'),
|
||||||
|
children: [
|
||||||
|
{
|
||||||
|
path: 'dashboard',
|
||||||
|
name: 'Dashboard',
|
||||||
|
component: () => import('@/views/Dashboard.vue'),
|
||||||
|
meta: { title: '仪表盘' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'config/llm',
|
||||||
|
name: 'LlmConfig',
|
||||||
|
component: () => import('@/views/config/LlmConfig.vue'),
|
||||||
|
meta: { title: 'LLM 配置' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'config/sources',
|
||||||
|
name: 'Sources',
|
||||||
|
component: () => import('@/views/config/Sources.vue'),
|
||||||
|
meta: { title: '数据源管理' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'config/channels',
|
||||||
|
name: 'Channels',
|
||||||
|
component: () => import('@/views/config/Channels.vue'),
|
||||||
|
meta: { title: '推送渠道' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'config/topics',
|
||||||
|
name: 'Topics',
|
||||||
|
component: () => import('@/views/config/Topics.vue'),
|
||||||
|
meta: { title: '主题管理' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'reports',
|
||||||
|
name: 'Reports',
|
||||||
|
component: () => import('@/views/reports/ReportList.vue'),
|
||||||
|
meta: { title: '报告中心' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'reports/:id',
|
||||||
|
name: 'ReportDetail',
|
||||||
|
component: () => import('@/views/reports/ReportDetail.vue'),
|
||||||
|
meta: { title: '报告详情' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'articles',
|
||||||
|
name: 'Articles',
|
||||||
|
component: () => import('@/views/articles/ArticleList.vue'),
|
||||||
|
meta: { title: '资讯浏览' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'monitoring',
|
||||||
|
name: 'Monitoring',
|
||||||
|
component: () => import('@/views/monitoring/Monitoring.vue'),
|
||||||
|
meta: { title: '采集监控' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
path: 'agent',
|
||||||
|
name: 'AgentChat',
|
||||||
|
component: () => import('@/views/agent/AgentChat.vue'),
|
||||||
|
meta: { title: 'AI 对话' },
|
||||||
|
},
|
||||||
],
|
],
|
||||||
|
},
|
||||||
|
]
|
||||||
|
|
||||||
|
const router = createRouter({
|
||||||
|
history: createWebHistory(),
|
||||||
|
routes,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 路由守卫
|
||||||
|
router.beforeEach((to, _from, next) => {
|
||||||
|
// 设置页面标题
|
||||||
|
if (to.meta.title) {
|
||||||
|
document.title = `${to.meta.title} - 资讯聚合系统`
|
||||||
|
}
|
||||||
|
next()
|
||||||
})
|
})
|
||||||
|
|
||||||
export default router
|
export default router
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useAppStore = defineStore('app', () => {
|
||||||
|
// 侧边栏折叠状态
|
||||||
|
const sidebarCollapsed = ref(false)
|
||||||
|
|
||||||
|
// 切换侧边栏
|
||||||
|
const toggleSidebar = () => {
|
||||||
|
sidebarCollapsed.value = !sidebarCollapsed.value
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sidebarCollapsed,
|
||||||
|
toggleSidebar,
|
||||||
|
}
|
||||||
|
})
|
||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { defineStore } from 'pinia'
|
||||||
|
import { ref } from 'vue'
|
||||||
|
|
||||||
|
export const useUserStore = defineStore('user', () => {
|
||||||
|
const token = ref<string | null>(null)
|
||||||
|
const userInfo = ref<any>(null)
|
||||||
|
|
||||||
|
const setToken = (newToken: string) => {
|
||||||
|
token.value = newToken
|
||||||
|
localStorage.setItem('token', newToken)
|
||||||
|
}
|
||||||
|
|
||||||
|
const setUserInfo = (info: any) => {
|
||||||
|
userInfo.value = info
|
||||||
|
}
|
||||||
|
|
||||||
|
const logout = () => {
|
||||||
|
token.value = null
|
||||||
|
userInfo.value = null
|
||||||
|
localStorage.removeItem('token')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 初始化时从 localStorage 恢复 token
|
||||||
|
const initToken = () => {
|
||||||
|
const savedToken = localStorage.getItem('token')
|
||||||
|
if (savedToken) {
|
||||||
|
token.value = savedToken
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
token,
|
||||||
|
userInfo,
|
||||||
|
setToken,
|
||||||
|
setUserInfo,
|
||||||
|
logout,
|
||||||
|
initToken,
|
||||||
|
}
|
||||||
|
})
|
||||||
+59
-67
@@ -1,79 +1,71 @@
|
|||||||
|
@tailwind base;
|
||||||
|
@tailwind components;
|
||||||
|
@tailwind utilities;
|
||||||
|
|
||||||
|
@layer base {
|
||||||
:root {
|
:root {
|
||||||
font-family: system-ui, Avenir, Helvetica, Arial, sans-serif;
|
--background: 0 0% 100%;
|
||||||
line-height: 1.5;
|
--foreground: 240 10% 3.9%;
|
||||||
font-weight: 400;
|
--card: 0 0% 100%;
|
||||||
|
--card-foreground: 240 10% 3.9%;
|
||||||
color-scheme: light dark;
|
--popover: 0 0% 100%;
|
||||||
color: rgba(255, 255, 255, 0.87);
|
--popover-foreground: 240 10% 3.9%;
|
||||||
background-color: #242424;
|
--primary: 240 5.9% 10%;
|
||||||
|
--primary-foreground: 0 0% 98%;
|
||||||
font-synthesis: none;
|
--secondary: 240 4.8% 95.9%;
|
||||||
text-rendering: optimizeLegibility;
|
--secondary-foreground: 240 5.9% 10%;
|
||||||
-webkit-font-smoothing: antialiased;
|
--muted: 240 4.8% 95.9%;
|
||||||
-moz-osx-font-smoothing: grayscale;
|
--muted-foreground: 240 3.8% 46.1%;
|
||||||
|
--accent: 240 4.8% 95.9%;
|
||||||
|
--accent-foreground: 240 5.9% 10%;
|
||||||
|
--destructive: 0 84.2% 60.2%;
|
||||||
|
--destructive-foreground: 0 0% 98%;
|
||||||
|
--border: 240 5.9% 90%;
|
||||||
|
--input: 240 5.9% 90%;
|
||||||
|
--ring: 240 5.9% 10%;
|
||||||
|
--radius: 0.5rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
a {
|
.dark {
|
||||||
font-weight: 500;
|
--background: 240 10% 3.9%;
|
||||||
color: #646cff;
|
--foreground: 0 0% 98%;
|
||||||
text-decoration: inherit;
|
--card: 240 10% 3.9%;
|
||||||
|
--card-foreground: 0 0% 98%;
|
||||||
|
--popover: 240 10% 3.9%;
|
||||||
|
--popover-foreground: 0 0% 98%;
|
||||||
|
--primary: 0 0% 98%;
|
||||||
|
--primary-foreground: 240 5.9% 10%;
|
||||||
|
--secondary: 240 3.7% 15.9%;
|
||||||
|
--secondary-foreground: 0 0% 98%;
|
||||||
|
--muted: 240 3.7% 15.9%;
|
||||||
|
--muted-foreground: 240 5% 64.9%;
|
||||||
|
--accent: 240 3.7% 15.9%;
|
||||||
|
--accent-foreground: 0 0% 98%;
|
||||||
|
--destructive: 0 62.8% 30.6%;
|
||||||
|
--destructive-foreground: 0 0% 98%;
|
||||||
|
--border: 240 3.7% 15.9%;
|
||||||
|
--input: 240 3.7% 15.9%;
|
||||||
|
--ring: 240 4.9% 83.9%;
|
||||||
}
|
}
|
||||||
a:hover {
|
|
||||||
color: #535bf2;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@layer base {
|
||||||
|
* {
|
||||||
|
@apply border-border;
|
||||||
|
}
|
||||||
body {
|
body {
|
||||||
margin: 0;
|
@apply bg-background text-foreground;
|
||||||
display: flex;
|
font-feature-settings: "rlig" 1, "calt" 1;
|
||||||
place-items: center;
|
}
|
||||||
min-width: 320px;
|
|
||||||
min-height: 100vh;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
h1 {
|
/* 兼容 Element Plus 的过渡动画 */
|
||||||
font-size: 3.2em;
|
.fade-enter-active,
|
||||||
line-height: 1.1;
|
.fade-leave-active {
|
||||||
|
transition: opacity 0.3s ease;
|
||||||
}
|
}
|
||||||
|
|
||||||
button {
|
.fade-enter-from,
|
||||||
border-radius: 8px;
|
.fade-leave-to {
|
||||||
border: 1px solid transparent;
|
opacity: 0;
|
||||||
padding: 0.6em 1.2em;
|
|
||||||
font-size: 1em;
|
|
||||||
font-weight: 500;
|
|
||||||
font-family: inherit;
|
|
||||||
background-color: #1a1a1a;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: border-color 0.25s;
|
|
||||||
}
|
|
||||||
button:hover {
|
|
||||||
border-color: #646cff;
|
|
||||||
}
|
|
||||||
button:focus,
|
|
||||||
button:focus-visible {
|
|
||||||
outline: 4px auto -webkit-focus-ring-color;
|
|
||||||
}
|
|
||||||
|
|
||||||
.card {
|
|
||||||
padding: 2em;
|
|
||||||
}
|
|
||||||
|
|
||||||
#app {
|
|
||||||
max-width: 1280px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 2rem;
|
|
||||||
text-align: center;
|
|
||||||
}
|
|
||||||
|
|
||||||
@media (prefers-color-scheme: light) {
|
|
||||||
:root {
|
|
||||||
color: #213547;
|
|
||||||
background-color: #ffffff;
|
|
||||||
}
|
|
||||||
a:hover {
|
|
||||||
color: #747bff;
|
|
||||||
}
|
|
||||||
button {
|
|
||||||
background-color: #f9f9f9;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,169 @@
|
|||||||
|
<template>
|
||||||
|
<div class="space-y-8 animate-in fade-in duration-500">
|
||||||
|
<div class="flex flex-col gap-2">
|
||||||
|
<h2 class="text-3xl font-bold tracking-tight">概览 (Insights)</h2>
|
||||||
|
<p class="text-muted-foreground text-sm">系统当前运行状态与资讯采集实时汇总</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Bento Grid Stats -->
|
||||||
|
<div class="grid gap-4 md:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<div v-for="stat in statsCards" :key="stat.label" class="rounded-xl border bg-card p-6 shadow-sm transition-all hover:shadow-md group">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<p class="text-xs font-bold text-muted-foreground uppercase tracking-wider">{{ stat.label }}</p>
|
||||||
|
<h3 class="text-2xl font-bold tabular-nums">{{ stat.value }}</h3>
|
||||||
|
</div>
|
||||||
|
<div :class="['rounded-lg p-2.5 transition-colors group-hover:scale-110 duration-300', stat.bgClass]">
|
||||||
|
<component :is="stat.icon" :class="['h-5 w-5', stat.iconClass]" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="mt-4 flex items-center text-[10px] text-muted-foreground">
|
||||||
|
<TrendingUp class="mr-1 h-3 w-3 text-green-500" />
|
||||||
|
<span>较上周增长 12%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Main Content Area -->
|
||||||
|
<div class="grid gap-6 md:grid-cols-7">
|
||||||
|
<!-- Recent Reports (4 cols) -->
|
||||||
|
<div class="col-span-4 rounded-xl border bg-card shadow-sm overflow-hidden flex flex-col">
|
||||||
|
<div class="flex items-center justify-between border-b px-6 py-4 bg-muted/30">
|
||||||
|
<h3 class="font-semibold flex items-center gap-2">
|
||||||
|
<FileText class="h-4 w-4 text-blue-500" />
|
||||||
|
最近生成的报告
|
||||||
|
</h3>
|
||||||
|
<button @click="$router.push('/reports')" class="text-xs font-medium text-blue-600 hover:underline">全部</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 overflow-y-auto max-h-[400px]">
|
||||||
|
<div v-if="recentReports.length === 0" class="p-12 text-center text-muted-foreground italic text-sm">
|
||||||
|
暂无报告生成
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
v-for="report in recentReports"
|
||||||
|
:key="report.id"
|
||||||
|
@click="$router.push(`/reports/${report.id}`)"
|
||||||
|
class="flex items-center justify-between px-6 py-4 border-b last:border-0 hover:bg-muted/50 cursor-pointer transition-colors"
|
||||||
|
>
|
||||||
|
<div class="space-y-1 overflow-hidden pr-4">
|
||||||
|
<p class="text-sm font-medium truncate">{{ report.title }}</p>
|
||||||
|
<div class="flex items-center gap-2 text-[10px] text-muted-foreground">
|
||||||
|
<span class="px-1.5 py-0.5 rounded bg-blue-500/10 text-blue-600 font-bold uppercase">{{ report.topic?.name }}</span>
|
||||||
|
<span>•</span>
|
||||||
|
<span>{{ formatTime(report.createdAt) }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<span :class="['text-[10px] px-2 py-0.5 rounded-full font-semibold', getStatusClass(report.status)]">
|
||||||
|
{{ getStatusText(report.status) }}
|
||||||
|
</span>
|
||||||
|
<ChevronRight class="h-4 w-4 text-muted-foreground/50" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Collection Health (3 cols) -->
|
||||||
|
<div class="col-span-3 rounded-xl border bg-card shadow-sm flex flex-col">
|
||||||
|
<div class="flex items-center justify-between border-b px-6 py-4 bg-muted/30">
|
||||||
|
<h3 class="font-semibold flex items-center gap-2">
|
||||||
|
<Activity class="h-4 w-4 text-green-500" />
|
||||||
|
采集健康度
|
||||||
|
</h3>
|
||||||
|
<button @click="$router.push('/monitoring')" class="text-xs font-medium text-blue-600 hover:underline">监控详情</button>
|
||||||
|
</div>
|
||||||
|
<div class="p-6 space-y-6">
|
||||||
|
<div v-for="stat in collectionStats" :key="stat.id" class="space-y-3">
|
||||||
|
<div class="flex items-center justify-between text-sm">
|
||||||
|
<span class="font-medium text-foreground/80">{{ stat.name }}</span>
|
||||||
|
<span :class="['text-[10px] px-2 py-0.5 rounded uppercase font-bold', stat.lastLog?.status === 'success' ? 'bg-green-500/10 text-green-600' : 'bg-red-500/10 text-red-600']">
|
||||||
|
{{ stat.lastLog?.status === 'success' ? '正常' : '异常' }}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div class="h-1.5 w-full rounded-full bg-muted overflow-hidden">
|
||||||
|
<div
|
||||||
|
class="h-full bg-blue-500 transition-all duration-1000"
|
||||||
|
:style="{ width: `${Math.min((stat.totalArticles / 100) * 100, 100)}%` }"
|
||||||
|
></div>
|
||||||
|
</div>
|
||||||
|
<div class="flex justify-between text-[10px] text-muted-foreground">
|
||||||
|
<span>共采集 {{ stat.totalArticles }} 条</span>
|
||||||
|
<span>最后运行: {{ stat.lastCollectedAt ? formatTime(stat.lastCollectedAt) : '从未' }}</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div v-if="collectionStats.length === 0" class="text-center py-8 opacity-50 italic text-sm">
|
||||||
|
暂无监控数据
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import {
|
||||||
|
Link, Library, FileText, Newspaper,
|
||||||
|
Activity, TrendingUp, ChevronRight
|
||||||
|
} from 'lucide-vue-next'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Report, CollectionStats } from '@/api/types'
|
||||||
|
|
||||||
|
const stats = ref({ sources: 0, topics: 0, reports: 0, articles: 0 })
|
||||||
|
const recentReports = ref<Report[]>([])
|
||||||
|
const collectionStats = ref<CollectionStats[]>([])
|
||||||
|
|
||||||
|
const statsCards = computed(() => [
|
||||||
|
{ label: '数据源', value: stats.value.sources, icon: Link, bgClass: 'bg-blue-500/10', iconClass: 'text-blue-600' },
|
||||||
|
{ label: '订阅主题', value: stats.value.topics, icon: Library, bgClass: 'bg-green-500/10', iconClass: 'text-green-600' },
|
||||||
|
{ label: '资讯快报', value: stats.value.reports, icon: FileText, bgClass: 'bg-amber-500/10', iconClass: 'text-amber-600' },
|
||||||
|
{ label: '采集文章', value: stats.value.articles, icon: Newspaper, bgClass: 'bg-purple-500/10', iconClass: 'text-purple-600' },
|
||||||
|
])
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
try {
|
||||||
|
const [s, t, r, a] = await Promise.all([
|
||||||
|
request.get('/sources', { params: { limit: 1 } }),
|
||||||
|
request.get('/topics', { params: { limit: 1 } }),
|
||||||
|
request.get('/reports', { params: { limit: 1 } }),
|
||||||
|
request.get('/articles', { params: { limit: 1 } }),
|
||||||
|
])
|
||||||
|
stats.value = {
|
||||||
|
sources: s.pagination?.total || 0,
|
||||||
|
topics: t.pagination?.total || 0,
|
||||||
|
reports: r.pagination?.total || 0,
|
||||||
|
articles: a.pagination?.total || 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
const reportsRes = await request.get('/reports', { params: { limit: 5 } })
|
||||||
|
recentReports.value = reportsRes.data || []
|
||||||
|
|
||||||
|
const statsRes = await request.get('/collection-logs/stats')
|
||||||
|
collectionStats.value = (statsRes.data || []).slice(0, 4)
|
||||||
|
} catch (err) {
|
||||||
|
console.error(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusText = (status: string) => {
|
||||||
|
const map: any = { pending: '等待中', generating: '生成中', completed: '已就绪', failed: '失败' }
|
||||||
|
return map[status] || status
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusClass = (status: string) => {
|
||||||
|
const map: any = {
|
||||||
|
pending: 'bg-muted text-muted-foreground',
|
||||||
|
generating: 'bg-amber-500/10 text-amber-600',
|
||||||
|
completed: 'bg-green-500/10 text-green-600',
|
||||||
|
failed: 'bg-red-500/10 text-red-600'
|
||||||
|
}
|
||||||
|
return map[status] || ''
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
const date = new Date(time)
|
||||||
|
return `${date.getMonth()+1}/${date.getDate()} ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(loadData)
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,289 @@
|
|||||||
|
<template>
|
||||||
|
<div class="flex h-full flex-col bg-background lg:flex-row overflow-hidden rounded-xl border shadow-sm">
|
||||||
|
<!-- Main Chat Area -->
|
||||||
|
<div class="flex flex-1 flex-col overflow-hidden relative">
|
||||||
|
<!-- Chat Header -->
|
||||||
|
<header class="flex h-14 items-center justify-between border-b bg-card/50 px-4 backdrop-blur">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<div class="rounded-full bg-blue-500/10 p-1.5">
|
||||||
|
<Bot class="h-5 w-5 text-blue-600" />
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 class="text-sm font-semibold">AI 智能助手</h3>
|
||||||
|
<p class="text-[10px] text-muted-foreground">{{ activeTopicName || '就绪' }}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<el-popover placement="bottom-end" :width="320" trigger="click">
|
||||||
|
<template #reference>
|
||||||
|
<button class="flex items-center gap-1 rounded-md px-2 py-1.5 text-xs font-medium hover:bg-accent transition-colors">
|
||||||
|
<Settings2 class="h-4 w-4" />
|
||||||
|
<span>配置</span>
|
||||||
|
</button>
|
||||||
|
</template>
|
||||||
|
<div class="space-y-4 p-2">
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-xs font-bold text-muted-foreground uppercase">当前主题</label>
|
||||||
|
<el-select v-model="selectedTopicId" class="w-full" placeholder="选择主题">
|
||||||
|
<el-option v-for="t in topics" :key="t.id" :label="t.name" :value="t.id" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-xs font-bold text-muted-foreground uppercase">模型配置</label>
|
||||||
|
<el-select v-model="selectedLlmConfigId" class="w-full" placeholder="选择 LLM">
|
||||||
|
<el-option v-for="c in llmConfigs" :key="c.id" :label="c.name" :value="c.id" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
<div class="space-y-2">
|
||||||
|
<label class="text-xs font-bold text-muted-foreground uppercase">关联报告</label>
|
||||||
|
<el-select v-model="selectedReportId" class="w-full" placeholder="无" clearable>
|
||||||
|
<el-option v-for="r in reports" :key="r.id" :label="r.title" :value="r.id" />
|
||||||
|
</el-select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</el-popover>
|
||||||
|
|
||||||
|
<div class="h-4 w-px bg-border mx-1"></div>
|
||||||
|
|
||||||
|
<button @click="handleNewChat" class="rounded-md p-1.5 hover:bg-accent text-muted-foreground" title="新建对话">
|
||||||
|
<Plus class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
<button @click="showHistory = !showHistory" class="rounded-md p-1.5 hover:bg-accent text-muted-foreground lg:hidden">
|
||||||
|
<History class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<!-- Message List -->
|
||||||
|
<div ref="scrollContainer" class="flex-1 overflow-y-auto p-4 space-y-4">
|
||||||
|
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center space-y-4 opacity-50">
|
||||||
|
<div class="rounded-full bg-muted p-6">
|
||||||
|
<Sparkles class="h-12 w-12 text-muted-foreground" />
|
||||||
|
</div>
|
||||||
|
<div class="text-center">
|
||||||
|
<p class="text-sm font-medium">您可以询问关于已采集资讯或报告的问题</p>
|
||||||
|
<p class="text-xs">例如:“总结一下最近关于人工智能的重要新闻”</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<MessageItem
|
||||||
|
v-for="(message, index) in messages"
|
||||||
|
:key="index"
|
||||||
|
:message="{ ...message, id: message.id || index }"
|
||||||
|
:streaming="isLoading && index === messages.length - 1 && message.role === 'assistant'"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<!-- Loading state -->
|
||||||
|
<div v-if="isLoading && (!messages.length || messages[messages.length - 1]?.role !== 'assistant')" class="flex gap-3 animate-in slide-in-from-bottom-2">
|
||||||
|
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-md border bg-primary text-primary-foreground shadow">
|
||||||
|
<Bot class="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<div class="flex items-center gap-2 rounded-md border bg-card px-3 py-2 text-sm shadow-sm">
|
||||||
|
<Loader2 class="h-3 w-3 animate-spin text-blue-500" />
|
||||||
|
<span class="text-muted-foreground italic">Agent 正在思考...</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Input Area -->
|
||||||
|
<div class="p-4 border-t bg-card/30 backdrop-blur">
|
||||||
|
<div class="max-w-4xl mx-auto relative group">
|
||||||
|
<textarea
|
||||||
|
v-model="inputMessage"
|
||||||
|
@keydown.ctrl.enter="handleSendMessage"
|
||||||
|
placeholder="输入您的问题... (Ctrl+Enter 发送)"
|
||||||
|
class="w-full min-h-[100px] max-h-[200px] rounded-xl border border-border bg-background px-4 py-3 text-sm shadow-sm transition-all focus:border-blue-500 focus:ring-2 focus:ring-blue-500/20 resize-none pr-12"
|
||||||
|
:disabled="isLoading"
|
||||||
|
></textarea>
|
||||||
|
<button
|
||||||
|
@click="handleSendMessage"
|
||||||
|
:disabled="!inputMessage.trim() || isLoading"
|
||||||
|
class="absolute bottom-3 right-3 rounded-lg bg-primary p-2 text-primary-foreground shadow-lg transition-all hover:scale-105 active:scale-95 disabled:opacity-50 disabled:grayscale disabled:hover:scale-100"
|
||||||
|
>
|
||||||
|
<SendHorizontal class="h-4 w-4" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<p class="mt-2 text-center text-[10px] text-muted-foreground">
|
||||||
|
基于 Vercel AI SDK 构建 · 已连接至 {{ activeModelName }}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Desktop History Sidebar -->
|
||||||
|
<aside v-show="showHistory" class="hidden lg:flex w-80 flex-col border-l bg-muted/10 animate-in slide-in-from-right duration-300">
|
||||||
|
<div class="flex h-14 items-center justify-between border-b px-4">
|
||||||
|
<h4 class="text-xs font-bold uppercase tracking-wider text-muted-foreground">对话历史</h4>
|
||||||
|
<button @click="loadConversations" class="rounded-md p-1.5 hover:bg-accent text-muted-foreground">
|
||||||
|
<RefreshCw class="h-3.5 w-3.5" :class="{ 'animate-spin': loadingHistory }" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<div class="flex-1 overflow-y-auto p-3 space-y-2">
|
||||||
|
<div
|
||||||
|
v-for="conv in conversations"
|
||||||
|
:key="conv.id"
|
||||||
|
@click="loadConversation(conv)"
|
||||||
|
:class="[
|
||||||
|
'group relative flex flex-col gap-1 rounded-lg border p-3 text-left transition-all cursor-pointer hover:border-blue-500/50 hover:bg-background',
|
||||||
|
conversationId === conv.id ? 'border-blue-500 bg-background shadow-sm' : 'border-transparent bg-transparent'
|
||||||
|
]"
|
||||||
|
>
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<span class="text-xs font-semibold truncate pr-4">{{ conv.topic?.name || '新对话' }}</span>
|
||||||
|
<span class="text-[10px] text-muted-foreground shrink-0">{{ formatTime(conv.updatedAt) }}</span>
|
||||||
|
</div>
|
||||||
|
<p class="text-[11px] text-muted-foreground line-clamp-2 leading-relaxed">
|
||||||
|
{{ conv.lastMessage?.content || '暂无预览内容' }}
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
@click.stop="handleDeleteConversation(conv.id)"
|
||||||
|
class="absolute right-2 bottom-2 opacity-0 group-hover:opacity-100 p-1 text-destructive hover:bg-destructive/10 rounded transition-opacity"
|
||||||
|
>
|
||||||
|
<Trash2 class="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
<el-empty v-if="conversations.length === 0" description="尚无历史" :image-size="40" />
|
||||||
|
</div>
|
||||||
|
</aside>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted, nextTick, watch } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import {
|
||||||
|
Bot, Settings2, Plus, History, Sparkles, SendHorizontal,
|
||||||
|
Loader2, RefreshCw, Trash2
|
||||||
|
} from 'lucide-vue-next'
|
||||||
|
import MessageItem from '@/components/agent/MessageItem.vue'
|
||||||
|
import { useAgentChat } from '@/composables/useAgentChat'
|
||||||
|
import { getConversations, deleteConversation, type Conversation } from '@/api/agent'
|
||||||
|
import request from '@/api/request'
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const scrollContainer = ref<HTMLElement>()
|
||||||
|
|
||||||
|
// Data
|
||||||
|
const topics = ref<any[]>([])
|
||||||
|
const llmConfigs = ref<any[]>([])
|
||||||
|
const reports = ref<any[]>([])
|
||||||
|
const conversations = ref<Conversation[]>([])
|
||||||
|
const loadingHistory = ref(false)
|
||||||
|
|
||||||
|
// Selections
|
||||||
|
const selectedTopicId = ref<number>()
|
||||||
|
const selectedLlmConfigId = ref<number>()
|
||||||
|
const selectedReportId = ref<number>()
|
||||||
|
|
||||||
|
const showHistory = ref(true)
|
||||||
|
const inputMessage = ref('')
|
||||||
|
|
||||||
|
const {
|
||||||
|
messages, isLoading, conversationId, sendMessage,
|
||||||
|
clearMessages, loadMessages
|
||||||
|
} = useAgentChat()
|
||||||
|
|
||||||
|
const activeTopicName = computed(() => topics.value.find(t => t.id === selectedTopicId.value)?.name)
|
||||||
|
const activeModelName = computed(() => llmConfigs.value.find(c => c.id === selectedLlmConfigId.value)?.model || '默认模型')
|
||||||
|
|
||||||
|
// Auto-scroll logic
|
||||||
|
watch([messages, isLoading], () => {
|
||||||
|
nextTick(() => {
|
||||||
|
if (scrollContainer.value) {
|
||||||
|
scrollContainer.value.scrollTop = scrollContainer.value.scrollHeight
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
onMounted(async () => {
|
||||||
|
await Promise.all([loadTopics(), loadLlmConfigs(), loadReports(), loadConversations()])
|
||||||
|
|
||||||
|
if (route.query.topicId) selectedTopicId.value = Number(route.query.topicId)
|
||||||
|
if (route.query.reportId) selectedReportId.value = Number(route.query.reportId)
|
||||||
|
|
||||||
|
if (!selectedTopicId.value && topics.value.length > 0) selectedTopicId.value = topics.value[0].id
|
||||||
|
if (!selectedLlmConfigId.value && llmConfigs.value.length > 0) selectedLlmConfigId.value = llmConfigs.value[0].id
|
||||||
|
})
|
||||||
|
|
||||||
|
async function loadTopics() {
|
||||||
|
const res = await request.get('/topics')
|
||||||
|
topics.value = res.data || []
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLlmConfigs() {
|
||||||
|
const res = await request.get('/llm-configs')
|
||||||
|
llmConfigs.value = res.data || []
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadReports() {
|
||||||
|
const res = await request.get('/reports', { params: { status: 'completed', limit: 10 } })
|
||||||
|
reports.value = res.data || []
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadConversations() {
|
||||||
|
loadingHistory.value = true
|
||||||
|
try {
|
||||||
|
conversations.value = await getConversations()
|
||||||
|
} finally {
|
||||||
|
loadingHistory.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleSendMessage() {
|
||||||
|
if (!inputMessage.value.trim() || isLoading.value) return
|
||||||
|
if (!selectedTopicId.value || !selectedLlmConfigId.value) {
|
||||||
|
ElMessage.warning('请先选择主题和模型配置')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const msg = inputMessage.value
|
||||||
|
inputMessage.value = ''
|
||||||
|
await sendMessage({
|
||||||
|
topicId: selectedTopicId.value,
|
||||||
|
llmConfigId: selectedLlmConfigId.value,
|
||||||
|
reportId: selectedReportId.value,
|
||||||
|
message: msg
|
||||||
|
})
|
||||||
|
loadConversations()
|
||||||
|
}
|
||||||
|
|
||||||
|
function handleNewChat() {
|
||||||
|
clearMessages()
|
||||||
|
selectedReportId.value = undefined
|
||||||
|
inputMessage.value = ''
|
||||||
|
}
|
||||||
|
|
||||||
|
function loadConversation(conv: Conversation) {
|
||||||
|
selectedTopicId.value = conv.topicId
|
||||||
|
selectedReportId.value = conv.reportId
|
||||||
|
loadMessages(conv.messages || [], conv.id)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDeleteConversation(id: number) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm('彻底删除此对话历史?', '警告', { type: 'warning' })
|
||||||
|
await deleteConversation(id)
|
||||||
|
if (id === conversationId.value) handleNewChat()
|
||||||
|
loadConversations()
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(time: string): string {
|
||||||
|
const date = new Date(time)
|
||||||
|
const diff = Date.now() - date.getTime()
|
||||||
|
if (diff < 60000) return '刚刚'
|
||||||
|
if (diff < 3600000) return `${Math.floor(diff / 60000)}m前`
|
||||||
|
if (diff < 86400000) return `${Math.floor(diff / 3600000)}h前`
|
||||||
|
return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric' })
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
::-webkit-scrollbar {
|
||||||
|
width: 5px;
|
||||||
|
}
|
||||||
|
::-webkit-scrollbar-thumb {
|
||||||
|
@apply bg-muted rounded-full;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,277 @@
|
|||||||
|
<template>
|
||||||
|
<div class="article-list">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>资讯浏览</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card class="filter-card">
|
||||||
|
<el-form :inline="true" :model="filters">
|
||||||
|
<el-form-item label="数据源">
|
||||||
|
<el-select v-model="filters.sourceId" placeholder="全部数据源" clearable style="width: 180px">
|
||||||
|
<el-option
|
||||||
|
v-for="item in sources"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="主题">
|
||||||
|
<el-select v-model="filters.topicId" placeholder="全部主题" clearable style="width: 180px">
|
||||||
|
<el-option
|
||||||
|
v-for="item in topics"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="日期范围">
|
||||||
|
<el-date-picker
|
||||||
|
v-model="filters.dateRange"
|
||||||
|
type="daterange"
|
||||||
|
range-separator="至"
|
||||||
|
start-placeholder="开始日期"
|
||||||
|
end-placeholder="结束日期"
|
||||||
|
value-format="YYYY-MM-DD"
|
||||||
|
style="width: 260px"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="loadData">查询</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-card style="margin-top: 20px">
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="title" label="标题" min-width="250" show-overflow-tooltip />
|
||||||
|
<el-table-column label="数据源" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag size="small">{{ row.source?.name || '-' }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="url" label="链接" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-link v-if="row.url" :href="row.url" target="_blank" type="primary">查看</el-link>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="publishedAt" label="发布时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.publishedAt ? formatTime(row.publishedAt) : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="collectedAt" label="采集时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.collectedAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="120" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleView(row)">详情</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50, 100]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 详情对话框 -->
|
||||||
|
<el-dialog v-model="detailVisible" title="资讯详情" width="700px">
|
||||||
|
<template v-if="currentArticle">
|
||||||
|
<el-descriptions :column="2" border>
|
||||||
|
<el-descriptions-item label="标题" :span="2">{{ currentArticle.title }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="数据源">{{ currentArticle.source?.name || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="链接">
|
||||||
|
<el-link v-if="currentArticle.url" :href="currentArticle.url" target="_blank" type="primary">
|
||||||
|
{{ currentArticle.url }}
|
||||||
|
</el-link>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="发布时间">
|
||||||
|
{{ currentArticle.publishedAt ? formatTime(currentArticle.publishedAt) : '-' }}
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="采集时间">{{ formatTime(currentArticle.collectedAt) }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
|
||||||
|
<el-divider />
|
||||||
|
|
||||||
|
<div v-if="currentArticle.summary" class="article-section">
|
||||||
|
<h4>摘要</h4>
|
||||||
|
<p>{{ currentArticle.summary }}</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-if="currentArticle.content" class="article-section">
|
||||||
|
<h4>内容</h4>
|
||||||
|
<div class="article-content">{{ currentArticle.content }}</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Article, Source, Topic } from '@/api/types'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const tableData = ref<Article[]>([])
|
||||||
|
const sources = ref<Source[]>([])
|
||||||
|
const topics = ref<Topic[]>([])
|
||||||
|
const detailVisible = ref(false)
|
||||||
|
const currentArticle = ref<Article | null>(null)
|
||||||
|
|
||||||
|
const pagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 20,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const filters = reactive({
|
||||||
|
sourceId: null as number | null,
|
||||||
|
topicId: null as number | null,
|
||||||
|
dateRange: null as [string, string] | null,
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const params: Record<string, any> = {
|
||||||
|
page: pagination.page,
|
||||||
|
limit: pagination.limit,
|
||||||
|
}
|
||||||
|
if (filters.sourceId) params.sourceId = filters.sourceId
|
||||||
|
if (filters.topicId) params.topicId = filters.topicId
|
||||||
|
if (filters.dateRange) {
|
||||||
|
params.startDate = filters.dateRange[0]
|
||||||
|
params.endDate = filters.dateRange[1]
|
||||||
|
}
|
||||||
|
|
||||||
|
const res = await request.get('/articles', { params })
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadOptions = async () => {
|
||||||
|
try {
|
||||||
|
const [sourceRes, topicRes] = await Promise.all([
|
||||||
|
request.get('/sources', { params: { limit: 100 } }),
|
||||||
|
request.get('/topics', { params: { limit: 100 } }),
|
||||||
|
])
|
||||||
|
sources.value = sourceRes.data || []
|
||||||
|
topics.value = topicRes.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载选项失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetFilters = () => {
|
||||||
|
filters.sourceId = null
|
||||||
|
filters.topicId = null
|
||||||
|
filters.dateRange = null
|
||||||
|
loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleView = async (row: Article) => {
|
||||||
|
try {
|
||||||
|
const res = await request.get(`/articles/${row.id}`)
|
||||||
|
currentArticle.value = res.data
|
||||||
|
detailVisible.value = true
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取详情失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: Article) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除资讯 "${row.title}" 吗?`, '提示', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
await request.delete(`/articles/${row.id}`)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadData()
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('删除失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
loadOptions()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.article-list {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-card :deep(.el-form-item) {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.article-section {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.article-section h4 {
|
||||||
|
margin-bottom: 10px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.article-content {
|
||||||
|
max-height: 300px;
|
||||||
|
overflow-y: auto;
|
||||||
|
padding: 15px;
|
||||||
|
background-color: #fafafa;
|
||||||
|
border-radius: 4px;
|
||||||
|
line-height: 1.8;
|
||||||
|
white-space: pre-wrap;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
<template>
|
||||||
|
<div class="channels">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>推送渠道管理</h2>
|
||||||
|
<el-button type="primary" @click="handleAdd">
|
||||||
|
<el-icon><Plus /></el-icon>
|
||||||
|
新增渠道
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="名称" min-width="150" />
|
||||||
|
<el-table-column prop="type" label="类型" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="getTypeTagType(row.type)">{{ getTypeLabel(row.type) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="enabled" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch v-model="row.enabled" @change="handleToggleEnabled(row)" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="createdAt" label="创建时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.createdAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="150" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 新增/编辑对话框 -->
|
||||||
|
<el-dialog
|
||||||
|
v-model="dialogVisible"
|
||||||
|
:title="isEdit ? '编辑推送渠道' : '新增推送渠道'"
|
||||||
|
width="550px"
|
||||||
|
@close="resetForm"
|
||||||
|
>
|
||||||
|
<el-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formData"
|
||||||
|
:rules="formRules"
|
||||||
|
label-width="100px"
|
||||||
|
>
|
||||||
|
<el-form-item label="名称" prop="name">
|
||||||
|
<el-input v-model="formData.name" placeholder="请输入渠道名称" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="类型" prop="type">
|
||||||
|
<el-select v-model="formData.type" placeholder="请选择类型" style="width: 100%">
|
||||||
|
<el-option label="邮件" value="email" />
|
||||||
|
<el-option label="钉钉" value="dingtalk" />
|
||||||
|
<el-option label="企业微信" value="wechat" />
|
||||||
|
<el-option label="Slack" value="slack" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<!-- 邮件配置 -->
|
||||||
|
<template v-if="formData.type === 'email'">
|
||||||
|
<el-divider content-position="left">邮件配置</el-divider>
|
||||||
|
<el-form-item label="SMTP 服务器" prop="config.host">
|
||||||
|
<el-input v-model="formData.config.host" placeholder="如:smtp.gmail.com" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="端口" prop="config.port">
|
||||||
|
<el-input-number v-model="formData.config.port" :min="1" :max="65535" style="width: 100%" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="用户名">
|
||||||
|
<el-input v-model="formData.config.user" placeholder="SMTP 用户名" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="密码">
|
||||||
|
<el-input v-model="formData.config.pass" type="password" show-password placeholder="SMTP 密码" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="发件人">
|
||||||
|
<el-input v-model="formData.config.from" placeholder="发件人邮箱地址" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="收件人" prop="config.to">
|
||||||
|
<el-input v-model="formData.config.to" placeholder="收件人邮箱,多个用逗号分隔" />
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 钉钉配置 -->
|
||||||
|
<template v-if="formData.type === 'dingtalk'">
|
||||||
|
<el-divider content-position="left">钉钉配置</el-divider>
|
||||||
|
<el-form-item label="Webhook" prop="config.webhook">
|
||||||
|
<el-input v-model="formData.config.webhook" placeholder="钉钉机器人 Webhook 地址" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="签名密钥">
|
||||||
|
<el-input v-model="formData.config.secret" placeholder="加签密钥(可选)" />
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- 企业微信配置 -->
|
||||||
|
<template v-if="formData.type === 'wechat'">
|
||||||
|
<el-divider content-position="left">企业微信配置</el-divider>
|
||||||
|
<el-form-item label="Webhook" prop="config.webhook">
|
||||||
|
<el-input v-model="formData.config.webhook" placeholder="企业微信机器人 Webhook 地址" />
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<!-- Slack 配置 -->
|
||||||
|
<template v-if="formData.type === 'slack'">
|
||||||
|
<el-divider content-position="left">Slack 配置</el-divider>
|
||||||
|
<el-form-item label="Webhook" prop="config.webhook">
|
||||||
|
<el-input v-model="formData.config.webhook" placeholder="Slack Webhook URL" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="频道">
|
||||||
|
<el-input v-model="formData.config.channel" placeholder="频道名称(可选)" />
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<el-form-item label="启用状态">
|
||||||
|
<el-switch v-model="formData.enabled" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitting">
|
||||||
|
确定
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { Plus } from '@element-plus/icons-vue'
|
||||||
|
import type { FormInstance, FormRules } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Channel } from '@/api/types'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const tableData = ref<Channel[]>([])
|
||||||
|
const formRef = ref<FormInstance>()
|
||||||
|
|
||||||
|
const pagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formData = reactive({
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
type: 'email' as 'email' | 'dingtalk' | 'wechat' | 'slack',
|
||||||
|
config: {
|
||||||
|
// 邮件
|
||||||
|
host: '',
|
||||||
|
port: 587,
|
||||||
|
user: '',
|
||||||
|
pass: '',
|
||||||
|
from: '',
|
||||||
|
to: '',
|
||||||
|
// 钉钉/企业微信/Slack
|
||||||
|
webhook: '',
|
||||||
|
secret: '',
|
||||||
|
channel: '',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '请输入渠道名称', trigger: 'blur' }],
|
||||||
|
type: [{ required: true, message: '请选择类型', trigger: 'change' }],
|
||||||
|
'config.to': [{ required: true, message: '请输入收件人', trigger: 'blur' }],
|
||||||
|
'config.webhook': [{ required: true, message: '请输入 Webhook 地址', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get('/channels', {
|
||||||
|
params: {
|
||||||
|
page: pagination.page,
|
||||||
|
limit: pagination.limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
isEdit.value = false
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = (row: Channel) => {
|
||||||
|
isEdit.value = true
|
||||||
|
const config = row.config || {}
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
type: row.type,
|
||||||
|
config: {
|
||||||
|
host: config.host || '',
|
||||||
|
port: config.port || 587,
|
||||||
|
user: config.user || '',
|
||||||
|
pass: config.pass || '',
|
||||||
|
from: config.from || '',
|
||||||
|
to: config.to || '',
|
||||||
|
webhook: config.webhook || '',
|
||||||
|
secret: config.secret || '',
|
||||||
|
channel: config.channel || '',
|
||||||
|
},
|
||||||
|
enabled: row.enabled,
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: Channel) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除渠道 "${row.name}" 吗?`, '提示', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
await request.delete(`/channels/${row.id}`)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadData()
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('删除失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleEnabled = async (row: Channel) => {
|
||||||
|
try {
|
||||||
|
await request.put(`/channels/${row.id}`, {
|
||||||
|
enabled: row.enabled,
|
||||||
|
})
|
||||||
|
ElMessage.success(row.enabled ? '已启用' : '已禁用')
|
||||||
|
} catch (error) {
|
||||||
|
row.enabled = !row.enabled
|
||||||
|
console.error('更新状态失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!formRef.value) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await formRef.value.validate()
|
||||||
|
submitting.value = true
|
||||||
|
|
||||||
|
// 根据类型构建配置对象
|
||||||
|
let config: Record<string, any> = {}
|
||||||
|
|
||||||
|
if (formData.type === 'email') {
|
||||||
|
config = {
|
||||||
|
host: formData.config.host,
|
||||||
|
port: formData.config.port,
|
||||||
|
user: formData.config.user,
|
||||||
|
pass: formData.config.pass,
|
||||||
|
from: formData.config.from,
|
||||||
|
to: formData.config.to,
|
||||||
|
}
|
||||||
|
} else if (formData.type === 'dingtalk') {
|
||||||
|
config = {
|
||||||
|
webhook: formData.config.webhook,
|
||||||
|
secret: formData.config.secret || undefined,
|
||||||
|
}
|
||||||
|
} else if (formData.type === 'wechat') {
|
||||||
|
config = {
|
||||||
|
webhook: formData.config.webhook,
|
||||||
|
}
|
||||||
|
} else if (formData.type === 'slack') {
|
||||||
|
config = {
|
||||||
|
webhook: formData.config.webhook,
|
||||||
|
channel: formData.config.channel || undefined,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
name: formData.name,
|
||||||
|
type: formData.type,
|
||||||
|
config,
|
||||||
|
enabled: formData.enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEdit.value) {
|
||||||
|
await request.put(`/channels/${formData.id}`, data)
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
} else {
|
||||||
|
await request.post('/channels', data)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
}
|
||||||
|
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadData()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('提交失败', error)
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
type: 'email',
|
||||||
|
config: {
|
||||||
|
host: '',
|
||||||
|
port: 587,
|
||||||
|
user: '',
|
||||||
|
pass: '',
|
||||||
|
from: '',
|
||||||
|
to: '',
|
||||||
|
webhook: '',
|
||||||
|
secret: '',
|
||||||
|
channel: '',
|
||||||
|
},
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
formRef.value?.resetFields()
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeLabel = (type: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
email: '邮件',
|
||||||
|
dingtalk: '钉钉',
|
||||||
|
wechat: '企业微信',
|
||||||
|
slack: 'Slack',
|
||||||
|
}
|
||||||
|
return map[type] || type
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeTagType = (type: string) => {
|
||||||
|
const map: Record<string, 'success' | 'warning' | 'info' | 'danger'> = {
|
||||||
|
email: 'info',
|
||||||
|
dingtalk: 'success',
|
||||||
|
wechat: 'warning',
|
||||||
|
slack: 'danger',
|
||||||
|
}
|
||||||
|
return map[type] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.channels {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,281 @@
|
|||||||
|
<template>
|
||||||
|
<div class="llm-config">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>LLM 配置管理</h2>
|
||||||
|
<el-button type="primary" @click="handleAdd">
|
||||||
|
<el-icon><Plus /></el-icon>
|
||||||
|
新增配置
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="名称" min-width="120" />
|
||||||
|
<el-table-column prop="baseUrl" label="API 地址" min-width="200" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="model" label="模型" min-width="120" />
|
||||||
|
<el-table-column prop="apiKey" label="API Key" min-width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span>{{ maskApiKey(row.apiKey) }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="enabled" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch
|
||||||
|
v-model="row.enabled"
|
||||||
|
@change="handleToggleEnabled(row)"
|
||||||
|
/>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="createdAt" label="创建时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.createdAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="150" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 新增/编辑对话框 -->
|
||||||
|
<el-dialog
|
||||||
|
v-model="dialogVisible"
|
||||||
|
:title="isEdit ? '编辑 LLM 配置' : '新增 LLM 配置'"
|
||||||
|
width="500px"
|
||||||
|
@close="resetForm"
|
||||||
|
>
|
||||||
|
<el-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formData"
|
||||||
|
:rules="formRules"
|
||||||
|
label-width="100px"
|
||||||
|
>
|
||||||
|
<el-form-item label="名称" prop="name">
|
||||||
|
<el-input v-model="formData.name" placeholder="请输入配置名称" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="API 地址" prop="baseUrl">
|
||||||
|
<el-input v-model="formData.baseUrl" placeholder="如:https://api.openai.com/v1" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="模型" prop="model">
|
||||||
|
<el-input v-model="formData.model" placeholder="如:gpt-4、gpt-3.5-turbo" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="API Key" prop="apiKey">
|
||||||
|
<el-input
|
||||||
|
v-model="formData.apiKey"
|
||||||
|
type="password"
|
||||||
|
show-password
|
||||||
|
placeholder="请输入 API Key"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="启用状态">
|
||||||
|
<el-switch v-model="formData.enabled" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitting">
|
||||||
|
确定
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { Plus } from '@element-plus/icons-vue'
|
||||||
|
import type { FormInstance, FormRules } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { LlmConfig } from '@/api/types'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const tableData = ref<LlmConfig[]>([])
|
||||||
|
const formRef = ref<FormInstance>()
|
||||||
|
|
||||||
|
const pagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formData = reactive({
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
baseUrl: '',
|
||||||
|
model: '',
|
||||||
|
apiKey: '',
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '请输入配置名称', trigger: 'blur' }],
|
||||||
|
baseUrl: [{ required: true, message: '请输入 API 地址', trigger: 'blur' }],
|
||||||
|
model: [{ required: true, message: '请输入模型名称', trigger: 'blur' }],
|
||||||
|
apiKey: [{ required: true, message: '请输入 API Key', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get('/llm-configs', {
|
||||||
|
params: {
|
||||||
|
page: pagination.page,
|
||||||
|
limit: pagination.limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
isEdit.value = false
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = (row: LlmConfig) => {
|
||||||
|
isEdit.value = true
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
baseUrl: row.baseUrl,
|
||||||
|
model: row.model,
|
||||||
|
apiKey: row.apiKey,
|
||||||
|
enabled: row.enabled,
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: LlmConfig) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除配置 "${row.name}" 吗?`, '提示', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
await request.delete(`/llm-configs/${row.id}`)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadData()
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('删除失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleEnabled = async (row: LlmConfig) => {
|
||||||
|
try {
|
||||||
|
await request.put(`/llm-configs/${row.id}`, {
|
||||||
|
enabled: row.enabled,
|
||||||
|
})
|
||||||
|
ElMessage.success(row.enabled ? '已启用' : '已禁用')
|
||||||
|
} catch (error) {
|
||||||
|
row.enabled = !row.enabled
|
||||||
|
console.error('更新状态失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!formRef.value) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await formRef.value.validate()
|
||||||
|
submitting.value = true
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
name: formData.name,
|
||||||
|
baseUrl: formData.baseUrl,
|
||||||
|
model: formData.model,
|
||||||
|
apiKey: formData.apiKey,
|
||||||
|
enabled: formData.enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEdit.value) {
|
||||||
|
await request.put(`/llm-configs/${formData.id}`, data)
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
} else {
|
||||||
|
await request.post('/llm-configs', data)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
}
|
||||||
|
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadData()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('提交失败', error)
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
baseUrl: '',
|
||||||
|
model: '',
|
||||||
|
apiKey: '',
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
formRef.value?.resetFields()
|
||||||
|
}
|
||||||
|
|
||||||
|
const maskApiKey = (key: string) => {
|
||||||
|
if (!key || key.length < 8) return '****'
|
||||||
|
return key.slice(0, 4) + '****' + key.slice(-4)
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.llm-config {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,255 @@
|
|||||||
|
<template>
|
||||||
|
<div class="space-y-6 animate-in fade-in duration-500">
|
||||||
|
<div class="flex items-center justify-between">
|
||||||
|
<div class="space-y-1">
|
||||||
|
<h2 class="text-2xl font-bold tracking-tight">数据源 (Sources)</h2>
|
||||||
|
<p class="text-sm text-muted-foreground">管理系统采集资讯的来源,包括 RSS、API 及网页爬虫</p>
|
||||||
|
</div>
|
||||||
|
<el-button type="primary" @click="handleAdd" class="!rounded-lg !px-6 shadow-sm">
|
||||||
|
<el-icon class="mr-2"><Plus /></el-icon>
|
||||||
|
新增来源
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Modern Table -->
|
||||||
|
<div class="rounded-xl border bg-card shadow-sm overflow-hidden">
|
||||||
|
<el-table :data="tableData" v-loading="loading" class="modern-table">
|
||||||
|
<el-table-column prop="name" label="数据源名称" min-width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="flex items-center gap-3">
|
||||||
|
<div :class="['p-2 rounded-lg bg-muted', getTypeIconClass(row.type)]">
|
||||||
|
<component :is="getTypeIcon(row.type)" class="h-4 w-4" />
|
||||||
|
</div>
|
||||||
|
<span class="font-medium text-sm">{{ row.name }}</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="类型" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="text-xs font-bold uppercase tracking-wider text-muted-foreground">{{ getTypeLabel(row.type) }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column prop="cronExpression" label="频率" width="140">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<code class="px-1.5 py-0.5 rounded bg-muted text-[10px] font-mono">{{ row.cronExpression }}</code>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="健康状态" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<span :class="['h-2 w-2 rounded-full', row.enabled ? 'bg-green-500 shadow-[0_0_8px_rgba(34,197,94,0.5)]' : 'bg-muted']"></span>
|
||||||
|
<span class="text-xs">{{ row.enabled ? '运行中' : '已停止' }}</span>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="最后同步" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span class="text-xs text-muted-foreground italic">{{ row.lastCollectedAt ? formatTime(row.lastCollectedAt) : '从未同步' }}</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
|
||||||
|
<el-table-column label="操作" width="180" fixed="right" align="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<div class="flex justify-end gap-1">
|
||||||
|
<el-button type="primary" link @click="handleEdit(row)" title="编辑">
|
||||||
|
<el-icon><EditPen /></el-icon>
|
||||||
|
</el-button>
|
||||||
|
<el-button type="success" link @click="handleCollect(row)" title="立即采集">
|
||||||
|
<el-icon><Refresh /></el-icon>
|
||||||
|
</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)" title="删除">
|
||||||
|
<el-icon><Delete /></el-icon>
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="px-6 py-4 border-t flex justify-end">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
size="small"
|
||||||
|
layout="prev, pager, next"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Side Drawer Form -->
|
||||||
|
<el-drawer
|
||||||
|
v-model="drawerVisible"
|
||||||
|
:title="isEdit ? '编辑数据源' : '新增数据源'"
|
||||||
|
size="480px"
|
||||||
|
direction="rtl"
|
||||||
|
@close="resetForm"
|
||||||
|
>
|
||||||
|
<el-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formData"
|
||||||
|
:rules="formRules"
|
||||||
|
label-position="top"
|
||||||
|
class="space-y-6"
|
||||||
|
>
|
||||||
|
<div class="space-y-4 rounded-xl border bg-muted/30 p-4">
|
||||||
|
<p class="text-sm font-bold">基础信息</p>
|
||||||
|
<el-form-item prop="name" label="名称">
|
||||||
|
<el-input v-model="formData.name" placeholder="Hacker News Top" />
|
||||||
|
</el-form-item>
|
||||||
|
<div class="grid grid-cols-2 gap-4">
|
||||||
|
<el-form-item prop="type" label="协议类型">
|
||||||
|
<el-select v-model="formData.type" class="w-full">
|
||||||
|
<el-option label="RSS Feed" value="rss" />
|
||||||
|
<el-option label="JSON API" value="api" />
|
||||||
|
<el-option label="Browser Crawler" value="playwright" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item prop="cronExpression" label="采集频率">
|
||||||
|
<el-input v-model="formData.cronExpression" placeholder="0 * * * *" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="space-y-4 rounded-xl border bg-muted/30 p-4">
|
||||||
|
<p class="text-sm font-bold">连接配置</p>
|
||||||
|
<el-form-item prop="config.url" label="目标 URL">
|
||||||
|
<el-input v-model="formData.config.url" placeholder="https://..." />
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<template v-if="formData.type === 'api'">
|
||||||
|
<el-form-item label="HTTP Method">
|
||||||
|
<el-select v-model="formData.config.method" class="w-full">
|
||||||
|
<el-option label="GET" value="GET" />
|
||||||
|
<el-option label="POST" value="POST" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<template v-if="formData.type === 'playwright'">
|
||||||
|
<el-form-item label="List Selector (CSS)">
|
||||||
|
<el-input v-model="formData.config.listSelector" placeholder=".news-list > .item" />
|
||||||
|
</el-form-item>
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-form-item>
|
||||||
|
<div class="flex items-center gap-2">
|
||||||
|
<el-switch v-model="formData.enabled" />
|
||||||
|
<span class="text-sm font-medium">启用此采集任务</span>
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
|
||||||
|
<template #footer>
|
||||||
|
<div class="flex gap-3 px-4 py-4 border-t">
|
||||||
|
<el-button @click="drawerVisible = false" class="flex-1">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitting" class="flex-1">
|
||||||
|
{{ isEdit ? '保存更改' : '立即创建' }}
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
</el-drawer>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import {
|
||||||
|
Plus, EditPen, Delete, Refresh
|
||||||
|
} from '@element-plus/icons-vue'
|
||||||
|
import { Rss, Globe, Code2 } from 'lucide-vue-next'
|
||||||
|
import type { FormInstance, FormRules } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Source } from '@/api/types'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const drawerVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const tableData = ref<Source[]>([])
|
||||||
|
const formRef = ref<FormInstance>()
|
||||||
|
|
||||||
|
const pagination = reactive({ page: 1, limit: 10, total: 0 })
|
||||||
|
const formData = reactive({
|
||||||
|
id: 0, name: '', type: 'rss', cronExpression: '0 * * * *',
|
||||||
|
config: { url: '', method: 'GET', listSelector: '' },
|
||||||
|
enabled: true
|
||||||
|
})
|
||||||
|
|
||||||
|
const formRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '名称必填', trigger: 'blur' }],
|
||||||
|
'config.url': [{ required: true, message: 'URL必填', trigger: 'blur' }]
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get('/sources', { params: { page: pagination.page, limit: pagination.limit } })
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAdd = () => { isEdit.value = false; drawerVisible.value = true }
|
||||||
|
const handleEdit = (row: Source) => {
|
||||||
|
isEdit.value = true
|
||||||
|
Object.assign(formData, { id: row.id, name: row.name, type: row.type, cronExpression: row.cronExpression, config: { ...row.config }, enabled: row.enabled })
|
||||||
|
drawerVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!formRef.value) return
|
||||||
|
await formRef.value.validate()
|
||||||
|
submitting.value = true
|
||||||
|
try {
|
||||||
|
const method = isEdit.value ? 'put' : 'post'
|
||||||
|
const url = isEdit.value ? `/sources/${formData.id}` : '/sources'
|
||||||
|
await request[method](url, formData)
|
||||||
|
ElMessage.success('操作成功')
|
||||||
|
drawerVisible.value = false
|
||||||
|
loadData()
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCollect = async (row: Source) => {
|
||||||
|
await request.post(`/sources/${row.id}/collect`)
|
||||||
|
ElMessage.success('采集任务已排队')
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: Source) => {
|
||||||
|
await ElMessageBox.confirm('确定彻底删除该数据源?', '删除确认', { type: 'warning' })
|
||||||
|
await request.delete(`/sources/${row.id}`)
|
||||||
|
loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
Object.assign(formData, { id: 0, name: '', type: 'rss', cronExpression: '0 * * * *', config: { url: '', method: 'GET' }, enabled: true })
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeIcon = (type: string) => {
|
||||||
|
if (type === 'rss') return Rss
|
||||||
|
if (type === 'api') return Code2
|
||||||
|
return Globe
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeIconClass = (type: string) => {
|
||||||
|
if (type === 'rss') return 'text-orange-500'
|
||||||
|
if (type === 'api') return 'text-blue-500'
|
||||||
|
return 'text-purple-500'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeLabel = (type: string) => ({ rss: 'RSS Feed', api: 'REST API', playwright: 'Crawler' }[type] || type)
|
||||||
|
const formatTime = (t: string) => new Date(t).toLocaleString('zh-CN', { month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit' })
|
||||||
|
|
||||||
|
onMounted(loadData)
|
||||||
|
</script>
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
<template>
|
||||||
|
<div class="topics">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>主题管理</h2>
|
||||||
|
<el-button type="primary" @click="handleAdd">
|
||||||
|
<el-icon><Plus /></el-icon>
|
||||||
|
新增主题
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card>
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="名称" min-width="150" />
|
||||||
|
<el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip />
|
||||||
|
<el-table-column prop="processMode" label="处理模式" width="120">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag>{{ getProcessModeLabel(row.processMode) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="LLM 配置" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.llmConfig?.name || '未配置' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="enabled" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-switch v-model="row.enabled" @change="handleToggleEnabled(row)" />
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="200" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
|
||||||
|
<el-button type="success" link @click="handleGenerateReport(row)">生成报告</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<!-- 新增/编辑对话框 -->
|
||||||
|
<el-dialog
|
||||||
|
v-model="dialogVisible"
|
||||||
|
:title="isEdit ? '编辑主题' : '新增主题'"
|
||||||
|
width="650px"
|
||||||
|
@close="resetForm"
|
||||||
|
>
|
||||||
|
<el-form
|
||||||
|
ref="formRef"
|
||||||
|
:model="formData"
|
||||||
|
:rules="formRules"
|
||||||
|
label-width="100px"
|
||||||
|
>
|
||||||
|
<el-form-item label="名称" prop="name">
|
||||||
|
<el-input v-model="formData.name" placeholder="请输入主题名称" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="描述">
|
||||||
|
<el-input
|
||||||
|
v-model="formData.description"
|
||||||
|
type="textarea"
|
||||||
|
:rows="2"
|
||||||
|
placeholder="请输入主题描述"
|
||||||
|
/>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="处理模式" prop="processMode">
|
||||||
|
<el-select v-model="formData.processMode" placeholder="请选择处理模式" style="width: 100%">
|
||||||
|
<el-option label="聚合" value="aggregate" />
|
||||||
|
<el-option label="摘要" value="summary" />
|
||||||
|
<el-option label="深度分析" value="deep_analysis" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="LLM 配置">
|
||||||
|
<el-select
|
||||||
|
v-model="formData.llmConfigId"
|
||||||
|
placeholder="请选择 LLM 配置"
|
||||||
|
style="width: 100%"
|
||||||
|
clearable
|
||||||
|
>
|
||||||
|
<el-option
|
||||||
|
v-for="item in llmConfigs"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="调度配置" prop="scheduleConfig">
|
||||||
|
<el-input
|
||||||
|
v-model="formData.scheduleCron"
|
||||||
|
placeholder="Cron 表达式,如:0 0 * * 0(每周日)"
|
||||||
|
>
|
||||||
|
<template #append>
|
||||||
|
<el-tooltip content="每天: 0 0 * * * 每周: 0 0 * * 0 每月: 0 0 1 * *" raw-content>
|
||||||
|
<el-icon><QuestionFilled /></el-icon>
|
||||||
|
</el-tooltip>
|
||||||
|
</template>
|
||||||
|
</el-input>
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<el-divider content-position="left">关联数据源</el-divider>
|
||||||
|
<el-form-item label="数据源">
|
||||||
|
<el-select
|
||||||
|
v-model="formData.sourceIds"
|
||||||
|
multiple
|
||||||
|
placeholder="请选择关联的数据源"
|
||||||
|
style="width: 100%"
|
||||||
|
>
|
||||||
|
<el-option
|
||||||
|
v-for="item in sources"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<el-divider content-position="left">关联推送渠道</el-divider>
|
||||||
|
<el-form-item label="推送渠道">
|
||||||
|
<el-select
|
||||||
|
v-model="formData.channelIds"
|
||||||
|
multiple
|
||||||
|
placeholder="请选择关联的推送渠道"
|
||||||
|
style="width: 100%"
|
||||||
|
>
|
||||||
|
<el-option
|
||||||
|
v-for="item in channels"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
|
||||||
|
<el-form-item label="启用状态">
|
||||||
|
<el-switch v-model="formData.enabled" />
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
<template #footer>
|
||||||
|
<el-button @click="dialogVisible = false">取消</el-button>
|
||||||
|
<el-button type="primary" @click="handleSubmit" :loading="submitting">
|
||||||
|
确定
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-dialog>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { Plus, QuestionFilled } from '@element-plus/icons-vue'
|
||||||
|
import type { FormInstance, FormRules } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Topic, LlmConfig, Source, Channel } from '@/api/types'
|
||||||
|
|
||||||
|
const loading = ref(false)
|
||||||
|
const submitting = ref(false)
|
||||||
|
const dialogVisible = ref(false)
|
||||||
|
const isEdit = ref(false)
|
||||||
|
const tableData = ref<Topic[]>([])
|
||||||
|
const formRef = ref<FormInstance>()
|
||||||
|
|
||||||
|
// 下拉选项数据
|
||||||
|
const llmConfigs = ref<LlmConfig[]>([])
|
||||||
|
const sources = ref<Source[]>([])
|
||||||
|
const channels = ref<Channel[]>([])
|
||||||
|
|
||||||
|
const pagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formData = reactive({
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
processMode: 'summary' as 'aggregate' | 'summary' | 'deep_analysis',
|
||||||
|
llmConfigId: null as number | null,
|
||||||
|
scheduleCron: '0 0 * * 0',
|
||||||
|
sourceIds: [] as number[],
|
||||||
|
channelIds: [] as number[],
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const formRules: FormRules = {
|
||||||
|
name: [{ required: true, message: '请输入主题名称', trigger: 'blur' }],
|
||||||
|
processMode: [{ required: true, message: '请选择处理模式', trigger: 'change' }],
|
||||||
|
scheduleConfig: [{ required: true, message: '请输入调度配置', trigger: 'blur' }],
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get('/topics', {
|
||||||
|
params: {
|
||||||
|
page: pagination.page,
|
||||||
|
limit: pagination.limit,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadOptions = async () => {
|
||||||
|
try {
|
||||||
|
const [llmRes, sourceRes, channelRes] = await Promise.all([
|
||||||
|
request.get('/llm-configs', { params: { limit: 100 } }),
|
||||||
|
request.get('/sources', { params: { limit: 100 } }),
|
||||||
|
request.get('/channels', { params: { limit: 100 } }),
|
||||||
|
])
|
||||||
|
llmConfigs.value = llmRes.data || []
|
||||||
|
sources.value = sourceRes.data || []
|
||||||
|
channels.value = channelRes.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载选项数据失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
isEdit.value = false
|
||||||
|
dialogVisible.value = true
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleEdit = async (row: Topic) => {
|
||||||
|
isEdit.value = true
|
||||||
|
|
||||||
|
// 获取详情以获取关联数据
|
||||||
|
try {
|
||||||
|
const res = await request.get(`/topics/${row.id}`)
|
||||||
|
const topic = res.data
|
||||||
|
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: topic.id,
|
||||||
|
name: topic.name,
|
||||||
|
description: topic.description || '',
|
||||||
|
processMode: topic.processMode,
|
||||||
|
llmConfigId: topic.llmConfigId,
|
||||||
|
scheduleCron: topic.scheduleConfig?.cron || '0 0 * * 0',
|
||||||
|
sourceIds: topic.topicSources?.map((ts: any) => ts.source.id) || [],
|
||||||
|
channelIds: topic.topicChannels?.map((tc: any) => tc.channel.id) || [],
|
||||||
|
enabled: topic.enabled,
|
||||||
|
})
|
||||||
|
dialogVisible.value = true
|
||||||
|
} catch (error) {
|
||||||
|
console.error('获取主题详情失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: Topic) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除主题 "${row.name}" 吗?`, '提示', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
await request.delete(`/topics/${row.id}`)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadData()
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('删除失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleToggleEnabled = async (row: Topic) => {
|
||||||
|
try {
|
||||||
|
await request.put(`/topics/${row.id}`, {
|
||||||
|
enabled: row.enabled,
|
||||||
|
})
|
||||||
|
ElMessage.success(row.enabled ? '已启用' : '已禁用')
|
||||||
|
} catch (error) {
|
||||||
|
row.enabled = !row.enabled
|
||||||
|
console.error('更新状态失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleGenerateReport = async (row: Topic) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要为主题 "${row.name}" 生成报告吗?`, '提示', {
|
||||||
|
type: 'info',
|
||||||
|
})
|
||||||
|
await request.post(`/topics/${row.id}/generate-report`)
|
||||||
|
ElMessage.success('报告生成任务已触发')
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('触发报告生成失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleSubmit = async () => {
|
||||||
|
if (!formRef.value) return
|
||||||
|
|
||||||
|
try {
|
||||||
|
await formRef.value.validate()
|
||||||
|
submitting.value = true
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
name: formData.name,
|
||||||
|
description: formData.description || undefined,
|
||||||
|
processMode: formData.processMode,
|
||||||
|
llmConfigId: formData.llmConfigId || undefined,
|
||||||
|
scheduleConfig: { cron: formData.scheduleCron },
|
||||||
|
sourceIds: formData.sourceIds,
|
||||||
|
channelIds: formData.channelIds,
|
||||||
|
enabled: formData.enabled,
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isEdit.value) {
|
||||||
|
await request.put(`/topics/${formData.id}`, data)
|
||||||
|
ElMessage.success('更新成功')
|
||||||
|
} else {
|
||||||
|
await request.post('/topics', data)
|
||||||
|
ElMessage.success('创建成功')
|
||||||
|
}
|
||||||
|
|
||||||
|
dialogVisible.value = false
|
||||||
|
loadData()
|
||||||
|
} catch (error) {
|
||||||
|
console.error('提交失败', error)
|
||||||
|
} finally {
|
||||||
|
submitting.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetForm = () => {
|
||||||
|
Object.assign(formData, {
|
||||||
|
id: 0,
|
||||||
|
name: '',
|
||||||
|
description: '',
|
||||||
|
processMode: 'summary',
|
||||||
|
llmConfigId: null,
|
||||||
|
scheduleCron: '0 0 * * 0',
|
||||||
|
sourceIds: [],
|
||||||
|
channelIds: [],
|
||||||
|
enabled: true,
|
||||||
|
})
|
||||||
|
formRef.value?.resetFields()
|
||||||
|
}
|
||||||
|
|
||||||
|
const getProcessModeLabel = (mode: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
aggregate: '聚合',
|
||||||
|
summary: '摘要',
|
||||||
|
deep_analysis: '深度分析',
|
||||||
|
}
|
||||||
|
return map[mode] || mode
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
loadOptions()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.topics {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,469 @@
|
|||||||
|
<template>
|
||||||
|
<div class="monitoring">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>采集监控</h2>
|
||||||
|
<el-button type="primary" @click="loadData">
|
||||||
|
<el-icon><Refresh /></el-icon>
|
||||||
|
刷新
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 统计图表 -->
|
||||||
|
<el-row :gutter="20">
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<span>采集趋势(近7天)</span>
|
||||||
|
</template>
|
||||||
|
<v-chart class="chart" :option="trendChartOption" autoresize />
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
<el-col :span="12">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<span>数据源采集分布</span>
|
||||||
|
</template>
|
||||||
|
<v-chart class="chart" :option="pieChartOption" autoresize />
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- 数据源状态概览 -->
|
||||||
|
<el-row :gutter="20" style="margin-top: 20px">
|
||||||
|
<el-col :span="24">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<span>数据源状态概览</span>
|
||||||
|
</template>
|
||||||
|
<el-table :data="statsData" v-loading="statsLoading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="name" label="数据源" min-width="150" />
|
||||||
|
<el-table-column prop="type" label="类型" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="getTypeTagType(row.type)" size="small">{{ getTypeLabel(row.type) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="enabled" label="状态" width="80">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="row.enabled ? 'success' : 'info'" size="small">
|
||||||
|
{{ row.enabled ? '启用' : '禁用' }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="totalArticles" label="文章数" width="100" />
|
||||||
|
<el-table-column prop="totalCollections" label="采集次数" width="100" />
|
||||||
|
<el-table-column label="最后采集" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.lastCollectedAt ? formatTime(row.lastCollectedAt) : '从未采集' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="最后状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag
|
||||||
|
v-if="row.lastLog"
|
||||||
|
:type="row.lastLog.status === 'success' ? 'success' : (row.lastLog.status === 'running' ? 'warning' : 'danger')"
|
||||||
|
size="small"
|
||||||
|
>
|
||||||
|
{{ getLogStatusText(row.lastLog.status) }}
|
||||||
|
</el-tag>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="100" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleCollect(row)" :disabled="!row.enabled">
|
||||||
|
采集
|
||||||
|
</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
|
||||||
|
<!-- 采集日志 -->
|
||||||
|
<el-row :gutter="20" style="margin-top: 20px">
|
||||||
|
<el-col :span="24">
|
||||||
|
<el-card>
|
||||||
|
<template #header>
|
||||||
|
<div class="card-header">
|
||||||
|
<span>采集日志</span>
|
||||||
|
<div class="filter-inline">
|
||||||
|
<el-select v-model="logFilters.sourceId" placeholder="全部数据源" clearable size="small" style="width: 150px">
|
||||||
|
<el-option
|
||||||
|
v-for="item in sources"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
<el-select v-model="logFilters.status" placeholder="全部状态" clearable size="small" style="width: 120px; margin-left: 10px">
|
||||||
|
<el-option label="成功" value="success" />
|
||||||
|
<el-option label="失败" value="failed" />
|
||||||
|
<el-option label="运行中" value="running" />
|
||||||
|
</el-select>
|
||||||
|
<el-button type="primary" size="small" style="margin-left: 10px" @click="loadLogs">查询</el-button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
<el-table :data="logsData" v-loading="logsLoading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column label="数据源" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.source?.name || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="status" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="getLogStatusType(row.status)" size="small">
|
||||||
|
{{ getLogStatusText(row.status) }}
|
||||||
|
</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="articlesCount" label="采集数量" width="100" />
|
||||||
|
<el-table-column prop="startedAt" label="开始时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.startedAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="finishedAt" label="结束时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.finishedAt ? formatTime(row.finishedAt) : '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="errorMessage" label="错误信息" min-width="200" show-overflow-tooltip>
|
||||||
|
<template #default="{ row }">
|
||||||
|
<span v-if="row.errorMessage" class="error-text">{{ row.errorMessage }}</span>
|
||||||
|
<span v-else>-</span>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="logPagination.page"
|
||||||
|
v-model:page-size="logPagination.limit"
|
||||||
|
:total="logPagination.total"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadLogs"
|
||||||
|
@current-change="loadLogs"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</el-col>
|
||||||
|
</el-row>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, computed, onMounted } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { Refresh } from '@element-plus/icons-vue'
|
||||||
|
import { use } from 'echarts/core'
|
||||||
|
import { CanvasRenderer } from 'echarts/renderers'
|
||||||
|
import { LineChart, PieChart } from 'echarts/charts'
|
||||||
|
import {
|
||||||
|
TitleComponent,
|
||||||
|
TooltipComponent,
|
||||||
|
LegendComponent,
|
||||||
|
GridComponent,
|
||||||
|
} from 'echarts/components'
|
||||||
|
import VChart from 'vue-echarts'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { CollectionStats, CollectionLog, Source } from '@/api/types'
|
||||||
|
|
||||||
|
// 注册 ECharts 组件
|
||||||
|
use([
|
||||||
|
CanvasRenderer,
|
||||||
|
LineChart,
|
||||||
|
PieChart,
|
||||||
|
TitleComponent,
|
||||||
|
TooltipComponent,
|
||||||
|
LegendComponent,
|
||||||
|
GridComponent,
|
||||||
|
])
|
||||||
|
|
||||||
|
const statsLoading = ref(false)
|
||||||
|
const logsLoading = ref(false)
|
||||||
|
const statsData = ref<CollectionStats[]>([])
|
||||||
|
const logsData = ref<CollectionLog[]>([])
|
||||||
|
const sources = ref<Source[]>([])
|
||||||
|
|
||||||
|
const logFilters = reactive({
|
||||||
|
sourceId: null as number | null,
|
||||||
|
status: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const logPagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
// 采集趋势图表配置
|
||||||
|
const trendChartOption = computed(() => {
|
||||||
|
// 生成近7天的日期
|
||||||
|
const dates: string[] = []
|
||||||
|
const successData: number[] = []
|
||||||
|
const failedData: number[] = []
|
||||||
|
|
||||||
|
for (let i = 6; i >= 0; i--) {
|
||||||
|
const date = new Date()
|
||||||
|
date.setDate(date.getDate() - i)
|
||||||
|
dates.push(`${date.getMonth() + 1}/${date.getDate()}`)
|
||||||
|
|
||||||
|
// 统计当天的成功和失败次数
|
||||||
|
const dayStart = new Date(date)
|
||||||
|
dayStart.setHours(0, 0, 0, 0)
|
||||||
|
const dayEnd = new Date(date)
|
||||||
|
dayEnd.setHours(23, 59, 59, 999)
|
||||||
|
|
||||||
|
const dayLogs = logsData.value.filter(log => {
|
||||||
|
const logDate = new Date(log.startedAt)
|
||||||
|
return logDate >= dayStart && logDate <= dayEnd
|
||||||
|
})
|
||||||
|
|
||||||
|
successData.push(dayLogs.filter(l => l.status === 'success').length)
|
||||||
|
failedData.push(dayLogs.filter(l => l.status === 'failed').length)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'axis',
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
data: ['成功', '失败'],
|
||||||
|
bottom: 0,
|
||||||
|
},
|
||||||
|
grid: {
|
||||||
|
left: '3%',
|
||||||
|
right: '4%',
|
||||||
|
bottom: '15%',
|
||||||
|
top: '10%',
|
||||||
|
containLabel: true,
|
||||||
|
},
|
||||||
|
xAxis: {
|
||||||
|
type: 'category',
|
||||||
|
boundaryGap: false,
|
||||||
|
data: dates,
|
||||||
|
},
|
||||||
|
yAxis: {
|
||||||
|
type: 'value',
|
||||||
|
minInterval: 1,
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
name: '成功',
|
||||||
|
type: 'line',
|
||||||
|
smooth: true,
|
||||||
|
data: successData,
|
||||||
|
itemStyle: { color: '#67c23a' },
|
||||||
|
areaStyle: { color: 'rgba(103, 194, 58, 0.1)' },
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: '失败',
|
||||||
|
type: 'line',
|
||||||
|
smooth: true,
|
||||||
|
data: failedData,
|
||||||
|
itemStyle: { color: '#f56c6c' },
|
||||||
|
areaStyle: { color: 'rgba(245, 108, 108, 0.1)' },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
// 数据源采集分布饼图配置
|
||||||
|
const pieChartOption = computed(() => {
|
||||||
|
const data = statsData.value
|
||||||
|
.filter(s => s.totalArticles > 0)
|
||||||
|
.map(s => ({
|
||||||
|
name: s.name,
|
||||||
|
value: s.totalArticles,
|
||||||
|
}))
|
||||||
|
|
||||||
|
return {
|
||||||
|
tooltip: {
|
||||||
|
trigger: 'item',
|
||||||
|
formatter: '{b}: {c} ({d}%)',
|
||||||
|
},
|
||||||
|
legend: {
|
||||||
|
orient: 'vertical',
|
||||||
|
right: '5%',
|
||||||
|
top: 'center',
|
||||||
|
},
|
||||||
|
series: [
|
||||||
|
{
|
||||||
|
type: 'pie',
|
||||||
|
radius: ['40%', '70%'],
|
||||||
|
center: ['40%', '50%'],
|
||||||
|
avoidLabelOverlap: false,
|
||||||
|
itemStyle: {
|
||||||
|
borderRadius: 4,
|
||||||
|
borderColor: '#fff',
|
||||||
|
borderWidth: 2,
|
||||||
|
},
|
||||||
|
label: {
|
||||||
|
show: false,
|
||||||
|
},
|
||||||
|
emphasis: {
|
||||||
|
label: {
|
||||||
|
show: true,
|
||||||
|
fontSize: 14,
|
||||||
|
fontWeight: 'bold',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
data: data.length > 0 ? data : [{ name: '暂无数据', value: 1 }],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadData = () => {
|
||||||
|
loadStats()
|
||||||
|
loadLogs()
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadStats = async () => {
|
||||||
|
statsLoading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get('/collection-logs/stats')
|
||||||
|
statsData.value = res.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载统计数据失败', error)
|
||||||
|
} finally {
|
||||||
|
statsLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadLogs = async () => {
|
||||||
|
logsLoading.value = true
|
||||||
|
try {
|
||||||
|
const params: Record<string, any> = {
|
||||||
|
page: logPagination.page,
|
||||||
|
limit: logPagination.limit,
|
||||||
|
}
|
||||||
|
if (logFilters.sourceId) params.sourceId = logFilters.sourceId
|
||||||
|
if (logFilters.status) params.status = logFilters.status
|
||||||
|
|
||||||
|
const res = await request.get('/collection-logs', { params })
|
||||||
|
logsData.value = res.data || []
|
||||||
|
logPagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载日志失败', error)
|
||||||
|
} finally {
|
||||||
|
logsLoading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadSources = async () => {
|
||||||
|
try {
|
||||||
|
const res = await request.get('/sources', { params: { limit: 100 } })
|
||||||
|
sources.value = res.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据源失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCollect = async (row: CollectionStats) => {
|
||||||
|
try {
|
||||||
|
await request.post(`/sources/${row.id}/collect`)
|
||||||
|
ElMessage.success('采集任务已触发')
|
||||||
|
// 延迟刷新数据
|
||||||
|
setTimeout(() => {
|
||||||
|
loadData()
|
||||||
|
}, 1000)
|
||||||
|
} catch (error) {
|
||||||
|
console.error('触发采集失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeLabel = (type: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
rss: 'RSS',
|
||||||
|
api: 'API',
|
||||||
|
playwright: '爬虫',
|
||||||
|
}
|
||||||
|
return map[type] || type
|
||||||
|
}
|
||||||
|
|
||||||
|
const getTypeTagType = (type: string) => {
|
||||||
|
const map: Record<string, 'success' | 'warning' | 'info'> = {
|
||||||
|
rss: 'success',
|
||||||
|
api: 'warning',
|
||||||
|
playwright: 'info',
|
||||||
|
}
|
||||||
|
return map[type] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getLogStatusType = (status: string) => {
|
||||||
|
const map: Record<string, 'success' | 'warning' | 'danger'> = {
|
||||||
|
success: 'success',
|
||||||
|
running: 'warning',
|
||||||
|
failed: 'danger',
|
||||||
|
}
|
||||||
|
return map[status] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getLogStatusText = (status: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
success: '成功',
|
||||||
|
running: '运行中',
|
||||||
|
failed: '失败',
|
||||||
|
}
|
||||||
|
return map[status] || status
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
loadSources()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.monitoring {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.chart {
|
||||||
|
height: 280px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.card-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-inline {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-text {
|
||||||
|
color: #f56c6c;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
<template>
|
||||||
|
<div class="report-detail" v-loading="loading">
|
||||||
|
<div class="page-header">
|
||||||
|
<el-button @click="$router.back()">
|
||||||
|
<el-icon><ArrowLeft /></el-icon>
|
||||||
|
返回
|
||||||
|
</el-button>
|
||||||
|
<h2>{{ report?.title || '报告详情' }}</h2>
|
||||||
|
<el-button type="primary" @click="handleRefresh" :loading="loading">
|
||||||
|
<el-icon><Refresh /></el-icon>
|
||||||
|
刷新
|
||||||
|
</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card v-if="report">
|
||||||
|
<div class="report-meta">
|
||||||
|
<el-descriptions :column="3" border>
|
||||||
|
<el-descriptions-item label="主题">{{ report.topic?.name || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="状态">
|
||||||
|
<el-tag :type="getStatusType(report.status)">{{ getStatusText(report.status) }}</el-tag>
|
||||||
|
</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="LLM 配置">{{ report.topic?.llmConfig?.name || '-' }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="周期开始">{{ formatDate(report.periodStart) }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="周期结束">{{ formatDate(report.periodEnd) }}</el-descriptions-item>
|
||||||
|
<el-descriptions-item label="创建时间">{{ formatTime(report.createdAt) }}</el-descriptions-item>
|
||||||
|
</el-descriptions>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-divider />
|
||||||
|
|
||||||
|
<div class="report-content">
|
||||||
|
<div class="content-header">
|
||||||
|
<h3>报告内容</h3>
|
||||||
|
<el-button-group v-if="report.status === 'completed'">
|
||||||
|
<el-button size="small" @click="copyContent">
|
||||||
|
<el-icon><CopyDocument /></el-icon>
|
||||||
|
复制
|
||||||
|
</el-button>
|
||||||
|
<el-button size="small" @click="downloadContent">
|
||||||
|
<el-icon><Download /></el-icon>
|
||||||
|
下载
|
||||||
|
</el-button>
|
||||||
|
</el-button-group>
|
||||||
|
</div>
|
||||||
|
<div v-if="report.status === 'failed'" class="error-message">
|
||||||
|
<el-alert :title="report.errorMessage || '生成失败'" type="error" show-icon :closable="false" />
|
||||||
|
</div>
|
||||||
|
<div v-else-if="report.status === 'pending' || report.status === 'generating'" class="pending-message">
|
||||||
|
<el-empty description="报告正在生成中,请稍后刷新查看">
|
||||||
|
<el-button type="primary" @click="handleRefresh">刷新状态</el-button>
|
||||||
|
</el-empty>
|
||||||
|
</div>
|
||||||
|
<div v-else class="content-body markdown-body" v-html="renderedContent"></div>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-empty v-else-if="!loading" description="报告不存在" />
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, computed, onMounted } from 'vue'
|
||||||
|
import { useRoute } from 'vue-router'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { ArrowLeft, Refresh, CopyDocument, Download } from '@element-plus/icons-vue'
|
||||||
|
import MarkdownIt from 'markdown-it'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Report } from '@/api/types'
|
||||||
|
|
||||||
|
// 初始化 markdown-it
|
||||||
|
const md = new MarkdownIt({
|
||||||
|
html: true,
|
||||||
|
linkify: true,
|
||||||
|
typographer: true,
|
||||||
|
breaks: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
const route = useRoute()
|
||||||
|
const loading = ref(false)
|
||||||
|
const report = ref<Report | null>(null)
|
||||||
|
|
||||||
|
const renderedContent = computed(() => {
|
||||||
|
if (!report.value?.content) return ''
|
||||||
|
return md.render(report.value.content)
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadReport = async () => {
|
||||||
|
const id = route.params.id
|
||||||
|
if (!id) return
|
||||||
|
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const res = await request.get(`/reports/${id}`)
|
||||||
|
report.value = res.data
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载报告失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleRefresh = () => {
|
||||||
|
loadReport()
|
||||||
|
}
|
||||||
|
|
||||||
|
const copyContent = async () => {
|
||||||
|
if (!report.value?.content) return
|
||||||
|
try {
|
||||||
|
await navigator.clipboard.writeText(report.value.content)
|
||||||
|
ElMessage.success('已复制到剪贴板')
|
||||||
|
} catch (error) {
|
||||||
|
ElMessage.error('复制失败')
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const downloadContent = () => {
|
||||||
|
if (!report.value?.content) return
|
||||||
|
const blob = new Blob([report.value.content], { type: 'text/markdown' })
|
||||||
|
const url = URL.createObjectURL(blob)
|
||||||
|
const a = document.createElement('a')
|
||||||
|
a.href = url
|
||||||
|
a.download = `${report.value.title || '报告'}.md`
|
||||||
|
document.body.appendChild(a)
|
||||||
|
a.click()
|
||||||
|
document.body.removeChild(a)
|
||||||
|
URL.revokeObjectURL(url)
|
||||||
|
ElMessage.success('下载成功')
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusType = (status: string) => {
|
||||||
|
const map: Record<string, 'info' | 'warning' | 'success' | 'danger'> = {
|
||||||
|
pending: 'info',
|
||||||
|
generating: 'warning',
|
||||||
|
completed: 'success',
|
||||||
|
failed: 'danger',
|
||||||
|
}
|
||||||
|
return map[status] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusText = (status: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
pending: '待处理',
|
||||||
|
generating: '生成中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
}
|
||||||
|
return map[status] || status
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatDate = (date: string) => {
|
||||||
|
if (!date) return '-'
|
||||||
|
return new Date(date).toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
if (!time) return '-'
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadReport()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.report-detail {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-meta {
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-content .content-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 15px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.report-content .content-header h3 {
|
||||||
|
margin: 0;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.content-body {
|
||||||
|
padding: 24px;
|
||||||
|
background-color: #fff;
|
||||||
|
border: 1px solid #ebeef5;
|
||||||
|
border-radius: 4px;
|
||||||
|
line-height: 1.8;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Markdown 样式 */
|
||||||
|
.markdown-body :deep(h1) {
|
||||||
|
font-size: 24px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 24px 0 16px;
|
||||||
|
padding-bottom: 8px;
|
||||||
|
border-bottom: 1px solid #ebeef5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(h2) {
|
||||||
|
font-size: 20px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 20px 0 12px;
|
||||||
|
padding-bottom: 6px;
|
||||||
|
border-bottom: 1px solid #ebeef5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(h3) {
|
||||||
|
font-size: 18px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 16px 0 10px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(h4) {
|
||||||
|
font-size: 16px;
|
||||||
|
font-weight: 600;
|
||||||
|
margin: 14px 0 8px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(p) {
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(ul),
|
||||||
|
.markdown-body :deep(ol) {
|
||||||
|
padding-left: 24px;
|
||||||
|
margin: 12px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(li) {
|
||||||
|
margin: 6px 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(blockquote) {
|
||||||
|
margin: 16px 0;
|
||||||
|
padding: 12px 20px;
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
border-left: 4px solid #409eff;
|
||||||
|
color: #606266;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(code) {
|
||||||
|
padding: 2px 6px;
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
border-radius: 3px;
|
||||||
|
font-family: 'Consolas', 'Monaco', monospace;
|
||||||
|
font-size: 14px;
|
||||||
|
color: #e6a23c;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(pre) {
|
||||||
|
margin: 16px 0;
|
||||||
|
padding: 16px;
|
||||||
|
background-color: #282c34;
|
||||||
|
border-radius: 4px;
|
||||||
|
overflow-x: auto;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(pre code) {
|
||||||
|
padding: 0;
|
||||||
|
background-color: transparent;
|
||||||
|
color: #abb2bf;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(table) {
|
||||||
|
width: 100%;
|
||||||
|
margin: 16px 0;
|
||||||
|
border-collapse: collapse;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(th),
|
||||||
|
.markdown-body :deep(td) {
|
||||||
|
padding: 10px 12px;
|
||||||
|
border: 1px solid #ebeef5;
|
||||||
|
text-align: left;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(th) {
|
||||||
|
background-color: #f5f7fa;
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(tr:nth-child(even)) {
|
||||||
|
background-color: #fafafa;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(a) {
|
||||||
|
color: #409eff;
|
||||||
|
text-decoration: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(a:hover) {
|
||||||
|
text-decoration: underline;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(hr) {
|
||||||
|
margin: 24px 0;
|
||||||
|
border: none;
|
||||||
|
border-top: 1px solid #ebeef5;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(img) {
|
||||||
|
max-width: 100%;
|
||||||
|
border-radius: 4px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(strong) {
|
||||||
|
font-weight: 600;
|
||||||
|
}
|
||||||
|
|
||||||
|
.markdown-body :deep(em) {
|
||||||
|
font-style: italic;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error-message,
|
||||||
|
.pending-message {
|
||||||
|
padding: 20px;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
<template>
|
||||||
|
<div class="report-list">
|
||||||
|
<div class="page-header">
|
||||||
|
<h2>报告中心</h2>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<el-card class="filter-card">
|
||||||
|
<el-form :inline="true" :model="filters">
|
||||||
|
<el-form-item label="主题">
|
||||||
|
<el-select v-model="filters.topicId" placeholder="全部主题" clearable style="width: 200px">
|
||||||
|
<el-option
|
||||||
|
v-for="item in topics"
|
||||||
|
:key="item.id"
|
||||||
|
:label="item.name"
|
||||||
|
:value="item.id"
|
||||||
|
/>
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="状态">
|
||||||
|
<el-select v-model="filters.status" placeholder="全部状态" clearable style="width: 150px">
|
||||||
|
<el-option label="待处理" value="pending" />
|
||||||
|
<el-option label="生成中" value="generating" />
|
||||||
|
<el-option label="已完成" value="completed" />
|
||||||
|
<el-option label="失败" value="failed" />
|
||||||
|
</el-select>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item>
|
||||||
|
<el-button type="primary" @click="loadData">查询</el-button>
|
||||||
|
<el-button @click="resetFilters">重置</el-button>
|
||||||
|
</el-form-item>
|
||||||
|
</el-form>
|
||||||
|
</el-card>
|
||||||
|
|
||||||
|
<el-card style="margin-top: 20px">
|
||||||
|
<el-table :data="tableData" v-loading="loading" stripe>
|
||||||
|
<el-table-column prop="id" label="ID" width="80" />
|
||||||
|
<el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
|
||||||
|
<el-table-column label="主题" width="150">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ row.topic?.name || '-' }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="status" label="状态" width="100">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-tag :type="getStatusType(row.status)">{{ getStatusText(row.status) }}</el-tag>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="周期" width="200">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatDate(row.periodStart) }} ~ {{ formatDate(row.periodEnd) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column prop="createdAt" label="创建时间" width="180">
|
||||||
|
<template #default="{ row }">
|
||||||
|
{{ formatTime(row.createdAt) }}
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
<el-table-column label="操作" width="150" fixed="right">
|
||||||
|
<template #default="{ row }">
|
||||||
|
<el-button type="primary" link @click="handleView(row)">查看</el-button>
|
||||||
|
<el-button type="danger" link @click="handleDelete(row)">删除</el-button>
|
||||||
|
</template>
|
||||||
|
</el-table-column>
|
||||||
|
</el-table>
|
||||||
|
|
||||||
|
<div class="pagination-wrapper">
|
||||||
|
<el-pagination
|
||||||
|
v-model:current-page="pagination.page"
|
||||||
|
v-model:page-size="pagination.limit"
|
||||||
|
:total="pagination.total"
|
||||||
|
:page-sizes="[10, 20, 50]"
|
||||||
|
layout="total, sizes, prev, pager, next, jumper"
|
||||||
|
@size-change="loadData"
|
||||||
|
@current-change="loadData"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</el-card>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup lang="ts">
|
||||||
|
import { ref, reactive, onMounted } from 'vue'
|
||||||
|
import { useRouter } from 'vue-router'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import request from '@/api/request'
|
||||||
|
import type { Report, Topic } from '@/api/types'
|
||||||
|
|
||||||
|
const router = useRouter()
|
||||||
|
const loading = ref(false)
|
||||||
|
const tableData = ref<Report[]>([])
|
||||||
|
const topics = ref<Topic[]>([])
|
||||||
|
|
||||||
|
const pagination = reactive({
|
||||||
|
page: 1,
|
||||||
|
limit: 10,
|
||||||
|
total: 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
const filters = reactive({
|
||||||
|
topicId: null as number | null,
|
||||||
|
status: '',
|
||||||
|
})
|
||||||
|
|
||||||
|
const loadData = async () => {
|
||||||
|
loading.value = true
|
||||||
|
try {
|
||||||
|
const params: Record<string, any> = {
|
||||||
|
page: pagination.page,
|
||||||
|
limit: pagination.limit,
|
||||||
|
}
|
||||||
|
if (filters.topicId) params.topicId = filters.topicId
|
||||||
|
if (filters.status) params.status = filters.status
|
||||||
|
|
||||||
|
const res = await request.get('/reports', { params })
|
||||||
|
tableData.value = res.data || []
|
||||||
|
pagination.total = res.pagination?.total || 0
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载数据失败', error)
|
||||||
|
} finally {
|
||||||
|
loading.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const loadTopics = async () => {
|
||||||
|
try {
|
||||||
|
const res = await request.get('/topics', { params: { limit: 100 } })
|
||||||
|
topics.value = res.data || []
|
||||||
|
} catch (error) {
|
||||||
|
console.error('加载主题失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const resetFilters = () => {
|
||||||
|
filters.topicId = null
|
||||||
|
filters.status = ''
|
||||||
|
loadData()
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleView = (row: Report) => {
|
||||||
|
router.push(`/reports/${row.id}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleDelete = async (row: Report) => {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(`确定要删除报告 "${row.title}" 吗?`, '提示', {
|
||||||
|
type: 'warning',
|
||||||
|
})
|
||||||
|
await request.delete(`/reports/${row.id}`)
|
||||||
|
ElMessage.success('删除成功')
|
||||||
|
loadData()
|
||||||
|
} catch (error: any) {
|
||||||
|
if (error !== 'cancel') {
|
||||||
|
console.error('删除失败', error)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusType = (status: string) => {
|
||||||
|
const map: Record<string, 'info' | 'warning' | 'success' | 'danger'> = {
|
||||||
|
pending: 'info',
|
||||||
|
generating: 'warning',
|
||||||
|
completed: 'success',
|
||||||
|
failed: 'danger',
|
||||||
|
}
|
||||||
|
return map[status] || 'info'
|
||||||
|
}
|
||||||
|
|
||||||
|
const getStatusText = (status: string) => {
|
||||||
|
const map: Record<string, string> = {
|
||||||
|
pending: '待处理',
|
||||||
|
generating: '生成中',
|
||||||
|
completed: '已完成',
|
||||||
|
failed: '失败',
|
||||||
|
}
|
||||||
|
return map[status] || status
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatDate = (date: string) => {
|
||||||
|
if (!date) return '-'
|
||||||
|
return new Date(date).toLocaleDateString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
const formatTime = (time: string) => {
|
||||||
|
return new Date(time).toLocaleString('zh-CN')
|
||||||
|
}
|
||||||
|
|
||||||
|
onMounted(() => {
|
||||||
|
loadData()
|
||||||
|
loadTopics()
|
||||||
|
})
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
.report-list {
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header {
|
||||||
|
display: flex;
|
||||||
|
justify-content: space-between;
|
||||||
|
align-items: center;
|
||||||
|
margin-bottom: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
.page-header h2 {
|
||||||
|
margin: 0;
|
||||||
|
font-size: 20px;
|
||||||
|
color: #303133;
|
||||||
|
}
|
||||||
|
|
||||||
|
.filter-card :deep(.el-form-item) {
|
||||||
|
margin-bottom: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.pagination-wrapper {
|
||||||
|
margin-top: 20px;
|
||||||
|
display: flex;
|
||||||
|
justify-content: flex-end;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
/** @type {import('tailwindcss').Config} */
|
||||||
|
export default {
|
||||||
|
darkMode: 'class',
|
||||||
|
content: [
|
||||||
|
'./index.html',
|
||||||
|
'./src/**/*.{vue,js,ts,jsx,tsx}',
|
||||||
|
],
|
||||||
|
theme: {
|
||||||
|
container: {
|
||||||
|
center: true,
|
||||||
|
padding: '2rem',
|
||||||
|
screens: {
|
||||||
|
'2xl': '1400px',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
extend: {
|
||||||
|
colors: {
|
||||||
|
border: 'hsl(var(--border))',
|
||||||
|
input: 'hsl(var(--input))',
|
||||||
|
ring: 'hsl(var(--ring))',
|
||||||
|
background: 'hsl(var(--background))',
|
||||||
|
foreground: 'hsl(var(--foreground))',
|
||||||
|
primary: {
|
||||||
|
DEFAULT: 'hsl(var(--primary))',
|
||||||
|
foreground: 'hsl(var(--primary-foreground))',
|
||||||
|
},
|
||||||
|
secondary: {
|
||||||
|
DEFAULT: 'hsl(var(--secondary))',
|
||||||
|
foreground: 'hsl(var(--secondary-foreground))',
|
||||||
|
},
|
||||||
|
destructive: {
|
||||||
|
DEFAULT: 'hsl(var(--destructive))',
|
||||||
|
foreground: 'hsl(var(--destructive-foreground))',
|
||||||
|
},
|
||||||
|
muted: {
|
||||||
|
DEFAULT: 'hsl(var(--muted))',
|
||||||
|
foreground: 'hsl(var(--muted-foreground))',
|
||||||
|
},
|
||||||
|
accent: {
|
||||||
|
DEFAULT: 'hsl(var(--accent))',
|
||||||
|
foreground: 'hsl(var(--accent-foreground))',
|
||||||
|
},
|
||||||
|
popover: {
|
||||||
|
DEFAULT: 'hsl(var(--popover))',
|
||||||
|
foreground: 'hsl(var(--popover-foreground))',
|
||||||
|
},
|
||||||
|
card: {
|
||||||
|
DEFAULT: 'hsl(var(--card))',
|
||||||
|
foreground: 'hsl(var(--card-foreground))',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
borderRadius: {
|
||||||
|
lg: 'var(--radius)',
|
||||||
|
md: 'calc(var(--radius) - 2px)',
|
||||||
|
sm: 'calc(var(--radius) - 4px)',
|
||||||
|
},
|
||||||
|
keyframes: {
|
||||||
|
'accordion-down': {
|
||||||
|
from: { height: 0 },
|
||||||
|
to: { height: 'var(--radix-accordion-content-height)' },
|
||||||
|
},
|
||||||
|
'accordion-up': {
|
||||||
|
from: { height: 'var(--radix-accordion-content-height)' },
|
||||||
|
to: { height: 0 },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
animation: {
|
||||||
|
'accordion-down': 'accordion-down 0.2s ease-out',
|
||||||
|
'accordion-up': 'accordion-up 0.2s ease-out',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
plugins: [
|
||||||
|
require('@tailwindcss/typography'),
|
||||||
|
],
|
||||||
|
}
|
||||||
Reference in new issue
Block a user