refactor: centralize llm backend configuration
This commit is contained in:
@@ -1,11 +1,8 @@
|
||||
[GlobalNews]
|
||||
enable = true
|
||||
command = ["全球新闻", "国际新闻", "环球新闻", "政经新闻", "政治经济新闻"]
|
||||
backend = "dify_chat_global_news"
|
||||
command-format = """
|
||||
🌍全球新闻指令:
|
||||
全球新闻 - 获取最新的全球政治经济新闻
|
||||
"""
|
||||
|
||||
|
||||
authorization = "Bearer app-rhhKkbvHd2IAQoGX7xTzXZJj" # 请替换为真实的Authorization token
|
||||
url = 'http://192.168.2.240/v1/chat-messages'
|
||||
@@ -1,8 +1,6 @@
|
||||
import asyncio
|
||||
import json
|
||||
import threading
|
||||
import time # 添加这一行
|
||||
import aiohttp
|
||||
from typing import Dict, Any, List, Optional, Tuple
|
||||
|
||||
from base.plugin_common.message_plugin_interface import MessagePluginInterface
|
||||
@@ -11,6 +9,7 @@ from utils.decorator.plugin_decorators import plugin_stats_decorator
|
||||
from utils.robot_cmd.robot_command import Feature, PermissionStatus, GroupBotManager
|
||||
from utils.decorator.points_decorator import plugin_points_cost
|
||||
from utils.markdown_to_image import convert_md_str_to_image
|
||||
from utils.ai.unified_llm import UnifiedLLMClient
|
||||
from wechat_ipad import WechatAPIClient
|
||||
|
||||
# 导入新闻抓取函数
|
||||
@@ -75,9 +74,19 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
["全球新闻", "国际新闻", "环球新闻", "政经新闻"])
|
||||
self.command_format = self._config.get("GlobalNews", {}).get("command-format",
|
||||
"全球新闻 - 获取最新的全球政治经济新闻")
|
||||
self.enable = self._config.get("GlobalNews", {}).get("enable", True)
|
||||
self._key = self._config.get("GlobalNews", {}).get("authorization", "")
|
||||
self._url = self._config.get("GlobalNews", {}).get("url", "")
|
||||
plugin_config = self._config.get("GlobalNews", {})
|
||||
self.enable = plugin_config.get("enable", True)
|
||||
llm_config = plugin_config.get("llm", {}) or {}
|
||||
if not llm_config:
|
||||
llm_config = {
|
||||
"backend": plugin_config.get("backend", ""),
|
||||
"provider": "dify",
|
||||
"mode": "chat",
|
||||
"authorization": plugin_config.get("authorization", ""),
|
||||
"url": plugin_config.get("url", ""),
|
||||
"response_mode": "blocking",
|
||||
}
|
||||
self.llm_client = UnifiedLLMClient(llm_config)
|
||||
self.LOG.debug(f"[{self.name}] 插件初始化完成,指令:{self._commands}")
|
||||
return True
|
||||
|
||||
@@ -186,9 +195,7 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
news_titles = "\n".join(results)
|
||||
|
||||
# 使用AI分析新闻
|
||||
markdown_news = await self._run_in_executor(
|
||||
self.dify_news_title_analyze, news_titles
|
||||
)
|
||||
markdown_news = await self._run_in_executor(self.analyze_news_titles, news_titles)
|
||||
|
||||
# 转换为图片
|
||||
image_path = await self._run_in_executor(
|
||||
@@ -205,61 +212,15 @@ class GlobalNewsPlugin(MessagePluginInterface):
|
||||
loop = asyncio.get_event_loop()
|
||||
return await loop.run_in_executor(None, func, *args)
|
||||
|
||||
async def dify_news_title_analyze(self, content: str) -> str:
|
||||
"""异步分析新闻标题
|
||||
Args:
|
||||
content: 新闻标题内容
|
||||
Returns:
|
||||
str: 分析后的内容
|
||||
"""
|
||||
# 设置Authorization和URL
|
||||
data = {
|
||||
"response_mode": "blocking",
|
||||
"conversation_id": "",
|
||||
"inputs": {},
|
||||
"query": content,
|
||||
"user": "a-bot-global_news"
|
||||
}
|
||||
|
||||
# 设置请求头
|
||||
headers = {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Authorization": self._key
|
||||
}
|
||||
|
||||
try:
|
||||
async with aiohttp.ClientSession() as session:
|
||||
async with session.post(self._url, headers=headers, json=data) as response:
|
||||
if response.status != 200:
|
||||
self.LOG.error(f"新闻分析请求失败: {response.status}")
|
||||
return None
|
||||
|
||||
response_data = await response.json()
|
||||
self.LOG.debug(f"新闻分析响应: {response_data}")
|
||||
return self.extract_content(response_data)
|
||||
|
||||
except Exception as e:
|
||||
self.LOG.error(f"新闻分析请求出错: {e}")
|
||||
return None
|
||||
|
||||
def extract_content(self, data):
|
||||
"""解析API响应内容
|
||||
Args:
|
||||
data: API返回的响应数据,可以是字典或字符串
|
||||
Returns:
|
||||
str: 提取的answer内容
|
||||
"""
|
||||
try:
|
||||
# 如果是字符串,尝试解析为字典
|
||||
if isinstance(data, str):
|
||||
data = json.loads(data)
|
||||
# 如果是字典,直接获取answer
|
||||
if isinstance(data, dict):
|
||||
answer = data.get('answer', '')
|
||||
if answer:
|
||||
return answer
|
||||
|
||||
return None
|
||||
except Exception as e:
|
||||
self.LOG.error(f"解析响应失败: {str(e)}")
|
||||
def analyze_news_titles(self, content: str) -> Optional[str]:
|
||||
"""同步分析新闻标题,便于在线程池中复用。"""
|
||||
response = self.llm_client.run(
|
||||
prompt=content,
|
||||
user="a-bot-global_news",
|
||||
inputs={"query": content},
|
||||
tag="global_news",
|
||||
)
|
||||
if not response:
|
||||
self.LOG.error(f"新闻分析请求失败: {self.llm_client.last_error}")
|
||||
return None
|
||||
return response.get("text") or None
|
||||
|
||||
Reference in New Issue
Block a user