This commit is contained in:
春河晴
2025-06-10 16:43:45 +09:00
parent cf39f2fe84
commit b0c553703f
18 changed files with 500 additions and 489 deletions

View File

@@ -19,19 +19,19 @@ from src.plugin_system.apis.independent_apis import IndependentAPI, StaticAPI
__all__ = [
# 原有统一API
'PluginAPI',
'create_plugin_api',
'create_command_api',
"PluginAPI",
"create_plugin_api",
"create_command_api",
# 原有单独API
'MessageAPI',
'LLMAPI',
'DatabaseAPI',
'ConfigAPI',
'UtilsAPI',
'StreamAPI',
'HearflowAPI',
"MessageAPI",
"LLMAPI",
"DatabaseAPI",
"ConfigAPI",
"UtilsAPI",
"StreamAPI",
"HearflowAPI",
# 新增分类API
'ActionAPI', # 需要Action依赖的API
'IndependentAPI', # 独立API
'StaticAPI', # 静态API
]
"ActionAPI", # 需要Action依赖的API
"IndependentAPI", # 独立API
"StaticAPI", # 静态API
]

View File

@@ -11,37 +11,40 @@ from src.common.logger_manager import get_logger
logger = get_logger("action_apis")
class ActionAPI(MessageAPI, DatabaseAPI):
"""
Action相关API聚合类
聚合了需要Action组件依赖的API功能。这些API需要以下依赖
- _services: 包含chat_stream、expressor、replyer、observations等服务对象
- log_prefix: 日志前缀
- thinking_id: 思考ID
- cycle_timers: 计时器
- action_data: Action数据
使用场景:
- 在Action组件中使用需要发送消息、存储数据等功能
- 需要访问聊天上下文和执行环境的操作
"""
def __init__(self,
chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[ActionAPI]",
thinking_id: str = "",
cycle_timers: dict = None,
action_data: dict = None):
def __init__(
self,
chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[ActionAPI]",
thinking_id: str = "",
cycle_timers: dict = None,
action_data: dict = None,
):
"""
初始化Action相关API
Args:
chat_stream: 聊天流对象
expressor: 表达器对象
expressor: 表达器对象
replyer: 回复器对象
observations: 观察列表
log_prefix: 日志前缀
@@ -54,32 +57,32 @@ class ActionAPI(MessageAPI, DatabaseAPI):
"chat_stream": chat_stream,
"expressor": expressor,
"replyer": replyer,
"observations": observations or []
"observations": observations or [],
}
self.log_prefix = log_prefix
self.thinking_id = thinking_id
self.cycle_timers = cycle_timers or {}
self.action_data = action_data or {}
logger.debug(f"{self.log_prefix} ActionAPI 初始化完成")
def set_chat_stream(self, chat_stream):
"""设置聊天流对象"""
self._services["chat_stream"] = chat_stream
logger.debug(f"{self.log_prefix} 设置聊天流")
def set_expressor(self, expressor):
"""设置表达器对象"""
self._services["expressor"] = expressor
logger.debug(f"{self.log_prefix} 设置表达器")
def set_replyer(self, replyer):
"""设置回复器对象"""
self._services["replyer"] = replyer
logger.debug(f"{self.log_prefix} 设置回复器")
def set_observations(self, observations):
"""设置观察列表"""
self._services["observations"] = observations or []
logger.debug(f"{self.log_prefix} 设置观察列表")
logger.debug(f"{self.log_prefix} 设置观察列表")

View File

@@ -14,93 +14,95 @@ from src.common.logger_manager import get_logger
logger = get_logger("independent_apis")
class IndependentAPI(LLMAPI, ConfigAPI, UtilsAPI, StreamAPI, HearflowAPI):
"""
独立API聚合类
聚合了不需要Action组件依赖的API功能。这些API的特点
- 不需要chat_stream、expressor等服务对象
- 可以独立调用不依赖Action执行上下文
- 主要是工具类方法和配置查询方法
包含的API
- LLMAPI: LLM模型调用仅需要全局配置
- ConfigAPI: 配置读取(使用全局配置)
- UtilsAPI: 工具方法(文件操作、时间处理等)
- StreamAPI: 聊天流查询使用ChatManager
- HearflowAPI: 心流状态控制使用heartflow
使用场景:
- 在Command组件中使用
- 独立的工具函数调用
- 配置查询和系统状态检查
"""
def __init__(self, log_prefix: str = "[IndependentAPI]"):
"""
初始化独立API
Args:
log_prefix: 日志前缀,用于区分不同的调用来源
"""
self.log_prefix = log_prefix
logger.debug(f"{self.log_prefix} IndependentAPI 初始化完成")
# 提供便捷的静态访问方式
class StaticAPI:
"""
静态API类
提供完全静态的API访问方式不需要实例化适合简单的工具调用。
"""
# LLM相关
@staticmethod
def get_available_models():
"""获取可用的LLM模型"""
api = LLMAPI()
return api.get_available_models()
@staticmethod
async def generate_with_model(prompt: str, model_config: dict, **kwargs):
"""使用LLM生成内容"""
api = LLMAPI()
api.log_prefix = "[StaticAPI]"
return await api.generate_with_model(prompt, model_config, **kwargs)
# 配置相关
@staticmethod
def get_global_config(key: str, default=None):
"""获取全局配置"""
api = ConfigAPI()
return api.get_global_config(key, default)
@staticmethod
async def get_user_id_by_name(person_name: str):
"""根据用户名获取用户ID"""
api = ConfigAPI()
return await api.get_user_id_by_person_name(person_name)
# 工具相关
@staticmethod
def get_timestamp():
"""获取当前时间戳"""
api = UtilsAPI()
return api.get_timestamp()
@staticmethod
def format_time(timestamp=None, format_str="%Y-%m-%d %H:%M:%S"):
"""格式化时间"""
api = UtilsAPI()
return api.format_time(timestamp, format_str)
@staticmethod
def generate_unique_id():
"""生成唯一ID"""
api = UtilsAPI()
return api.generate_unique_id()
# 聊天流相关
@staticmethod
def get_chat_stream_by_group_id(group_id: str, platform: str = "qq"):
@@ -108,14 +110,14 @@ class StaticAPI:
api = StreamAPI()
api.log_prefix = "[StaticAPI]"
return api.get_chat_stream_by_group_id(group_id, platform)
@staticmethod
def get_all_group_chat_streams(platform: str = "qq"):
"""获取所有群聊聊天流"""
api = StreamAPI()
api.log_prefix = "[StaticAPI]"
return api.get_all_group_chat_streams(platform)
# 心流相关
@staticmethod
async def get_sub_hearflow_by_chat_id(chat_id: str):
@@ -123,10 +125,10 @@ class StaticAPI:
api = HearflowAPI()
api.log_prefix = "[StaticAPI]"
return await api.get_sub_hearflow_by_chat_id(chat_id)
@staticmethod
async def set_sub_hearflow_chat_state(chat_id: str, target_state):
"""设置子心流状态"""
api = HearflowAPI()
api.log_prefix = "[StaticAPI]"
return await api.set_sub_hearflow_chat_state(chat_id, target_state)
return await api.set_sub_hearflow_chat_state(chat_id, target_state)

View File

@@ -174,9 +174,9 @@ class MessageAPI:
"""
try:
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
expressor: DefaultExpressor = services.get("expressor")
chat_stream: ChatStream = services.get("chat_stream")
@@ -221,7 +221,7 @@ class MessageAPI:
return success
except Exception as e:
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
logger.error(f"{log_prefix} 发送消息时出错: {e}")
traceback.print_exc()
return False
@@ -237,9 +237,9 @@ class MessageAPI:
bool: 是否发送成功
"""
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
expressor: DefaultExpressor = services.get("expressor")
chat_stream: ChatStream = services.get("chat_stream")
@@ -276,10 +276,10 @@ class MessageAPI:
anchor_message.update_chat_stream(chat_stream)
# 调用内部方法发送消息
cycle_timers = getattr(self, 'cycle_timers', {})
reasoning = getattr(self, 'reasoning', '插件生成')
thinking_id = getattr(self, 'thinking_id', 'plugin_thinking')
cycle_timers = getattr(self, "cycle_timers", {})
reasoning = getattr(self, "reasoning", "插件生成")
thinking_id = getattr(self, "thinking_id", "plugin_thinking")
success, _ = await expressor.deal_reply(
cycle_timers=cycle_timers,
action_data=reply_data,
@@ -303,9 +303,9 @@ class MessageAPI:
bool: 是否发送成功
"""
# 安全获取服务和日志前缀
services = getattr(self, '_services', {})
log_prefix = getattr(self, 'log_prefix', '[MessageAPI]')
services = getattr(self, "_services", {})
log_prefix = getattr(self, "log_prefix", "[MessageAPI]")
replyer: DefaultReplyer = services.get("replyer")
chat_stream: ChatStream = services.get("chat_stream")
@@ -342,10 +342,10 @@ class MessageAPI:
anchor_message.update_chat_stream(chat_stream)
# 调用内部方法发送消息
cycle_timers = getattr(self, 'cycle_timers', {})
reasoning = getattr(self, 'reasoning', '插件生成')
thinking_id = getattr(self, 'thinking_id', 'plugin_thinking')
cycle_timers = getattr(self, "cycle_timers", {})
reasoning = getattr(self, "reasoning", "插件生成")
thinking_id = getattr(self, "thinking_id", "plugin_thinking")
success, _ = await replyer.deal_reply(
cycle_timers=cycle_timers,
action_data=reply_data,
@@ -362,7 +362,7 @@ class MessageAPI:
Returns:
str: 聊天类型 ("group""private")
"""
services = getattr(self, '_services', {})
services = getattr(self, "_services", {})
chat_stream: ChatStream = services.get("chat_stream")
if chat_stream and hasattr(chat_stream, "group_info"):
return "group" if chat_stream.group_info else "private"
@@ -378,7 +378,7 @@ class MessageAPI:
List[Dict]: 消息列表,每个消息包含发送者、内容等信息
"""
messages = []
services = getattr(self, '_services', {})
services = getattr(self, "_services", {})
observations = services.get("observations", [])
if observations and len(observations) > 0:

View File

@@ -5,7 +5,6 @@
提供所有插件API功能的统一访问入口
"""
from typing import Dict, Any, Optional
from src.common.logger_manager import get_logger
# 导入所有API模块
@@ -23,28 +22,25 @@ logger = get_logger("plugin_api")
class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI, HearflowAPI):
"""
插件API聚合类
集成了所有可供插件使用的API功能提供统一的访问接口。
插件组件可以直接使用此API实例来访问各种功能。
特性:
- 聚合所有API模块的功能
- 支持依赖注入和配置
- 提供统一的错误处理和日志记录
"""
def __init__(self,
chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[PluginAPI]"):
def __init__(
self, chat_stream=None, expressor=None, replyer=None, observations=None, log_prefix: str = "[PluginAPI]"
):
"""
初始化插件API
Args:
chat_stream: 聊天流对象
expressor: 表达器对象
expressor: 表达器对象
replyer: 回复器对象
observations: 观察列表
log_prefix: 日志前缀
@@ -54,105 +50,96 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
"chat_stream": chat_stream,
"expressor": expressor,
"replyer": replyer,
"observations": observations or []
"observations": observations or [],
}
self.log_prefix = log_prefix
# 调用所有父类的初始化
super().__init__()
logger.debug(f"{self.log_prefix} PluginAPI 初始化完成")
def set_chat_stream(self, chat_stream):
"""设置聊天流对象"""
self._services["chat_stream"] = chat_stream
logger.debug(f"{self.log_prefix} 设置聊天流: {getattr(chat_stream, 'stream_id', 'Unknown')}")
def set_expressor(self, expressor):
"""设置表达器对象"""
self._services["expressor"] = expressor
logger.debug(f"{self.log_prefix} 设置表达器")
def set_replyer(self, replyer):
"""设置回复器对象"""
self._services["replyer"] = replyer
logger.debug(f"{self.log_prefix} 设置回复器")
def set_observations(self, observations):
"""设置观察列表"""
self._services["observations"] = observations or []
logger.debug(f"{self.log_prefix} 设置观察列表,数量: {len(observations or [])}")
def get_service(self, service_name: str):
"""获取指定的服务对象"""
return self._services.get(service_name)
def has_service(self, service_name: str) -> bool:
"""检查是否有指定的服务对象"""
return service_name in self._services and self._services[service_name] is not None
# 便捷的工厂函数
def create_plugin_api(chat_stream=None,
expressor=None,
replyer=None,
observations=None,
log_prefix: str = "[Plugin]") -> PluginAPI:
def create_plugin_api(
chat_stream=None, expressor=None, replyer=None, observations=None, log_prefix: str = "[Plugin]"
) -> PluginAPI:
"""
创建插件API实例的便捷函数
Args:
chat_stream: 聊天流对象
expressor: 表达器对象
replyer: 回复器对象
replyer: 回复器对象
observations: 观察列表
log_prefix: 日志前缀
Returns:
PluginAPI: 配置好的插件API实例
"""
return PluginAPI(
chat_stream=chat_stream,
expressor=expressor,
replyer=replyer,
observations=observations,
log_prefix=log_prefix
chat_stream=chat_stream, expressor=expressor, replyer=replyer, observations=observations, log_prefix=log_prefix
)
def create_command_api(message, log_prefix: str = "[Command]") -> PluginAPI:
"""
为命令创建插件API实例的便捷函数
Args:
message: 消息对象,应该包含 chat_stream 等信息
log_prefix: 日志前缀
Returns:
PluginAPI: 配置好的插件API实例
"""
chat_stream = getattr(message, 'chat_stream', None)
api = PluginAPI(
chat_stream=chat_stream,
log_prefix=log_prefix
)
chat_stream = getattr(message, "chat_stream", None)
api = PluginAPI(chat_stream=chat_stream, log_prefix=log_prefix)
return api
# 导出主要接口
__all__ = [
'PluginAPI',
'create_plugin_api',
'create_command_api',
"PluginAPI",
"create_plugin_api",
"create_command_api",
# 也可以导出各个API类供单独使用
'MessageAPI',
'LLMAPI',
'DatabaseAPI',
'ConfigAPI',
'UtilsAPI',
'StreamAPI',
'HearflowAPI'
]
"MessageAPI",
"LLMAPI",
"DatabaseAPI",
"ConfigAPI",
"UtilsAPI",
"StreamAPI",
"HearflowAPI",
]