refactor: 延迟导入 StreamContext 以提高类型检查性能
This commit is contained in:
@@ -1,13 +1,15 @@
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Any
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from src.chat.planner_actions.action_manager import ChatterActionManager
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
from src.common.logger import get_logger
|
||||
from src.plugin_system.base.base_chatter import BaseChatter
|
||||
from src.plugin_system.base.component_types import ChatType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
|
||||
logger = get_logger("chatter_manager")
|
||||
|
||||
|
||||
@@ -82,7 +84,7 @@ class ChatterManager:
|
||||
del self.instances[stream_id]
|
||||
logger.info(f"清理不活跃聊天流实例: {stream_id}")
|
||||
|
||||
async def process_stream_context(self, stream_id: str, context: StreamContext) -> dict:
|
||||
async def process_stream_context(self, stream_id: str, context: "StreamContext") -> dict:
|
||||
"""处理流上下文"""
|
||||
chat_type = context.chat_type
|
||||
logger.debug(f"处理流 {stream_id},聊天类型: {chat_type.value}")
|
||||
@@ -127,17 +129,6 @@ class ChatterManager:
|
||||
self.stats["failed_executions"] += 1
|
||||
logger.warning(f"流 {stream_id} 处理失败,不清空未读消息")
|
||||
|
||||
# 从 mood_manager 获取最新的 chat_stream 并同步回 StreamContext
|
||||
try:
|
||||
from src.mood.mood_manager import mood_manager
|
||||
|
||||
mood = mood_manager.get_mood_by_chat_id(stream_id)
|
||||
if mood and mood.chat_stream:
|
||||
context.chat_stream = mood.chat_stream
|
||||
logger.debug(f"已将最新的 chat_stream 同步回流 {stream_id} 的 StreamContext")
|
||||
except Exception as sync_e:
|
||||
logger.error(f"同步 chat_stream 回 StreamContext 失败: {sync_e}")
|
||||
|
||||
# 记录处理结果
|
||||
actions_count = result.get("actions_count", 0)
|
||||
logger.debug(f"流 {stream_id} 处理完成: 成功={success}, 动作数={actions_count}")
|
||||
|
||||
@@ -6,15 +6,17 @@
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Any
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from src.chat.energy_system import energy_manager
|
||||
from src.common.data_models.database_data_model import DatabaseMessages
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config
|
||||
from src.plugin_system.base.component_types import ChatType
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
|
||||
logger = get_logger("context_manager")
|
||||
|
||||
# 全局背景任务集合(用于异步初始化等后台任务)
|
||||
@@ -24,7 +26,7 @@ _background_tasks = set()
|
||||
class SingleStreamContextManager:
|
||||
"""单流上下文管理器 - 每个实例只管理一个 stream 的上下文"""
|
||||
|
||||
def __init__(self, stream_id: str, context: StreamContext, max_context_size: int | None = None):
|
||||
def __init__(self, stream_id: str, context: "StreamContext", max_context_size: int | None = None):
|
||||
self.stream_id = stream_id
|
||||
self.context = context
|
||||
|
||||
@@ -47,7 +49,7 @@ class SingleStreamContextManager:
|
||||
_background_tasks.add(task)
|
||||
task.add_done_callback(_background_tasks.discard)
|
||||
|
||||
def get_context(self) -> StreamContext:
|
||||
def get_context(self) -> "StreamContext":
|
||||
"""获取流上下文"""
|
||||
self._update_access_stats()
|
||||
return self.context
|
||||
|
||||
@@ -5,15 +5,17 @@
|
||||
|
||||
import asyncio
|
||||
import time
|
||||
from typing import Any
|
||||
from typing import Any, TYPE_CHECKING
|
||||
|
||||
from src.chat.chatter_manager import ChatterManager
|
||||
from src.chat.energy_system import energy_manager
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config
|
||||
from src.plugin_system.apis.chat_api import get_chat_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
|
||||
logger = get_logger("stream_loop_manager")
|
||||
|
||||
|
||||
@@ -294,7 +296,7 @@ class StreamLoopManager:
|
||||
|
||||
logger.info(f"🏁 [流工作器] stream={stream_id[:8]}, 任务ID={task_id}, 循环结束")
|
||||
|
||||
async def _get_stream_context(self, stream_id: str) -> StreamContext | None:
|
||||
async def _get_stream_context(self, stream_id: str) -> "StreamContext" | None:
|
||||
"""获取流上下文
|
||||
|
||||
Args:
|
||||
@@ -313,7 +315,7 @@ class StreamLoopManager:
|
||||
logger.error(f"获取流上下文失败 {stream_id}: {e}")
|
||||
return None
|
||||
|
||||
async def _has_messages_to_process(self, context: StreamContext) -> bool:
|
||||
async def _has_messages_to_process(self, context: "StreamContext") -> bool:
|
||||
"""检查是否有消息需要处理
|
||||
|
||||
Args:
|
||||
@@ -332,7 +334,7 @@ class StreamLoopManager:
|
||||
logger.error(f"检查消息状态失败: {e}")
|
||||
return False
|
||||
|
||||
async def _process_stream_messages(self, stream_id: str, context: StreamContext) -> bool:
|
||||
async def _process_stream_messages(self, stream_id: str, context: "StreamContext") -> bool:
|
||||
"""处理流消息 - 支持子任务管理
|
||||
|
||||
Args:
|
||||
@@ -577,7 +579,7 @@ class StreamLoopManager:
|
||||
logger.debug(f"检查流 {stream_id} 是否需要强制分发失败: {e}")
|
||||
return False
|
||||
|
||||
def _get_unread_count(self, context: StreamContext) -> int:
|
||||
def _get_unread_count(self, context: "StreamContext") -> int:
|
||||
try:
|
||||
unread_messages = context.unread_messages
|
||||
if unread_messages is None:
|
||||
@@ -586,7 +588,7 @@ class StreamLoopManager:
|
||||
except Exception:
|
||||
return 0
|
||||
|
||||
def _needs_force_dispatch_for_context(self, context: StreamContext, unread_count: int | None = None) -> bool:
|
||||
def _needs_force_dispatch_for_context(self, context: "StreamContext", unread_count: int | None = None) -> bool:
|
||||
if not self.force_dispatch_unread_threshold or self.force_dispatch_unread_threshold <= 0:
|
||||
return False
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ from typing import TYPE_CHECKING, Any, cast
|
||||
from src.chat.message_receive.chat_stream import ChatStream, get_chat_manager
|
||||
from src.chat.planner_actions.action_manager import ChatterActionManager
|
||||
from src.chat.utils.chat_message_builder import build_readable_messages, get_raw_msg_before_timestamp_with_chat
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
from src.common.logger import get_logger
|
||||
from src.config.config import global_config, model_config
|
||||
from src.llm_models.utils_model import LLMRequest
|
||||
@@ -15,7 +14,7 @@ from src.plugin_system.base.component_types import ActionInfo
|
||||
from src.plugin_system.core.global_announcement_manager import global_announcement_manager
|
||||
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
from src.common.data_models.message_manager_data_model import StreamContext
|
||||
|
||||
logger = get_logger("action_manager")
|
||||
|
||||
@@ -182,7 +181,7 @@ class ActionModifier:
|
||||
|
||||
logger.info(f"{self.log_prefix} 当前可用动作: {available_actions_text}||移除: {removals_summary}")
|
||||
|
||||
def _check_action_associated_types(self, all_actions: dict[str, ActionInfo], chat_context: StreamContext):
|
||||
def _check_action_associated_types(self, all_actions: dict[str, ActionInfo], chat_context: "StreamContext"):
|
||||
type_mismatched_actions: list[tuple[str, str]] = []
|
||||
for action_name, action_info in all_actions.items():
|
||||
if action_info.associated_types and not chat_context.check_types(action_info.associated_types):
|
||||
|
||||
@@ -543,12 +543,6 @@ class ChatterPlanFilter:
|
||||
f"[{action}] 找不到目标消息,target_message_id: {action_data.get('target_message_id')}"
|
||||
)
|
||||
|
||||
# 从action_data中提取should_quote_reply参数
|
||||
should_quote_reply = action_data.get("should_quote_reply")
|
||||
# 严格按照标准格式,只接受布尔值
|
||||
if not isinstance(should_quote_reply, bool):
|
||||
should_quote_reply = None
|
||||
|
||||
return ActionPlannerInfo(
|
||||
action_type=action,
|
||||
reasoning=reasoning,
|
||||
|
||||
@@ -201,6 +201,15 @@ class ChatterActionPlanner:
|
||||
plan_filter = ChatterPlanFilter(self.chat_id, available_actions)
|
||||
filtered_plan = await plan_filter.filter(initial_plan)
|
||||
|
||||
# 检查reply动作是否可用
|
||||
reply_action_available = "reply" in available_actions or "respond" in available_actions
|
||||
if filtered_plan.decided_actions and not reply_action_available:
|
||||
logger.info("Focus模式 - 回复动作不可用,移除所有回复相关动作")
|
||||
filtered_plan.decided_actions = [
|
||||
action for action in filtered_plan.decided_actions
|
||||
if action.action_type not in ["reply", "respond"]
|
||||
]
|
||||
|
||||
# 7. 检查是否正在处理相同的目标消息,防止重复回复
|
||||
target_message_id = None
|
||||
if filtered_plan and filtered_plan.decided_actions:
|
||||
|
||||
Reference in New Issue
Block a user