实现内容处理模块

- 添加 LLM 类型定义 (llm.ts)
- 实现 LLM 客户端封装 (llm-client.ts)
- 实现内容处理服务 (processor.service.ts)
  - 简单聚合模式 (aggregate)
  - AI 摘要模式 (summary)
  - AI 深度分析模式 (deep_analysis)
  - 去重和排序功能

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Opus 4.5 committed 2026-02-04 21:17:54 +08:00
1 parent fe7714a3a6
commit d8553c06fa
3 files changed
+348

No files matched your search

+232
View File
@@ -0,0 +1,232 @@
import { Article } from '@prisma/client';
import { LlmClient } from '../utils/llm-client';
import { LlmClientConfig } from '../types/llm';
import { ProcessMode } from '../types';
import logger from '../utils/logger';
export interface ProcessedContent {
content: string;
mode: ProcessMode;
articlesCount: number;
}
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();
}
});
}
}