移除conn.logger

This commit is contained in:
Chingfeng Li 2025-09-10 15:25:38 +08:00
parent 9b07eead08
commit 5ced0d557a
13 changed files with 152 additions and 116 deletions

View file

@ -45,6 +45,8 @@ from core.utils import textUtils
TAG = __name__
logger = setup_logging()
auto_import_modules("plugins_func.functions")
@ -66,7 +68,6 @@ class ConnectionHandler:
self.common_config = config
self.config = copy.deepcopy(config)
self.session_id = str(uuid.uuid4())
self.logger = setup_logging()
self.server = server # 保存server实例的引用
self.auth = AuthMiddleware(config)
@ -157,7 +158,7 @@ class ConnectionHandler:
self.features = None
# 初始化提示词管理器
self.prompt_manager = PromptManager(config, self.logger)
self.prompt_manager = PromptManager(config)
self.session_context = SessionContext(self.session_id)
@ -173,7 +174,7 @@ class ConnectionHandler:
# 从 WebSocket 请求中获取路径
request_path = ws.request.path
if not request_path:
self.logger.bind(tag=TAG).error("无法获取请求路径")
logger.bind(tag=TAG).error("无法获取请求路径")
return
parsed_url = urlparse(request_path)
query_params = parse_qs(parsed_url.query)
@ -191,7 +192,7 @@ class ConnectionHandler:
self.client_ip = real_ip.split(",")[0].strip()
else:
self.client_ip = ws.remote_address[0]
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"{self.client_ip} conn - Headers: {self.headers}"
)
@ -224,25 +225,25 @@ class ConnectionHandler:
async for message in self.websocket:
await self._route_message(message, self.session_context)
except websockets.exceptions.ConnectionClosed:
self.logger.bind(tag=TAG).info("客户端断开连接")
logger.bind(tag=TAG).info("客户端断开连接")
except AuthenticationError as e:
self.logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
logger.bind(tag=TAG).error(f"Authentication failed: {str(e)}")
return
except Exception as e:
stack_trace = traceback.format_exc()
self.logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}")
logger.bind(tag=TAG).error(f"Connection error: {str(e)}-{stack_trace}")
return
finally:
try:
await self._save_and_close(ws)
except Exception as final_error:
self.logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}")
logger.bind(tag=TAG).error(f"最终清理时出错: {final_error}")
# 确保即使保存记忆失败,也要关闭连接
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"强制关闭连接时出错: {close_error}"
)
@ -260,7 +261,7 @@ class ConnectionHandler:
self.memory.save_memory(self.dialogue.dialogue)
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
finally:
try:
loop.close()
@ -270,13 +271,13 @@ class ConnectionHandler:
# 启动线程保存记忆,不等待完成
threading.Thread(target=save_memory_task, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
logger.bind(tag=TAG).error(f"保存记忆失败: {e}")
finally:
# 立即关闭连接,不等待记忆保存完成
try:
await self.close(ws)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"保存记忆后关闭连接失败: {close_error}"
)
@ -295,7 +296,7 @@ class ConnectionHandler:
"""处理服务器重启请求"""
try:
self.logger.bind(tag=TAG).info("收到服务器重启指令,准备执行...")
logger.bind(tag=TAG).info("收到服务器重启指令,准备执行...")
# 发送确认响应
await self.websocket.send(
@ -313,7 +314,7 @@ class ConnectionHandler:
def restart_server():
"""实际执行重启的方法"""
time.sleep(1)
self.logger.bind(tag=TAG).info("执行服务器重启...")
logger.bind(tag=TAG).info("执行服务器重启...")
subprocess.Popen(
[sys.executable, "app.py"],
stdin=sys.stdin,
@ -327,7 +328,7 @@ class ConnectionHandler:
threading.Thread(target=restart_server, daemon=True).start()
except Exception as e:
self.logger.bind(tag=TAG).error(f"重启失败: {str(e)}")
logger.bind(tag=TAG).error(f"重启失败: {str(e)}")
await self.websocket.send(
json.dumps(
{
@ -344,7 +345,7 @@ class ConnectionHandler:
self.selected_module_str = build_module_string(
self.config.get("selected_module", {})
)
self.logger = create_connection_logger(self.selected_module_str)
logger = create_connection_logger(self.selected_module_str)
"""初始化组件"""
if self.config.get("prompt") is not None:
@ -352,7 +353,7 @@ class ConnectionHandler:
# 使用快速提示词进行初始化
prompt = self.prompt_manager.get_quick_prompt(user_prompt)
self.change_system_prompt(prompt)
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"快速初始化组件: prompt成功 {prompt[:50]}..."
)
@ -386,7 +387,7 @@ class ConnectionHandler:
self._init_prompt_enhancement()
except Exception as e:
self.logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
logger.bind(tag=TAG).error(f"实例化组件失败: {e}")
def _init_prompt_enhancement(self):
# 更新上下文信息
@ -396,7 +397,7 @@ class ConnectionHandler:
)
if enhanced_prompt:
self.change_system_prompt(enhanced_prompt)
self.logger.bind(tag=TAG).info("系统提示词已增强更新")
logger.bind(tag=TAG).info("系统提示词已增强更新")
def _init_report_threads(self):
"""初始化ASR和TTS上报线程"""
@ -409,7 +410,7 @@ class ConnectionHandler:
target=self._report_worker, daemon=True
)
self.report_thread.start()
self.logger.bind(tag=TAG).info("TTS上报线程已启动")
logger.bind(tag=TAG).info("TTS上报线程已启动")
def _initialize_tts(self):
"""初始化TTS"""
@ -443,13 +444,13 @@ class ConnectionHandler:
voiceprint_provider = VoiceprintProvider(voiceprint_config)
if voiceprint_provider is not None and voiceprint_provider.enabled:
self.voiceprint_provider = voiceprint_provider
self.logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
logger.bind(tag=TAG).info("声纹识别功能已在连接时动态启用")
else:
self.logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整")
logger.bind(tag=TAG).warning("声纹识别功能启用但配置不完整")
else:
self.logger.bind(tag=TAG).info("声纹识别功能未启用")
logger.bind(tag=TAG).info("声纹识别功能未启用")
except Exception as e:
self.logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}")
logger.bind(tag=TAG).warning(f"声纹识别初始化失败: {str(e)}")
def _initialize_private_config(self):
"""如果是从配置文件获取,则进行二次实例化"""
@ -464,7 +465,7 @@ class ConnectionHandler:
self.headers.get("client-id", self.headers.get("device-id")),
)
private_config["delete_audio"] = bool(self.config.get("delete_audio", True))
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"{time.time() - begin_time} 秒,获取差异化配置成功: {json.dumps(filter_sensitive_info(private_config), ensure_ascii=False)}"
)
except DeviceNotFoundException as e:
@ -476,7 +477,7 @@ class ConnectionHandler:
private_config = {}
except Exception as e:
self.need_bind = True
self.logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
logger.bind(tag=TAG).error(f"获取差异化配置失败: {e}")
private_config = {}
init_llm, init_tts, init_memory, init_intent = (
@ -551,7 +552,7 @@ class ConnectionHandler:
self.config["mcp_endpoint"] = private_config["mcp_endpoint"]
try:
modules = initialize_modules(
self.logger,
logger,
private_config,
init_vad,
init_asr,
@ -561,7 +562,7 @@ class ConnectionHandler:
init_intent,
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
logger.bind(tag=TAG).error(f"初始化组件失败: {e}")
modules = {}
if modules.get("tts", None) is not None:
self.tts = modules["tts"]
@ -609,14 +610,14 @@ class ConnectionHandler:
memory_llm = llm_utils.create_instance(
memory_llm_type, memory_llm_config
)
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"为记忆总结创建了专用LLM: {memory_llm_name}, 类型: {memory_llm_type}"
)
self.memory.set_llm(memory_llm)
else:
# 否则使用主LLM
self.memory.set_llm(self.llm)
self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
def _initialize_intent(self):
if self.intent is None:
@ -651,14 +652,14 @@ class ConnectionHandler:
intent_llm = llm_utils.create_instance(
intent_llm_type, intent_llm_config
)
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"为意图识别创建了专用LLM: {intent_llm_name}, 类型: {intent_llm_type}"
)
self.intent.set_llm(intent_llm)
else:
# 否则使用主LLM
self.intent.set_llm(self.llm)
self.logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
logger.bind(tag=TAG).info("使用主LLM作为意图识别模型")
"""加载统一工具处理器"""
self.func_handler = UnifiedToolHandler(self)
@ -673,7 +674,7 @@ class ConnectionHandler:
self.dialogue.update_system_message(self.prompt)
def chat(self, query, depth=0):
self.logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
logger.bind(tag=TAG).info(f"大模型收到用户消息: {query}")
self.llm_finish_task = False
# 为最顶层时新建会话ID和发送FIRST请求
@ -720,7 +721,7 @@ class ConnectionHandler:
),
)
except Exception as e:
self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}")
return None
# 处理流式响应
@ -796,7 +797,7 @@ class ConnectionHandler:
bHasError = True
response_message.append(content_arguments)
if bHasError:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"function call error: {content_arguments}"
)
if not bHasError:
@ -806,7 +807,7 @@ class ConnectionHandler:
self.tts_MessageText = text_buff
self.dialogue.put(Message(role="assistant", content=text_buff))
response_message.clear()
self.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}"
)
function_call_data = {
@ -839,7 +840,7 @@ class ConnectionHandler:
)
self.llm_finish_task = True
# 使用lambda延迟计算,只有在DEBUG级别时才执行get_llm_dialogue()
self.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
lambda: json.dumps(
self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False
)
@ -907,13 +908,13 @@ class ConnectionHandler:
# 提交任务到线程池
self.executor.submit(self._process_report, *item)
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
logger.bind(tag=TAG).error(f"聊天记录上报线程异常: {e}")
except queue.Empty:
continue
except Exception as e:
self.logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
logger.bind(tag=TAG).error(f"聊天记录上报工作线程异常: {e}")
self.logger.bind(tag=TAG).info("聊天记录上报线程已退出")
logger.bind(tag=TAG).info("聊天记录上报线程已退出")
def _process_report(self, type, text, audio_data, report_time):
"""处理上报任务"""
@ -921,14 +922,14 @@ class ConnectionHandler:
# 执行上报(传入二进制数据)
report(self, type, text, audio_data, report_time)
except Exception as e:
self.logger.bind(tag=TAG).error(f"上报处理异常: {e}")
logger.bind(tag=TAG).error(f"上报处理异常: {e}")
finally:
# 标记任务完成
self.report_queue.task_done()
def clearSpeakStatus(self):
self.client_is_speaking = False
self.logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
logger.bind(tag=TAG).debug(f"清除服务端讲话状态")
async def close(self, ws=None):
"""资源清理方法"""
@ -947,7 +948,7 @@ class ConnectionHandler:
try:
await self.func_handler.cleanup()
except Exception as cleanup_error:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"清理工具处理器时出错: {cleanup_error}"
)
@ -992,7 +993,7 @@ class ConnectionHandler:
# 如果关闭失败,忽略错误
pass
except Exception as ws_error:
self.logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}")
logger.bind(tag=TAG).error(f"关闭WebSocket连接时出错: {ws_error}")
if self.tts:
await self.tts.close()
@ -1002,14 +1003,14 @@ class ConnectionHandler:
try:
self.executor.shutdown(wait=False)
except Exception as executor_error:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"关闭线程池时出错: {executor_error}"
)
self.executor = None
self.logger.bind(tag=TAG).info("连接资源已释放")
logger.bind(tag=TAG).info("连接资源已释放")
except Exception as e:
self.logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
logger.bind(tag=TAG).error(f"关闭连接时出错: {e}")
finally:
# 确保停止事件被设置
if self.stop_event:
@ -1018,7 +1019,7 @@ class ConnectionHandler:
def clear_queues(self):
"""清空所有任务队列"""
if self.tts:
self.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"开始清理: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
)
@ -1036,7 +1037,7 @@ class ConnectionHandler:
except queue.Empty:
break
self.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"清理结束: TTS队列大小={self.tts.tts_text_queue.qsize()}, 音频队列大小={self.tts.tts_audio_queue.qsize()}"
)
@ -1044,7 +1045,7 @@ class ConnectionHandler:
self.client_audio_buffer = bytearray()
self.client_have_voice = False
self.client_voice_stop = False
self.logger.bind(tag=TAG).debug("VAD states reset.")
logger.bind(tag=TAG).debug("VAD states reset.")
def chat_and_close(self, text):
"""Chat with the user and then close the connection"""
@ -1055,7 +1056,7 @@ class ConnectionHandler:
# After chat is complete, close the connection
self.close_after_chat = True
except Exception as e:
self.logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
logger.bind(tag=TAG).error(f"Chat and close error: {str(e)}")
async def _check_timeout(self):
"""检查连接超时"""
@ -1069,20 +1070,20 @@ class ConnectionHandler:
> self.timeout_seconds * 1000
):
if not self.stop_event.is_set():
self.logger.bind(tag=TAG).info("连接超时,准备关闭")
logger.bind(tag=TAG).info("连接超时,准备关闭")
# 设置停止事件,防止重复处理
self.stop_event.set()
# 使用 try-except 包装关闭操作,确保不会因为异常而阻塞
try:
await self.close(self.websocket)
except Exception as close_error:
self.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"超时关闭连接时出错: {close_error}"
)
break
# 每10秒检查一次,避免过于频繁
await asyncio.sleep(10)
except Exception as e:
self.logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
logger.bind(tag=TAG).error(f"超时检查任务出错: {e}")
finally:
self.logger.bind(tag=TAG).info("超时检查任务已退出")
logger.bind(tag=TAG).info("超时检查任务已退出")

View file

@ -1,10 +1,13 @@
import json
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
async def handleAbortMessage(conn):
conn.logger.bind(tag=TAG).info("Abort message received")
logger.bind(tag=TAG).info("Abort message received")
# 设置成打断状态,会自动打断llm、tts任务
conn.client_abort = True
conn.clear_queues()
@ -13,4 +16,4 @@ async def handleAbortMessage(conn):
json.dumps({"type": "tts", "state": "stop", "session_id": conn.session_id})
)
conn.clearSpeakStatus()
conn.logger.bind(tag=TAG).info("Abort message received-end")
logger.bind(tag=TAG).info("Abort message received-end")

View file

@ -3,6 +3,7 @@ import json
import random
import asyncio
from config.logger import setup_logging
from config.system_config import SystemConfig
from core.session.session_context import SessionContext
from core.utils.dialogue import Message
@ -32,6 +33,7 @@ _wakeup_response_lock = asyncio.Lock()
config = SystemConfig()
logger = setup_logging()
async def handleHelloMessage(conn, msg_json, session_context: SessionContext):
"""处理hello消息"""
@ -42,15 +44,15 @@ async def handleHelloMessage(conn, msg_json, session_context: SessionContext):
session_context.audio_format = audio_params
if audio_params:
format = audio_params.get("format")
conn.logger.bind(tag=TAG).info(f"客户端音频格式: {format}")
logger.bind(tag=TAG).info(f"客户端音频格式: {format}")
welcome_msg["audio_params"] = audio_params
features = msg_json.get("features")
if features:
conn.logger.bind(tag=TAG).info(f"客户端特性: {features}")
logger.bind(tag=TAG).info(f"客户端特性: {features}")
conn.features = features
session_context.features = features
if features.get("mcp"):
conn.logger.bind(tag=TAG).info("客户端支持MCP")
logger.bind(tag=TAG).info("客户端支持MCP")
conn.mcp_client = MCPClient()
session_context.mcp_client = conn.mcp_client
# 发送初始化
@ -105,7 +107,7 @@ async def checkWakeupWords(conn, text):
# 播放唤醒词回复
conn.client_abort = False
conn.logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
logger.bind(tag=TAG).info(f"播放唤醒词回复: {response.get('text')}")
await sendAudioMessage(conn, SentenceType.FIRST, opus_packets, response.get("text"))
await sendAudioMessage(conn, SentenceType.LAST, [], None)

View file

@ -1,6 +1,8 @@
import json
import uuid
import asyncio
from config.logger import setup_logging
from core.utils.dialogue import Message
from core.providers.tts.dto.dto import ContentType
from core.handle.helloHandle import checkWakeupWords
@ -11,6 +13,7 @@ from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
TAG = __name__
logger = setup_logging()
async def handle_user_intent(conn, text):
# 预处理输入文本,处理可能的JSON格式
@ -51,7 +54,7 @@ async def check_direct_exit(conn, text):
cmd_exit = conn.cmd_exit
for cmd in cmd_exit:
if text == cmd:
conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
await send_stt_message(conn, text)
await conn.close()
return True
@ -61,7 +64,7 @@ async def check_direct_exit(conn, text):
async def analyze_intent_with_llm(conn, text):
"""使用LLM分析用户意图"""
if not hasattr(conn, "intent") or not conn.intent:
conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
logger.bind(tag=TAG).warning("意图识别服务未初始化")
return None
# 对话历史记录
@ -70,7 +73,7 @@ async def analyze_intent_with_llm(conn, text):
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
return intent_result
except Exception as e:
conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
return None
@ -84,7 +87,7 @@ async def process_intent_result(conn, intent_result, original_text):
# 检查是否有function_call
if "function_call" in intent_data:
# 直接从意图识别获取了function_call
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
)
function_name = intent_data["function_call"]["name"]
@ -122,7 +125,7 @@ async def process_intent_result(conn, intent_result, original_text):
conn.loop,
).result()
except Exception as e:
conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}")
logger.bind(tag=TAG).error(f"工具调用失败: {e}")
result = ActionResponse(
action=Action.ERROR, result=str(e), response=str(e)
)
@ -160,7 +163,7 @@ async def process_intent_result(conn, intent_result, original_text):
return True
return False
except json.JSONDecodeError as e:
conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
return False

View file

@ -1,6 +1,8 @@
import time
import json
import asyncio
from config.logger import setup_logging
from core.utils.util import audio_to_data
from core.handle.abortHandle import handleAbortMessage
from core.handle.intentHandler import handle_user_intent
@ -9,6 +11,7 @@ from core.handle.sendAudioHandle import send_stt_message, SentenceType
TAG = __name__
logger = setup_logging()
async def handleAudioMessage(conn, audio):
# 当前片段是否有人说话
@ -46,7 +49,7 @@ async def startToChat(conn, text):
if 'speaker' in data and 'content' in data:
speaker_name = data['speaker']
actual_text = data['content']
conn.logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
logger.bind(tag=TAG).info(f"解析到说话人信息: {speaker_name}")
# 直接使用JSON格式的文本,不解析
actual_text = text
@ -104,7 +107,7 @@ async def no_voice_close_connect(conn, have_voice):
conn.client_abort = False
end_prompt = conn.config.get("end_prompt", {})
if end_prompt and end_prompt.get("enable", True) is False:
conn.logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
logger.bind(tag=TAG).info("结束对话,无需发送结束提示语")
await conn.close()
return
prompt = end_prompt.get("prompt")
@ -128,7 +131,7 @@ async def check_bind_device(conn):
if conn.bind_code:
# 确保bind_code是6位数字
if len(conn.bind_code) != 6:
conn.logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
logger.bind(tag=TAG).error(f"无效的绑定码格式: {conn.bind_code}")
text = "绑定码格式错误,请检查配置。"
await send_stt_message(conn, text)
return
@ -149,7 +152,7 @@ async def check_bind_device(conn):
num_packets = audio_to_data(num_path)
conn.tts.tts_audio_queue.put((SentenceType.MIDDLE, num_packets, None))
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
logger.bind(tag=TAG).error(f"播放数字音频失败: {e}")
continue
conn.tts.tts_audio_queue.put((SentenceType.LAST, [], None))
else:

View file

@ -13,10 +13,13 @@ import time
import opuslib_next
from config.logger import setup_logging
from config.manage_api_client import report as manage_report
TAG = __name__
logger = setup_logging()
def report(conn, type, text, opus_data, report_time):
"""执行聊天记录上报操作
@ -43,7 +46,7 @@ def report(conn, type, text, opus_data, report_time):
report_time=report_time,
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
logger.bind(tag=TAG).error(f"聊天记录上报失败: {e}")
def opus_to_wav(conn, opus_data):
@ -64,7 +67,7 @@ def opus_to_wav(conn, opus_data):
pcm_frame = decoder.decode(opus_packet, 960) # 960 samples = 60ms
pcm_data.append(pcm_frame)
except opuslib_next.OpusError as e:
conn.logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
logger.bind(tag=TAG).error(f"Opus解码错误: {e}", exc_info=True)
if not pcm_data:
raise ValueError("没有有效的PCM数据")
@ -109,16 +112,16 @@ def enqueue_tts_report(conn, text, opus_data):
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
if conn.chat_history_conf == 2:
conn.report_queue.put((2, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
)
else:
conn.report_queue.put((2, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"TTS数据已加入上报队列: {conn.device_id}, 不上报音频"
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}")
logger.bind(tag=TAG).error(f"加入TTS上报队列失败: {text}, {e}")
def enqueue_asr_report(conn, text, opus_data):
@ -137,13 +140,13 @@ def enqueue_asr_report(conn, text, opus_data):
# 使用连接对象的队列,传入文本和二进制数据而非文件路径
if conn.chat_history_conf == 2:
conn.report_queue.put((1, text, opus_data, int(time.time())))
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 音频大小: {len(opus_data)} "
)
else:
conn.report_queue.put((1, text, None, int(time.time())))
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"ASR数据已加入上报队列: {conn.device_id}, 不上报音频"
)
except Exception as e:
conn.logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}")
logger.bind(tag=TAG).debug(f"加入ASR上报队列失败: {text}, {e}")

View file

@ -1,16 +1,19 @@
import json
import time
import asyncio
from config.logger import setup_logging
from core.utils import textUtils
from core.utils.util import audio_to_data
from core.providers.tts.dto.dto import SentenceType
TAG = __name__
logger = setup_logging()
async def sendAudioMessage(conn, sentenceType, audios, text):
if conn.tts.tts_audio_first_sentence:
conn.logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
logger.bind(tag=TAG).info(f"发送第一段语音: {text}")
conn.tts.tts_audio_first_sentence = False
await send_tts_message(conn, "start", None)
@ -20,7 +23,7 @@ async def sendAudioMessage(conn, sentenceType, audios, text):
await sendAudio(conn, audios)
# 发送句子开始消息
if sentenceType is not SentenceType.MIDDLE:
conn.logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
logger.bind(tag=TAG).info(f"发送音频消息: {sentenceType}, {text}")
# 发送结束消息(如果是最后一个文本)
if conn.llm_finish_task and sentenceType == SentenceType.LAST:

View file

@ -1,6 +1,7 @@
import time
from typing import Dict, Any
from config.logger import setup_logging
from core.handle.receiveAudioHandle import handleAudioMessage, startToChat
from core.handle.reportHandle import enqueue_asr_report
from core.handle.sendAudioHandle import send_stt_message, send_tts_message
@ -11,6 +12,8 @@ from core.utils.util import remove_punctuation_and_length
TAG = __name__
logger = setup_logging()
class ListenTextMessageHandler(TextMessageHandler):
"""Listen消息处理器"""
@ -21,7 +24,7 @@ class ListenTextMessageHandler(TextMessageHandler):
async def handle(self, conn, msg_json: Dict[str, Any], session_context: SessionContext) -> None:
if "mode" in msg_json:
conn.client_listen_mode = msg_json["mode"]
conn.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"客户端拾音模式:{conn.client_listen_mode}"
)
if msg_json["state"] == "start":

View file

@ -2,6 +2,7 @@ import asyncio
import json
from typing import Dict, Any
from config.logger import setup_logging
from core.handle.textMessageHandler import TextMessageHandler
from core.handle.textMessageType import TextMessageType
from core.providers.tools.device_mcp import handle_mcp_message
@ -9,6 +10,8 @@ from core.session.session_context import SessionContext
TAG = __name__
logger = setup_logging()
class ServerTextMessageHandler(TextMessageHandler):
"""MCP消息处理器"""
@ -77,7 +80,7 @@ class ServerTextMessageHandler(TextMessageHandler):
)
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}")
logger.bind(tag=TAG).error(f"更新配置失败: {str(e)}")
await conn.websocket.send(
json.dumps(
{

View file

@ -1,10 +1,12 @@
import json
from config.logger import setup_logging
from core.handle.textMessageHandlerRegistry import TextMessageHandlerRegistry
from core.session.session_context import SessionContext
TAG = __name__
logger = setup_logging()
class TextMessageProcessor:
"""消息处理器主类"""
@ -23,20 +25,20 @@ class TextMessageProcessor:
message_type = msg_json.get("type")
# 记录日志
conn.logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}")
logger.bind(tag=TAG).info(f"收到{message_type}消息:{message}")
# 获取并执行处理器
handler = self.registry.get_handler(message_type)
if handler:
await handler.handle(conn, msg_json, session_context)
else:
conn.logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
logger.bind(tag=TAG).error(f"收到未知类型消息:{message}")
# 处理纯数字消息
elif isinstance(msg_json, int):
conn.logger.bind(tag=TAG).info(f"收到数字消息:{message}")
logger.bind(tag=TAG).info(f"收到数字消息:{message}")
await conn.websocket.send(message)
except json.JSONDecodeError:
# 非JSON消息直接转发
conn.logger.bind(tag=TAG).error(f"解析到错误的消息:{message}")
logger.bind(tag=TAG).error(f"解析到错误的消息:{message}")
await conn.websocket.send(message)

View file

@ -11,6 +11,8 @@ from jinja2 import Template
TAG = __name__
logger = setup_logging()
WEEKDAY_MAP = {
"Monday": "星期一",
"Tuesday": "星期二",
@ -49,9 +51,8 @@ EMOJI_List = [
class PromptManager:
"""系统提示词管理器,负责管理和更新系统提示词"""
def __init__(self, config: Dict[str, Any], logger=None):
def __init__(self, config: Dict[str, Any]):
self.config = config
self.logger = logger or setup_logging()
self.base_prompt_template = None
self.last_update_time = 0
@ -73,7 +74,7 @@ class PromptManager:
cached_template = self.cache_manager.get(self.CacheType.CONFIG, cache_key)
if cached_template is not None:
self.base_prompt_template = cached_template
self.logger.bind(tag=TAG).debug("从缓存加载基础提示词模板")
logger.bind(tag=TAG).debug("从缓存加载基础提示词模板")
return
# 缓存未命中,从文件读取
@ -86,11 +87,11 @@ class PromptManager:
self.CacheType.CONFIG, cache_key, template_content
)
self.base_prompt_template = template_content
self.logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存")
logger.bind(tag=TAG).debug("成功加载基础提示词模板并缓存")
else:
self.logger.bind(tag=TAG).warning("未找到agent-base-prompt.txt文件")
logger.bind(tag=TAG).warning("未找到agent-base-prompt.txt文件")
except Exception as e:
self.logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}")
logger.bind(tag=TAG).error(f"加载提示词模板失败: {e}")
def get_quick_prompt(self, user_prompt: str, device_id: str = None) -> str:
"""快速获取系统提示词(使用用户配置)"""
@ -99,10 +100,10 @@ class PromptManager:
self.CacheType.DEVICE_PROMPT, device_cache_key
)
if cached_device_prompt is not None:
self.logger.bind(tag=TAG).debug(f"使用设备 {device_id} 的缓存提示词")
logger.bind(tag=TAG).debug(f"使用设备 {device_id} 的缓存提示词")
return cached_device_prompt
else:
self.logger.bind(tag=TAG).debug(
logger.bind(tag=TAG).debug(
f"设备 {device_id} 无缓存提示词,使用传入的提示词"
)
@ -110,9 +111,9 @@ class PromptManager:
if device_id:
device_cache_key = f"device_prompt:{device_id}"
self.cache_manager.set(self.CacheType.CONFIG, device_cache_key, user_prompt)
self.logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存")
logger.bind(tag=TAG).debug(f"设备 {device_id} 的提示词已缓存")
self.logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...")
logger.bind(tag=TAG).info(f"使用快速提示词: {user_prompt[:50]}...")
return user_prompt
def _get_current_time_info(self) -> tuple:
@ -142,7 +143,7 @@ class PromptManager:
# 缓存未命中,调用API获取
from core.utils.util import get_ip_info
ip_info = get_ip_info(client_ip, self.logger)
ip_info = get_ip_info(client_ip, logger)
city = ip_info.get("city", "未知位置")
location = f"{city}"
@ -150,7 +151,7 @@ class PromptManager:
self.cache_manager.set(self.CacheType.LOCATION, client_ip, location)
return location
except Exception as e:
self.logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
logger.bind(tag=TAG).error(f"获取位置信息失败: {e}")
return "未知位置"
def _get_weather_info(self, conn, location: str) -> str:
@ -174,7 +175,7 @@ class PromptManager:
return "天气信息获取失败"
except Exception as e:
self.logger.bind(tag=TAG).error(f"获取天气信息失败: {e}")
logger.bind(tag=TAG).error(f"获取天气信息失败: {e}")
return "天气信息获取失败"
def update_context_info(self, conn, client_ip: str):
@ -184,10 +185,10 @@ class PromptManager:
local_address = self._get_location_info(client_ip)
# 获取天气信息(使用全局缓存)
self._get_weather_info(conn, local_address)
self.logger.bind(tag=TAG).info(f"上下文信息更新完成")
logger.bind(tag=TAG).info(f"上下文信息更新完成")
except Exception as e:
self.logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}")
logger.bind(tag=TAG).error(f"更新上下文信息失败: {e}")
def build_enhanced_prompt(
self, user_prompt: str, device_id: str, client_ip: str = None
@ -235,11 +236,11 @@ class PromptManager:
self.cache_manager.set(
self.CacheType.DEVICE_PROMPT, device_cache_key, enhanced_prompt
)
self.logger.bind(tag=TAG).info(
logger.bind(tag=TAG).info(
f"构建增强提示词成功,长度: {len(enhanced_prompt)}"
)
return enhanced_prompt
except Exception as e:
self.logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}")
logger.bind(tag=TAG).error(f"构建增强提示词失败: {e}")
return user_prompt

View file

@ -1,6 +1,11 @@
import json
from config.logger import setup_logging
TAG = __name__
logger = setup_logging()
EMOJI_MAP = {
"😂": "laughing",
"😭": "crying",
@ -98,7 +103,7 @@ async def get_emotion(conn, text):
)
)
except Exception as e:
conn.logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}")
logger.bind(tag=TAG).warning(f"发送情绪表情失败,错误:{e}")
return

View file

@ -5,6 +5,8 @@ import random
import difflib
import traceback
from pathlib import Path
from config.logger import setup_logging
from core.handle.sendAudioHandle import send_stt_message
from plugins_func.register import register_function, ToolType, ActionResponse, Action
from core.utils.dialogue import Message
@ -12,6 +14,8 @@ from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType, ContentType
TAG = __name__
logger = setup_logging()
MUSIC_CACHE = {}
play_music_function_desc = {
@ -42,7 +46,7 @@ def play_music(conn, song_name: str):
# 检查事件循环状态
if not conn.loop.is_running():
conn.logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
return ActionResponse(
action=Action.RESPONSE, result="系统繁忙", response="请稍后再试"
)
@ -56,9 +60,9 @@ def play_music(conn, song_name: str):
def handle_done(f):
try:
f.result() # 可在此处理成功逻辑
conn.logger.bind(tag=TAG).info("播放完成")
logger.bind(tag=TAG).info("播放完成")
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放失败: {e}")
logger.bind(tag=TAG).error(f"播放失败: {e}")
task.add_done_callback(handle_done)
@ -66,7 +70,7 @@ def play_music(conn, song_name: str):
action=Action.NONE, result="指令已接收", response="正在为您播放音乐"
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
return ActionResponse(
action=Action.RESPONSE, result=str(e), response="播放音乐时出错了"
)
@ -147,7 +151,7 @@ async def handle_music_command(conn, text):
"""处理音乐播放指令"""
clean_text = re.sub(r"[^\w\s]", "", text).strip()
conn.logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
logger.bind(tag=TAG).debug(f"检查是否是音乐命令: {clean_text}")
# 尝试匹配具体歌名
if os.path.exists(MUSIC_CACHE["music_dir"]):
@ -162,7 +166,7 @@ async def handle_music_command(conn, text):
if potential_song:
best_match = _find_best_match(potential_song, MUSIC_CACHE["music_files"])
if best_match:
conn.logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
await play_local_music(conn, specific_file=best_match)
return True
# 检查是否是通用播放音乐命令
@ -192,7 +196,7 @@ async def play_local_music(conn, specific_file=None):
"""播放本地音乐文件"""
try:
if not os.path.exists(MUSIC_CACHE["music_dir"]):
conn.logger.bind(tag=TAG).error(
logger.bind(tag=TAG).error(
f"音乐目录不存在: " + MUSIC_CACHE["music_dir"]
)
return
@ -203,13 +207,13 @@ async def play_local_music(conn, specific_file=None):
music_path = os.path.join(MUSIC_CACHE["music_dir"], specific_file)
else:
if not MUSIC_CACHE["music_files"]:
conn.logger.bind(tag=TAG).error("未找到MP3音乐文件")
logger.bind(tag=TAG).error("未找到MP3音乐文件")
return
selected_music = random.choice(MUSIC_CACHE["music_files"])
music_path = os.path.join(MUSIC_CACHE["music_dir"], selected_music)
if not os.path.exists(music_path):
conn.logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
return
text = _get_random_play_prompt(selected_music)
await send_stt_message(conn, text)
@ -249,5 +253,5 @@ async def play_local_music(conn, specific_file=None):
)
except Exception as e:
conn.logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
conn.logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")
logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}")
logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}")