feat:继续重构插件api

This commit is contained in:
SengokuCola
2025-06-10 19:16:58 +08:00
parent e5007cc8cd
commit de0bdd3766
19 changed files with 2161 additions and 682 deletions

View File

@@ -16,29 +16,36 @@ class DatabaseAPI:
"""
async def store_action_info(
self, action_build_into_prompt: bool = False, action_prompt_display: str = "", action_done: bool = True
self,
action_build_into_prompt: bool = False,
action_prompt_display: str = "",
action_done: bool = True,
thinking_id: str = "",
action_data: dict = None
) -> None:
"""存储action执行信息到数据库
"""存储action信息到数据库
Args:
action_build_into_prompt: 是否构建到提示中
action_prompt_display: 动作显示内容
action_done: 动作是否完成
action_prompt_display: 显示的action提示信息
action_done: action是否完成
thinking_id: 思考ID
action_data: action数据如果不提供则使用空字典
"""
try:
chat_stream = self._services.get("chat_stream")
chat_stream = self.get_service("chat_stream")
if not chat_stream:
logger.error(f"{self.log_prefix} 无法存储action信息缺少chat_stream服务")
return
action_time = time.time()
action_id = f"{action_time}_{self.thinking_id}"
action_id = f"{action_time}_{thinking_id}"
ActionRecords.create(
action_id=action_id,
time=action_time,
action_name=self.__class__.__name__,
action_data=str(self.action_data),
action_data=str(action_data or {}),
action_done=action_done,
action_build_into_prompt=action_build_into_prompt,
action_prompt_display=action_prompt_display,

View File

@@ -54,7 +54,10 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
}
self.log_prefix = log_prefix
# 存储action上下文信息
self._action_context = {}
# 调用所有父类的初始化
super().__init__()
@@ -88,6 +91,17 @@ class PluginAPI(MessageAPI, LLMAPI, DatabaseAPI, ConfigAPI, UtilsAPI, StreamAPI,
"""检查是否有指定的服务对象"""
return service_name in self._services and self._services[service_name] is not None
def set_action_context(self, thinking_id: str = None, shutting_down: bool = False, **kwargs):
"""设置action上下文信息"""
if thinking_id:
self._action_context["thinking_id"] = thinking_id
self._action_context["shutting_down"] = shutting_down
self._action_context.update(kwargs)
def get_action_context(self, key: str, default=None):
"""获取action上下文信息"""
return self._action_context.get(key, default)
# 便捷的工厂函数
def create_plugin_api(

View File

@@ -1,6 +1,8 @@
from typing import Optional, List, Dict, Any
from typing import Optional, List, Dict, Any, Tuple
from src.common.logger_manager import get_logger
from src.chat.message_receive.chat_stream import ChatManager, ChatStream
from src.chat.focus_chat.hfc_utils import parse_thinking_id_to_timestamp
import asyncio
logger = get_logger("stream_api")
@@ -157,3 +159,62 @@ class StreamAPI:
except Exception as e:
logger.error(f"{self.log_prefix} 异步通过群ID获取聊天流时出错: {e}")
return None
async def wait_for_new_message(self, timeout: int = 1200) -> Tuple[bool, str]:
"""等待新消息或超时
Args:
timeout: 超时时间默认1200秒
Returns:
Tuple[bool, str]: (是否收到新消息, 空字符串)
"""
try:
# 获取必要的服务对象
observations = self.get_service("observations")
if not observations:
logger.warning(f"{self.log_prefix} 无法获取observations服务无法等待新消息")
return False, ""
# 获取第一个观察对象通常是ChattingObservation
observation = observations[0] if observations else None
if not observation:
logger.warning(f"{self.log_prefix} 无观察对象,无法等待新消息")
return False, ""
# 从action上下文获取thinking_id
thinking_id = self.get_action_context("thinking_id")
if not thinking_id:
logger.warning(f"{self.log_prefix} 无thinking_id无法等待新消息")
return False, ""
logger.info(f"{self.log_prefix} 开始等待新消息... (超时: {timeout}秒)")
wait_start_time = asyncio.get_event_loop().time()
while True:
# 检查关闭标志
shutting_down = self.get_action_context("shutting_down", False)
if shutting_down:
logger.info(f"{self.log_prefix} 等待新消息时检测到关闭信号,中断等待")
return False, ""
# 检查新消息
thinking_id_timestamp = parse_thinking_id_to_timestamp(thinking_id)
if await observation.has_new_messages_since(thinking_id_timestamp):
logger.info(f"{self.log_prefix} 检测到新消息")
return True, ""
# 检查超时
if asyncio.get_event_loop().time() - wait_start_time > timeout:
logger.warning(f"{self.log_prefix} 等待新消息超时({timeout}秒)")
return False, ""
# 短暂休眠
await asyncio.sleep(0.5)
except asyncio.CancelledError:
logger.info(f"{self.log_prefix} 等待新消息被中断 (CancelledError)")
return False, ""
except Exception as e:
logger.error(f"{self.log_prefix} 等待新消息时发生错误: {e}")
return False, f"等待新消息失败: {str(e)}"