From f3e7fa8a029c2d2ddcf89487af896d692a945028 Mon Sep 17 00:00:00 2001 From: hrz <1710360675@qq.com> Date: Mon, 17 Mar 2025 00:38:33 +0800 Subject: [PATCH] =?UTF-8?q?update:intent=5Fllm=E9=9F=B3=E4=B9=90=E6=8F=92?= =?UTF-8?q?=E4=BB=B6=E5=8C=96=E8=B0=83=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/core/connection.py | 2 +- .../core/handle/intentHandler.py | 48 +++++++++++-------- .../core/handle/musicHandler.py | 10 ++-- .../providers/intent/intent_llm/intent_llm.py | 5 +- .../plugins_func/functions/play_music.py | 24 ++++++++-- 5 files changed, 58 insertions(+), 31 deletions(-) diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 52596ba65..65af1ee0b 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -20,7 +20,7 @@ from plugins_func.register import Action from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError from core.utils.auth_code_gen import AuthCodeGenerator -import plugins_func.loadplugins +import plugins_func.loadplugins TAG = __name__ diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 320c47934..1799516ce 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -1,5 +1,6 @@ from config.logger import setup_logging import json +import uuid from core.handle.sendAudioHandle import send_stt_message from core.utils.util import remove_punctuation_and_length @@ -8,30 +9,16 @@ logger = setup_logging() async def handle_user_intent(conn, text): - """ - Handle user intent before starting chat - - Args: - conn: Connection object - text: User's text input - - Returns: - bool: True if intent was handled, False if should proceed to chat - """ # 检查是否有明确的退出命令 if await check_direct_exit(conn, text): return True - if conn.use_function_call_mode: # 使用支持function calling的聊天方法,不再进行意图分析 return False - # 使用LLM进行意图分析 intent = await analyze_intent_with_llm(conn, text) - if not intent: return False - # 处理各种意图 return await process_intent_result(conn, intent, text) @@ -58,7 +45,6 @@ async def analyze_intent_with_llm(conn, text): dialogue = conn.dialogue try: intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) - # 尝试解析JSON结果 try: intent_data = json.loads(intent_result) @@ -79,9 +65,6 @@ async def process_intent_result(conn, intent, original_text): # 处理退出意图 if "结束聊天" in intent: logger.bind(tag=TAG).info(f"识别到退出意图: {intent}") - - # 如果正在播放音乐,可以关了 TODO - # 如果是明确的离别意图,发送告别语并关闭连接 await send_stt_message(conn, original_text) conn.executor.submit(conn.chat_and_close, original_text) @@ -90,10 +73,37 @@ async def process_intent_result(conn, intent, original_text): # 处理播放音乐意图 if "播放音乐" in intent: logger.bind(tag=TAG).info(f"识别到音乐播放意图: {intent}") - await conn.music_handler.handle_music_command(conn, intent) + # 调用play_music函数来播放音乐 + song_name = extract_text_in_brackets(intent) + function_id = str(uuid.uuid4().hex) + function_name = "play_music" + function_arguments = '{ "song_name": "' + song_name + '" }' + + function_call_data = { + "name": function_name, + "id": function_id, + "arguments": function_arguments + } + conn.func_handler.handle_llm_function_call(conn, function_call_data) return True # 其他意图处理可以在这里扩展 # 默认返回False,表示继续常规聊天流程 return False + + +def extract_text_in_brackets(s): + """ + 从字符串中提取中括号内的文字 + + :param s: 输入字符串 + :return: 中括号内的文字,如果不存在则返回空字符串 + """ + left_bracket_index = s.find('[') + right_bracket_index = s.find(']') + + if left_bracket_index != -1 and right_bracket_index != -1 and left_bracket_index < right_bracket_index: + return s[left_bracket_index + 1:right_bracket_index] + else: + return "" \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py index b650b847a..1317b29b5 100644 --- a/main/xiaozhi-server/core/handle/musicHandler.py +++ b/main/xiaozhi-server/core/handle/musicHandler.py @@ -44,6 +44,7 @@ class MusicManager: def get_music_files(self): music_files = [] + music_file_names = [] for file in self.music_dir.rglob("*"): # 判断是否是文件 if file.is_file(): @@ -54,7 +55,8 @@ class MusicManager: # music_files.append(str(file.resolve())) # 添加绝对路径 # 添加相对路径 music_files.append(str(file.relative_to(self.music_dir))) - return music_files + music_file_names.append(os.path.splitext(str(file.relative_to(self.music_dir)))[0]) + return music_files, music_file_names class MusicHandler: @@ -74,7 +76,7 @@ class MusicHandler: self.refresh_time = 60 # 获取音乐文件列表 - self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files() + self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files() self.scan_time = time.time() logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}") @@ -87,7 +89,7 @@ class MusicHandler: if os.path.exists(self.music_dir): if time.time() - self.scan_time > self.refresh_time: # 刷新音乐文件列表 - self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files() + self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files() self.scan_time = time.time() logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}") @@ -136,4 +138,4 @@ class MusicHandler: except Exception as e: logger.bind(tag=TAG).error(f"播放音乐失败: {str(e)}") - logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") \ No newline at end of file + logger.bind(tag=TAG).error(f"详细错误: {traceback.format_exc()}") 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 04319438c..754d410a4 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 @@ -89,7 +89,7 @@ class IntentProvider(IntentProviderBase): msgStr += f"User: {text}\n" user_prompt = f"当前的对话如下:\n{msgStr}" - prompt_music = f"{self.promot}\n{conn.music_handler.music_files}\n" + prompt_music = f"{self.promot}\n{conn.music_handler.music_file_names}\n" logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") # 使用LLM进行意图识别 intent = self.llm.response_no_stream( @@ -100,8 +100,7 @@ class IntentProvider(IntentProviderBase): # 使用正则表达式提取 {} 中的内容 match = re.search(r'\{.*?\}', intent) if match: - result = match.group(0) # 获取匹配到的内容(包含 {}) - print(result) # 输出:{intent: '播放音乐 [中秋月]'} + result = match.group(0) intent = result else: intent = "{intent: '继续聊天'}" diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py index 9e3372a3b..c07697a0a 100644 --- a/main/xiaozhi-server/plugins_func/functions/play_music.py +++ b/main/xiaozhi-server/plugins_func/functions/play_music.py @@ -29,12 +29,28 @@ def play_music(conn, song_name: str): try: music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐" - # 执行音乐播放命令 + # 检查事件循环状态 + if not conn.loop.is_running(): + logger.bind(tag=TAG).error("事件循环未运行,无法提交任务") + return ActionResponse(action=Action.RESPONSE, result="系统繁忙", response="请稍后再试") + + # 提交异步任务 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="还想听什么歌?") + + # 非阻塞回调处理 + def handle_done(f): + try: + f.result() # 可在此处理成功逻辑 + logger.bind(tag=TAG).info("播放完成") + except Exception as e: + logger.bind(tag=TAG).error(f"播放失败: {e}") + + future.add_done_callback(handle_done) + + return ActionResponse(action=Action.RESPONSE, result="指令已接收", response="正在为您播放音乐") except Exception as e: - logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") \ No newline at end of file + logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}") + return ActionResponse(action=Action.RESPONSE, result=str(e), response="播放音乐时出错了") \ No newline at end of file