@@ -63,7 +63,7 @@
+
+
\ No newline at end of file
diff --git a/main/manager-web/vue.config.js b/main/manager-web/vue.config.js
index 01e210fa9..9e72e068b 100644
--- a/main/manager-web/vue.config.js
+++ b/main/manager-web/vue.config.js
@@ -1,14 +1,23 @@
const { defineConfig } = require('@vue/cli-service');
const dotenv = require('dotenv');
+// 确保加载 .env 文件
dotenv.config();
module.exports = defineConfig({
devServer: {
// Bug 修复:将代理配置为环境变量中定义的 API 基础 URL
- proxy: process.env.VUE_APP_API_BASE_URL,
- client: {
- overlay: false,
+ 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/config.yaml b/main/xiaozhi-server/config.yaml
index 5de5e0b9c..c0cf8ff1d 100644
--- a/main/xiaozhi-server/config.yaml
+++ b/main/xiaozhi-server/config.yaml
@@ -58,6 +58,8 @@ delete_audio: true
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120
+# TTS请求超时时间(秒)
+tts_timeout: 10
CMD_exit:
- "退出"
@@ -188,8 +190,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类型
@@ -418,6 +421,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/core/connection.py b/main/xiaozhi-server/core/connection.py
index 77a2936a3..bba25371e 100644
--- a/main/xiaozhi-server/core/connection.py
+++ b/main/xiaozhi-server/core/connection.py
@@ -489,7 +489,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:
@@ -497,7 +498,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/intentHandler.py b/main/xiaozhi-server/core/handle/intentHandler.py
index d94eb96a8..320c47934 100644
--- a/main/xiaozhi-server/core/handle/intentHandler.py
+++ b/main/xiaozhi-server/core/handle/intentHandler.py
@@ -1,6 +1,7 @@
from config.logger import setup_logging
import json
from core.handle.sendAudioHandle import send_stt_message
+from core.utils.util import remove_punctuation_and_length
TAG = __name__
logger = setup_logging()
@@ -37,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:
@@ -55,7 +57,7 @@ async def analyze_intent_with_llm(conn, text):
# 对话历史记录
dialogue = conn.dialogue
try:
- intent_result = await conn.intent.detect_intent(dialogue.dialogue, text)
+ 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 198fa59fa..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,42 +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:
- logger.bind(tag=TAG).info(f"分析用户意图: {text}")
+ 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
)
- intent_result = intent.strip()
- logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
- return intent_result
+ # 使用正则表达式提取大括号中的内容
+ # 使用正则表达式提取 {} 中的内容
+ 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()
\ 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 84737608e..e6f013ca4 100644
--- a/main/xiaozhi-server/core/providers/tts/base.py
+++ b/main/xiaozhi-server/core/providers/tts/base.py
@@ -41,19 +41,20 @@ class TTSProviderBase(ABC):
async def text_to_speak(self, text, output_file):
pass
- def wav_to_opus_data(self, wav_file_path):
- # 使用pydub加载PCM文件
+ def audio_to_opus_data(self, audio_file_path):
+ """音频文件转换为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)
+ audio = AudioSegment.from_file(audio_file_path, format=file_type)
+ # 转换为单声道/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}")