diff --git a/backend/app/news_agent/analyzer.py b/backend/app/news_agent/analyzer.py index 181a7ed..b02824b 100644 --- a/backend/app/news_agent/analyzer.py +++ b/backend/app/news_agent/analyzer.py @@ -9,19 +9,19 @@ from datetime import datetime from app.utils.logger import logger from app.news_agent.fetcher import NewsItem from app.config import get_settings -from openai import OpenAI +from openai import AsyncOpenAI class NewsAnalyzer: - """新闻 LLM 分析器 (DeepSeek)""" + """新闻 LLM 分析器 (DeepSeek) - 异步版本""" def __init__(self): self.settings = get_settings() self.client = None try: - # 使用 DeepSeek API - self.client = OpenAI( + # 使用 DeepSeek API (异步客户端) + self.client = AsyncOpenAI( api_key=self.settings.deepseek_api_key, base_url="https://api.deepseek.com" ) @@ -249,9 +249,9 @@ class NewsAnalyzer: logger.error(f"JSON 数组解析失败: {e}, 响应: {response[:500]}") return None - def analyze_single(self, news_item: NewsItem) -> Optional[Dict[str, Any]]: + async def analyze_single(self, news_item: NewsItem) -> Optional[Dict[str, Any]]: """ - 分析单条新闻 + 分析单条新闻 (异步) Args: news_item: 新闻项 @@ -268,7 +268,7 @@ class NewsAnalyzer: for attempt in range(self.max_retries): try: - response = self.client.chat.completions.create( + response = await self.client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "system", "content": "你是一名专业的金融新闻分析师,擅长分析新闻标题对市场的影响。"}, @@ -294,9 +294,9 @@ class NewsAnalyzer: logger.error(f"分析新闻时出错: {e}") return None - def analyze_batch(self, news_items: List[NewsItem]) -> List[Optional[Dict[str, Any]]]: + async def analyze_batch(self, news_items: List[NewsItem]) -> List[Optional[Dict[str, Any]]]: """ - 批量分析新闻 + 批量分析新闻 (异步) Args: news_items: 新闻项列表 @@ -317,7 +317,7 @@ class NewsAnalyzer: try: prompt = self._build_batch_analysis_prompt(batch) - response = self.client.chat.completions.create( + response = await self.client.chat.completions.create( model="deepseek-chat", messages=[ {"role": "system", "content": "你是一名专业的金融新闻分析师,擅长分析新闻标题对市场的影响。"}, diff --git a/backend/app/news_agent/news_agent.py b/backend/app/news_agent/news_agent.py index 7c036f8..96a53ac 100644 --- a/backend/app/news_agent/news_agent.py +++ b/backend/app/news_agent/news_agent.py @@ -186,9 +186,9 @@ class NewsAgent: high_priority_articles = [] if self.use_llm: - # 只使用批量分析 + # 只使用批量分析 (异步) items_to_analyze = [item for _, item in saved_articles] - results = self.analyzer.analyze_batch(items_to_analyze) + results = await self.analyzer.analyze_batch(items_to_analyze) for (article, _), result in zip(saved_articles, results): if result: