From 52e54daa2b73eb69e9a95a27bf61e924bdd39f0c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=84=E5=87=A4=E7=A7=91=E6=8A=80?= Date: Thu, 17 Apr 2025 23:15:03 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B8=85=E7=90=86=E6=84=8F=E5=9B=BE=E8=AF=86?= =?UTF-8?q?=E5=88=AB=E6=A8=A1=E5=9D=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/core/connection.py | 62 ++--- .../core/handle/intentHandler.py | 150 ------------ .../core/handle/receiveAudioHandle.py | 27 ++- .../core/providers/intent/base.py | 45 ---- .../intent/function_call/function_call.py | 22 -- .../providers/intent/intent_llm/intent_llm.py | 217 ------------------ .../providers/intent/nointent/nointent.py | 22 -- .../xiaozhi-server/core/providers/llm/base.py | 2 +- .../core/providers/llm/coze/coze.py | 2 +- .../core/providers/llm/dify/dify.py | 2 +- .../core/providers/llm/ollama/ollama.py | 2 +- .../core/providers/llm/openai/openai.py | 28 ++- .../providers/llm/xinference/xinference.py | 2 +- main/xiaozhi-server/core/utils/intent.py | 17 -- main/xiaozhi-server/core/utils/util.py | 16 +- main/xiaozhi-server/core/websocket_server.py | 2 - 16 files changed, 74 insertions(+), 544 deletions(-) delete mode 100644 main/xiaozhi-server/core/handle/intentHandler.py delete mode 100644 main/xiaozhi-server/core/providers/intent/base.py delete mode 100644 main/xiaozhi-server/core/providers/intent/function_call/function_call.py delete mode 100644 main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py delete mode 100644 main/xiaozhi-server/core/providers/intent/nointent/nointent.py delete mode 100644 main/xiaozhi-server/core/utils/intent.py diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 22cb981e1..de3504b02 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -44,7 +44,7 @@ class TTSException(RuntimeError): class ConnectionHandler: def __init__( - self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory, _intent + self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _memory ): self.config = copy.deepcopy(config) self.logger = setup_logging() @@ -78,7 +78,6 @@ class ConnectionHandler: self.llm = _llm self.tts = _tts self.memory = _memory - self.intent = _intent # vad相关变量 self.client_audio_buffer = bytearray() @@ -111,6 +110,7 @@ class ConnectionHandler: self.close_after_chat = False # 是否在聊天结束后关闭连接 self.use_function_call_mode = False + self.use_function_call_by_prompt = False async def handle_connection(self, ws): try: @@ -209,8 +209,10 @@ class ConnectionHandler: """加载记忆""" self._initialize_memory() + """加载意图识别""" self._initialize_intent() + """加载位置信息""" self.client_ip_info = get_ip_info(self.client_ip, self.logger) if self.client_ip_info is not None and "city" in self.client_ip_info: @@ -311,8 +313,6 @@ class ConnectionHandler: self.tts = modules["tts"] if modules.get("llm", None) is not None: self.llm = modules["llm"] - if modules.get("intent", None) is not None: - self.intent = modules["intent"] if modules.get("memory", None) is not None: self.memory = modules["memory"] if modules.get("prompt", None) is not None: @@ -324,44 +324,13 @@ class ConnectionHandler: self.memory.init_memory(device_id, self.llm) def _initialize_intent(self): - if ( - self.config["Intent"][self.config["selected_module"]["Intent"]]["type"] - == "function_call" - ): + intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]]["type"] + if (intent_type == "function_call"): self.use_function_call_mode = True - """初始化意图识别模块""" - # 获取意图识别配置 - intent_config = self.config["Intent"] - intent_type = self.config["Intent"][self.config["selected_module"]["Intent"]][ - "type" - ] - - # 如果使用 nointent,直接返回 - if intent_type == "nointent": + elif (intent_type == "intent_llm"): + self.use_function_call_by_prompt = True + else: return - # 使用 intent_llm 模式 - elif intent_type == "intent_llm": - intent_llm_name = intent_config[self.config["selected_module"]["Intent"]][ - "llm" - ] - - if intent_llm_name and intent_llm_name in self.config["LLM"]: - # 如果配置了专用LLM,则创建独立的LLM实例 - from core.utils import llm as llm_utils - - intent_llm_config = self.config["LLM"][intent_llm_name] - intent_llm_type = intent_llm_config.get("type", intent_llm_name) - intent_llm = llm_utils.create_instance( - intent_llm_type, intent_llm_config - ) - self.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作为意图识别模型") """加载插件""" self.func_handler = FunctionHandler(self) @@ -453,7 +422,11 @@ class ConnectionHandler: ) return True - def chat_with_function_calling(self, query, tool_call=False): + # 处理函数调用的结果 + # query: 用户输入的查询 + # tool_call: 是否是工具调用 + # use_system_prompt: 是否使用系统提示词,原则上只有不支持function calling的模型才会使用 + def chat_with_function_calling(self, query, tool_call=False, use_system_prompt=False): self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") """Chat with function calling for intent detection using streaming""" @@ -483,6 +456,7 @@ class ConnectionHandler: self.session_id, self.dialogue.get_llm_dialogue_with_memory(memory_str), functions=functions, + use_system_prompt=use_system_prompt, ) except Exception as e: self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") @@ -601,7 +575,7 @@ class ConnectionHandler: result = self.func_handler.handle_llm_function_call( self, function_call_data ) - self._handle_function_result(result, function_call_data, text_index + 1) + self._handle_function_result(result, function_call_data, text_index + 1, use_system_prompt) # 处理最后剩余的文本 full_text = "".join(response_message) @@ -671,7 +645,7 @@ class ConnectionHandler: return ActionResponse(action=Action.REQLLM, result="工具调用出错", response="") - def _handle_function_result(self, result, function_call_data, text_index): + def _handle_function_result(self, result, function_call_data, text_index, use_system_prompt): if result.action == Action.RESPONSE: # 直接回复前端 text = result.response self.recode_first_last_text(text, text_index) @@ -705,7 +679,7 @@ class ConnectionHandler: self.dialogue.put( Message(role="tool", tool_call_id=function_id, content=text) ) - self.chat_with_function_calling(text, tool_call=True) + self.chat_with_function_calling(text, tool_call=True, use_system_prompt=use_system_prompt) elif result.action == Action.NOTFOUND: text = result.result self.recode_first_last_text(text, text_index) diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py deleted file mode 100644 index 90d8e1d59..000000000 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ /dev/null @@ -1,150 +0,0 @@ -from config.logger import setup_logging -import json -import uuid -from core.handle.sendAudioHandle import send_stt_message -from core.handle.helloHandle import checkWakeupWords -from core.utils.util import remove_punctuation_and_length -from core.utils.dialogue import Message -from loguru import logger - -TAG = __name__ -logger = setup_logging() - - -async def handle_user_intent(conn, text): - # 检查是否有明确的退出命令 - if await check_direct_exit(conn, text): - return True - # 检查是否是唤醒词 - if await checkWakeupWords(conn, text): - return True - - if conn.use_function_call_mode: - # 使用支持function calling的聊天方法,不再进行意图分析 - return False - # 使用LLM进行意图分析 - intent_result = await analyze_intent_with_llm(conn, text) - if not intent_result: - return False - # 处理各种意图 - return await process_intent_result(conn, intent_result, text) - - -async def check_direct_exit(conn, text): - """检查是否有明确的退出命令""" - _, text = remove_punctuation_and_length(text) - cmd_exit = conn.cmd_exit - for cmd in cmd_exit: - if text == cmd: - logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}") - await send_stt_message(conn, text) - await conn.close() - return True - return False - - -async def analyze_intent_with_llm(conn, text): - """使用LLM分析用户意图""" - if not hasattr(conn, "intent") or not conn.intent: - logger.bind(tag=TAG).warning("意图识别服务未初始化") - return None - - # 对话历史记录 - dialogue = conn.dialogue - try: - intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text) - return intent_result - except Exception as e: - logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") - - return None - - -async def process_intent_result(conn, intent_result, original_text): - """处理意图识别结果""" - try: - # 尝试将结果解析为JSON - intent_data = json.loads(intent_result) - - # 检查是否有function_call - if "function_call" in intent_data: - # 直接从意图识别获取了function_call - logger.bind(tag=TAG).debug( - f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}" - ) - function_name = intent_data["function_call"]["name"] - if function_name == "continue_chat": - return False - - if function_name == "play_music": - funcItem = conn.func_handler.get_function(function_name) - if not funcItem: - conn.func_handler.function_registry.register_function("play_music") - - function_args = None - if "arguments" in intent_data["function_call"]: - function_args = intent_data["function_call"]["arguments"] - # 确保参数是字符串格式的JSON - if isinstance(function_args, dict): - function_args = json.dumps(function_args) - - function_call_data = { - "name": function_name, - "id": str(uuid.uuid4().hex), - "arguments": function_args, - } - - await send_stt_message(conn, original_text) - - # 使用executor执行函数调用和结果处理 - def process_function_call(): - conn.dialogue.put(Message(role="user", content=original_text)) - result = conn.func_handler.handle_llm_function_call( - conn, function_call_data - ) - if result and function_name != "play_music": - # 获取当前最新的文本索引 - text = result.response - if text is None: - text = result.result - if text is not None: - text_index = ( - conn.tts_last_text_index + 1 - if hasattr(conn, "tts_last_text_index") - else 0 - ) - conn.recode_first_last_text(text, text_index) - future = conn.executor.submit( - conn.speak_and_play, text, text_index - ) - conn.llm_finish_task = True - conn.tts_queue.put(future) - conn.dialogue.put(Message(role="assistant", content=text)) - - # 将函数执行放在线程池中 - conn.executor.submit(process_function_call) - return True - return False - except json.JSONDecodeError as e: - logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}") - 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 "" diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 09f342dc7..5629a628e 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -3,7 +3,7 @@ import time import asyncio from core.utils.util import remove_punctuation_and_length from core.handle.sendAudioHandle import send_stt_message -from core.handle.intentHandler import handle_user_intent +from core.handle.helloHandle import checkWakeupWords TAG = __name__ logger = setup_logging() @@ -47,6 +47,29 @@ async def handleAudioMessage(conn, audio): conn.reset_vad_states() +async def handle_user_intent(conn, text): + # 检查是否有明确的退出命令 + if await check_direct_exit(conn, text): + return True + # 检查是否是唤醒词 + if await checkWakeupWords(conn, text): + return True + + return False + + +async def check_direct_exit(conn, text): + """检查是否有明确的退出命令""" + _, text = remove_punctuation_and_length(text) + cmd_exit = conn.cmd_exit + for cmd in cmd_exit: + if text == cmd: + logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}") + await send_stt_message(conn, text) + await conn.close() + return True + return False + async def startToChat(conn, text): if conn.need_bind: await check_bind_device(conn) @@ -64,6 +87,8 @@ async def startToChat(conn, text): if conn.use_function_call_mode: # 使用支持function calling的聊天方法 conn.executor.submit(conn.chat_with_function_calling, text) + elif conn.use_function_call_by_prompt: + conn.executor.submit(conn.chat_with_function_calling, text, False, True) else: conn.executor.submit(conn.chat, text) diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py deleted file mode 100644 index 040dd0254..000000000 --- a/main/xiaozhi-server/core/providers/intent/base.py +++ /dev/null @@ -1,45 +0,0 @@ -from abc import ABC, abstractmethod -from typing import List, Dict -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - - -class IntentProviderBase(ABC): - def __init__(self, config): - self.config = config - self.intent_options = [ - { - "name": "handle_exit_intent", - "desc": "结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候", - }, - { - "name": "play_music", - "desc": "播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图", - }, - {"name": "get_time", "desc": "获取今天日期或者当前时间信息"}, - {"name": "continue_chat", "desc": "继续聊天"}, - ] - - def set_llm(self, llm): - self.llm = llm - # 获取模型名称和类型信息 - model_name = getattr(llm, "model_name", str(llm.__class__.__name__)) - # 记录更详细的日志 - logger.bind(tag=TAG).info(f"意图识别设置LLM: {model_name}") - - @abstractmethod - async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: - """ - 检测用户最后一句话的意图 - Args: - dialogue_history: 对话历史记录列表,每条记录包含role和content - Returns: - 返回识别出的意图,格式为: - - "继续聊天" - - "结束聊天" - - "播放音乐 歌名" 或 "随机播放音乐" - - "查询天气 地点名" 或 "查询天气 [当前位置]" - """ - pass diff --git a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py b/main/xiaozhi-server/core/providers/intent/function_call/function_call.py deleted file mode 100644 index d43ada429..000000000 --- a/main/xiaozhi-server/core/providers/intent/function_call/function_call.py +++ /dev/null @@ -1,22 +0,0 @@ -from ..base import IntentProviderBase -from typing import List, Dict -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - - -class IntentProvider(IntentProviderBase): - async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: - """ - 默认的意图识别实现,始终返回继续聊天 - Args: - dialogue_history: 对话历史记录列表 - text: 本次对话记录 - Returns: - 固定返回"继续聊天" - """ - logger.bind(tag=TAG).debug( - "Using functionCallProvider, always returning continue chat" - ) - return '{"function_call": {"name": "continue_chat"}}' 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 deleted file mode 100644 index 05d01c102..000000000 --- a/main/xiaozhi-server/core/providers/intent/intent_llm/intent_llm.py +++ /dev/null @@ -1,217 +0,0 @@ -from typing import List, Dict -from ..base import IntentProviderBase -from plugins_func.functions.play_music import initialize_music_handler -from config.logger import setup_logging -import re -import json -import hashlib -import time - -TAG = __name__ -logger = setup_logging() - - -class IntentProvider(IntentProviderBase): - def __init__(self, config): - super().__init__(config) - self.llm = None - self.promot = self.get_intent_system_prompt() - # 添加缓存管理 - self.intent_cache = {} # 缓存意图识别结果 - self.cache_expiry = 600 # 缓存有效期10分钟 - self.cache_max_size = 100 # 最多缓存100个意图 - - def get_intent_system_prompt(self) -> str: - """ - 根据配置的意图选项动态生成系统提示词 - Returns: - 格式化后的系统提示词 - """ - - prompt = ( - "你是一个意图识别助手。请分析用户的最后一句话,判断用户意图属于以下哪一类:\n" - "" - f"{str(self.intent_options)}" - "\n" - "处理步骤:" - "1. 思考意图类型,生成function_call格式" - "\n\n" - "返回格式示例:\n" - '1. 播放音乐意图: {"function_call": {"name": "play_music", "arguments": {"song_name": "音乐名称"}}}\n' - '2. 结束对话意图: {"function_call": {"name": "handle_exit_intent", "arguments": {"say_goodbye": "goodbye"}}}\n' - '3. 获取当天日期时间: {"function_call": {"name": "get_time"}}\n' - '4. 继续聊天意图: {"function_call": {"name": "continue_chat"}}\n' - "\n" - "注意:\n" - '- 播放音乐:无歌名时,song_name设为"random"\n' - "- 如果没有明显的意图,应按照继续聊天意图处理\n" - "- 只返回纯JSON,不要任何其他内容\n" - "\n" - "示例分析:\n" - "```\n" - "用户: 你也太搞笑了\n" - '返回: {"function_call": {"name": "continue_chat"}}\n' - "```\n" - "```\n" - "用户: 现在是几号了?现在几点了?\n" - '返回: {"function_call": {"name": "get_time"}}\n' - "```\n" - "```\n" - "用户: 我们明天再聊吧\n" - '返回: {"function_call": {"name": "handle_exit_intent"}}\n' - "```\n" - "```\n" - "用户: 播放中秋月\n" - '返回: {"function_call": {"name": "play_music", "arguments": {"song_name": "中秋月"}}}\n' - "```\n" - "```\n" - "可用的音乐名称:\n" - ) - return prompt - - def clean_cache(self): - """清理过期缓存""" - now = time.time() - # 找出过期键 - expired_keys = [ - k - for k, v in self.intent_cache.items() - if now - v["timestamp"] > self.cache_expiry - ] - for key in expired_keys: - del self.intent_cache[key] - - # 如果缓存太大,移除最旧的条目 - if len(self.intent_cache) > self.cache_max_size: - # 按时间戳排序并保留最新的条目 - sorted_items = sorted( - self.intent_cache.items(), key=lambda x: x[1]["timestamp"] - ) - for key, _ in sorted_items[: len(sorted_items) - self.cache_max_size]: - del self.intent_cache[key] - - async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: - if not self.llm: - raise ValueError("LLM provider not set") - - # 记录整体开始时间 - total_start_time = time.time() - - # 打印使用的模型信息 - model_info = getattr(self.llm, "model_name", str(self.llm.__class__.__name__)) - logger.bind(tag=TAG).debug(f"使用意图识别模型: {model_info}") - - # 计算缓存键 - cache_key = hashlib.md5(text.encode()).hexdigest() - - # 检查缓存 - if cache_key in self.intent_cache: - cache_entry = self.intent_cache[cache_key] - # 检查缓存是否过期 - if time.time() - cache_entry["timestamp"] <= self.cache_expiry: - cache_time = time.time() - total_start_time - logger.bind(tag=TAG).debug( - f"使用缓存的意图: {cache_key} -> {cache_entry['intent']}, 耗时: {cache_time:.4f}秒" - ) - return cache_entry["intent"] - - # 清理缓存 - self.clean_cache() - - # 构建用户最后一句话的提示 - msgStr = "" - - # 只使用最后两句即可 - if len(dialogue_history) >= 2: - # 保证最少有两句话的时候处理 - msgStr += f"{dialogue_history[-2].role}: {dialogue_history[-2].content}\n" - msgStr += f"{dialogue_history[-1].role}: {dialogue_history[-1].content}\n" - - msgStr += f"User: {text}\n" - user_prompt = f"当前的对话如下:\n{msgStr}" - music_config = initialize_music_handler(conn) - music_file_names = music_config["music_file_names"] - prompt_music = f"{self.promot}\n{music_file_names}\n" - logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}") - - # 记录预处理完成时间 - preprocess_time = time.time() - total_start_time - logger.bind(tag=TAG).debug(f"意图识别预处理耗时: {preprocess_time:.4f}秒") - - # 使用LLM进行意图识别 - llm_start_time = time.time() - logger.bind(tag=TAG).debug(f"开始LLM意图识别调用, 模型: {model_info}") - - intent = self.llm.response_no_stream( - system_prompt=prompt_music, user_prompt=user_prompt - ) - - # 记录LLM调用完成时间 - llm_time = time.time() - llm_start_time - logger.bind(tag=TAG).debug( - f"LLM意图识别完成, 模型: {model_info}, 调用耗时: {llm_time:.4f}秒" - ) - - # 记录后处理开始时间 - postprocess_start_time = time.time() - - # 清理和解析响应 - intent = intent.strip() - # 尝试提取JSON部分 - match = re.search(r"\{.*\}", intent, re.DOTALL) - if match: - intent = match.group(0) - - # 记录总处理时间 - total_time = time.time() - total_start_time - logger.bind(tag=TAG).debug( - f"【意图识别性能】模型: {model_info}, 总耗时: {total_time:.4f}秒, LLM调用: {llm_time:.4f}秒, 查询: '{text[:20]}...'" - ) - - # 尝试解析为JSON - try: - intent_data = json.loads(intent) - # 如果包含function_call,则格式化为适合处理的格式 - if "function_call" in intent_data: - function_data = intent_data["function_call"] - function_name = function_data.get("name") - function_args = function_data.get("arguments", {}) - - # 记录识别到的function call - logger.bind(tag=TAG).info( - f"识别到function call: {function_name}, 参数: {function_args}" - ) - - # 添加到缓存 - self.intent_cache[cache_key] = { - "intent": intent, - "timestamp": time.time(), - } - - # 后处理时间 - postprocess_time = time.time() - postprocess_start_time - logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒") - - # 确保返回完全序列化的JSON字符串 - return intent - else: - # 添加到缓存 - self.intent_cache[cache_key] = { - "intent": intent, - "timestamp": time.time(), - } - - # 后处理时间 - postprocess_time = time.time() - postprocess_start_time - logger.bind(tag=TAG).debug(f"意图后处理耗时: {postprocess_time:.4f}秒") - - # 返回普通意图 - return intent - except json.JSONDecodeError: - # 后处理时间 - postprocess_time = time.time() - postprocess_start_time - logger.bind(tag=TAG).error( - f"无法解析意图JSON: {intent}, 后处理耗时: {postprocess_time:.4f}秒" - ) - # 如果解析失败,默认返回继续聊天意图 - return '{"intent": "继续聊天"}' diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py deleted file mode 100644 index 4b08ae8f1..000000000 --- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py +++ /dev/null @@ -1,22 +0,0 @@ -from ..base import IntentProviderBase -from typing import List, Dict -from config.logger import setup_logging - -TAG = __name__ -logger = setup_logging() - - -class IntentProvider(IntentProviderBase): - async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str: - """ - 默认的意图识别实现,始终返回继续聊天 - Args: - dialogue_history: 对话历史记录列表 - text: 本次对话记录 - Returns: - 固定返回"继续聊天" - """ - logger.bind(tag=TAG).debug( - "Using NoIntentProvider, always returning continue chat" - ) - return '{"function_call": {"name": "continue_chat"}}' diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py index 97d0d8e72..5029badd8 100644 --- a/main/xiaozhi-server/core/providers/llm/base.py +++ b/main/xiaozhi-server/core/providers/llm/base.py @@ -26,7 +26,7 @@ class LLMProviderBase(ABC): logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") return "【LLM服务响应异常】" - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): """ Default implementation for function calling (streaming) This should be overridden by providers that support function calls diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py index 416d4ce34..9a402f972 100644 --- a/main/xiaozhi-server/core/providers/llm/coze/coze.py +++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py @@ -48,7 +48,7 @@ class LLMProvider(LLMProviderBase): print(event.message.content, end="", flush=True) yield event.message.content - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): if len(dialogue) == 2 and functions is not None and len(functions) > 0: # 第一次调用llm, 取最后一条用户消息,附加tool提示词 last_msg = dialogue[-1]["content"] diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py index 09f0739e1..22f46f80c 100644 --- a/main/xiaozhi-server/core/providers/llm/dify/dify.py +++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py @@ -83,7 +83,7 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error(f"Error in response generation: {e}") yield "【服务响应异常】" - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): if len(dialogue) == 2 and functions is not None and len(functions) > 0: # 第一次调用llm, 取最后一条用户消息,附加tool提示词 last_msg = dialogue[-1]["content"] diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index fb34ced5d..2c1b1d965 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -49,7 +49,7 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") yield "【Ollama服务响应异常】" - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): try: stream = self.client.chat.completions.create( model=self.model_name, diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index 2c04662ba..a26612d22 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -2,6 +2,8 @@ import openai from config.logger import setup_logging from core.utils.util import check_model_key from core.providers.llm.base import LLMProviderBase +from core.providers.llm.system_prompt import get_system_prompt_for_function +import json TAG = __name__ logger = setup_logging() @@ -63,11 +65,29 @@ class LLMProvider(LLMProviderBase): except Exception as e: logger.bind(tag=TAG).error(f"Error in response generation: {e}") - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): try: - stream = self.client.chat.completions.create( - model=self.model_name, messages=dialogue, stream=True, tools=functions - ) + if not use_system_prompt: + stream = self.client.chat.completions.create( + model=self.model_name, messages=dialogue, stream=True, tools=functions + ) + else: + print(dialogue) + # 使用系统提示词, 需要将functions添加到对话中 + system_prompt = dialogue[0]["content"] + if system_prompt == None : + system_prompt = "" + + # 将functions转换为字符串格式 + function_str = json.dumps(functions, ensure_ascii=False) + + print (f"system_prompt: {system_prompt}..") + modify_msg = get_system_prompt_for_function(function_str) + system_prompt + dialogue[0]["content"] = modify_msg + + stream = self.client.chat.completions.create( + model=self.model_name, messages=dialogue, stream=True + ) for chunk in stream: yield chunk.choices[0].delta.content, chunk.choices[0].delta.tool_calls diff --git a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py index b90b0418d..a40489056 100644 --- a/main/xiaozhi-server/core/providers/llm/xinference/xinference.py +++ b/main/xiaozhi-server/core/providers/llm/xinference/xinference.py @@ -57,7 +57,7 @@ class LLMProvider(LLMProviderBase): logger.bind(tag=TAG).error(f"Error in Xinference response generation: {e}") yield "【Xinference服务响应异常】" - def response_with_functions(self, session_id, dialogue, functions=None): + def response_with_functions(self, session_id, dialogue, functions=None, use_system_prompt=False): try: logger.bind(tag=TAG).debug(f"Sending function call request to Xinference with model: {self.model_name}, dialogue length: {len(dialogue)}") if functions: diff --git a/main/xiaozhi-server/core/utils/intent.py b/main/xiaozhi-server/core/utils/intent.py deleted file mode 100644 index 747ecf38a..000000000 --- a/main/xiaozhi-server/core/utils/intent.py +++ /dev/null @@ -1,17 +0,0 @@ -import os -import sys -from config.logger import setup_logging -import importlib - -logger = setup_logging() - - -def create_instance(class_name, *args, **kwargs): - # 创建intent实例 - if os.path.exists(os.path.join('core', 'providers', 'intent', class_name, f'{class_name}.py')): - lib_name = f'core.providers.intent.{class_name}.{class_name}' - if lib_name not in sys.modules: - sys.modules[lib_name] = importlib.import_module(f'{lib_name}') - return sys.modules[lib_name].IntentProvider(*args, **kwargs) - - raise ValueError(f"不支持的intent类型: {class_name},请检查该配置的type是否设置正确") \ No newline at end of file diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py index e9e6795a8..ceacc9eb9 100644 --- a/main/xiaozhi-server/core/utils/util.py +++ b/main/xiaozhi-server/core/utils/util.py @@ -4,7 +4,7 @@ import subprocess import re import requests from typing import Dict, Any -from core.utils import tts, llm, intent, memory, vad, asr +from core.utils import tts, llm, memory, vad, asr TAG = __name__ @@ -267,20 +267,6 @@ def initialize_modules( ) logger.bind(tag=TAG).info(f"初始化组件: llm成功 {select_llm_module}") - # 初始化Intent模块 - if init_intent: - select_intent_module = config["selected_module"]["Intent"] - intent_type = ( - select_intent_module - if "type" not in config["Intent"][select_intent_module] - else config["Intent"][select_intent_module]["type"] - ) - modules["intent"] = intent.create_instance( - intent_type, - config["Intent"][select_intent_module], - ) - logger.bind(tag=TAG).info(f"初始化组件: intent成功 {select_intent_module}") - # 初始化Memory模块 if init_memory: select_memory_module = config["selected_module"]["Memory"] diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py index cb4dee08a..e02cf0f9f 100644 --- a/main/xiaozhi-server/core/websocket_server.py +++ b/main/xiaozhi-server/core/websocket_server.py @@ -18,7 +18,6 @@ class WebSocketServer: self._asr = modules["asr"] self._tts = modules["tts"] self._llm = modules["llm"] - self._intent = modules["intent"] self._memory = modules["memory"] self.active_connections = set() @@ -52,7 +51,6 @@ class WebSocketServer: self._llm, self._tts, self._memory, - self._intent, ) self.active_connections.add(handler) try: