Files
akmon/uni_modules/ak-ai-news/examples/usage-example.uts
2026-01-20 08:04:15 +08:00

547 lines
20 KiB
Plaintext
Raw Permalink Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// AI News System Usage Examples
import {
AIServiceManager,
AITranslationService,
AIContentAnalysisService,
AIChatService,
AIRecommendationService,
ContentProcessingPipeline,
type AIServiceConfig,
type ContentInfo,
type ChatOptions
} from '../index.uts'
/**
* AI新闻系统使用示例
* 展示如何集成和使用多语言AI新闻系统的各种功能
*/
export class AINewsSystemExample {
private serviceManager: AIServiceManager
constructor() {
// 配置AI服务
const aiConfig: AIServiceConfig = {
openai: {
apiKey: 'your-openai-api-key',
model: 'gpt-3.5-turbo',
maxTokens: 2000,
temperature: 0.7
},
google: {
apiKey: 'your-google-api-key',
model: 'gemini-pro'
},
baidu: {
apiKey: 'your-baidu-api-key',
secretKey: 'your-baidu-secret-key',
model: 'ernie-bot'
},
costLimits: {
dailyUSD: 100,
monthlyUSD: 2000,
perRequestUSD: 5
},
qualityThresholds: {
translation: 0.8,
sentiment: 0.7,
credibility: 0.6
}
}
// 初始化服务管理器
this.serviceManager = new AIServiceManager(aiConfig)
}
/**
* 初始化系统
*/
async initializeSystem(): Promise<void> {
console.log('🚀 Initializing AI News System...')
const response = await this.serviceManager.initialize()
if (response.success) {
console.log('✅ AI News System initialized successfully')
} else {
console.error('❌ Failed to initialize AI News System:', response.error)
throw new Error(response.error)
}
}
/**
* 示例1: 新闻内容翻译
*/
async exampleTranslation(): Promise<void> {
console.log('\n📝 Example 1: News Translation')
console.log('================================')
const translationService = this.serviceManager.getTranslationService()
// 翻译中文新闻到英文
const chineseNews = "人工智能技术在新闻行业的应用正在快速发展,自动化内容生成、智能推荐和多语言翻译等功能大大提高了新闻生产和传播的效率。"
console.log('Original Chinese text:', chineseNews)
const translationResult = await translationService.translateText(
chineseNews,
'en',
'zh-CN',
{
provider: 'openai',
culturalAdaptation: true,
preserveFormatting: true
}
)
if (translationResult.success && translationResult.data) {
console.log('✅ Translation successful:')
console.log('- Translated text:', translationResult.data.translatedText)
console.log('- Quality score:', translationResult.data.qualityScore)
console.log('- Provider:', translationResult.data.provider)
console.log('- Tokens used:', translationResult.data.tokensUsed)
console.log('- Cost:', `$${translationResult.data.costUSD.toFixed(4)}`)
} else {
console.error('❌ Translation failed:', translationResult.error)
}
// 批量翻译示例
const newsTexts = [
"今日股市行情分析",
"科技创新推动经济发展",
"环保政策最新动态"
]
console.log('\n📚 Batch translation example:')
const batchResult = await translationService.translateBatch(
newsTexts,
'en',
'zh-CN',
{ provider: 'google' },
{
batchSize: 2,
concurrency: 2,
onProgress: (completed, total) => {
console.log(`Progress: ${completed}/${total}`)
}
}
)
if (batchResult.success && batchResult.data) {
console.log('✅ Batch translation completed:')
batchResult.data.forEach((result, index) => {
console.log(`${index + 1}. ${result.translatedText}`)
})
}
}
/**
* 示例2: 新闻内容分析
*/
async exampleContentAnalysis(): Promise<void> {
console.log('\n🔍 Example 2: Content Analysis')
console.log('================================')
const analysisService = this.serviceManager.getAnalysisService()
const newsContent = `
特斯拉公司今日宣布,其最新的自动驾驶技术取得重大突破。
该技术采用先进的人工智能算法,能够在复杂路况下实现更安全的自动驾驶。
据公司CEO埃隆·马斯克表示这项技术将在未来六个月内开始量产。
市场分析师认为,这一创新将进一步巩固特斯拉在电动汽车市场的领先地位。
投资者对此消息反应积极特斯拉股价在盘后交易中上涨了8%。
`
console.log('Analyzing content:', newsContent.substring(0, 100) + '...')
const analysisResult = await analysisService.analyzeContent(newsContent, {
types: ['sentiment', 'entities', 'topics', 'categories', 'readability', 'credibility', 'summary', 'keywords'],
provider: 'openai',
language: 'zh-CN',
includeScores: true
})
if (analysisResult.success && analysisResult.data) {
const analysis = analysisResult.data
console.log('✅ Analysis completed:')
console.log('- Sentiment:', analysis.sentimentLabel, `(${analysis.sentimentScore.toFixed(2)})`)
console.log('- Readability score:', analysis.readabilityScore.toFixed(2))
console.log('- Credibility score:', analysis.credibilityScore.toFixed(2))
console.log('- Keywords:', analysis.keywords.join(', '))
console.log('- Entities found:', analysis.entities.length)
analysis.entities.forEach(entity => {
console.log(` - ${entity.text} (${entity.type}, confidence: ${entity.confidence.toFixed(2)})`)
})
console.log('- Categories:')
analysis.categories.forEach(category => {
console.log(` - ${category.categoryName} (confidence: ${category.confidence.toFixed(2)})`)
})
console.log('- Summary:', analysis.summary)
} else {
console.error('❌ Analysis failed:', analysisResult.error)
}
}
/**
* 示例3: AI聊天助手
*/
async exampleChatAssistant(): Promise<void> {
console.log('\n💬 Example 3: AI Chat Assistant')
console.log('================================')
const chatService = this.serviceManager.getChatService()
// 创建聊天会话
const sessionResponse = await chatService.createChatSession(
'user123',
'zh-CN',
{
provider: 'openai',
temperature: 0.7,
maxTokens: 1000
}
)
if (sessionResponse.success && sessionResponse.data) {
const session = sessionResponse.data
console.log('✅ Chat session created:', session.id)
// 发送消息
const messages = [
"今天有什么重要的科技新闻吗?",
"请分析一下人工智能对新闻行业的影响",
"帮我推荐一些相关的新闻文章"
]
for (const messageText of messages) {
console.log(`\n👤 User: ${messageText}`)
const messageResponse = await chatService.sendMessage(
session.id,
messageText,
{ provider: 'openai' }
)
if (messageResponse.success && messageResponse.data) {
const message = messageResponse.data
console.log(`🤖 Assistant: ${message.content}`)
console.log(` Response time: ${message.responseTimeMs}ms`)
console.log(` Tokens used: ${message.tokensUsed}`)
} else {
console.error('❌ Message failed:', messageResponse.error)
}
// 模拟对话间隔
await this.delay(1000)
}
// 获取对话历史
const history = chatService.getChatHistory(session.id, 10)
console.log(`\n📋 Conversation history (${history.length} messages):`)
history.forEach((msg, index) => {
console.log(`${index + 1}. [${msg.type}] ${msg.content.substring(0, 50)}...`)
})
// 结束会话
await chatService.endChatSession(session.id)
console.log('✅ Chat session ended')
} else {
console.error('❌ Failed to create chat session:', sessionResponse.error)
}
}
/**
* 示例4: 个性化推荐
*/
async exampleRecommendations(): Promise<void> {
console.log('\n🎯 Example 4: Personalized Recommendations')
console.log('==========================================')
const recommendationService = this.serviceManager.getRecommendationService()
// 模拟新闻内容
const availableNews: ContentInfo[] = [
{
id: 'news1',
title: 'AI技术突破新一代自然语言处理模型发布',
content: '研究人员发布了新的大型语言模型,在多项任务上超越了现有技术...',
originalLanguage: 'zh-CN',
publishedAt: Date.now() - 1000 * 60 * 60, // 1小时前
categoryId: 'technology',
tags: ['AI', '技术', '创新'],
keywords: ['人工智能', '语言模型', '技术突破'],
quality: 0.9,
viewCount: 1500,
likeCount: 120,
shareCount: 45,
status: 'published'
},
{
id: 'news2',
title: '全球经济展望:数字化转型加速发展',
content: '世界银行最新报告显示,数字化转型正在重塑全球经济格局...',
originalLanguage: 'zh-CN',
publishedAt: Date.now() - 1000 * 60 * 60 * 2, // 2小时前
categoryId: 'economy',
tags: ['经济', '数字化', '转型'],
keywords: ['经济发展', '数字化', '全球'],
quality: 0.85,
viewCount: 2100,
likeCount: 180,
shareCount: 67,
status: 'published'
},
{
id: 'news3',
title: '环保新政策:碳中和目标实施细则发布',
content: '政府发布了实现碳中和目标的详细实施方案,涉及多个行业的转型升级...',
originalLanguage: 'zh-CN',
publishedAt: Date.now() - 1000 * 60 * 60 * 3, // 3小时前
categoryId: 'environment',
tags: ['环保', '政策', '碳中和'],
keywords: ['环保政策', '碳中和', '可持续发展'],
quality: 0.88,
viewCount: 980,
likeCount: 75,
shareCount: 23,
status: 'published'
}
]
// 记录用户行为(模拟)
await recommendationService.recordUserBehavior({
userId: 'user123',
contentId: 'news1',
actionType: 'view',
timestamp: Date.now() - 1000 * 60 * 30, // 30分钟前
duration: 120 // 阅读了2分钟
})
await recommendationService.recordUserBehavior({
userId: 'user123',
contentId: 'news1',
actionType: 'like',
timestamp: Date.now() - 1000 * 60 * 25
})
// 获取个性化推荐
console.log('Generating personalized recommendations...')
const recommendationResponse = await recommendationService.getPersonalizedRecommendations(
'user123',
availableNews,
{
algorithm: 'hybrid',
maxResults: 5,
diversityWeight: 0.3,
freshnessWeight: 0.4,
personalizedWeight: 0.3,
qualityThreshold: 0.7,
excludeViewed: false
},
{
currentTime: Date.now(),
recentViews: ['news1'],
deviceType: 'mobile'
}
)
if (recommendationResponse.success && recommendationResponse.data) {
console.log('✅ Personalized recommendations:')
recommendationResponse.data.forEach((rec, index) => {
const news = availableNews.find(n => n.id === rec.contentId)
console.log(`${index + 1}. ${news?.title}`)
console.log(` Score: ${rec.score.toFixed(3)}, Reason: ${rec.reason}`)
console.log(` Algorithm: ${rec.algorithm}, Type: ${rec.recommendationType}`)
})
} else {
console.error('❌ Recommendations failed:', recommendationResponse.error)
}
// 获取热门推荐
console.log('\n🔥 Trending recommendations:')
const trendingResponse = await recommendationService.getTrendingRecommendations(
availableNews,
24, // 24小时内
3
)
if (trendingResponse.success && trendingResponse.data) {
trendingResponse.data.forEach((rec, index) => {
const news = availableNews.find(n => n.id === rec.contentId)
console.log(`${index + 1}. ${news?.title} (Score: ${rec.score.toFixed(3)})`)
})
}
}
/**
* 示例5: 自动化内容处理管道
*/
async exampleContentPipeline(): Promise<void> {
console.log('\n⚙ Example 5: Automated Content Processing')
console.log('==========================================')
const pipeline = this.serviceManager.getProcessingPipeline()
// 模拟原始新闻内容
const rawContent: ContentInfo = {
id: 'raw_news_001',
title: '突破性医疗技术:基因编辑治疗癌症取得重大进展',
content: `
美国斯坦福大学医学院的研究团队今日宣布,他们在基因编辑技术治疗癌症方面取得了重大突破。
该团队利用CRISPR-Cas9技术成功修改了T细胞的基因使其能够更有效地识别和攻击癌细胞。
在临床试验中接受治疗的20名患者中有18名病情得到显著改善治疗有效率达到90%。
研究负责人张华教授表示这项技术有望在未来3-5年内进入大规模临床应用阶段。
美国食品药品监督管理局(FDA)已批准该技术进入二期临床试验。
业内专家认为,这一突破将为癌症治疗带来革命性变化,可能挽救数百万患者的生命。
`.trim(),
originalLanguage: 'zh-CN',
publishedAt: Date.now(),
tags: [],
keywords: [],
quality: 0,
viewCount: 0,
likeCount: 0,
shareCount: 0,
status: 'draft'
}
console.log('Processing content:', rawContent.title)
console.log('Original content length:', rawContent.content.length, 'characters')
// 执行自动化处理
const processingResponse = await pipeline.processContent(rawContent)
if (processingResponse.success && processingResponse.data) {
const result = processingResponse.data
console.log('✅ Content processing completed:')
console.log('- Processing time:', `${result.processingTime}ms`)
console.log('- Total cost:', `$${result.totalCost.toFixed(4)}`)
console.log('- Final status:', result.status)
console.log('- Quality score:', result.qualityScore.toFixed(3))
console.log('\n📊 Analysis results:')
if (result.analysis) {
console.log('- Sentiment:', result.analysis.sentimentLabel, `(${result.analysis.sentimentScore.toFixed(2)})`)
console.log('- Readability:', result.analysis.readabilityScore.toFixed(2))
console.log('- Credibility:', result.analysis.credibilityScore.toFixed(2))
console.log('- Keywords:', result.analysis.keywords.slice(0, 5).join(', '))
}
console.log('\n🌐 Translation results:')
Object.entries(result.translations).forEach(([lang, translation]) => {
console.log(`- ${lang}: ${translation.translatedText.substring(0, 80)}...`)
console.log(` Quality: ${translation.qualityScore.toFixed(2)}, Cost: $${translation.costUSD.toFixed(4)}`)
})
console.log('\n📂 Categories:', result.categories.join(', '))
if (result.errors.length > 0) {
console.log('\n⚠ Errors encountered:')
result.errors.forEach(error => console.log(`- ${error}`))
}
} else {
console.error('❌ Content processing failed:', processingResponse.error)
}
}
/**
* 示例6: 系统监控和统计
*/
async exampleSystemMonitoring(): Promise<void> {
console.log('\n📈 Example 6: System Monitoring')
console.log('================================')
// 获取服务健康状态
const servicesHealth = this.serviceManager.getServicesHealth()
console.log('🏥 Services Health Status:')
Object.entries(servicesHealth).forEach(([serviceName, health]) => {
const statusIcon = health.status === 'ready' ? '✅' : health.status === 'error' ? '❌' : '⚠️'
console.log(`${statusIcon} ${serviceName}: ${health.status}`)
console.log(` Response time: ${health.responseTime}ms`)
console.log(` Error rate: ${(health.errorRate * 100).toFixed(1)}%`)
console.log(` Capabilities: ${health.capabilities.join(', ')}`)
})
// 获取管理器统计
const stats = this.serviceManager.getManagerStatistics()
console.log('\n📊 Manager Statistics:')
console.log('- Total requests:', stats.totalRequests)
console.log('- Success rate:', `${((stats.successfulRequests / Math.max(stats.totalRequests, 1)) * 100).toFixed(1)}%`)
console.log('- Average response time:', `${stats.avgResponseTime.toFixed(0)}ms`)
console.log('- Total cost:', `$${stats.totalCost.toFixed(2)}`)
console.log('\n💰 Cost breakdown by provider:')
Object.entries(stats.costBreakdown).forEach(([provider, cost]) => {
if (cost > 0) {
console.log(`- ${provider}: $${cost.toFixed(4)}`)
}
})
// 获取各服务的详细统计
console.log('\n📋 Individual Service Statistics:')
const translationStats = this.serviceManager.getTranslationService().getStatistics()
console.log('Translation Service:')
console.log(`- Total requests: ${translationStats.totalRequests}`)
console.log(`- Success rate: ${((translationStats.successCount / Math.max(translationStats.totalRequests, 1)) * 100).toFixed(1)}%`)
console.log(`- Cache hit rate: ${(translationStats.cacheHitRate * 100).toFixed(1)}%`)
console.log(`- Average quality: ${translationStats.avgQuality.toFixed(2)}`)
const analysisStats = this.serviceManager.getAnalysisService().getStatistics()
console.log('\nAnalysis Service:')
console.log(`- Total analyses: ${analysisStats.totalAnalyses}`)
console.log(`- Success rate: ${((analysisStats.successCount / Math.max(analysisStats.totalAnalyses, 1)) * 100).toFixed(1)}%`)
console.log(`- Average processing time: ${analysisStats.avgProcessingTimeMs.toFixed(0)}ms`)
const chatStats = this.serviceManager.getChatService().getChatStatistics()
console.log('\nChat Service:')
console.log(`- Total sessions: ${chatStats.totalSessions}`)
console.log(`- Total messages: ${chatStats.totalMessages}`)
console.log(`- Average response time: ${chatStats.avgResponseTime.toFixed(0)}ms`)
const recommendationStats = this.serviceManager.getRecommendationService().getRecommendationStatistics()
console.log('\nRecommendation Service:')
console.log(`- Total recommendations: ${recommendationStats.totalRecommendations}`)
console.log(`- Click-through rate: ${(recommendationStats.clickThroughRate * 100).toFixed(1)}%`)
console.log(`- User satisfaction: ${recommendationStats.userSatisfactionScore.toFixed(2)}`)
}
/**
* 运行所有示例
*/
async runAllExamples(): Promise<void> {
try {
await this.initializeSystem()
await this.exampleTranslation()
await this.exampleContentAnalysis()
await this.exampleChatAssistant()
await this.exampleRecommendations()
await this.exampleContentPipeline()
await this.exampleSystemMonitoring()
console.log('\n🎉 All examples completed successfully!')
} catch (error) {
console.error('\n💥 Example execution failed:', error)
} finally {
// 清理资源
await this.serviceManager.shutdown()
console.log('\n🛑 System shutdown completed')
}
}
private async delay(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms))
}
}
// 导出使用示例函数
export async function runAINewsSystemExamples(): Promise<void> {
const example = new AINewsSystemExample()
await example.runAllExamples()
}
// 如果直接运行此文件,执行示例
if (typeof require !== 'undefined' && require.main === module) {
runAINewsSystemExamples().catch(console.error)
}