diff --git a/backend/src/services/processor.service.ts b/backend/src/services/processor.service.ts new file mode 100644 index 0000000..0e3c463 --- /dev/null +++ b/backend/src/services/processor.service.ts @@ -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 { + 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 { + 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 { + 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 { + 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 { + 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(); + 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(); + } + }); + } +} diff --git a/backend/src/types/llm.ts b/backend/src/types/llm.ts new file mode 100644 index 0000000..001eee8 --- /dev/null +++ b/backend/src/types/llm.ts @@ -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; +} diff --git a/backend/src/utils/llm-client.ts b/backend/src/utils/llm-client.ts new file mode 100644 index 0000000..ef609b6 --- /dev/null +++ b/backend/src/utils/llm-client.ts @@ -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 { + 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 { + 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; + } + } +}