This commit is contained in:
tcmofashi
2025-04-09 17:50:54 +08:00
parent d50ea59f34
commit 08e5dd2f7b
18 changed files with 439 additions and 514 deletions

View File

@@ -4,6 +4,7 @@ import logging
from pathlib import Path
from logging.handlers import RotatingFileHandler
def setup_crash_logger():
"""设置崩溃日志记录器"""
# 创建logs/crash目录如果不存在
@@ -11,46 +12,42 @@ def setup_crash_logger():
crash_log_dir.mkdir(parents=True, exist_ok=True)
# 创建日志记录器
crash_logger = logging.getLogger('crash_logger')
crash_logger = logging.getLogger("crash_logger")
crash_logger.setLevel(logging.ERROR)
# 设置日志格式
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s\n'
'异常类型: %(exc_info)s\n'
'详细信息:\n%(message)s\n'
'-------------------\n'
"%(asctime)s - %(name)s - %(levelname)s\n异常类型: %(exc_info)s\n详细信息:\n%(message)s\n-------------------\n"
)
# 创建按大小轮转的文件处理器最大10MB保留5个备份
log_file = crash_log_dir / "crash.log"
file_handler = RotatingFileHandler(
log_file,
maxBytes=10*1024*1024, # 10MB
maxBytes=10 * 1024 * 1024, # 10MB
backupCount=5,
encoding='utf-8'
encoding="utf-8",
)
file_handler.setFormatter(formatter)
crash_logger.addHandler(file_handler)
return crash_logger
def log_crash(exc_type, exc_value, exc_traceback):
"""记录崩溃信息到日志文件"""
if exc_type is None:
return
# 获取崩溃日志记录器
crash_logger = logging.getLogger('crash_logger')
crash_logger = logging.getLogger("crash_logger")
# 获取完整的异常堆栈信息
stack_trace = ''.join(traceback.format_exception(exc_type, exc_value, exc_traceback))
stack_trace = "".join(traceback.format_exception(exc_type, exc_value, exc_traceback))
# 记录崩溃信息
crash_logger.error(
stack_trace,
exc_info=(exc_type, exc_value, exc_traceback)
)
crash_logger.error(stack_trace, exc_info=(exc_type, exc_value, exc_traceback))
def install_crash_handler():
"""安装全局异常处理器"""

View File

@@ -10,6 +10,7 @@ from .conversation_info import ConversationInfo
logger = get_module_logger("action_planner")
class ActionPlannerInfo:
def __init__(self):
self.done_action = []
@@ -23,20 +24,13 @@ class ActionPlanner:
def __init__(self, stream_id: str):
self.llm = LLM_request(
model=global_config.llm_normal,
temperature=0.7,
max_tokens=1000,
request_type="action_planning"
model=global_config.llm_normal, temperature=0.7, max_tokens=1000, request_type="action_planning"
)
self.personality_info = Individuality.get_instance().get_prompt(type = "personality", x_person = 2, level = 2)
self.personality_info = Individuality.get_instance().get_prompt(type="personality", x_person=2, level=2)
self.name = global_config.BOT_NICKNAME
self.chat_observer = ChatObserver.get_instance(stream_id)
async def plan(
self,
observation_info: ObservationInfo,
conversation_info: ConversationInfo
) -> Tuple[str, str]:
async def plan(self, observation_info: ObservationInfo, conversation_info: ConversationInfo) -> Tuple[str, str]:
"""规划下一步行动
Args:
@@ -49,14 +43,13 @@ class ActionPlanner:
# 构建提示词
logger.debug(f"开始规划行动:当前目标: {conversation_info.goal_list}")
#构建对话目标
# 构建对话目标
if conversation_info.goal_list:
goal, reasoning = conversation_info.goal_list[-1]
else:
goal = "目前没有明确对话目标"
reasoning = "目前没有明确对话目标,最好思考一个对话目标"
# 获取聊天历史记录
chat_history_list = observation_info.chat_history
chat_history_text = ""
@@ -72,7 +65,6 @@ class ActionPlanner:
observation_info.clear_unprocessed_messages()
personality_text = f"你的名字是{self.name}{self.personality_info}"
# 构建action历史文本
@@ -81,8 +73,6 @@ class ActionPlanner:
for action in action_history_list:
action_history_text += f"{action}\n"
prompt = f"""{personality_text}。现在你在参与一场QQ聊天请分析以下内容根据信息决定下一步行动
当前对话目标:{goal}
@@ -114,9 +104,7 @@ rethink_goal: 重新思考对话目标,当发现对话目标不合适时选择
# 使用简化函数提取JSON内容
success, result = get_items_from_json(
content,
"action", "reason",
default_values={"action": "direct_reply", "reason": "没有明确原因"}
content, "action", "reason", default_values={"action": "direct_reply", "reason": "没有明确原因"}
)
if not success:

View File

@@ -17,7 +17,7 @@ class ChatObserver:
_instances: Dict[str, "ChatObserver"] = {}
@classmethod
def get_instance(cls, stream_id: str, message_storage: Optional[MessageStorage] = None) -> 'ChatObserver':
def get_instance(cls, stream_id: str, message_storage: Optional[MessageStorage] = None) -> "ChatObserver":
"""获取或创建观察器实例
Args:
@@ -84,10 +84,7 @@ class ChatObserver:
"""
logger.debug(f"检查距离上一次观察之后是否有了新消息: {self.last_check_time}")
new_message_exists = await self.message_storage.has_new_messages(
self.stream_id,
self.last_check_time
)
new_message_exists = await self.message_storage.has_new_messages(self.stream_id, self.last_check_time)
if new_message_exists:
logger.debug("发现新消息")
@@ -114,11 +111,7 @@ class ChatObserver:
self.last_user_speak_time = message["time"]
# 发送新消息通知
notification = create_new_message_notification(
sender="chat_observer",
target="pfc",
message=message
)
notification = create_new_message_notification(sender="chat_observer", target="pfc", message=message)
await self.notification_manager.send_notification(notification)
# 检查并更新冷场状态
@@ -144,19 +137,12 @@ class ChatObserver:
# 如果冷场状态发生变化,发送通知
if is_cold != self.is_cold_chat_state:
self.is_cold_chat_state = is_cold
notification = create_cold_chat_notification(
sender="chat_observer",
target="pfc",
is_cold=is_cold
)
notification = create_cold_chat_notification(sender="chat_observer", target="pfc", is_cold=is_cold)
await self.notification_manager.send_notification(notification)
async def get_new_message(self) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""获取上一次观察的时间点后的新消息,插入到历史记录中,并返回新消息和历史记录两个对象"""
messages = await self.message_storage.get_messages_after(
self.stream_id,
self.last_message_read
)
messages = await self.message_storage.get_messages_after(self.stream_id, self.last_message_read)
for message in messages:
await self._add_message_to_history(message)
return messages, self.message_history
@@ -224,10 +210,7 @@ class ChatObserver:
Returns:
List[Dict[str, Any]]: 新消息列表
"""
new_messages = await self.message_storage.get_messages_after(
self.stream_id,
self.last_message_read
)
new_messages = await self.message_storage.get_messages_after(self.stream_id, self.last_message_read)
if new_messages:
self.last_message_read = new_messages[-1]["message_id"]
@@ -243,17 +226,15 @@ class ChatObserver:
Returns:
List[Dict[str, Any]]: 最多5条消息
"""
new_messages = await self.message_storage.get_messages_before(
self.stream_id,
time_point
)
new_messages = await self.message_storage.get_messages_before(self.stream_id, time_point)
if new_messages:
self.last_message_read = new_messages[-1]["message_id"]
return new_messages
'''主要观察循环'''
"""主要观察循环"""
async def _update_loop(self):
"""更新循环"""
try:
@@ -396,17 +377,16 @@ class ChatObserver:
bool: 是否有新消息
"""
try:
messages = await self.message_storage.get_messages_for_stream(
self.stream_id,
limit=50
)
messages = await self.message_storage.get_messages_for_stream(self.stream_id, limit=50)
if not messages:
return False
# 检查是否有新消息
has_new_messages = False
if messages and (not self.message_cache or messages[0]["message_id"] != self.message_cache[0]["message_id"]):
if messages and (
not self.message_cache or messages[0]["message_id"] != self.message_cache[0]["message_id"]
):
has_new_messages = True
self.message_cache = messages

View File

@@ -4,8 +4,10 @@ from dataclasses import dataclass
from datetime import datetime
from abc import ABC, abstractmethod
class ChatState(Enum):
"""聊天状态枚举"""
NORMAL = auto() # 正常状态
NEW_MESSAGE = auto() # 有新消息
COLD_CHAT = auto() # 冷场状态
@@ -15,8 +17,10 @@ class ChatState(Enum):
SILENT = auto() # 沉默状态
ERROR = auto() # 错误状态
class NotificationType(Enum):
"""通知类型枚举"""
NEW_MESSAGE = auto() # 新消息通知
COLD_CHAT = auto() # 冷场通知
ACTIVE_CHAT = auto() # 活跃通知
@@ -27,9 +31,11 @@ class NotificationType(Enum):
USER_LEFT = auto() # 用户离开通知
ERROR = auto() # 错误通知
@dataclass
class ChatStateInfo:
"""聊天状态信息"""
state: ChatState
last_message_time: Optional[float] = None
last_message_content: Optional[str] = None
@@ -38,9 +44,11 @@ class ChatStateInfo:
cold_duration: float = 0.0 # 冷场持续时间(秒)
active_duration: float = 0.0 # 活跃持续时间(秒)
@dataclass
class Notification:
"""通知基类"""
type: NotificationType
timestamp: float
sender: str # 发送者标识
@@ -49,15 +57,13 @@ class Notification:
def to_dict(self) -> Dict[str, Any]:
"""转换为字典格式"""
return {
"type": self.type.name,
"timestamp": self.timestamp,
"data": self.data
}
return {"type": self.type.name, "timestamp": self.timestamp, "data": self.data}
@dataclass
class StateNotification(Notification):
"""持续状态通知"""
is_active: bool = True
def to_dict(self) -> Dict[str, Any]:
@@ -65,6 +71,7 @@ class StateNotification(Notification):
base_dict["is_active"] = self.is_active
return base_dict
class NotificationHandler(ABC):
"""通知处理器接口"""
@@ -73,6 +80,7 @@ class NotificationHandler(ABC):
"""处理通知"""
pass
class NotificationManager:
"""通知管理器"""
@@ -141,10 +149,9 @@ class NotificationManager:
"""检查特定状态是否活跃"""
return state_type in self._active_states
def get_notification_history(self,
sender: Optional[str] = None,
target: Optional[str] = None,
limit: Optional[int] = None) -> List[Notification]:
def get_notification_history(
self, sender: Optional[str] = None, target: Optional[str] = None, limit: Optional[int] = None
) -> List[Notification]:
"""获取通知历史
Args:
@@ -164,6 +171,7 @@ class NotificationManager:
return history
# 一些常用的通知创建函数
def create_new_message_notification(sender: str, target: str, message: Dict[str, Any]) -> Notification:
"""创建新消息通知"""
@@ -176,10 +184,11 @@ def create_new_message_notification(sender: str, target: str, message: Dict[str,
"message_id": message.get("message_id"),
"content": message.get("content"),
"sender": message.get("sender"),
"time": message.get("time")
}
"time": message.get("time"),
},
)
def create_cold_chat_notification(sender: str, target: str, is_cold: bool) -> StateNotification:
"""创建冷场状态通知"""
return StateNotification(
@@ -188,9 +197,10 @@ def create_cold_chat_notification(sender: str, target: str, is_cold: bool) -> St
sender=sender,
target=target,
data={"is_cold": is_cold},
is_active=is_cold
is_active=is_cold,
)
def create_active_chat_notification(sender: str, target: str, is_active: bool) -> StateNotification:
"""创建活跃状态通知"""
return StateNotification(
@@ -199,9 +209,10 @@ def create_active_chat_notification(sender: str, target: str, is_active: bool) -
sender=sender,
target=target,
data={"is_active": is_active},
is_active=is_active
is_active=is_active,
)
class ChatStateManager:
"""聊天状态管理器"""

View File

@@ -54,16 +54,15 @@ class Conversation:
logger.error(traceback.format_exc())
raise
try:
#决策所需要的信息,包括自身自信和观察信息两部分
#注册观察器和观测信息
# 决策所需要的信息,包括自身自信和观察信息两部分
# 注册观察器和观测信息
self.chat_observer = ChatObserver.get_instance(self.stream_id)
self.chat_observer.start()
self.observation_info = ObservationInfo()
self.observation_info.bind_to_chat_observer(self.stream_id)
#对话信息
# 对话信息
self.conversation_info = ConversationInfo()
except Exception as e:
logger.error(f"初始化对话实例:注册信息组件失败: {e}")
@@ -74,7 +73,6 @@ class Conversation:
self.should_continue = True
asyncio.create_task(self.start())
async def start(self):
"""开始对话流程"""
try:
@@ -84,16 +82,12 @@ class Conversation:
logger.error(f"启动对话系统失败: {e}")
raise
async def _plan_and_action_loop(self):
"""思考步PFC核心循环模块"""
# 获取最近的消息历史
while self.should_continue:
# 使用决策信息来辅助行动规划
action, reason = await self.action_planner.plan(
self.observation_info,
self.conversation_info
)
action, reason = await self.action_planner.plan(self.observation_info, self.conversation_info)
if self._check_new_messages_after_planning():
continue
@@ -108,7 +102,6 @@ class Conversation:
return True
return False
def _convert_to_message(self, msg_dict: Dict[str, Any]) -> Message:
"""将消息字典转换为Message对象"""
try:
@@ -122,31 +115,31 @@ class Conversation:
time=msg_dict["time"],
user_info=user_info,
processed_plain_text=msg_dict.get("processed_plain_text", ""),
detailed_plain_text=msg_dict.get("detailed_plain_text", "")
detailed_plain_text=msg_dict.get("detailed_plain_text", ""),
)
except Exception as e:
logger.warning(f"转换消息时出错: {e}")
raise
async def _handle_action(self, action: str, reason: str, observation_info: ObservationInfo, conversation_info: ConversationInfo):
async def _handle_action(
self, action: str, reason: str, observation_info: ObservationInfo, conversation_info: ConversationInfo
):
"""处理规划的行动"""
logger.info(f"执行行动: {action}, 原因: {reason}")
# 记录action历史先设置为stop完成后再设置为done
conversation_info.done_action.append({
conversation_info.done_action.append(
{
"action": action,
"reason": reason,
"status": "start",
"time": datetime.datetime.now().strftime("%H:%M:%S")
})
"time": datetime.datetime.now().strftime("%H:%M:%S"),
}
)
if action == "direct_reply":
self.state = ConversationState.GENERATING
self.generated_reply = await self.reply_generator.generate(
observation_info,
conversation_info
)
self.generated_reply = await self.reply_generator.generate(observation_info, conversation_info)
# # 检查回复是否合适
# is_suitable, reason, need_replan = await self.reply_generator.check_reply(
@@ -159,12 +152,14 @@ class Conversation:
await self._send_reply()
conversation_info.done_action.append({
conversation_info.done_action.append(
{
"action": action,
"reason": reason,
"status": "done",
"time": datetime.datetime.now().strftime("%H:%M:%S")
})
"time": datetime.datetime.now().strftime("%H:%M:%S"),
}
)
elif action == "fetch_knowledge":
self.state = ConversationState.FETCHING
@@ -175,10 +170,7 @@ class Conversation:
if knowledge:
if topic not in self.conversation_info.knowledge_list:
self.conversation_info.knowledge_list.append({
"topic": topic,
"knowledge": knowledge
})
self.conversation_info.knowledge_list.append({"topic": topic, "knowledge": knowledge})
else:
self.conversation_info.knowledge_list[topic] += knowledge
@@ -186,7 +178,6 @@ class Conversation:
self.state = ConversationState.RETHINKING
await self.goal_analyzer.analyze_goal(conversation_info, observation_info)
elif action == "listening":
self.state = ConversationState.LISTENING
logger.info("倾听对方发言...")
@@ -210,9 +201,7 @@ class Conversation:
latest_message = self._convert_to_message(messages[0])
await self.direct_sender.send_message(
chat_stream=self.chat_stream,
content="TODO:超时消息",
reply_to_message=latest_message
chat_stream=self.chat_stream, content="TODO:超时消息", reply_to_message=latest_message
)
except Exception as e:
logger.error(f"发送超时消息失败: {str(e)}")
@@ -231,9 +220,7 @@ class Conversation:
latest_message = self._convert_to_message(messages[0])
try:
await self.direct_sender.send_message(
chat_stream=self.chat_stream,
content=self.generated_reply,
reply_to_message=latest_message
chat_stream=self.chat_stream, content=self.generated_reply, reply_to_message=latest_message
)
self.chat_observer.trigger_update() # 触发立即更新
if not await self.chat_observer.wait_for_update():

View File

@@ -1,5 +1,3 @@
class ConversationInfo:
def __init__(self):
self.done_action = []

View File

@@ -7,6 +7,7 @@ from src.plugins.chat.message import MessageSending
logger = get_module_logger("message_sender")
class DirectMessageSender:
"""直接消息发送器"""
@@ -33,10 +34,7 @@ class DirectMessageSender:
# 检查是否需要引用回复
if reply_to_message:
reply_id = reply_to_message.message_id
message_sending = MessageSending(
segments=segments,
reply_to_id=reply_id
)
message_sending = MessageSending(segments=segments, reply_to_id=reply_id)
else:
message_sending = MessageSending(segments=segments)

View File

@@ -2,6 +2,7 @@ from abc import ABC, abstractmethod
from typing import List, Dict, Any, Optional
from src.common.database import db
class MessageStorage(ABC):
"""消息存储接口"""
@@ -45,6 +46,7 @@ class MessageStorage(ABC):
"""
pass
class MongoDBMessageStorage(MessageStorage):
"""MongoDB消息存储实现"""
@@ -60,32 +62,23 @@ class MongoDBMessageStorage(MessageStorage):
if last_message:
query["time"] = {"$gt": last_message["time"]}
return list(
self.db.messages.find(query).sort("time", 1)
)
return list(self.db.messages.find(query).sort("time", 1))
async def get_messages_before(self, chat_id: str, time_point: float, limit: int = 5) -> List[Dict[str, Any]]:
query = {
"chat_id": chat_id,
"time": {"$lt": time_point}
}
query = {"chat_id": chat_id, "time": {"$lt": time_point}}
messages = list(
self.db.messages.find(query).sort("time", -1).limit(limit)
)
messages = list(self.db.messages.find(query).sort("time", -1).limit(limit))
# 将消息按时间正序排列
messages.reverse()
return messages
async def has_new_messages(self, chat_id: str, after_time: float) -> bool:
query = {
"chat_id": chat_id,
"time": {"$gt": after_time}
}
query = {"chat_id": chat_id, "time": {"$gt": after_time}}
return self.db.messages.find_one(query) is not None
# # 创建一个内存消息存储实现,用于测试
# class InMemoryMessageStorage(MessageStorage):
# """内存消息存储实现,主要用于测试"""

View File

@@ -7,10 +7,11 @@ if TYPE_CHECKING:
logger = get_module_logger("notification_handler")
class PFCNotificationHandler(NotificationHandler):
"""PFC通知处理器"""
def __init__(self, conversation: 'Conversation'):
def __init__(self, conversation: "Conversation"):
"""初始化PFC通知处理器
Args:
@@ -68,4 +69,3 @@ class PFCNotificationHandler(NotificationHandler):
observation_info.conversation_cold_duration = cold_duration
logger.info(f"对话已冷: {cold_duration}")

View File

@@ -1,5 +1,5 @@
#Programmable Friendly Conversationalist
#Prefrontal cortex
# Programmable Friendly Conversationalist
# Prefrontal cortex
from typing import List, Optional, Dict, Any, Set
from ..message.message_base import UserInfo
import time
@@ -10,10 +10,11 @@ from .chat_states import NotificationHandler
logger = get_module_logger("observation_info")
class ObservationInfoHandler(NotificationHandler):
"""ObservationInfo的通知处理器"""
def __init__(self, observation_info: 'ObservationInfo'):
def __init__(self, observation_info: "ObservationInfo"):
"""初始化处理器
Args:
@@ -62,8 +63,7 @@ class ObservationInfoHandler(NotificationHandler):
# 处理消息删除通知
message_id = data.get("message_id")
self.observation_info.unprocessed_messages = [
msg for msg in self.observation_info.unprocessed_messages
if msg.get("message_id") != message_id
msg for msg in self.observation_info.unprocessed_messages if msg.get("message_id") != message_id
]
elif notification_type == "USER_JOINED":
@@ -83,16 +83,17 @@ class ObservationInfoHandler(NotificationHandler):
error_msg = data.get("error", "")
logger.error(f"收到错误通知: {error_msg}")
@dataclass
class ObservationInfo:
"""决策信息类用于收集和管理来自chat_observer的通知信息"""
#data_list
# data_list
chat_history: List[str] = field(default_factory=list)
unprocessed_messages: List[Dict[str, Any]] = field(default_factory=list)
active_users: Set[str] = field(default_factory=set)
#data
# data
last_bot_speak_time: Optional[float] = None
last_user_speak_time: Optional[float] = None
last_message_time: Optional[float] = None
@@ -102,7 +103,7 @@ class ObservationInfo:
new_messages_count: int = 0
cold_chat_duration: float = 0.0
#state
# state
is_typing: bool = False
has_unread_messages: bool = False
is_cold_chat: bool = False
@@ -124,28 +125,20 @@ class ObservationInfo:
"""
self.chat_observer = ChatObserver.get_instance(stream_id)
self.chat_observer.notification_manager.register_handler(
target="observation_info",
notification_type="NEW_MESSAGE",
handler=self.handler
target="observation_info", notification_type="NEW_MESSAGE", handler=self.handler
)
self.chat_observer.notification_manager.register_handler(
target="observation_info",
notification_type="COLD_CHAT",
handler=self.handler
target="observation_info", notification_type="COLD_CHAT", handler=self.handler
)
def unbind_from_chat_observer(self):
"""解除与chat_observer的绑定"""
if self.chat_observer:
self.chat_observer.notification_manager.unregister_handler(
target="observation_info",
notification_type="NEW_MESSAGE",
handler=self.handler
target="observation_info", notification_type="NEW_MESSAGE", handler=self.handler
)
self.chat_observer.notification_manager.unregister_handler(
target="observation_info",
notification_type="COLD_CHAT",
handler=self.handler
target="observation_info", notification_type="COLD_CHAT", handler=self.handler
)
self.chat_observer = None

View File

@@ -53,14 +53,13 @@ class GoalAnalyzer:
Returns:
Tuple[str, str, str]: (目标, 方法, 原因)
"""
#构建对话目标
# 构建对话目标
goal_list = conversation_info.goal_list
goal_text = ""
for goal, reason in goal_list:
goal_text += f"目标:{goal};"
goal_text += f"原因:{reason}\n"
# 获取聊天历史记录
chat_history_list = observation_info.chat_history
chat_history_text = ""
@@ -76,7 +75,6 @@ class GoalAnalyzer:
observation_info.clear_unprocessed_messages()
personality_text = f"你的名字是{self.name}{self.personality_info}"
# 构建action历史文本
@@ -85,7 +83,6 @@ class GoalAnalyzer:
for action in action_history_list:
action_history_text += f"{action}\n"
prompt = f"""{personality_text}。现在你在参与一场QQ聊天请分析以下聊天记录并根据你的性格特征确定多个明确的对话目标。
这些目标应该反映出对话的不同方面和意图。
@@ -122,17 +119,12 @@ class GoalAnalyzer:
# 使用简化函数提取JSON内容
success, result = get_items_from_json(
content,
"goal", "reasoning",
required_types={"goal": str, "reasoning": str}
content, "goal", "reasoning", required_types={"goal": str, "reasoning": str}
)
#TODO
# TODO
conversation_info.goal_list.append(result)
async def _update_goals(self, new_goal: str, method: str, reasoning: str):
"""更新目标列表
@@ -233,8 +225,10 @@ class GoalAnalyzer:
# 尝试解析JSON
success, result = get_items_from_json(
content,
"goal_achieved", "stop_conversation", "reason",
required_types={"goal_achieved": bool, "stop_conversation": bool, "reason": str}
"goal_achieved",
"stop_conversation",
"reason",
required_types={"goal_achieved": bool, "stop_conversation": bool, "reason": str},
)
if not success:
@@ -285,7 +279,6 @@ class Waiter:
logger.info("等待中...")
class DirectMessageSender:
"""直接发送消息到平台的发送器"""

View File

@@ -5,6 +5,7 @@ import traceback
logger = get_module_logger("pfc_manager")
class PFCManager:
"""PFC对话管理器负责管理所有对话实例"""
@@ -16,7 +17,7 @@ class PFCManager:
_initializing: Dict[str, bool] = {}
@classmethod
def get_instance(cls) -> 'PFCManager':
def get_instance(cls) -> "PFCManager":
"""获取管理器单例
Returns:
@@ -60,7 +61,6 @@ class PFCManager:
return conversation_instance
async def _initialize_conversation(self, conversation: Conversation):
"""初始化会话实例
@@ -84,7 +84,6 @@ class PFCManager:
logger.error(traceback.format_exc())
# 清理失败的初始化
async def get_conversation(self, stream_id: str) -> Optional[Conversation]:
"""获取已存在的会话实例

View File

@@ -4,6 +4,7 @@ from typing import Literal
class ConversationState(Enum):
"""对话状态"""
INIT = "初始化"
RETHINKING = "重新思考"
ANALYZING = "分析历史"

View File

@@ -16,21 +16,14 @@ class ReplyGenerator:
def __init__(self, stream_id: str):
self.llm = LLM_request(
model=global_config.llm_normal,
temperature=0.7,
max_tokens=300,
request_type="reply_generation"
model=global_config.llm_normal, temperature=0.7, max_tokens=300, request_type="reply_generation"
)
self.personality_info = Individuality.get_instance().get_prompt(type = "personality", x_person = 2, level = 2)
self.personality_info = Individuality.get_instance().get_prompt(type="personality", x_person=2, level=2)
self.name = global_config.BOT_NICKNAME
self.chat_observer = ChatObserver.get_instance(stream_id)
self.reply_checker = ReplyChecker(stream_id)
async def generate(
self,
observation_info: ObservationInfo,
conversation_info: ConversationInfo
) -> str:
async def generate(self, observation_info: ObservationInfo, conversation_info: ConversationInfo) -> str:
"""生成回复
Args:
@@ -58,7 +51,6 @@ class ReplyGenerator:
for msg in chat_history_list:
chat_history_text += f"{msg}\n"
# 整理知识缓存
knowledge_text = ""
knowledge_list = conversation_info.knowledge_list
@@ -107,12 +99,7 @@ class ReplyGenerator:
logger.error(f"生成回复时出错: {e}")
return "抱歉,我现在有点混乱,让我重新思考一下..."
async def check_reply(
self,
reply: str,
goal: str,
retry_count: int = 0
) -> Tuple[bool, str, bool]:
async def check_reply(self, reply: str, goal: str, retry_count: int = 0) -> Tuple[bool, str, bool]:
"""检查回复是否合适
Args:

View File

@@ -3,6 +3,7 @@ from .chat_observer import ChatObserver
logger = get_module_logger("waiter")
class Waiter:
"""等待器,用于等待对话流中的事件"""

View File

@@ -46,7 +46,6 @@ class ChatBot:
chat_id = str(message.chat_stream.stream_id)
if global_config.enable_pfc_chatting:
await self.pfc_manager.get_or_create_conversation(chat_id)
except Exception as e:

View File

@@ -24,7 +24,7 @@ config_config = LogConfig(
# 配置主程序日志格式
logger = get_module_logger("config", config=config_config)
#考虑到实际上配置文件中的mai_version是不会自动更新的,所以采用硬编码
# 考虑到实际上配置文件中的mai_version是不会自动更新的,所以采用硬编码
is_test = True
mai_version_main = "0.6.2"
mai_version_fix = "snapshot-1"