From 63b326b01cc9140982d8bf1cd6240309c700d5c2 Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Sun, 9 Mar 2025 16:34:36 +0800 Subject: [PATCH] =?UTF-8?q?update:=E4=BC=98=E5=8C=96=E6=84=8F=E5=9B=BE?= =?UTF-8?q?=E8=AF=86=E5=88=AB=E7=9A=84=E9=85=8D=E7=BD=AE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/config.yaml | 30 ++++----- .../handle => config}/functionCallConfig.py | 4 +- main/xiaozhi-server/core/connection.py | 9 ++- .../core/handle/intentHandler.py | 66 +++++++++++-------- .../core/handle/musicHandler.py | 34 +++------- .../providers/intent/intent_llm/intent_llm.py | 2 +- main/xiaozhi-server/core/websocket_server.py | 12 ++-- 7 files changed, 77 insertions(+), 80 deletions(-) rename main/xiaozhi-server/{core/handle => config}/functionCallConfig.py (80%) diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 6476476ae..e1e6cd8de 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -58,29 +58,37 @@ delete_audio: true # 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 close_connection_no_voice_time: 120 -# 是否使用函数调用模式, 默认为false,需要大模型支持tools调用 -use_function_call_mode: false - CMD_exit: - "退出" - "关闭" # 具体处理时选择的模块(The module selected for specific processing) selected_module: - ASR: FunASR + # 语音活动检测模块,默认使用SileroVAD模型 VAD: SileroVAD + # 语音识别模块,默认使用FunASR本地模型 + ASR: FunASR # 将根据配置名称对应的type调用实际的LLM适配器 LLM: ChatGLMLLM # TTS将根据配置名称对应的type调用实际的TTS适配器 TTS: EdgeTTS - Memory: nomem + # 记忆模块,默认使用本地压缩记忆,如果想使用超长记忆,推荐使用mem0ai + Memory: mem_local_short + # 意图识别模块,默认不开启。开启后,可以播放音乐、控制音量、识别退出指令 Intent: nointent +# 意图识别,是用于理解用户意图的模块,例如:播放音乐 Intent: + # 不使用意图识别 nointent: type: nointent + # 意图识别使用大模型,优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间 intent_llm: type: intent_llm + # 意图识别使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快 + # 新手使用function_call,建议使用:AliLLM,并把的model_name设置为:qwen-max + function_call: + type: function_call Memory: mem0ai: @@ -341,18 +349,6 @@ module_test: # 本地音乐播放配置 music: - music_commands: - - "来一首歌" - - "唱一首歌" - - "播放音乐" - - "来点音乐" - - "背景音乐" - - "放首歌" - - "播放歌曲" - - "来点背景音乐" - - "我想听歌" - - "我要听歌" - - "放点音乐" music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件 music_ext: # 音乐文件类型,p3格式效率最高 - ".mp3" diff --git a/main/xiaozhi-server/core/handle/functionCallConfig.py b/main/xiaozhi-server/config/functionCallConfig.py similarity index 80% rename from main/xiaozhi-server/core/handle/functionCallConfig.py rename to main/xiaozhi-server/config/functionCallConfig.py index 508cb8926..dd9b55fc4 100644 --- a/main/xiaozhi-server/core/handle/functionCallConfig.py +++ b/main/xiaozhi-server/config/functionCallConfig.py @@ -20,13 +20,13 @@ FunctionCallConfig = [ "type": "function", "function": { "name": "play_music", - "description": "当用户想播放音乐时调用", + "description": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎", "parameters": { "type": "object", "properties": { "song_name": { "type": "string", - "description": "要播放的歌曲名称,如果没有指定具体歌名则为'random'" + "description": "歌曲名称,如果没有指定具体歌名则为'random'" } }, "required": ["song_name"] diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 1dc85d9c7..114c553bb 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -91,7 +91,12 @@ class ConnectionHandler: self.is_device_verified = False # 添加设备验证状态标志 self.music_handler = _music self.close_after_chat = False # 是否在聊天结束后关闭连接 - self.use_function_call_mode = self.config.get("use_function_call_mode", False) # 是否使用function calling模式,开启后可以通过函数调用处理意图 + self.use_function_call_mode = False + if self.config["selected_module"]["Intent"] == 'function_call': + self.use_function_call_mode = True + + self.logger.bind(tag=TAG).info(f"use_function_call_mode:{self.use_function_call_mode}") + async def handle_connection(self, ws): try: @@ -227,7 +232,7 @@ class ConnectionHandler: future = asyncio.run_coroutine_threadsafe(self.memory.query_memory(query), self.loop) memory_str = future.result() - self.logger.bind(tag=TAG).info(f"记忆内容: {memory_str}") + self.logger.bind(tag=TAG).debug(f"记忆内容: {memory_str}") llm_responses = self.llm.response( self.session_id, self.dialogue.get_llm_dialogue_with_memory(memory_str) diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 653deaa19..cae22b2ce 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -2,16 +2,17 @@ from config.logger import setup_logging import json from core.handle.sendAudioHandle import send_stt_message from core.utils.dialogue import Message -from core.handle.functionCallConfig import FunctionCallConfig +from config.functionCallConfig import FunctionCallConfig import asyncio from enum import Enum TAG = __name__ logger = setup_logging() + class Action(Enum): NOTFOUND = (0, "没有找到函数") - NONE = (1, "啥也不干") + NONE = (1, "啥也不干") RESPONSE = (2, "直接回复") REQLLM = (3, "调用函数后再请求llm生成回复") @@ -19,20 +20,23 @@ class Action(Enum): self.code = code self.message = message + class ActionResponse: - def __init__(self, action : Action, result, response): - self.action = action # 动作类型 - self.result = result # 动作产生的结果 - self.response = response # 直接回复的内容 + def __init__(self, action: Action, result, response): + self.action = action # 动作类型 + self.result = result # 动作产生的结果 + self.response = response # 直接回复的内容 + def get_functions(): """获取功能调用配置""" return FunctionCallConfig + def handle_llm_function_call(conn, function_call_data): try: function_name = function_call_data["name"] - + if function_name == "handle_exit_intent": # 处理退出意图 try: @@ -42,30 +46,34 @@ def handle_llm_function_call(conn, function_call_data): return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye) except Exception as e: logger.bind(tag=TAG).error(f"处理退出意图错误: {e}") - + elif function_name == "play_music": # 处理音乐播放意图 try: - args = json.loads(function_call_data["arguments"]) - song_name = args.get("song_name", "random") + song_name = "random" + arguments = function_call_data["arguments"] + if arguments is not None and len(arguments) > 0: + args = json.loads(arguments) + song_name = args.get("song_name", "random") music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐" - + # 执行音乐播放命令 future = asyncio.run_coroutine_threadsafe( conn.music_handler.handle_music_command(conn, music_intent), conn.loop ) future.result() - return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?") + return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?") except Exception as e: logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") else: return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="") except Exception as e: logger.bind(tag=TAG).error(f"处理function call错误: {e}") - + return None + async def handle_user_intent(conn, text): """ Handle user intent before starting chat @@ -80,19 +88,19 @@ async def handle_user_intent(conn, text): # 检查是否有明确的退出命令 if await check_direct_exit(conn, text): return True - + if conn.use_function_call_mode: # 使用支持function calling的聊天方法,不再进行意图分析 return False - + logger.bind(tag=TAG).info(f"分析用户意图: {text}") # 使用LLM进行意图分析 intent = await analyze_intent_with_llm(conn, text) - + if not intent: return False - + # 处理各种意图 return await process_intent_result(conn, intent, text) @@ -113,15 +121,15 @@ async def analyze_intent_with_llm(conn, text): if not hasattr(conn, 'intent') or not conn.intent: logger.bind(tag=TAG).warning("意图识别服务未初始化") return None - + # 创建对话历史记录 dialogue = conn.dialogue dialogue.put(Message(role="user", content=text)) - + try: - intent_result = await conn.intent.detect_intent(dialogue.dialogue) + intent_result = await conn.intent.detect_intent(dialogue.dialogue) logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}") - + # 尝试解析JSON结果 try: intent_data = json.loads(intent_result) @@ -130,10 +138,10 @@ async def analyze_intent_with_llm(conn, text): except json.JSONDecodeError: # 如果不是JSON格式,尝试直接获取意图文本 return intent_result.strip() - + except Exception as e: logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") - + return None @@ -142,21 +150,21 @@ async def process_intent_result(conn, intent, original_text): # 处理退出意图 if "结束聊天" in intent: logger.bind(tag=TAG).info(f"识别到退出意图: {intent}") - - #如果正在播放音乐,可以关了 TODO + + # 如果正在播放音乐,可以关了 TODO # 如果是明确的离别意图,发送告别语并关闭连接 - await send_stt_message(conn, original_text) + await send_stt_message(conn, original_text) conn.executor.submit(conn.chat_and_close, original_text) return True - + # 处理播放音乐意图 if "播放音乐" in intent: logger.bind(tag=TAG).info(f"识别到音乐播放意图: {intent}") await conn.music_handler.handle_music_command(conn, intent) return True - + # 其他意图处理可以在这里扩展 - + # 默认返回False,表示继续常规聊天流程 return False diff --git a/main/xiaozhi-server/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py index a7510120c..022d6dc46 100644 --- a/main/xiaozhi-server/core/handle/musicHandler.py +++ b/main/xiaozhi-server/core/handle/musicHandler.py @@ -15,7 +15,7 @@ logger = setup_logging() def _extract_song_name(text): """从用户输入中提取歌名""" - for keyword in ["听", "播放", "放", "唱"]: + for keyword in ["播放音乐"]: if keyword in text: parts = text.split(keyword) if len(parts) > 1: @@ -36,6 +36,7 @@ def _find_best_match(potential_song, music_files): best_match = music_file return best_match + class MusicManager: def __init__(self, music_dir, music_ext): self.music_dir = Path(music_dir) @@ -55,23 +56,20 @@ class MusicManager: music_files.append(str(file.relative_to(self.music_dir))) return music_files + class MusicHandler: def __init__(self, config): self.config = config - self.music_related_keywords = [] if "music" in self.config: self.music_config = self.config["music"] self.music_dir = os.path.abspath( self.music_config.get("music_dir", "./music") # 默认路径修改 ) - self.music_related_keywords = self.music_config.get("music_commands", []) self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3")) self.refresh_time = self.music_config.get("refresh_time", 60) else: self.music_dir = os.path.abspath("./music") - self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌", - "播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"] self.music_ext = (".mp3", ".wav", ".p3") self.refresh_time = 60 @@ -100,13 +98,9 @@ class MusicHandler: logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") await self.play_local_music(conn, specific_file=best_match) return True - # 检查是否是通用播放音乐命令 - if any(cmd in clean_text for cmd in self.music_related_keywords): - await self.play_local_music(conn) - return True - - return False + await self.play_local_music(conn) + return True async def play_local_music(self, conn, specific_file=None): """播放本地音乐文件""" @@ -117,26 +111,18 @@ class MusicHandler: # 确保路径正确性 if specific_file: - music_path = os.path.join(self.music_dir, specific_file) - if not os.path.exists(music_path): - logger.bind(tag=TAG).error(f"指定的音乐文件不存在: {music_path}") - return selected_music = specific_file + music_path = os.path.join(self.music_dir, specific_file) else: - if time.time() - self.scan_time > self.refresh_time: - # 刷新音乐文件列表 - self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files() - self.scan_time = time.time() - logger.bind(tag=TAG).debug(f"刷新的音乐文件列表: {self.music_files}") - if not self.music_files: logger.bind(tag=TAG).error("未找到MP3音乐文件") return selected_music = random.choice(self.music_files) music_path = os.path.join(self.music_dir, selected_music) - if not os.path.exists(music_path): - logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") - return + + if not os.path.exists(music_path): + logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") + return text = f"正在播放{selected_music}" await send_stt_message(conn, text) conn.tts_first_text_index = 0 diff --git a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py index 382101577..c3930296a 100644 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ b/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py @@ -29,7 +29,7 @@ class IntentProvider(IntentProviderBase): prompt = ( "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n" f"{', '.join(intent_list)}\n" - "如果是播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n" + "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n" "如果听不出具体歌名,可以返回'随机播放音乐'。\n" "只需要返回意图结果的json,不要解释。" "返回格式如下:\n" diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index 7983cdbee..14d16497d 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -21,10 +21,6 @@ class WebSocketServer: has_memory_cfg = self.config.get("Memory") and memory_cls_name in self.config["Memory"] memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {} - intent_cls_name = self.config["selected_module"].get("Intent", "nointent") # 默认使用nointent - has_intent_cfg = self.config.get("Intent") and intent_cls_name in self.config["Intent"] - intent_cfg = self.config["Intent"][intent_cls_name] if has_intent_cfg else {} - """创建处理模块实例""" return ( vad.create_instance( @@ -56,7 +52,13 @@ class WebSocketServer: ), MusicHandler(self.config), memory.create_instance(memory_cls_name, memory_cfg), - intent.create_instance(intent_cls_name, intent_cfg), + intent.create_instance( + self.config["selected_module"]["Intent"] + if not 'type' in self.config["Intent"][self.config["selected_module"]["Intent"]] + else + self.config["Intent"][self.config["selected_module"]["Intent"]]["type"], + self.config["Intent"][self.config["selected_module"]["Intent"]] + ), ) async def start(self):