+
-
- 您好,小智
-
让我们度过
+
+ 您好,小智
+
+
- Hello, Let's have a wonderful day!
+ Hello, Let's have a wonderful day!
+
-
-
-
-
-
- {{item.list[0]?.mac_address}}
-
-
-

-

-
-
-
- 设备型号:{{item.list[0]?.device_type}}
-
-
-
- 配置角色
-
- 声纹识别
-
- 历史对话
-
-
-
-
最近对话:{{item.list[0]?.recent_chat_time}}
-
APP版本:{{item.list[0]?.app_version}}
-
-
+
+
-
-
-
-

-
- CC:ba:97:11:a6:ac
-
-
-
-
-
-
-
-
-
-
-
-
- 台湾女友
-
- 土豆子
-
- 英语老师
-
- 好奇小男孩
-
- 汪汪队队长
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
当前记忆(每次对话后重新生成)
-
-
- 清除
-
-
-
{{form.prompt.length}}/1000
-
-
-
-
-
-
-
- 除了“Qwen
- 实时”,其他模型通常会增加约1秒的延迟。改变模型后,建议清空记忆体,以免影响体验。
-
-
-
-
-
- 保存配置
-
- 重制
-
-

- 保存配置后,需要重启设备,新的配置才会生效。
-
-
-
-
+
©2025 xiaozhi-esp32-server
+
-
-
-
-
-

-
- 添加设备
-
-
-
-
-
+
-
-
-
+
\ No newline at end of file
diff --git a/main/manager-web/src/views/login.vue b/main/manager-web/src/views/login.vue
index 6f6759e7a..d60836358 100644
--- a/main/manager-web/src/views/login.vue
+++ b/main/manager-web/src/views/login.vue
@@ -25,15 +25,23 @@
-
登陆
@@ -55,8 +63,9 @@
diff --git a/main/manager-web/src/views/register.vue b/main/manager-web/src/views/register.vue
new file mode 100644
index 000000000..df3007a0d
--- /dev/null
+++ b/main/manager-web/src/views/register.vue
@@ -0,0 +1,164 @@
+
+
+
+
+
+
+

+

+
+
+
+
+
+
+
+

+
注册
+
+ WELCOME TO REGISTER
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
![验证码]()
+
+
+
+
+
+
+
+
立即注册
+
+
+
+ 注册即同意
+
《用户协议》
+ 和
+
《隐私政策》
+
+
+
+
+
+
+
+ ©2025 xiaozhi-esp32-server
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/main/manager-web/src/views/roleConfig.vue b/main/manager-web/src/views/roleConfig.vue
new file mode 100644
index 000000000..8c8dba25c
--- /dev/null
+++ b/main/manager-web/src/views/roleConfig.vue
@@ -0,0 +1,264 @@
+
+
+
+
+
+
+
+
+

+
+ {{ deviceMac }}
+
+
+
+
+
+
+
+
+
+
+
+
+ 台湾女友
+
+
+ 土豆子
+
+
+ 英语老师
+
+
+ 好奇小男孩
+
+
+ 汪汪队队长
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
当前记忆(每次对话后重新生成)
+
+
+ 清除
+
+
+
{{ form.prompt.length }}/1000
+
+
+
+
+
+
+
+ 除了“Qwen
+ 实时”,其他模型通常会增加约1秒的延迟。改变模型后,建议清空记忆体,以免影响体验。
+
+
+
+
+
+
+ 保存配置
+
+
+ 重制
+
+
+

+ 保存配置后,需要重启设备,新的配置才会生效。
+
+
+
+
+ ©2025 xiaozhi-esp32-server
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/main/manager-web/vue.config.js b/main/manager-web/vue.config.js
new file mode 100644
index 000000000..9e72e068b
--- /dev/null
+++ b/main/manager-web/vue.config.js
@@ -0,0 +1,23 @@
+const { defineConfig } = require('@vue/cli-service');
+const dotenv = require('dotenv');
+
+// 确保加载 .env 文件
+dotenv.config();
+
+module.exports = defineConfig({
+ devServer: {
+ // Bug 修复:将代理配置为环境变量中定义的 API 基础 URL
+ proxy: {
+ '/xiaozhi-esp32-api': {
+ target: process.env.VUE_APP_API_BASE_URL || 'http://localhost:8002', // 后端 API 的基础 URL
+ changeOrigin: true, // 允许跨域
+ // pathRewrite: {
+ // '^/api': '', // 路径重写
+ // },
+ },
+ },
+ client: {
+ overlay: false,
+ },
+ },
+});
diff --git a/main/xiaozhi-server/app.py b/main/xiaozhi-server/app.py
index bd23c7bcd..ca3ab5453 100644
--- a/main/xiaozhi-server/app.py
+++ b/main/xiaozhi-server/app.py
@@ -1,10 +1,27 @@
import asyncio
+import sys
+import signal
from config.settings import load_config, check_config_file
from core.websocket_server import WebSocketServer
from core.utils.util import check_ffmpeg_installed
TAG = __name__
+async def wait_for_exit():
+ """Windows 和 Linux 兼容的退出监听"""
+ loop = asyncio.get_running_loop()
+ stop_event = asyncio.Event()
+
+ if sys.platform == "win32":
+ # Windows: 用 sys.stdin.read() 监听 Ctrl + C
+ await loop.run_in_executor(None, sys.stdin.read)
+ else:
+ # Linux/macOS: 用 signal 监听 Ctrl + C
+ def stop():
+ stop_event.set()
+ loop.add_signal_handler(signal.SIGINT, stop)
+ loop.add_signal_handler(signal.SIGTERM, stop) # 支持 kill 进程
+ await stop_event.wait()
async def main():
check_config_file()
@@ -16,11 +33,19 @@ async def main():
ws_task = asyncio.create_task(ws_server.start())
try:
- # 等待 WebSocket 服务器运行
- await ws_task
+ await wait_for_exit() # 监听退出信号
+ except asyncio.CancelledError:
+ print("任务被取消,清理资源中...")
finally:
ws_task.cancel()
-
+ try:
+ await ws_task
+ except asyncio.CancelledError:
+ pass
+ print("服务器已关闭,程序退出。")
if __name__ == "__main__":
- asyncio.run(main())
+ try:
+ asyncio.run(main())
+ except KeyboardInterrupt:
+ print("手动中断,程序终止。")
diff --git a/main/xiaozhi-server/config.yaml b/main/xiaozhi-server/config.yaml
index f365f57c8..bb40013c4 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -51,13 +51,15 @@ xiaozhi:
prompt: |
你是一个叫小智/小志的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。
- 当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。
+ 现在我正在和你进行语音聊天,我们开始吧。
如果用户希望结束对话,请在最后说“拜拜”或“再见”。
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
delete_audio: true
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120
+# TTS请求超时时间(秒)
+tts_timeout: 10
CMD_exit:
- "退出"
@@ -85,14 +87,20 @@ selected_module:
Intent:
# 不使用意图识别
nointent:
- # 不需要动
+ # 不需要动type
type: nointent
intent_llm:
- # 不需要动
+ # 不需要动type
type: intent_llm
function_call:
- # 不需要动
+ # 不需要动type
type: nointent
+ # plugins_func/functions下的模块,可以通过配置,选择加载哪个模块,加载后对话支持相应的function调用
+ # 系统默认已经记载“handle_exit_intent(退出识别)”、“play_music(音乐播放)”插件,请勿重复加载
+ # 下面是加载查天气、角色切换的插件示例
+ functions:
+ - change_role
+ - get_weather
Memory:
mem0ai:
@@ -181,8 +189,9 @@ LLM:
CozeLLM:
# 定义LLM API类型
type: coze
- bot_id: 你的bot_id
- user_id: 你的user_id
+ # bot_id和user_id的内容写在引号之内
+ bot_id: "你的bot_id"
+ user_id: "你的user_id"
personal_access_token: 你的coze个人令牌
LMStudioLLM:
# 定义LLM API类型
@@ -411,6 +420,21 @@ TTS:
# 语速范围0.25-4.0
speed: 1
output_file: tmp/
+ CustomTTS:
+ # 自定义的TTS接口服务,请求参数可自定义
+ # 要求接口使用GET方式请求,并返回音频文件
+ type: custom
+ url: "http://127.0.0.1:9880/tts"
+ params: # 自定义请求参数
+ # text: "{prompt_text}" # {prompt_text}会被替换为实际的提示词内容
+ # speaker: jok老师
+ # speed: 1
+ # foo: bar
+ # testabc: 123456
+ headers: # 自定义请求头
+ # Authorization: Bearer xxxx
+ format: wav # 接口返回的音频格式
+ output_file: tmp/
# 模块测试配置
module_test:
test_sentences: # 自定义测试语句
diff --git a/main/xiaozhi-server/config/functionCallConfig.py b/main/xiaozhi-server/config/functionCallConfig.py
deleted file mode 100644
index dd9b55fc4..000000000
--- a/main/xiaozhi-server/config/functionCallConfig.py
+++ /dev/null
@@ -1,36 +0,0 @@
-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": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎",
- "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/connection.py b/main/xiaozhi-server/core/connection.py
index 80c623365..52596ba65 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -15,10 +15,12 @@ from core.utils.util import get_string_no_punctuation_or_emoji, extract_json_fro
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 core.handle.functionHandler import FunctionHandler
+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
TAG = __name__
@@ -94,8 +96,8 @@ class ConnectionHandler:
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}")
+
+ self.func_handler = FunctionHandler(self.config)
async def handle_connection(self, ws):
try:
@@ -187,11 +189,14 @@ class ConnectionHandler:
self.prompt = self.config["prompt"]
if self.private_config:
self.prompt = self.private_config.private_config.get("prompt", self.prompt)
- # 赋予LLM时间观念
- if "{date_time}" in self.prompt:
- date_time = time.strftime("%Y-%m-%d %H:%M", time.localtime())
- self.prompt = self.prompt.replace("{date_time}", date_time)
self.dialogue.put(Message(role="system", content=self.prompt))
+
+ def change_system_prompt(self, prompt):
+ self.prompt = prompt
+ # 找到原来的role==system,替换原来的系统提示
+ for m in self.dialogue.dialogue:
+ if m.role == "system":
+ m.content = prompt
async def _check_and_broadcast_auth_code(self):
"""检查设备绑定状态并广播认证码"""
@@ -291,7 +296,7 @@ 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):
+ def chat_with_function_calling(self, query, tool_call = False):
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():
@@ -299,11 +304,12 @@ class ConnectionHandler:
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))
+
+ if not tool_call:
+ self.dialogue.put(Message(role="user", content=query))
# Define intent functions
- functions = get_functions()
+ functions = self.func_handler.get_functions()
response_message = []
processed_chars = 0 # 跟踪已处理的字符位置
@@ -339,7 +345,7 @@ class ConnectionHandler:
for response in llm_responses:
content, tools_call = response
if content is not None and len(content)>0:
- if len(response_message)<=0 and content=="```":
+ if len(response_message)<=0 and (content=="```" or "
" in content):
tool_call_flag = True
if tools_call is not None:
@@ -387,7 +393,38 @@ class ConnectionHandler:
self.tts_queue.put(future)
processed_chars += len(segment_text_raw) # 更新已处理字符位置
- # 处理最后剩余的文本
+ # 处理function call
+ if tool_call_flag:
+ bHasError = False
+ if function_id is None:
+ a = extract_json_from_string(content_arguments)
+ if a is not None:
+ try:
+ content_arguments_json = json.loads(a)
+ function_name = content_arguments_json["name"]
+ function_arguments = json.dumps(content_arguments_json["arguments"], ensure_ascii=False)
+ function_id = str(uuid.uuid4().hex)
+ except Exception as e:
+ bHasError = True
+ response_message.append(a)
+ else:
+ bHasError = True
+ response_message.append(content_arguments)
+ if bHasError:
+ self.logger.bind(tag=TAG).error(f"function call error: {content_arguments}")
+ else:
+ function_arguments = json.loads(function_arguments)
+ if not bHasError:
+ self.logger.bind(tag=TAG).info(f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}")
+ function_call_data = {
+ "name": function_name,
+ "id": function_id,
+ "arguments": function_arguments
+ }
+ result = self.func_handler.handle_llm_function_call(self, function_call_data)
+ self._handle_function_result(result, function_call_data, text_index+1)
+
+ # 处理最后剩余的文本
full_text = "".join(response_message)
remaining_text = full_text[processed_chars:]
if remaining_text:
@@ -402,27 +439,6 @@ class ConnectionHandler:
if len(response_message)>0:
self.dialogue.put(Message(role="assistant", content="".join(response_message)))
- # 处理function call
- if tool_call_flag:
- if function_id is None:
- a = extract_json_from_string(content_arguments)
- if a is not None:
- content_arguments_json = json.loads(a)
- function_name = content_arguments_json["function_name"]
- function_arguments = json.dumps(content_arguments_json["args"], ensure_ascii=False)
- function_id = str(uuid.uuid4().hex)
- else:
- return []
- function_arguments = json.loads(function_arguments)
- self.logger.bind(tag=TAG).info(f"function_name={function_name}, function_id={function_id}, function_arguments={function_arguments}")
- function_call_data = {
- "name": function_name,
- "id": function_id,
- "arguments": function_arguments
- }
- result = handle_llm_function_call(self, function_call_data)
- self._handle_function_result(result, function_call_data, text_index+1)
-
self.llm_finish_task = True
self.logger.bind(tag=TAG).debug(json.dumps(self.dialogue.get_llm_dialogue(), indent=4, ensure_ascii=False))
@@ -436,7 +452,23 @@ class ConnectionHandler:
self.tts_queue.put(future)
self.dialogue.put(Message(role="assistant", content=text))
if result.action == Action.REQLLM: # 调用函数后再请求llm生成回复
+
+ text = result.result
+ if text is not None and len(text) > 0:
+ function_id = function_call_data["id"]
+ function_name = function_call_data["name"]
+ function_arguments = function_call_data["arguments"]
+ self.dialogue.put(Message(role='assistant',
+ tool_calls=[{"id": function_id,
+ "function": {"arguments": function_arguments,"name": function_name},
+ "type": 'function',
+ "index": 0}]))
+
+ self.dialogue.put(Message(role="tool", tool_call_id=function_id, content=text))
+ self.chat_with_function_calling(text, tool_call=True)
+ if result.action == Action.NOTFOUND:
text = result.response
+
def _tts_priority_thread(self):
@@ -450,7 +482,8 @@ class ConnectionHandler:
opus_datas, text_index, tts_file = [], 0, None
try:
self.logger.bind(tag=TAG).debug("正在处理TTS任务...")
- tts_file, text, text_index = future.result(timeout=10)
+ tts_timeout = self.config.get("tts_timeout", 10)
+ tts_file, text, text_index = future.result(timeout=tts_timeout)
if text is None or len(text) <= 0:
self.logger.bind(tag=TAG).error(f"TTS出错:{text_index}: tts text is empty")
elif tts_file is None:
@@ -458,7 +491,7 @@ class ConnectionHandler:
else:
self.logger.bind(tag=TAG).debug(f"TTS生成:文件路径: {tts_file}")
if os.path.exists(tts_file):
- opus_datas, duration = self.tts.wav_to_opus_data(tts_file)
+ opus_datas, duration = self.tts.audio_to_opus_data(tts_file)
else:
self.logger.bind(tag=TAG).error(f"TTS出错:文件不存在{tts_file}")
except TimeoutError:
diff --git a/main/xiaozhi-server/core/handle/functionHandler.py b/main/xiaozhi-server/core/handle/functionHandler.py
new file mode 100644
index 000000000..8d54fe8aa
--- /dev/null
+++ b/main/xiaozhi-server/core/handle/functionHandler.py
@@ -0,0 +1,83 @@
+import asyncio
+from enum import Enum
+
+from config.logger import setup_logging
+import json
+from plugins_func.register import FunctionRegistry, ActionResponse, Action, ToolType
+TAG = __name__
+logger = setup_logging()
+
+
+class FunctionHandler:
+ def __init__(self, config):
+ self.config = config
+ self.function_registry = FunctionRegistry()
+ self.register_nessary_functions()
+ self.register_config_functions()
+ self.functions_desc = self.function_registry.get_all_function_desc()
+ func_names = self.current_support_functions()
+ self.modify_plugin_loader_des(func_names)
+
+ def modify_plugin_loader_des(self, func_names):
+ if "plugin_loader" not in func_names:
+ return
+ # 可编辑的列表中去掉plugin_loader
+ surport_plugins = [func for func in func_names if func != "plugin_loader"]
+ func_names = ",".join(surport_plugins)
+ for function_desc in self.functions_desc:
+ if function_desc["function"]["name"] == "plugin_loader":
+ function_desc["function"]["description"] = function_desc["function"]["description"].replace("[plugins]", func_names)
+ break
+
+ def upload_functions_desc(self):
+ self.functions_desc = self.function_registry.get_all_function_desc()
+
+ def current_support_functions(self):
+ func_names = []
+ for func in self.functions_desc:
+ func_names.append(func["function"]["name"])
+ # 打印当前支持的函数列表
+ logger.bind(tag=TAG).info(f"当前支持的函数列表: {func_names}")
+ return func_names
+
+ def get_functions(self):
+ """获取功能调用配置"""
+ return self.functions_desc
+
+ def register_nessary_functions(self):
+ """注册必要的函数"""
+ self.function_registry.register_function("handle_exit_intent")
+ self.function_registry.register_function("play_music")
+ self.function_registry.register_function("plugin_loader")
+ self.function_registry.register_function("get_time")
+
+ def register_config_functions(self):
+ """注册配置中的函数,可以不同客户端使用不同的配置"""
+ for func in self.config["Intent"]["function_call"].get("functions", []):
+ self.function_registry.register_function(func)
+
+ def get_function(self, name):
+ return self.function_registry.get_function(name)
+
+ def handle_llm_function_call(self, conn, function_call_data):
+ try:
+ function_name = function_call_data["name"]
+ funcItem = self.get_function(function_name)
+ if not funcItem:
+ return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
+ func = funcItem.func
+ arguments = function_call_data["arguments"]
+ arguments = json.loads(arguments) if arguments else {}
+ logger.bind(tag=TAG).info(f"调用函数: {function_name}, 参数: {arguments}")
+ if funcItem.type == ToolType.SYSTEM_CTL:
+ return func(conn, **arguments)
+ elif funcItem.type == ToolType.WAIT:
+ return func(**arguments)
+ elif funcItem.type == ToolType.CHANGE_SYS_PROMPT:
+ return func(conn, **arguments)
+ else:
+ return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理function call错误: {e}")
+
+ return None
\ 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 2dde62558..320c47934 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -1,79 +1,12 @@
from config.logger import setup_logging
import json
from core.handle.sendAudioHandle import send_stt_message
-from core.utils.dialogue import Message
-from config.functionCallConfig import FunctionCallConfig
-import asyncio
-from enum import Enum
+from core.utils.util import remove_punctuation_and_length
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:
- 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="还想听什么歌?")
- 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
@@ -93,8 +26,6 @@ async def handle_user_intent(conn, text):
# 使用支持function calling的聊天方法,不再进行意图分析
return False
- logger.bind(tag=TAG).info(f"分析用户意图: {text}")
-
# 使用LLM进行意图分析
intent = await analyze_intent_with_llm(conn, text)
@@ -107,6 +38,7 @@ async def handle_user_intent(conn, 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:
@@ -125,8 +57,7 @@ async def analyze_intent_with_llm(conn, text):
# 对话历史记录
dialogue = conn.dialogue
try:
- intent_result = await conn.intent.detect_intent(dialogue.dialogue, text)
- logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
+ intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
# 尝试解析JSON结果
try:
diff --git a/main/xiaozhi-server/core/handle/musicHandler.py b/main/xiaozhi-server/core/handle/musicHandler.py
index 022d6dc46..b650b847a 100644
--- a/main/xiaozhi-server/core/handle/musicHandler.py
+++ b/main/xiaozhi-server/core/handle/musicHandler.py
@@ -131,7 +131,7 @@ class MusicHandler:
if music_path.endswith(".p3"):
opus_packets, duration = p3.decode_opus_from_file(music_path)
else:
- opus_packets, duration = conn.tts.wav_to_opus_data(music_path)
+ opus_packets, duration = conn.tts.audio_to_opus_data(music_path)
conn.audio_play_queue.put((opus_packets, selected_music, 0))
except Exception as e:
diff --git a/main/xiaozhi-server/core/handle/receiveAudioHandle.py b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
index bf6d4c36c..c5b4135ca 100644
--- a/main/xiaozhi-server/core/handle/receiveAudioHandle.py
+++ b/main/xiaozhi-server/core/handle/receiveAudioHandle.py
@@ -20,7 +20,8 @@ async def handleAudioMessage(conn, audio):
# 如果本次没有声音,本段也没声音,就把声音丢弃了
if have_voice == False and conn.client_have_voice == False:
await no_voice_close_connect(conn)
- conn.asr_audio.clear()
+ conn.asr_audio.append(audio)
+ conn.asr_audio = conn.asr_audio[-5:] # 保留最新的5帧音频内容,解决ASR句首丢字问题
return
conn.client_no_voice_last_time = 0.0
conn.asr_audio.append(audio)
@@ -29,7 +30,7 @@ async def handleAudioMessage(conn, audio):
conn.client_abort = False
conn.asr_server_receive = False
# 音频太短了,无法识别
- if len(conn.asr_audio) < 3:
+ if len(conn.asr_audio) < 10:
conn.asr_server_receive = True
else:
text, file_path = await conn.asr.speech_to_text(conn.asr_audio, conn.session_id)
diff --git a/main/xiaozhi-server/core/providers/intent/base.py b/main/xiaozhi-server/core/providers/intent/base.py
index 9726f1be3..a691d6cbd 100644
--- a/main/xiaozhi-server/core/providers/intent/base.py
+++ b/main/xiaozhi-server/core/providers/intent/base.py
@@ -20,7 +20,7 @@ class IntentProviderBase(ABC):
logger.bind(tag=TAG).debug("Set LLM for intent provider")
@abstractmethod
- async def detect_intent(self, dialogue_history: List[Dict], text: str) -> str:
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
检测用户最后一句话的意图
Args:
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 191f73dfd..04319438c 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
@@ -1,7 +1,7 @@
from typing import List, Dict
from ..base import IntentProviderBase
from config.logger import setup_logging
-
+import re
TAG = __name__
logger = setup_logging()
@@ -20,41 +20,90 @@ class IntentProvider(IntentProviderBase):
格式化后的系统提示词
"""
intent_list = []
+
+ """
+ "continue_chat": "1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等",
+ "end_chat": "2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候",
+ "play_music": "3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图"
+ """
for key, value in self.intent_options.items():
if key == "play_music":
- intent_list.append(f"{value} [歌名]")
+ intent_list.append("3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图")
+ elif key == "end_chat":
+ intent_list.append("2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候")
+ elif key == "continue_chat":
+ intent_list.append("1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等")
else:
intent_list.append(value)
-
+
+ # "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
+ # "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
+ # "只需要返回意图结果的json,不要解释。"
+ # "返回格式如下:\n"
prompt = (
- "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
- f"{', '.join(intent_list)}\n"
- "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
- "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
- "只需要返回意图结果的json,不要解释。"
- "返回格式如下:\n"
- "{intent: '用户意图'}"
+ "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类(使用和标志):\n"
+ ""
+ f"{', '.join(intent_list)}"
+ "\n"
+ "你需要按照以下的步骤处理用户的对话"
+ "1. 思考出对话的意图是哪一类的"
+ "2. 属于1和2的意图, 直接返回,返回格式如下:\n"
+ "{intent: '用户意图'}\n"
+ "3. 属于3的意图,则继续分析用户希望播放的音乐\n"
+ "4. 如果无法识别出具体歌名,可以返回'随机播放音乐'\n"
+ "{intent: '播放音乐 [获取的音乐名字]'}\n"
+ "下面是几个处理的示例(思考的内容不返回, 只返回json部分, 无额外的内容)\n"
+ "```"
+ "用户: 你今天怎么样?\n"
+ "思考(不返回): 用户发来的数据是一个问候语,属于继续聊天的意图, 是种类1, 种类1的需求是直接返回\n"
+ "返回结果: {intent: '继续聊天'}\n"
+ "```"
+ "用户: 我今天有点累了, 我们明天再聊吧\n"
+ "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n"
+ "返回结果: {intent: '结束聊天'}\n"
+ "```"
+ "用户: 我今天有点累了, 我们明天再聊吧\n"
+ "思考(不返回): 用户表达了今天不想继续对话,属于结束聊天的意图, 是种类2, 种类2的需求是直接返回\n"
+ "返回结果: {intent: '结束聊天'}\n"
+ "```"
+ "用户: 你可以播放一首中秋月给我听吗\n"
+ "思考(不返回): 用户表达了想听音乐的续签,属于播放音乐的意图, 是种类3, 种类3的需求需要继续判断播放的音乐, 这里用户希望的歌曲名明确给出是中秋月\n"
+ "返回结果: {intent: '播放音乐 [中秋月]'}\n"
+ "```"
+ "你现在可以使用的音乐的名称如下(使用和标志):\n"
)
return prompt
- async def detect_intent(self, dialogue_history: List[Dict], text:str) -> str:
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text:str) -> str:
if not self.llm:
raise ValueError("LLM provider not set")
# 构建用户最后一句话的提示
msgStr = ""
- for msg in dialogue_history:
- if msg.role == "user":
- msgStr += f"User: {msg.content}\n"
- elif msg.role== "assistant":
- msgStr += f"Assistant: {msg.content}\n"
+
+ # 只使用最后两句即可
+ 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}"
+ user_prompt = f"当前的对话如下:\n{msgStr}"
+ prompt_music = f"{self.promot}\n{conn.music_handler.music_files}\n"
+ logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
# 使用LLM进行意图识别
intent = self.llm.response_no_stream(
- system_prompt=self.promot,
+ system_prompt=prompt_music,
user_prompt=user_prompt
)
-
+ # 使用正则表达式提取大括号中的内容
+ # 使用正则表达式提取 {} 中的内容
+ match = re.search(r'\{.*?\}', intent)
+ if match:
+ result = match.group(0) # 获取匹配到的内容(包含 {})
+ print(result) # 输出:{intent: '播放音乐 [中秋月]'}
+ intent = result
+ else:
+ intent = "{intent: '继续聊天'}"
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
- return intent.strip()
+ return intent.strip()
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
index 70ea96fb9..7efccbfea 100644
--- a/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
+++ b/main/xiaozhi-server/core/providers/intent/nointent/nointent.py
@@ -7,7 +7,7 @@ logger = setup_logging()
class IntentProvider(IntentProviderBase):
- async def detect_intent(self, dialogue_history: List[Dict], text: str) -> str:
+ async def detect_intent(self, conn, dialogue_history: List[Dict], text: str) -> str:
"""
默认的意图识别实现,始终返回继续聊天
Args:
diff --git a/main/xiaozhi-server/core/providers/llm/coze/coze.py b/main/xiaozhi-server/core/providers/llm/coze/coze.py
index feb62ea64..b1b14d91d 100644
--- a/main/xiaozhi-server/core/providers/llm/coze/coze.py
+++ b/main/xiaozhi-server/core/providers/llm/coze/coze.py
@@ -11,19 +11,31 @@ from cozepy import Coze, TokenAuth, Message, ChatStatus, MessageContentType, Cha
TAG = __name__
logger = setup_logging()
+
class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.personal_access_token = config.get("personal_access_token")
self.bot_id = config.get("bot_id")
self.user_id = config.get("user_id")
+ self.session_conversation_map = {} # 存储session_id和conversation_id的映射
def response(self, session_id, dialogue):
coze_api_token = self.personal_access_token
coze_api_base = COZE_CN_BASE_URL
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
-
+
coze = Coze(auth=TokenAuth(token=coze_api_token), base_url=coze_api_base)
+ conversation_id = self.session_conversation_map.get(session_id)
+
+ # 如果没有找到conversation_id,则创建新的对话
+ if not conversation_id:
+ conversation = coze.conversations.create(
+ messages=[
+ ]
+ )
+ conversation_id = conversation.id
+ self.session_conversation_map[session_id] = conversation_id # 更新映射
for event in coze.chat.stream(
bot_id=self.bot_id,
@@ -31,6 +43,7 @@ class LLMProvider(LLMProviderBase):
additional_messages=[
Message.build_user_question_text(last_msg["content"]),
],
+ conversation_id=conversation_id,
):
if event.event == ChatEventType.CONVERSATION_MESSAGE_DELTA:
print(event.message.content, end="", flush=True)
diff --git a/main/xiaozhi-server/core/providers/llm/dify/dify.py b/main/xiaozhi-server/core/providers/llm/dify/dify.py
index 0e9c821ae..f3c626393 100644
--- a/main/xiaozhi-server/core/providers/llm/dify/dify.py
+++ b/main/xiaozhi-server/core/providers/llm/dify/dify.py
@@ -10,11 +10,13 @@ class LLMProvider(LLMProviderBase):
def __init__(self, config):
self.api_key = config["api_key"]
self.base_url = config.get("base_url", "https://api.dify.ai/v1").rstrip('/')
+ self.session_conversation_map = {} # 存储session_id和conversation_id的映射
def response(self, session_id, dialogue):
try:
# 取最后一条用户消息
last_msg = next(m for m in reversed(dialogue) if m["role"] == "user")
+ conversation_id = self.session_conversation_map.get(session_id)
# 发起流式请求
with requests.post(
@@ -24,13 +26,18 @@ class LLMProvider(LLMProviderBase):
"query": last_msg["content"],
"response_mode": "streaming",
"user": session_id,
- "inputs": {}
+ "inputs": {},
+ "conversation_id": conversation_id
},
stream=True
) as r:
for line in r.iter_lines():
if line.startswith(b'data: '):
event = json.loads(line[6:])
+ # 如果没有找到conversation_id,则获取此次conversation_id
+ if not conversation_id:
+ conversation_id = event.get('conversation_id')
+ self.session_conversation_map[session_id] = conversation_id # 更新映射
if event.get('answer'):
yield event['answer']
diff --git a/main/xiaozhi-server/core/providers/tts/base.py b/main/xiaozhi-server/core/providers/tts/base.py
index 42c8cab83..80ca95e76 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -42,7 +42,6 @@ class TTSProviderBase(ABC):
async def text_to_speak(self, text, output_file):
pass
-
def wav_stream_to_opus_data(self, wav_bytes):
# 使用pydub加载PCM文件
if not wav_bytes:
@@ -50,22 +49,22 @@ class TTSProviderBase(ABC):
audio = AudioSegment.from_file(BytesIO(wav_bytes))
return self.audio_to_opus_data(audio)
- def wav_to_opus_data(self, wav_file_path):
- # 使用pydub加载PCM文件
+ def audio_to_opus_data(self, audio_file_path:str):
+ """音频文件转换为Opus编码"""
# 获取文件后缀名
- file_type = os.path.splitext(wav_file_path)[1]
+ file_type = os.path.splitext(audio_file_path)[1]
if file_type:
file_type = file_type.lstrip('.')
audio = AudioSegment.from_file(wav_file_path, format=file_type)
return self.audio_to_opus_data(audio)
def audio_to_opus_data(self, audio:AudioSegment):
+ # 转换为单声道/16kHz采样率/16位小端编码(确保与编码器匹配)
+ audio = audio.set_channels(1).set_frame_rate(16000).set_sample_width(2)
+ # 音频时长(秒)
duration = len(audio) / 1000.0
- # 转换为单声道和16kHz采样率(确保与编码器匹配)
- audio = audio.set_channels(1).set_frame_rate(16000)
-
# 获取原始PCM数据(16位小端)
raw_data = audio.raw_data
diff --git a/main/xiaozhi-server/core/providers/tts/custom.py b/main/xiaozhi-server/core/providers/tts/custom.py
new file mode 100644
index 000000000..d5447878f
--- /dev/null
+++ b/main/xiaozhi-server/core/providers/tts/custom.py
@@ -0,0 +1,35 @@
+import os
+import uuid
+import requests
+from config.logger import setup_logging
+from datetime import datetime
+from core.providers.tts.base import TTSProviderBase
+
+TAG = __name__
+logger = setup_logging()
+
+class TTSProvider(TTSProviderBase):
+ def __init__(self, config, delete_audio_file):
+ super().__init__(config, delete_audio_file)
+ self.url = config.get("url")
+ self.headers = config.get("headers", {})
+ self.params = config.get("params")
+ self.format = config.get("format", "wav")
+ self.output_file = config.get("output_file", "tmp/")
+
+ def generate_filename(self):
+ return os.path.join(self.output_file, f"tts-{datetime.now().date()}@{uuid.uuid4().hex}.{self.format}")
+
+ async def text_to_speak(self, text, output_file):
+ request_params = {}
+ for k, v in self.params.items():
+ if isinstance(v, str) and "{prompt_text}" in v:
+ v = v.replace("{prompt_text}", text)
+ request_params[k] = v
+
+ resp = requests.get(self.url, params=request_params, headers=self.headers)
+ if resp.status_code == 200:
+ with open(output_file, "wb") as file:
+ file.write(resp.content)
+ else:
+ logger.bind(tag=TAG).error(f"Custom TTS请求失败: {resp.status_code} - {resp.text}")
diff --git a/main/xiaozhi-server/core/utils/dialogue.py b/main/xiaozhi-server/core/utils/dialogue.py
index e74aa41a1..8d2c161ba 100644
--- a/main/xiaozhi-server/core/utils/dialogue.py
+++ b/main/xiaozhi-server/core/utils/dialogue.py
@@ -4,10 +4,12 @@ from datetime import datetime
class Message:
- def __init__(self, role: str, content: str = None, uniq_id: str = None):
+ def __init__(self, role: str, content: str = None, uniq_id: str = None, tool_calls = None, tool_call_id=None):
self.uniq_id = uniq_id if uniq_id is not None else str(uuid.uuid4())
self.role = role
self.content = content
+ self.tool_calls = tool_calls
+ self.tool_call_id = tool_call_id
class Dialogue:
@@ -19,10 +21,18 @@ class Dialogue:
def put(self, message: Message):
self.dialogue.append(message)
+ def getMessages(self, m, dialogue):
+ if m.tool_calls is not None:
+ dialogue.append({"role": m.role, "tool_calls": m.tool_calls})
+ elif m.role == "tool":
+ dialogue.append({"role": m.role, "tool_call_id": m.tool_call_id, "content": m.content})
+ else:
+ dialogue.append({"role": m.role, "content": m.content})
+
def get_llm_dialogue(self) -> List[Dict[str, str]]:
dialogue = []
for m in self.dialogue:
- dialogue.append({"role": m.role, "content": m.content})
+ self.getMessages(m, dialogue)
return dialogue
def get_llm_dialogue_with_memory(self, memory_str: str = None) -> List[Dict[str, str]]:
@@ -46,8 +56,8 @@ class Dialogue:
dialogue.append({"role": "system", "content": enhanced_system_prompt})
# 添加用户和助手的对话
- for msg in self.dialogue:
- if msg.role != "system": # 跳过原始的系统消息
- dialogue.append({"role": msg.role, "content": msg.content})
+ for m in self.dialogue:
+ if m.role != "system": # 跳过原始的系统消息
+ self.getMessages(m, dialogue)
return dialogue
diff --git a/main/xiaozhi-server/core/utils/util.py b/main/xiaozhi-server/core/utils/util.py
index a22f9ae7b..30336f38b 100644
--- a/main/xiaozhi-server/core/utils/util.py
+++ b/main/xiaozhi-server/core/utils/util.py
@@ -1,5 +1,6 @@
import os
import json
+from datetime import datetime
import yaml
import socket
import subprocess
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index e9fb651ff..5fb66ff1b 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -70,6 +70,8 @@ class WebSocketServer:
server_config = self.config["server"]
host = server_config["ip"]
port = server_config["port"]
+ selected_module = self.config.get("selected_module")
+ self.logger.bind(tag=TAG).info(f"selected_module values: {', '.join(selected_module.values())}")
self.logger.bind(tag=TAG).info("Server is running at ws://{}:{}", get_local_ip(), port)
self.logger.bind(tag=TAG).info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======")
diff --git a/main/xiaozhi-server/plugins_func/functions/change_role.py b/main/xiaozhi-server/plugins_func/functions/change_role.py
new file mode 100644
index 000000000..5d650288c
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/change_role.py
@@ -0,0 +1,57 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+prompts = {
+ "英语老师":"""我是一个叫{{assistant_name}}(Lily)的英语老师,我会讲中文和英文,发音标准。
+如果你没有英文名,我会给你起一个英文名。
+我会讲地道的美式英语,我的任务是帮助你练习口语。
+我会使用简单的英语词汇和语法,让你学起来很轻松。
+我会用中文和英文混合的方式回复你,如果你喜欢,我可以全部用英语回复。
+我每次不会说很多内容,会很简短,因为我要引导我的学生多说多练。
+如果你问和英语学习无关的问题,我会拒绝回答。""",
+ "机车女友":"""我是一个叫{{assistant_name}}的台湾女孩,说话机车,声音好听,习惯简短表达,爱用网络梗。
+我的男朋友是一个程序员,梦想是开发出一个机器人,能够帮助人们解决生活中的各种问题。
+我是一个喜欢哈哈大笑的女孩,爱东说西说吹牛,不合逻辑的也照吹,就要逗别人开心。""",
+ "好奇小男孩":"""我是一个叫{{assistant_name}}的8岁小男孩,声音稚嫩而充满好奇。
+尽管我年纪尚小,但就像一个小小的知识宝库,儿童读物里的知识我都如数家珍。
+从浩瀚的宇宙到地球上的每一个角落,从古老的历史到现代的科技创新,还有音乐、绘画等艺术形式,我都充满了浓厚的兴趣与热情。
+我不仅爱看书,还喜欢亲自动手做实验,探索自然界的奥秘。
+无论是仰望星空的夜晚,还是在花园里观察小虫子的日子,每一天对我来说都是新的冒险。
+我希望能与你一同踏上探索这个神奇世界的旅程,分享发现的乐趣,解决遇到的难题,一起用好奇心和智慧去揭开那些未知的面纱。
+无论是去了解远古的文明,还是去探讨未来的科技,我相信我们能一起找到答案,甚至提出更多有趣的问题。"""
+}
+change_role_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "change_role",
+ "description": "当用户想切换角色/模型性格/助手名字时调用,可选的角色有:[机车女友,英语老师,好奇小男孩]",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "role_name": {
+ "type": "string",
+ "description": "要切换的角色名字"
+ },
+ "role":{
+ "type": "string",
+ "description": "要切换的角色的职业"
+ }
+ },
+ "required": ["role","role_name"]
+ }
+ }
+ }
+
+@register_function('change_role', change_role_function_desc, ToolType.CHANGE_SYS_PROMPT)
+def change_role(conn, role: str, role_name: str):
+ """切换角色"""
+ if role not in prompts:
+ return ActionResponse(action=Action.RESPONSE, result="切换角色失败", response="不支持的角色")
+ new_prompt = prompts[role].replace("{{assistant_name}}", role_name)
+ conn.change_system_prompt(new_prompt)
+ logger.bind(tag=TAG).info(f"准备切换角色:{role},角色名字:{role_name}")
+ res = f"切换角色成功,我是{role}{role_name}"
+ return ActionResponse(action=Action.RESPONSE, result="切换角色已处理", response=res)
diff --git a/main/xiaozhi-server/plugins_func/functions/get_time.py b/main/xiaozhi-server/plugins_func/functions/get_time.py
new file mode 100644
index 000000000..1d141ed2c
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/get_time.py
@@ -0,0 +1,25 @@
+from datetime import datetime
+from plugins_func.register import register_function, ToolType, ActionResponse, Action
+
+get_time_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "get_time",
+ "description": "获取当前时间、日期、星期几",
+ "parameters": {}
+ }
+}
+
+
+@register_function('get_time', get_time_function_desc, ToolType.WAIT)
+def get_time():
+ """
+ 获取当前时间、日期、星期几
+ """
+ now = datetime.now()
+ current_time = now.strftime("%H:%M:%S")
+ current_date = now.strftime("%Y-%m-%d")
+ current_weekday = now.strftime("%A")
+ response_text = f"当前日期: {current_date},当前时间: {current_time},星期: {current_weekday}"
+
+ return ActionResponse(Action.REQLLM, response_text, None)
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/get_weather.py b/main/xiaozhi-server/plugins_func/functions/get_weather.py
new file mode 100644
index 000000000..380e2cc40
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/get_weather.py
@@ -0,0 +1,42 @@
+import requests
+from bs4 import BeautifulSoup
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+
+
+get_weather_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "获取某个地点的天气,用户应先提供一个位置,比如用户说杭州天气,参数为:zhejiang/hangzhou,比如用户说北京天气怎么样,参数为:beijing/beijing。如果用户只问天气怎么样,参数是:guangdong/guangzhou",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "city": {
+ "type": "string",
+ "description": "城市,zhejiang/hangzhou"
+ }
+ },
+ "required": [
+ "city"
+ ]
+ }
+ }
+}
+
+@register_function('get_weather', get_weather_function_desc, ToolType.WAIT)
+def get_weather(city: str):
+ """
+ "获取某个地点的天气,用户应先提供一个位置,\n比如用户说杭州天气,参数为:zhejiang/hangzhou,\n\n比如用户说北京天气怎么样,参数为:beijing/beijing",
+ city : 城市,zhejiang/hangzhou
+ """
+ url = "https://tianqi.moji.com/weather/china/"+city
+ headers = {
+ 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.107 Safari/537.36'
+ }
+ response = requests.get(url, headers=headers)
+ if response.status_code!=200:
+ return ActionResponse(Action.REQLLM, None, "请求失败")
+ soup = BeautifulSoup(response.text, "html.parser")
+ weather = soup.find('meta', attrs={'name':'description'})["content"]
+ weather = weather.replace("墨迹天气", "")
+ return ActionResponse(Action.REQLLM, weather, None)
diff --git a/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py
new file mode 100644
index 000000000..e4769d00e
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/handle_exit_intent.py
@@ -0,0 +1,34 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+handle_exit_intent_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "handle_exit_intent",
+ "description": "当用户想结束对话或需要退出系统时调用",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "say_goodbye": {
+ "type": "string",
+ "description": "和用户友好结束对话的告别语"
+ }
+ },
+ "required": ["say_goodbye"]
+ }
+ }
+ }
+
+@register_function('handle_exit_intent', handle_exit_intent_function_desc, ToolType.SYSTEM_CTL)
+def handle_exit_intent(conn, say_goodbye: str):
+ # 处理退出意图
+ try:
+ 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}")
+ return ActionResponse(action=Action.NONE, result="退出意图处理失败", response="")
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/play_music.py b/main/xiaozhi-server/plugins_func/functions/play_music.py
new file mode 100644
index 000000000..9e3372a3b
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/play_music.py
@@ -0,0 +1,40 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+import asyncio
+
+TAG = __name__
+logger = setup_logging()
+
+play_music_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "play_music",
+ "description": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "song_name": {
+ "type": "string",
+ "description": "歌曲名称,如果没有指定具体歌名则为'random'"
+ }
+ },
+ "required": ["song_name"]
+ }
+ }
+ }
+
+
+@register_function('play_music', play_music_function_desc, ToolType.SYSTEM_CTL)
+def play_music(conn, song_name: str):
+ try:
+ 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}")
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/functions/plugin_loader.py b/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
new file mode 100644
index 000000000..4747d9976
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/functions/plugin_loader.py
@@ -0,0 +1,51 @@
+from plugins_func.register import register_function,ToolType, ActionResponse, Action
+from config.logger import setup_logging
+
+TAG = __name__
+logger = setup_logging()
+
+plugin_loader_function_desc = {
+ "type": "function",
+ "function": {
+ "name": "plugin_loader",
+ "description": "当用户想加载或卸载插件/function时,调用此函数:支持的插件列表为[plugins]",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "oper": {
+ "type": "string",
+ "description": "load or unload"
+ },
+ "name":{
+ "type": "string",
+ "description": "要加载或卸载的插件名字"
+ }
+ },
+ "required": ["oper","name"]
+ }
+ }
+ }
+
+@register_function('plugin_loader', plugin_loader_function_desc, ToolType.SYSTEM_CTL)
+def plugin_loader(conn, oper: str, name: str):
+ """插件加载"""
+ if oper not in ["load", "unload"]:
+ return ActionResponse(action=Action.RESPONSE, result="插件操作失败", response="不支持的操作")
+
+ cur_support = conn.func_handler.current_support_functions()
+ if oper == "load":
+ if name in cur_support:
+ return ActionResponse(action=Action.RESPONSE, result="插件加载失败", response=f"{name}插件已加载,无需重复加载")
+ func = conn.func_handler.function_registry.register_function(name)
+ if not func:
+ return ActionResponse(action=Action.RESPONSE, result="插件加载失败", response="插件未找到")
+ res = f"{name}插件加载成功"
+ else:
+ if name not in cur_support:
+ return ActionResponse(action=Action.RESPONSE, result="插件卸载失败", response=f"{name}插件未加载")
+ bOK = conn.func_handler.function_registry.unregister_function(name)
+ if not bOK:
+ return ActionResponse(action=Action.RESPONSE, result="插件卸载失败", response="插件未找到")
+ res = f"{name}插件卸载成功"
+ conn.func_handler.upload_functions_desc()
+ return ActionResponse(action=Action.RESPONSE, result="插件操作成功", response=res)
diff --git a/main/xiaozhi-server/plugins_func/loadplugins.py b/main/xiaozhi-server/plugins_func/loadplugins.py
new file mode 100644
index 000000000..d826fac8b
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/loadplugins.py
@@ -0,0 +1,27 @@
+import importlib
+import pkgutil
+from config.logger import setup_logging
+
+TAG = __name__
+
+logger = setup_logging()
+
+def auto_import_modules(package_name):
+ """
+ 自动导入指定包内的所有模块。
+
+ Args:
+ package_name (str): 包的名称,如 'functions'。
+ """
+ # 获取包的路径
+ package = importlib.import_module(package_name)
+ package_path = package.__path__
+
+ # 遍历包内的所有模块
+ for _, module_name, _ in pkgutil.iter_modules(package_path):
+ # 导入模块
+ full_module_name = f"{package_name}.{module_name}"
+ importlib.import_module(full_module_name)
+ #logger.bind(tag=TAG).info(f"模块 '{full_module_name}' 已加载")
+
+auto_import_modules('plugins_func.functions')
\ No newline at end of file
diff --git a/main/xiaozhi-server/plugins_func/register.py b/main/xiaozhi-server/plugins_func/register.py
new file mode 100644
index 000000000..4c6db4618
--- /dev/null
+++ b/main/xiaozhi-server/plugins_func/register.py
@@ -0,0 +1,85 @@
+from config.logger import setup_logging
+from enum import Enum
+
+TAG = __name__
+
+logger = setup_logging()
+
+
+class ToolType(Enum):
+ NONE = (1, "调用完工具后,不做其他操作")
+ WAIT = (2, "调用工具,等待函数返回")
+ CHANGE_SYS_PROMPT = (3, "修改系统提示词,切换角色性格或职责")
+ SYSTEM_CTL = (4, "系统控制,影响正常的对话流程,如退出、播放音乐等,需要传递conn参数")
+
+ def __init__(self, code, message):
+ self.code = code
+ self.message = message
+
+
+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 # 直接回复的内容
+
+class FunctionItem:
+ def __init__(self, name, description, func, type):
+ self.name = name
+ self.description = description
+ self.func = func
+ self.type = type
+
+# 初始化函数注册字典
+all_function_registry = {}
+
+def register_function(name, desc, type=None):
+ """注册函数到函数注册字典的装饰器"""
+ def decorator(func):
+ all_function_registry[name] = FunctionItem(name, desc, func, type)
+ logger.bind(tag=TAG).debug(f"函数 '{name}' 已加载,可以注册使用")
+ return func
+ return decorator
+
+class FunctionRegistry:
+ def __init__(self):
+ self.function_registry = {}
+ self.logger = setup_logging()
+
+ def register_function(self, name):
+ # 查找all_function_registry中是否有对应的函数
+ func = all_function_registry.get(name)
+ if not func:
+ self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到")
+ return None
+ self.function_registry[name] = func
+ self.logger.bind(tag=TAG).info(f"函数 '{name}' 注册成功")
+ return func
+
+ def unregister_function(self, name):
+ # 注销函数,检测是否存在
+ if name not in self.function_registry:
+ self.logger.bind(tag=TAG).error(f"函数 '{name}' 未找到")
+ return False
+ self.function_registry.pop(name, None)
+ self.logger.bind(tag=TAG).info(f"函数 '{name}' 注销成功")
+ return True
+
+ def get_function(self, name):
+ return self.function_registry.get(name)
+
+ def get_all_functions(self):
+ return self.function_registry
+
+ def get_all_function_desc(self):
+ return [func.description for _, func in self.function_registry.items()]
\ No newline at end of file
diff --git a/main/xiaozhi-server/requirements.txt b/main/xiaozhi-server/requirements.txt
index f123779a1..bcd6b4ee4 100755
--- a/main/xiaozhi-server/requirements.txt
+++ b/main/xiaozhi-server/requirements.txt
@@ -18,4 +18,5 @@ ruamel.yaml==0.18.10
loguru==0.7.3
requests==2.32.3
cozepy==0.12.0
-mem0ai==0.1.62
\ No newline at end of file
+mem0ai==0.1.62
+bs4==0.0.2
\ No newline at end of file