mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
update:intent_llm音乐插件化调用
This commit is contained in:
parent
8376b6f0f2
commit
f3e7fa8a02
5 changed files with 58 additions and 31 deletions
|
|
@ -1,5 +1,6 @@
|
||||||
from config.logger import setup_logging
|
from config.logger import setup_logging
|
||||||
import json
|
import json
|
||||||
|
import uuid
|
||||||
from core.handle.sendAudioHandle import send_stt_message
|
from core.handle.sendAudioHandle import send_stt_message
|
||||||
from core.utils.util import remove_punctuation_and_length
|
from core.utils.util import remove_punctuation_and_length
|
||||||
|
|
||||||
|
|
@ -8,30 +9,16 @@ logger = setup_logging()
|
||||||
|
|
||||||
|
|
||||||
async def handle_user_intent(conn, text):
|
async def handle_user_intent(conn, text):
|
||||||
"""
|
|
||||||
Handle user intent before starting chat
|
|
||||||
|
|
||||||
Args:
|
|
||||||
conn: Connection object
|
|
||||||
text: User's text input
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
bool: True if intent was handled, False if should proceed to chat
|
|
||||||
"""
|
|
||||||
# 检查是否有明确的退出命令
|
# 检查是否有明确的退出命令
|
||||||
if await check_direct_exit(conn, text):
|
if await check_direct_exit(conn, text):
|
||||||
return True
|
return True
|
||||||
|
|
||||||
if conn.use_function_call_mode:
|
if conn.use_function_call_mode:
|
||||||
# 使用支持function calling的聊天方法,不再进行意图分析
|
# 使用支持function calling的聊天方法,不再进行意图分析
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 使用LLM进行意图分析
|
# 使用LLM进行意图分析
|
||||||
intent = await analyze_intent_with_llm(conn, text)
|
intent = await analyze_intent_with_llm(conn, text)
|
||||||
|
|
||||||
if not intent:
|
if not intent:
|
||||||
return False
|
return False
|
||||||
|
|
||||||
# 处理各种意图
|
# 处理各种意图
|
||||||
return await process_intent_result(conn, intent, text)
|
return await process_intent_result(conn, intent, text)
|
||||||
|
|
||||||
|
|
@ -58,7 +45,6 @@ async def analyze_intent_with_llm(conn, text):
|
||||||
dialogue = conn.dialogue
|
dialogue = conn.dialogue
|
||||||
try:
|
try:
|
||||||
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
|
intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
|
||||||
|
|
||||||
# 尝试解析JSON结果
|
# 尝试解析JSON结果
|
||||||
try:
|
try:
|
||||||
intent_data = json.loads(intent_result)
|
intent_data = json.loads(intent_result)
|
||||||
|
|
@ -79,9 +65,6 @@ async def process_intent_result(conn, intent, original_text):
|
||||||
# 处理退出意图
|
# 处理退出意图
|
||||||
if "结束聊天" in intent:
|
if "结束聊天" in intent:
|
||||||
logger.bind(tag=TAG).info(f"识别到退出意图: {intent}")
|
logger.bind(tag=TAG).info(f"识别到退出意图: {intent}")
|
||||||
|
|
||||||
# 如果正在播放音乐,可以关了 TODO
|
|
||||||
|
|
||||||
# 如果是明确的离别意图,发送告别语并关闭连接
|
# 如果是明确的离别意图,发送告别语并关闭连接
|
||||||
await send_stt_message(conn, original_text)
|
await send_stt_message(conn, original_text)
|
||||||
conn.executor.submit(conn.chat_and_close, original_text)
|
conn.executor.submit(conn.chat_and_close, original_text)
|
||||||
|
|
@ -90,10 +73,37 @@ async def process_intent_result(conn, intent, original_text):
|
||||||
# 处理播放音乐意图
|
# 处理播放音乐意图
|
||||||
if "播放音乐" in intent:
|
if "播放音乐" in intent:
|
||||||
logger.bind(tag=TAG).info(f"识别到音乐播放意图: {intent}")
|
logger.bind(tag=TAG).info(f"识别到音乐播放意图: {intent}")
|
||||||
await conn.music_handler.handle_music_command(conn, intent)
|
# 调用play_music函数来播放音乐
|
||||||
|
song_name = extract_text_in_brackets(intent)
|
||||||
|
function_id = str(uuid.uuid4().hex)
|
||||||
|
function_name = "play_music"
|
||||||
|
function_arguments = '{ "song_name": "' + song_name + '" }'
|
||||||
|
|
||||||
|
function_call_data = {
|
||||||
|
"name": function_name,
|
||||||
|
"id": function_id,
|
||||||
|
"arguments": function_arguments
|
||||||
|
}
|
||||||
|
conn.func_handler.handle_llm_function_call(conn, function_call_data)
|
||||||
return True
|
return True
|
||||||
|
|
||||||
# 其他意图处理可以在这里扩展
|
# 其他意图处理可以在这里扩展
|
||||||
|
|
||||||
# 默认返回False,表示继续常规聊天流程
|
# 默认返回False,表示继续常规聊天流程
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
|
||||||
|
def extract_text_in_brackets(s):
|
||||||
|
"""
|
||||||
|
从字符串中提取中括号内的文字
|
||||||
|
|
||||||
|
:param s: 输入字符串
|
||||||
|
:return: 中括号内的文字,如果不存在则返回空字符串
|
||||||
|
"""
|
||||||
|
left_bracket_index = s.find('[')
|
||||||
|
right_bracket_index = s.find(']')
|
||||||
|
|
||||||
|
if left_bracket_index != -1 and right_bracket_index != -1 and left_bracket_index < right_bracket_index:
|
||||||
|
return s[left_bracket_index + 1:right_bracket_index]
|
||||||
|
else:
|
||||||
|
return ""
|
||||||
|
|
@ -44,6 +44,7 @@ class MusicManager:
|
||||||
|
|
||||||
def get_music_files(self):
|
def get_music_files(self):
|
||||||
music_files = []
|
music_files = []
|
||||||
|
music_file_names = []
|
||||||
for file in self.music_dir.rglob("*"):
|
for file in self.music_dir.rglob("*"):
|
||||||
# 判断是否是文件
|
# 判断是否是文件
|
||||||
if file.is_file():
|
if file.is_file():
|
||||||
|
|
@ -54,7 +55,8 @@ class MusicManager:
|
||||||
# music_files.append(str(file.resolve())) # 添加绝对路径
|
# music_files.append(str(file.resolve())) # 添加绝对路径
|
||||||
# 添加相对路径
|
# 添加相对路径
|
||||||
music_files.append(str(file.relative_to(self.music_dir)))
|
music_files.append(str(file.relative_to(self.music_dir)))
|
||||||
return music_files
|
music_file_names.append(os.path.splitext(str(file.relative_to(self.music_dir)))[0])
|
||||||
|
return music_files, music_file_names
|
||||||
|
|
||||||
|
|
||||||
class MusicHandler:
|
class MusicHandler:
|
||||||
|
|
@ -74,7 +76,7 @@ class MusicHandler:
|
||||||
self.refresh_time = 60
|
self.refresh_time = 60
|
||||||
|
|
||||||
# 获取音乐文件列表
|
# 获取音乐文件列表
|
||||||
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
||||||
self.scan_time = time.time()
|
self.scan_time = time.time()
|
||||||
logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}")
|
logger.bind(tag=TAG).debug(f"找到的音乐文件: {self.music_files}")
|
||||||
|
|
||||||
|
|
@ -87,7 +89,7 @@ class MusicHandler:
|
||||||
if os.path.exists(self.music_dir):
|
if os.path.exists(self.music_dir):
|
||||||
if time.time() - self.scan_time > self.refresh_time:
|
if time.time() - self.scan_time > self.refresh_time:
|
||||||
# 刷新音乐文件列表
|
# 刷新音乐文件列表
|
||||||
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
self.music_files, self.music_file_names = MusicManager(self.music_dir, self.music_ext).get_music_files()
|
||||||
self.scan_time = time.time()
|
self.scan_time = time.time()
|
||||||
logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}")
|
logger.bind(tag=TAG).debug(f"刷新的音乐文件: {self.music_files}")
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -89,7 +89,7 @@ class IntentProvider(IntentProviderBase):
|
||||||
|
|
||||||
msgStr += f"User: {text}\n"
|
msgStr += f"User: {text}\n"
|
||||||
user_prompt = f"当前的对话如下:\n{msgStr}"
|
user_prompt = f"当前的对话如下:\n{msgStr}"
|
||||||
prompt_music = f"{self.promot}\n<start>{conn.music_handler.music_files}\n<end>"
|
prompt_music = f"{self.promot}\n<start>{conn.music_handler.music_file_names}\n<end>"
|
||||||
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
logger.bind(tag=TAG).debug(f"User prompt: {prompt_music}")
|
||||||
# 使用LLM进行意图识别
|
# 使用LLM进行意图识别
|
||||||
intent = self.llm.response_no_stream(
|
intent = self.llm.response_no_stream(
|
||||||
|
|
@ -100,8 +100,7 @@ class IntentProvider(IntentProviderBase):
|
||||||
# 使用正则表达式提取 {} 中的内容
|
# 使用正则表达式提取 {} 中的内容
|
||||||
match = re.search(r'\{.*?\}', intent)
|
match = re.search(r'\{.*?\}', intent)
|
||||||
if match:
|
if match:
|
||||||
result = match.group(0) # 获取匹配到的内容(包含 {})
|
result = match.group(0)
|
||||||
print(result) # 输出:{intent: '播放音乐 [中秋月]'}
|
|
||||||
intent = result
|
intent = result
|
||||||
else:
|
else:
|
||||||
intent = "{intent: '继续聊天'}"
|
intent = "{intent: '继续聊天'}"
|
||||||
|
|
|
||||||
|
|
@ -29,12 +29,28 @@ def play_music(conn, song_name: str):
|
||||||
try:
|
try:
|
||||||
music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
|
music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
|
||||||
|
|
||||||
# 执行音乐播放命令
|
# 检查事件循环状态
|
||||||
|
if not conn.loop.is_running():
|
||||||
|
logger.bind(tag=TAG).error("事件循环未运行,无法提交任务")
|
||||||
|
return ActionResponse(action=Action.RESPONSE, result="系统繁忙", response="请稍后再试")
|
||||||
|
|
||||||
|
# 提交异步任务
|
||||||
future = asyncio.run_coroutine_threadsafe(
|
future = asyncio.run_coroutine_threadsafe(
|
||||||
conn.music_handler.handle_music_command(conn, music_intent),
|
conn.music_handler.handle_music_command(conn, music_intent),
|
||||||
conn.loop
|
conn.loop
|
||||||
)
|
)
|
||||||
future.result()
|
|
||||||
return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?")
|
# 非阻塞回调处理
|
||||||
|
def handle_done(f):
|
||||||
|
try:
|
||||||
|
f.result() # 可在此处理成功逻辑
|
||||||
|
logger.bind(tag=TAG).info("播放完成")
|
||||||
|
except Exception as e:
|
||||||
|
logger.bind(tag=TAG).error(f"播放失败: {e}")
|
||||||
|
|
||||||
|
future.add_done_callback(handle_done)
|
||||||
|
|
||||||
|
return ActionResponse(action=Action.RESPONSE, result="指令已接收", response="正在为您播放音乐")
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
|
logger.bind(tag=TAG).error(f"处理音乐意图错误: {e}")
|
||||||
|
return ActionResponse(action=Action.RESPONSE, result=str(e), response="播放音乐时出错了")
|
||||||
Loading…
Reference in a new issue