完成内容: - 创建前后端项目目录结构 - 初始化 Node.js + TypeScript 后端项目 (Fastify) - 初始化 Vue 3 + TypeScript 前端项目 (Vite) - 配置 Prisma ORM 和 MySQL 数据库 - 创建数据库 Schema 和种子数据 - 实现后端基础模块 (配置、日志、错误处理、验证) - 创建基础服务类 (BaseService) - 配置 Git 仓库和忽略文件 技术栈: - 后端:Fastify + Prisma + MySQL + Winston - 前端:Vue 3 + TypeScript + Element Plus + Pinia Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
582 lines
14 KiB
Markdown
582 lines
14 KiB
Markdown
# 任务 05:内容处理
|
||
|
||
## 任务概述
|
||
实现基于 LLM 的内容处理服务,支持三种处理模式:简单聚合、AI 摘要、AI 深度整理。
|
||
|
||
## 前置条件
|
||
- 任务 01-04 已完成
|
||
- 采集器已实现
|
||
|
||
## 任务目标
|
||
- 创建 LLM 客户端封装
|
||
- 实现内容处理服务
|
||
- 支持三种处理模式
|
||
- 实现去重逻辑
|
||
|
||
## 详细步骤
|
||
|
||
### 1. 创建 LLM 类型定义
|
||
|
||
创建 `backend/src/types/llm.ts`:
|
||
|
||
```typescript
|
||
export interface LlmMessage {
|
||
role: 'system' | 'user' | 'assistant'
|
||
content: string
|
||
}
|
||
|
||
export interface LlmResponse {
|
||
content: string
|
||
usage?: {
|
||
promptTokens: number
|
||
completionTokens: number
|
||
totalTokens: number
|
||
}
|
||
}
|
||
|
||
export interface LlmConfig {
|
||
baseUrl: string
|
||
model: string
|
||
apiKey: string
|
||
}
|
||
```
|
||
|
||
### 2. 创建 LLM 客户端
|
||
|
||
创建 `backend/src/utils/llm-client.ts`:
|
||
|
||
```typescript
|
||
import OpenAI from 'openai'
|
||
import type { LlmConfig, LlmMessage, LlmResponse } from '../types/llm'
|
||
import { logger } from './logger'
|
||
|
||
export class LlmClient {
|
||
private client: OpenAI
|
||
|
||
constructor(private config: LlmConfig) {
|
||
this.client = new OpenAI({
|
||
baseURL: config.baseUrl,
|
||
apiKey: config.apiKey,
|
||
})
|
||
}
|
||
|
||
async chat(messages: LlmMessage[], options?: {
|
||
temperature?: number
|
||
maxTokens?: number
|
||
}): Promise<LlmResponse> {
|
||
try {
|
||
logger.debug('调用 LLM', {
|
||
model: this.config.model,
|
||
messagesCount: messages.length,
|
||
})
|
||
|
||
const response = await this.client.chat.completions.create({
|
||
model: this.config.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.config.model,
|
||
messagesCount: messages.length,
|
||
})
|
||
|
||
const stream = await this.client.chat.completions.create({
|
||
model: this.config.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
|
||
}
|
||
}
|
||
}
|
||
```
|
||
|
||
### 3. 创建内容处理类型定义
|
||
|
||
更新 `backend/src/types/index.ts`:
|
||
|
||
```typescript
|
||
export * from './api'
|
||
export * from './collector'
|
||
export * from './llm'
|
||
|
||
export type ProcessMode = 'aggregate' | 'summary' | 'deep_analysis'
|
||
|
||
export interface ProcessedContent {
|
||
content: string
|
||
mode: ProcessMode
|
||
articlesCount: number
|
||
}
|
||
```
|
||
|
||
### 4. 创建内容处理服务
|
||
|
||
创建 `backend/src/services/processor.service.ts`:
|
||
|
||
```typescript
|
||
import type { Article } from '@prisma/client'
|
||
import { LlmClient } from '../utils/llm-client'
|
||
import type { LlmConfig, ProcessMode, ProcessedContent } from '../types'
|
||
import { logger } from '../utils/logger'
|
||
|
||
export class ProcessorService {
|
||
/**
|
||
* 处理资讯列表
|
||
*/
|
||
async processArticles(
|
||
articles: Article[],
|
||
mode: ProcessMode,
|
||
llmConfig: LlmConfig
|
||
): Promise<ProcessedContent> {
|
||
logger.info(`开始处理 ${articles.length} 条资讯,模式: ${mode}`)
|
||
|
||
switch (mode) {
|
||
case 'aggregate':
|
||
return this.aggregateArticles(articles)
|
||
case 'summary':
|
||
return this.summarizeArticles(articles, llmConfig)
|
||
case 'deep_analysis':
|
||
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: LlmConfig
|
||
): 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: LlmConfig
|
||
): 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 和标题相似度
|
||
*/
|
||
async deduplicateArticles(articles: Article[]): Promise<Article[]> {
|
||
const seen = new Set<string>()
|
||
const deduplicated: Article[] = []
|
||
|
||
for (const article of articles) {
|
||
// 基于 URL 去重
|
||
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()
|
||
}
|
||
})
|
||
}
|
||
}
|
||
```
|
||
|
||
### 5. 更新服务导出
|
||
|
||
更新 `backend/src/services/index.ts`:
|
||
|
||
```typescript
|
||
export * from './collector.service'
|
||
export * from './processor.service'
|
||
```
|
||
|
||
### 6. 创建测试脚本
|
||
|
||
创建 `backend/src/test-processor.ts`:
|
||
|
||
```typescript
|
||
import { ProcessorService } from './services/processor.service'
|
||
import prisma from './utils/prisma'
|
||
|
||
async function test() {
|
||
const processorService = new ProcessorService()
|
||
|
||
// 获取一些测试资讯
|
||
const articles = await prisma.article.findMany({
|
||
take: 5,
|
||
orderBy: { collectedAt: 'desc' },
|
||
})
|
||
|
||
if (articles.length === 0) {
|
||
console.log('没有资讯数据,请先运行采集器')
|
||
return
|
||
}
|
||
|
||
console.log(`找到 ${articles.length} 条资讯`)
|
||
|
||
// 测试去重
|
||
console.log('\n=== 测试去重 ===')
|
||
const deduplicated = await processorService.deduplicateArticles(articles)
|
||
console.log(`去重后: ${deduplicated.length} 条`)
|
||
|
||
// 测试排序
|
||
console.log('\n=== 测试排序 ===')
|
||
const sorted = processorService.sortArticlesByDate(deduplicated)
|
||
console.log('最新的资讯:', sorted[0]?.title)
|
||
|
||
// 测试简单聚合
|
||
console.log('\n=== 测试简单聚合 ===')
|
||
const aggregated = await processorService.processArticles(
|
||
deduplicated,
|
||
'aggregate',
|
||
as any // 聚合模式不需要 LLM
|
||
)
|
||
console.log(aggregated.content.substring(0, 500))
|
||
|
||
// 测试 AI 摘要(需要配置 LLM)
|
||
const llmConfig = await prisma.llmConfig.findFirst({
|
||
where: { enabled: true },
|
||
})
|
||
|
||
if (llmConfig) {
|
||
console.log('\n=== 测试 AI 摘要 ===')
|
||
try {
|
||
const summarized = await processorService.processArticles(
|
||
deduplicated.slice(0, 2), // 只测试 2 条
|
||
'summary',
|
||
{
|
||
baseUrl: llmConfig.baseUrl,
|
||
model: llmConfig.model,
|
||
apiKey: llmConfig.apiKey,
|
||
}
|
||
)
|
||
console.log(summarized.content.substring(0, 500))
|
||
} catch (error) {
|
||
console.error('AI 摘要失败:', error)
|
||
}
|
||
|
||
console.log('\n=== 测试 AI 深度整理 ===')
|
||
try {
|
||
const analyzed = await processorService.processArticles(
|
||
deduplicated.slice(0, 3), // 只测试 3 条
|
||
'deep_analysis',
|
||
{
|
||
baseUrl: llmConfig.baseUrl,
|
||
model: llmConfig.model,
|
||
apiKey: llmConfig.apiKey,
|
||
}
|
||
)
|
||
console.log(analyzed.content.substring(0, 500))
|
||
} catch (error) {
|
||
console.error('AI 深度整理失败:', error)
|
||
}
|
||
} else {
|
||
console.log('\n没有启用的 LLM 配置,跳过 AI 测试')
|
||
}
|
||
}
|
||
|
||
test()
|
||
.catch(console.error)
|
||
.finally(() => prisma.$disconnect())
|
||
```
|
||
|
||
## 验证步骤
|
||
|
||
### 1. 准备测试数据
|
||
|
||
确保数据库中有资讯数据:
|
||
```bash
|
||
# 如果没有,先运行采集器
|
||
npx tsx src/test-collector.ts
|
||
```
|
||
|
||
### 2. 配置 LLM
|
||
|
||
使用 Prisma Studio 更新 LLM 配置:
|
||
```bash
|
||
npm run prisma:studio
|
||
```
|
||
|
||
在 `llm_configs` 表中:
|
||
- 更新 `api_key` 为真实的 API Key
|
||
- 设置 `enabled` 为 `true`
|
||
|
||
### 3. 运行测试
|
||
|
||
```bash
|
||
npx tsx src/test-processor.ts
|
||
```
|
||
|
||
预期输出:
|
||
```
|
||
找到 5 条资讯
|
||
|
||
=== 测试去重 ===
|
||
去重后: 5 条
|
||
|
||
=== 测试排序 ===
|
||
最新的资讯: xxx
|
||
|
||
=== 测试简单聚合 ===
|
||
1. **标题1**
|
||
链接: https://...
|
||
发布时间: 2024-01-01 10:00:00
|
||
...
|
||
|
||
=== 测试 AI 摘要 ===
|
||
### 标题1
|
||
|
||
这是一个关于...的摘要
|
||
|
||
[查看原文](https://...)
|
||
...
|
||
|
||
=== 测试 AI 深度整理 ===
|
||
## 核心主题
|
||
...
|
||
```
|
||
|
||
### 4. 验证不同处理模式
|
||
|
||
测试三种模式的输出:
|
||
- **aggregate**:应该是简单的列表格式
|
||
- **summary**:应该有每条资讯的摘要
|
||
- **deep_analysis**:应该有结构化的分析报告
|
||
|
||
## 预期产物
|
||
|
||
- ✅ LLM 客户端封装完成
|
||
- ✅ 内容处理服务实现完成
|
||
- ✅ 三种处理模式实现完成
|
||
- ✅ 去重逻辑实现完成
|
||
- ✅ 排序功能实现完成
|
||
- ✅ 测试通过
|
||
|
||
## 常见问题
|
||
|
||
### 问题 1:LLM 调用失败
|
||
**解决方案**:
|
||
- 检查 API Key 是否正确
|
||
- 检查 baseUrl 是否正确
|
||
- 检查网络连接
|
||
- 查看错误日志
|
||
|
||
### 问题 2:摘要质量不好
|
||
**解决方案**:
|
||
- 调整 prompt
|
||
- 调整 temperature 参数
|
||
- 尝试不同的模型
|
||
|
||
### 问题 3:处理速度慢
|
||
**解决方案**:
|
||
- 减少单次处理的资讯数量
|
||
- 使用更快的模型
|
||
- 考虑并发处理(后续优化)
|
||
|
||
## 下一步
|
||
|
||
完成本任务后,继续 [任务 06:报告生成](./06-report-generator.md)。
|