From e903fd0bc287a582b6ad9d7488685d8383bedb36 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8E=84=E5=87=A4=E7=A7=91=E6=8A=80?= Date: Fri, 7 Mar 2025 15:40:00 +0800 Subject: [PATCH] =?UTF-8?q?=E9=80=9A=E8=BF=87=E4=BD=BF=E7=94=A8function=20?= =?UTF-8?q?call=E5=AE=9E=E7=8E=B0=E6=84=8F=E5=9B=BE=E8=AF=86=E5=88=AB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- main/xiaozhi-server/config.yaml | 3 + main/xiaozhi-server/core/connection.py | 115 ++++++++++++++++++ .../core/handle/functionCallConfig.py | 36 ++++++ .../core/handle/intentHandler.py | 70 ++++++++++- .../core/handle/receiveAudioHandle.py | 6 +- .../xiaozhi-server/core/providers/llm/base.py | 13 +- .../core/providers/llm/ollama/ollama.py | 91 +++++++++----- .../core/providers/llm/openai/openai.py | 38 ++++++ 8 files changed, 339 insertions(+), 33 deletions(-) create mode 100644 main/xiaozhi-server/core/handle/functionCallConfig.py diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml index 54d38e988..6476476ae 100644 --- a/main/xiaozhi-server/config.yaml +++ b/main/xiaozhi-server/config.yaml @@ -58,6 +58,9 @@ delete_audio: true # 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 close_connection_no_voice_time: 120 +# 是否使用函数调用模式, 默认为false,需要大模型支持tools调用 +use_function_call_mode: false + CMD_exit: - "退出" - "关闭" diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py index 77e221558..1dc85d9c7 100644 --- a/main/xiaozhi-server/core/connection.py +++ b/main/xiaozhi-server/core/connection.py @@ -15,6 +15,7 @@ from core.utils.util import get_string_no_punctuation_or_emoji from concurrent.futures import ThreadPoolExecutor, TimeoutError from core.handle.sendAudioHandle import sendAudioMessage from core.handle.receiveAudioHandle import handleAudioMessage +from core.handle.intentHandler import Action, get_functions, handle_llm_function_call from config.private_config import PrivateConfig from core.auth import AuthMiddleware, AuthenticationError from core.utils.auth_code_gen import AuthCodeGenerator @@ -90,6 +91,7 @@ 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模式,开启后可以通过函数调用处理意图 async def handle_connection(self, ws): try: @@ -286,6 +288,119 @@ class ConnectionHandler: self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)) return True + def chat_with_function_calling(self, query): + self.logger.bind(tag=TAG).debug(f"Chat with function calling start: {query}") + """Chat with function calling for intent detection using streaming""" + if self.isNeedAuth(): + self.llm_finish_task = True + future = asyncio.run_coroutine_threadsafe(self._check_and_broadcast_auth_code(), self.loop) + future.result() + return True + + self.dialogue.put(Message(role="user", content=query)) + + # Define intent functions + functions = get_functions() + + response_message = [] + processed_chars = 0 # 跟踪已处理的字符位置 + function_call_data = None # 存储function call数据 + + try: + start_time = time.time() + + # 使用带记忆的对话 + 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}") + + # 使用支持functions的streaming接口 + llm_responses = self.llm.response_with_functions( + self.session_id, + self.dialogue.get_llm_dialogue_with_memory(memory_str), + functions=functions + ) + except Exception as e: + self.logger.bind(tag=TAG).error(f"LLM 处理出错 {query}: {e}") + return None + + self.llm_finish_task = False + text_index = 0 + + # 处理流式响应 + for response in llm_responses: + if response["type"] == "content": + content = response["content"] + response_message.append(content) + + if self.client_abort: + break + + end_time = time.time() + self.logger.bind(tag=TAG).debug(f"大模型返回时间: {end_time - start_time} 秒, 生成token={content}") + + # 处理文本分段和TTS逻辑 + # 合并当前全部文本并处理未分割部分 + full_text = "".join(response_message) + current_text = full_text[processed_chars:] # 从未处理的位置开始 + + # 查找最后一个有效标点 + punctuations = ("。", "?", "!", "?", "!", ";", ";", ":", ":") + last_punct_pos = -1 + for punct in punctuations: + pos = current_text.rfind(punct) + if pos > last_punct_pos: + last_punct_pos = pos + + # 找到分割点则处理 + if last_punct_pos != -1: + segment_text_raw = current_text[:last_punct_pos + 1] + segment_text = get_string_no_punctuation_or_emoji(segment_text_raw) + if segment_text: + text_index += 1 + self.recode_first_last_text(segment_text, text_index) + future = self.executor.submit(self.speak_and_play, segment_text, text_index) + self.tts_queue.put(future) + processed_chars += len(segment_text_raw) # 更新已处理字符位置 + + elif response["type"] == "function_call": + # Extract function call data + function_call_data = { + "name": response["function_call"]["function"]["name"], + "arguments": response["function_call"]["function"]["arguments"] + } + self.logger.bind(tag=TAG).info(f"Function call detected: {function_call_data}") + + # 处理最后剩余的文本 + full_text = "".join(response_message) + remaining_text = full_text[processed_chars:] + if remaining_text: + segment_text = get_string_no_punctuation_or_emoji(remaining_text) + if segment_text: + text_index += 1 + self.recode_first_last_text(segment_text, text_index) + future = self.executor.submit(self.speak_and_play, segment_text, text_index) + self.tts_queue.put(future) + + # 存储对话内容 + self.dialogue.put(Message(role="assistant", content="".join(response_message))) + + # 处理function call + if function_call_data: + result = handle_llm_function_call(self, function_call_data) + if result.action == Action.RESPONSE: + text = result.response + text_index += 1 + self.recode_first_last_text(text, text_index) + future = self.executor.submit(self.speak_and_play, text, text_index) + self.tts_queue.put(future) + + self.llm_finish_task = True + self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False)) + + return True + def _tts_priority_thread(self): while not self.stop_event.is_set(): text = None diff --git a/main/xiaozhi-server/core/handle/functionCallConfig.py b/main/xiaozhi-server/core/handle/functionCallConfig.py new file mode 100644 index 000000000..508cb8926 --- /dev/null +++ b/main/xiaozhi-server/core/handle/functionCallConfig.py @@ -0,0 +1,36 @@ +FunctionCallConfig = [ + { + "type": "function", + "function": { + "name": "handle_exit_intent", + "description": "当用户想结束对话或需要退出系统时调用", + "parameters": { + "type": "object", + "properties": { + "say_goodbye": { + "type": "string", + "description": "和用户友好结束对话的告别语" + } + }, + "required": [] + } + } + }, + { + "type": "function", + "function": { + "name": "play_music", + "description": "当用户想播放音乐时调用", + "parameters": { + "type": "object", + "properties": { + "song_name": { + "type": "string", + "description": "要播放的歌曲名称,如果没有指定具体歌名则为'random'" + } + }, + "required": ["song_name"] + } + } + } + ] \ No newline at end of file diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py index 3b51a0a97..653deaa19 100644 --- a/main/xiaozhi-server/core/handle/intentHandler.py +++ b/main/xiaozhi-server/core/handle/intentHandler.py @@ -2,10 +2,70 @@ 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 +import asyncio +from enum import Enum TAG = __name__ logger = setup_logging() +class Action(Enum): + NOTFOUND = (0, "没有找到函数") + NONE = (1, "啥也不干") + RESPONSE = (2, "直接回复") + REQLLM = (3, "调用函数后再请求llm生成回复") + + def __init__(self, code, message): + 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 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: + say_goodbye = json.loads(function_call_data["arguments"]).get("say_goodbye", "再见") + conn.close_after_chat = True + logger.bind(tag=TAG).info(f"退出意图已处理:{say_goodbye}") + 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") + 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="还想听什么歌?") + 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 @@ -17,12 +77,16 @@ async def handle_user_intent(conn, text): Returns: bool: True if intent was handled, False if should proceed to chat """ - logger.bind(tag=TAG).info(f"分析用户意图: {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) diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py index 2b25b497a..97624898c 100644 --- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py +++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py @@ -54,7 +54,11 @@ async def startToChat(conn, text): # 意图未被处理,继续常规聊天流程 await send_stt_message(conn, text) - conn.executor.submit(conn.chat, text) + if conn.use_function_call_mode: + # 使用支持function calling的聊天方法 + conn.executor.submit(conn.chat_with_function_calling, text) + else: + conn.executor.submit(conn.chat, text) async def no_voice_close_connect(conn): diff --git a/main/xiaozhi-server/core/providers/llm/base.py b/main/xiaozhi-server/core/providers/llm/base.py index 88ec18471..d39a8589c 100644 --- a/main/xiaozhi-server/core/providers/llm/base.py +++ b/main/xiaozhi-server/core/providers/llm/base.py @@ -24,4 +24,15 @@ class LLMProviderBase(ABC): except Exception as e: logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") - return "【LLM服务响应异常】" \ No newline at end of file + return "【LLM服务响应异常】" + + def response_with_functions(self, session_id, dialogue, functions=None): + """ + Default implementation for function calling (streaming) + This should be overridden by providers that support function calls + + Returns: generator that yields either text tokens or a special function call token + """ + # For providers that don't support functions, just return regular response + for token in self.response(session_id, dialogue): + yield {"type": "content", "content": token} \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py index 0f2b97cdc..86d0f6ee8 100644 --- a/main/xiaozhi-server/core/providers/llm/ollama/ollama.py +++ b/main/xiaozhi-server/core/providers/llm/ollama/ollama.py @@ -1,5 +1,6 @@ from config.logger import setup_logging -import requests, json +from openai import OpenAI +import json from core.providers.llm.base import LLMProviderBase TAG = __name__ @@ -8,39 +9,73 @@ logger = setup_logging() class LLMProvider(LLMProviderBase): def __init__(self, config): - self.model_name = config.get("model_name") self.base_url = config.get("base_url", "http://localhost:11434") + # Initialize OpenAI client with Ollama base URL + #如果没有v1,增加v1 + if not self.base_url.endswith("/v1"): + self.base_url = f"{self.base_url}/v1" + + self.client = OpenAI( + base_url=self.base_url, + api_key="ollama" # Ollama doesn't need an API key but OpenAI client requires one + ) - def response(self, session_id, dialogue): + def response(self, session_id, dialogue): try: - # Convert dialogue format to Ollama format - prompt = "" - for msg in dialogue: - if msg["role"] == "system": - prompt += f"System: {msg['content']}\n" - elif msg["role"] == "user": - prompt += f"User: {msg['content']}\n" - elif msg["role"] == "assistant": - prompt += f"Assistant: {msg['content']}\n" - - # Make request to Ollama API - response = requests.post( - f"{self.base_url}/api/generate", - json={ - "model": self.model_name, - "prompt": prompt, - "stream": True - }, + responses = self.client.chat.completions.create( + model=self.model_name, + messages=dialogue, stream=True ) - - for line in response.iter_lines(): - if line: - json_response = json.loads(line) - if "response" in json_response: - yield json_response["response"] + + for chunk in responses: + try: + delta = chunk.choices[0].delta if getattr(chunk, 'choices', None) else None + content = delta.content if hasattr(delta, 'content') else '' + if content: + yield content + except Exception as e: + logger.bind(tag=TAG).error(f"Error processing chunk: {e}") except Exception as e: logger.bind(tag=TAG).error(f"Error in Ollama response generation: {e}") - yield "【Ollama服务响应异常】" \ No newline at end of file + yield "【Ollama服务响应异常】" + + def response_with_functions(self, session_id, dialogue, functions=None): + try: + stream = self.client.chat.completions.create( + model=self.model_name, + messages=dialogue, + stream=True, + tools=functions, + ) + + current_function_call = None + current_content = "" + + for chunk in stream: + delta = chunk.choices[0].delta + + if delta.content: + current_content += delta.content + yield {"type": "content", "content": delta.content} + + if delta.tool_calls: + tool_call = delta.tool_calls[0] + # Handle the function call data using proper attribute access + if not current_function_call: + current_function_call = { + "function": { + "name": tool_call.function.name, + "arguments": tool_call.function.arguments + } + } + + if current_function_call: + logger.bind(tag=TAG).debug(f"ollama Function call detected: {current_function_call}") + yield {"type": "function_call", "function_call": current_function_call} + + except Exception as e: + logger.bind(tag=TAG).error(f"Error in Ollama function call: {e}") + yield {"type": "content", "content": f"【Ollama服务响应异常: {str(e)}】"} \ No newline at end of file diff --git a/main/xiaozhi-server/core/providers/llm/openai/openai.py b/main/xiaozhi-server/core/providers/llm/openai/openai.py index e060248f9..79f0aacc7 100644 --- a/main/xiaozhi-server/core/providers/llm/openai/openai.py +++ b/main/xiaozhi-server/core/providers/llm/openai/openai.py @@ -47,3 +47,41 @@ 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): + try: + stream = self.client.chat.completions.create( + model=self.model_name, + messages=dialogue, + stream=True, + tools=functions, + ) + + current_function_call = None + current_content = "" + + for chunk in stream: + delta = chunk.choices[0].delta + + if delta.content: + current_content += delta.content + yield {"type": "content", "content": delta.content} + + if delta.tool_calls: + tool_call = delta.tool_calls[0] + # Handle the function call data using proper attribute access + if not current_function_call: + current_function_call = { + "function": { + "name": tool_call.function.name, + "arguments": tool_call.function.arguments + } + } + + if current_function_call: + logger.bind(tag=TAG).debug(f"ollama Function call detected: {current_function_call}") + yield {"type": "function_call", "function_call": current_function_call} + + except Exception as e: + self.logger.bind(tag=TAG).error(f"Error in function call streaming: {e}") + yield {"type": "content", "content": f"【OpenAI服务响应异常: {e}】"} \ No newline at end of file