-
确定
+
确定
@@ -234,7 +234,7 @@ export default {
filteredDeviceList: [], // 过滤后的设备列表
switchValue: false,
addDeviceDialogVisible: false,
- deviceCode: "",
+ deviceCode: "", // 设备验证码
settingDevice: false,
form: {
name: "",
@@ -257,7 +257,7 @@ export default {
},
methods: {
showAddDialog() {
- this.addDeviceDialogVisible = true;
+ this.addDeviceDialogVisible = true;
},
clickSettingDevice() {
this.settingDevice = true
@@ -312,6 +312,23 @@ export default {
this.$message.info('已取消解绑');
});
},
+ // 添加设备
+ addDevice() {
+ if (!this.deviceCode) {
+ this.$message.warning('请输入设备验证码');
+ return;
+ }
+
+ Api.user.bindDevice(this.deviceCode, ({ data }) => {
+ if (data.code === 0) {
+ this.$message.success('设备绑定成功');
+ this.addDeviceDialogVisible = false;
+ this.getList(); // 刷新设备列表
+ } else {
+ this.$message.error(data.msg || '设备绑定失败');
+ }
+ });
+ }
},
mounted() {
this.fetchUserInfo(); // 组件加载时获取用户信息
diff --git a/main/manager-web/src/views/login.vue b/main/manager-web/src/views/login.vue
index 6f6759e7a..d52d2c9bf 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/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 c8fbdb9ff..015b25513 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -53,6 +53,14 @@ prompt: |
请注意,要像一个人一样说话,请不要回复表情符号、代码、和xml标签。
当前时间是:{date_time},现在我正在和你进行语音聊天,我们开始吧。
如果用户希望结束对话,请在最后说“拜拜”或“再见”。
+ 下面是我家智能设备,可以通过homeassistant控制
+ 房间,设备别名,设备id
+ 书房,吸顶灯,light.649e3159aa36
+ 书房,homepod播放器,media_player.shu_fang_id
+ 书房,灯带,light.plug
+ 书房,窗帘,cover.curtain_158d000710f50
+ 书房,显示器挂灯,light.yeelink_lamp
+
# 使用完声音文件后删除文件(Delete the sound file when you are done using it)
delete_audio: true
@@ -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类型
@@ -311,36 +320,6 @@ TTS:
media_type: "wav"
streaming_mode: false
threshold: 30
- GSV:
- # GSV原神本地语音合成
- # 整合包下载:https://pan.ai-hobbyist.com/Infer%20Packs/TTS
- # 国内镜像:https://alist.hancat.work/d/cdn/GPT-Sovits%E8%AF%AD%E9%9F%B3%E5%90%88%E6%88%90%E6%95%B4%E5%90%88%E5%8C%85%EF%BC%8C%E6%94%AF%E6%8C%81%E5%A4%9A%E4%BA%BA%E5%AF%B9%E8%AF%9D%E3%80%82%E6%B0%B8%E4%B9%85%E5%85%8D%E8%B4%B9%EF%BC%8C%E4%B8%A5%E7%A6%81%E5%80%92%E5%8D%96%EF%BC%81.7z
- # 本TTS需要配合模型来使用,模型可以去这里下载:
- # 二次元 & 游戏角色 GPT-Sovits V2 语音合成模型:https://www.modelscope.cn/models/aihobbyist/Anime_GPT-Sovits_Models
- # 下载后将其解压到model文件夹
- # URL需要修改批处理文件才可生效,默认WebUI端口号为8080,API端口号为WebUI端口号+1
- url: "http://127.0.0.1:9881/infer_single"
- app_key: ""
- audio_dl_url: "http://127.0.0.1:9881"
- model_name: "【原神】须弥"
- speaker_name: "纳西妲"
- prompt_text_lang: "中文"
- emocton: "中立_neutral"
- text_lang: "中文"
- top_k: 10
- top_p: 1
- temperature: 1
- text_split_method: "按标点符号切"
- batch_size: 10
- batch_size: 0.75
- split_bucket: true
- speed_facter: 1
- fragment_interval: 0.3
- media_type: "wav"
- parallel_infer: true
- repetition_penalty: 1.35
- seed: -1
- output_file: tmp/
MinimaxTTS:
# Minimax语音合成服务,需要先在minimax平台创建账户充值,并获取登录信息
# 平台地址:https://platform.minimaxi.com/
@@ -463,4 +442,4 @@ manager:
enabled: false
ip: 0.0.0.0
port: 8002
-use_private_config: false
\ No newline at end of file
+use_private_config: false
diff --git a/main/xiaozhi-server/config/functionCallConfig.py b/main/xiaozhi-server/config/functionCallConfig.py
index dd9b55fc4..b8b35771a 100644
--- a/main/xiaozhi-server/config/functionCallConfig.py
+++ b/main/xiaozhi-server/config/functionCallConfig.py
@@ -17,20 +17,47 @@ FunctionCallConfig = [
}
},
{
- "type": "function",
- "function": {
- "name": "play_music",
- "description": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎",
+ "type": "function",
+ "function": {
+ "name": "hass_toggle_device",
+ "description": "用homeassistant帮助用户打开或关闭设备",
"parameters": {
"type": "object",
"properties": {
- "song_name": {
+ "state": {
"type": "string",
- "description": "歌曲名称,如果没有指定具体歌名则为'random'"
+ "enum": ["on", "off"],
+ "description": "指定开还是关,开是on,关是off"
+ },
+ "entity_id": {
+ "type": "string",
+ "description": "需要操作的设备id,homeassistant里的entity_id"
}
},
- "required": ["song_name"]
+ "required": ["state", "entity_id"]
+ }
+ }
+ },
+ {
+ "type": "function",
+ "function": {
+ "name": "hass_play_music",
+ "description": "用户想听音乐、有声书的时候使用,在房间的媒体播放器(media_player)里播放对应音频",
+ "parameters": {
+ "type": "object",
+ "properties": {
+ "media_content_id": {
+ "type": "string",
+ "description": "可以是音乐或有声书的专辑名称、歌曲名、演唱者,如果未指定就填random"
+ },
+ "entity_id": {
+ "type": "string",
+ "description": "需要操作的音箱的设备id,homeassistant里的entity_id,media_player开头"
+ }
+ },
+ "required": ["media_content_id", "entity_id"]
}
}
}
- ]
\ No newline at end of file
+
+ ]
diff --git a/main/xiaozhi-server/core/connection.py b/main/xiaozhi-server/core/connection.py
index 65696403d..0ea3d28ae 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -28,7 +28,7 @@ class TTSException(RuntimeError):
class ConnectionHandler:
- def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music, _memory, _intent):
+ def __init__(self, config: Dict[str, Any], _vad, _asr, _llm, _tts, _music, _hass, _memory, _intent):
self.config = config
self.logger = setup_logging()
self.auth = AuthMiddleware(config)
@@ -90,13 +90,12 @@ class ConnectionHandler:
self.auth_code_gen = AuthCodeGenerator.get_instance()
self.is_device_verified = False # 添加设备验证状态标志
self.music_handler = _music
+ self.hass_handler = _hass
self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = False
if self.config["selected_module"]["Intent"] == 'function_call':
self.use_function_call_mode = True
- self.logger.bind(tag=TAG).info(f"use_function_call_mode:{self.use_function_call_mode}")
-
async def handle_connection(self, ws):
try:
# 获取并验证headers
diff --git a/main/xiaozhi-server/core/handle/hassHandler.py b/main/xiaozhi-server/core/handle/hassHandler.py
new file mode 100644
index 000000000..24d19cb14
--- /dev/null
+++ b/main/xiaozhi-server/core/handle/hassHandler.py
@@ -0,0 +1,64 @@
+import requests
+from config.logger import setup_logging
+
+
+class HassHandler:
+ def __init__(self, config):
+ self.config = config
+ self.base_url = config["LLM"]['HomeAssistant']['base_url']
+ self.api_key = config["LLM"]['HomeAssistant']['api_key']
+ async def hass_toggle_device(self, conn, entity_id, state):
+ domains = entity_id.split(".")
+ if len(domains) > 1:
+ domain = domains[0]
+ else:
+ return "执行失败,错误的设备id"
+
+ if state == "on":
+ description = "打开"
+ if domain == 'cover':
+ action = "open_cover"
+ elif domain == 'vacuum':
+ action = "start"
+ else:
+ action = "turn_on"
+ elif state == "off":
+ description = "关闭"
+ if domain == 'cover':
+ action = "close_cover"
+ elif domain == 'vacuum':
+ action = "stop"
+ else:
+ action = "turn_off"
+ else:
+ return "执行失败,未知的action"
+ url = f"{self.base_url}/api/services/{domain}/{action}"
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json"
+ }
+ data = {
+ "entity_id": entity_id
+ }
+
+ response = requests.post(url, headers=headers, json=data)
+ if response.status_code == 200:
+ return f"设备已{description}"
+ else:
+ return f"切换失败,错误码: {response.status_code}"
+
+ async def hass_play_music(self, conn, entity_id, media_content_id):
+ url = f"{self.base_url}/api/services/music_assistant/play_media"
+ headers = {
+ "Authorization": f"Bearer {self.api_key}",
+ "Content-Type": "application/json"
+ }
+ data = {
+ "entity_id": entity_id,
+ "media_id": media_content_id
+ }
+ response = requests.post(url, headers=headers, json=data)
+ if response.status_code == 200:
+ return f"正在播放{media_content_id}的音乐"
+ else:
+ return f"音乐播放失败,错误码: {response.status_code}"
diff --git a/main/xiaozhi-server/core/handle/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index da0f5c91f..d1c8afe7c 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -2,6 +2,7 @@ from config.logger import setup_logging
import json
from core.handle.sendAudioHandle import send_stt_message
from core.utils.dialogue import Message
+from core.utils.util import remove_punctuation_and_length
from config.functionCallConfig import FunctionCallConfig
import asyncio
from enum import Enum
@@ -66,6 +67,39 @@ def handle_llm_function_call(conn, function_call_data):
return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?")
except Exception as e:
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
+
+ elif function_name == "hass_play_music":
+ #hass播放音乐
+ try:
+ arguments = json.loads(function_call_data["arguments"])
+ entity_id = arguments["entity_id"]
+ media_content_id = arguments["media_content_id"]
+
+ future = asyncio.run_coroutine_threadsafe(
+ conn.hass_handler.hass_play_music(conn, entity_id, media_content_id),
+ conn.loop
+ )
+ future.result()
+ return ActionResponse(action=Action.RESPONSE, result="音乐已播放", response=f"正在为你播放{media_content_id}")
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
+
+ elif function_name == "hass_toggle_device":
+ #hass控制设备
+ try:
+ arguments = json.loads(function_call_data["arguments"])
+ state = arguments["state"]
+ entity_id = arguments["entity_id"]
+
+ future = asyncio.run_coroutine_threadsafe(
+ conn.hass_handler.hass_toggle_device(conn, entity_id, state),
+ conn.loop
+ )
+ ha_response = future.result()
+ return ActionResponse(action=Action.RESPONSE, result="执行成功", response=ha_response)
+ except Exception as e:
+ logger.bind(tag=TAG).error(f"处理控制设备意图错误: {e}")
+
else:
return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="没有找到对应的函数处理相对于的功能呢,你可以需要添加预设的对应函数处理呢")
except Exception as e:
@@ -93,8 +127,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 +139,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 +158,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/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/tts/GSV.py b/main/xiaozhi-server/core/providers/tts/GSV.py
deleted file mode 100644
index 7a156c293..000000000
--- a/main/xiaozhi-server/core/providers/tts/GSV.py
+++ /dev/null
@@ -1,123 +0,0 @@
-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)
- # POST请求地址
- self.url = config.get("url")
- # 从配置中加载所有参数
- self.app_key = config.get("app_key")
- self.audio_dl_url = config.get("audio_dl_url")
- self.model_name = config.get("model_name")
- self.speaker_name = config.get("speaker_name")
- self.prompt_text_lang = config.get("prompt_text_lang")
- self.emotion = config.get("emotion")
- self.text_lang = config.get("text_lang")
- self.top_k = config.get("top_k")
- self.top_p = config.get("top_p")
- self.temperature = config.get("temperature")
- self.text_split_method = config.get("text_split_method")
- self.batch_size = config.get("batch_size")
- self.batch_threshold = config.get("batch_size")
- self.split_bucket = config.get("split_bucket")
- self.speed_facter = config.get("speed_facter")
- self.fragment_interval = config.get("fragment_interval")
- self.media_type = config.get("media_type")
- self.parallel_infer = config.get("parallel_infer")
- self.repetition_penalty = config.get("repetition_penalty")
- self.seed = config.get("seed")
-
- def generate_filename(self):
- """根据媒体类型生成文件名"""
- extension = f".{self.media_type}"
- return os.path.join(
- self.output_file,
- f"tts-{datetime.now().date()}@{uuid.uuid4().hex}{extension}"
- )
-
- async def text_to_speak(self, text, output_file):
- """文本转语音并保存音频文件"""
- # 构造请求体
- request_body = {
- "app_key": self.app_key,
- "audio_dl_url": self.audio_dl_url,
- "model_name": self.model_name,
- "speaker_name": self.speaker_name,
- "prompt_text_lang": self.prompt_text_lang,
- "emotion": self.emotion,
- "text": text,
- "text_lang": self.text_lang,
- "top_k": self.top_k,
- "top_p": self.top_p,
- "temperature": self.temperature,
- "text_split_method": self.text_split_method,
- "batch_size": self.batch_size,
- "batch_threshold": self.batch_threshold,
- "split_bucket": self.split_bucket,
- "speed_facter": self.speed_facter,
- "fragment_interval": self.fragment_interval,
- "media_type": self.media_type,
- "parallel_infer": self.parallel_infer,
- "repetition_penalty": self.repetition_penalty,
- "seed": self.seed
- }
-
- body = {
- "app_key": "",
- "audio_dl_url": "http://127.0.0.1:9881",
- "model_name": "【原神】须弥",
- "speaker_name": "纳西妲",
- "prompt_text_lang": "中文",
- "emotion": "中立_neutral",
- "text": text,
- "text_lang": "中文",
- "top_k": 10,
- "top_p": 1,
- "temperature": 1,
- "text_split_method": "按标点符号切",
- "batch_size": 10,
- "batch_threshold": 0.75,
- "split_bucket": True,
- "speed_facter": 1,
- "fragment_interval": 0.3,
- "media_type": "wav",
- "parallel_infer": True,
- "repetition_penalty": 1.35,
- "seed": -1
- }
-
- try:
- # 发送POST请求
- resp = requests.post(self.url, json=body)
- resp.raise_for_status()
-
- # 解析响应
- result = resp.json()
- if "audio_url" not in result:
- logger.bind(tag=TAG).error("响应中缺少音频地址")
- return
-
- # 下载音频文件
- audio_resp = requests.get(result["audio_url"])
- audio_resp.raise_for_status()
-
- # 保存文件
- with open(output_file, "wb") as f:
- f.write(audio_resp.content)
-
- logger.bind(tag=TAG).info(f"音频文件已保存至: {output_file}")
-
- except requests.exceptions.HTTPError as e:
- logger.bind(tag=TAG).error(f"HTTP请求失败: {str(e)}")
- except requests.exceptions.JSONDecodeError:
- logger.bind(tag=TAG).error("响应解析失败,无效的JSON格式")
- except Exception as e:
- logger.bind(tag=TAG).error(f"语音合成失败: {str(e)}")
\ No newline at end of file
diff --git a/main/xiaozhi-server/core/websocket_server.py b/main/xiaozhi-server/core/websocket_server.py
index 14d16497d..afa664c29 100644
--- a/main/xiaozhi-server/core/websocket_server.py
+++ b/main/xiaozhi-server/core/websocket_server.py
@@ -13,7 +13,7 @@ class WebSocketServer:
def __init__(self, config: dict):
self.config = config
self.logger = setup_logging()
- self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent = self._create_processing_instances()
+ self._vad, self._asr, self._llm, self._tts, self._music, self._hass, self._memory, self.intent = self._create_processing_instances()
self.active_connections = set() # 添加全局连接记录
def _create_processing_instances(self):
@@ -65,6 +65,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: {selected_module}")
self.logger.bind(tag=TAG).info("Server is running at ws://{}:{}", get_local_ip(), port)
self.logger.bind(tag=TAG).info("=======上面的地址是websocket协议地址,请勿用浏览器访问=======")
@@ -78,7 +80,7 @@ class WebSocketServer:
async def _handle_connection(self, websocket):
"""处理新连接,每次创建独立的ConnectionHandler"""
# 创建ConnectionHandler时传入当前server实例
- handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._music, self._memory, self.intent)
+ handler = ConnectionHandler(self.config, self._vad, self._asr, self._llm, self._tts, self._music, self._hass, self._memory, self.intent)
self.active_connections.add(handler)
try:
await handler.handle_connection(websocket)