update:优化意图识别的配置

This commit is contained in:
hrz 2025-03-09 16:34:36 +08:00
parent e903fd0bc2
commit 63b326b01c
7 changed files with 77 additions and 80 deletions

View file

@ -58,29 +58,37 @@ delete_audio: true
# 没有语音输入多久后断开连接(秒),默认2分钟,即120秒 # 没有语音输入多久后断开连接(秒),默认2分钟,即120秒
close_connection_no_voice_time: 120 close_connection_no_voice_time: 120
# 是否使用函数调用模式, 默认为false,需要大模型支持tools调用
use_function_call_mode: false
CMD_exit: CMD_exit:
- "退出" - "退出"
- "关闭" - "关闭"
# 具体处理时选择的模块(The module selected for specific processing) # 具体处理时选择的模块(The module selected for specific processing)
selected_module: selected_module:
ASR: FunASR # 语音活动检测模块,默认使用SileroVAD模型
VAD: SileroVAD VAD: SileroVAD
# 语音识别模块,默认使用FunASR本地模型
ASR: FunASR
# 将根据配置名称对应的type调用实际的LLM适配器 # 将根据配置名称对应的type调用实际的LLM适配器
LLM: ChatGLMLLM LLM: ChatGLMLLM
# TTS将根据配置名称对应的type调用实际的TTS适配器 # TTS将根据配置名称对应的type调用实际的TTS适配器
TTS: EdgeTTS TTS: EdgeTTS
Memory: nomem # 记忆模块,默认使用本地压缩记忆,如果想使用超长记忆,推荐使用mem0ai
Memory: mem_local_short
# 意图识别模块,默认不开启。开启后,可以播放音乐、控制音量、识别退出指令
Intent: nointent Intent: nointent
# 意图识别,是用于理解用户意图的模块,例如:播放音乐
Intent: Intent:
# 不使用意图识别
nointent: nointent:
type: nointent type: nointent
# 意图识别使用大模型,优点:通用性强,缺点:增加串行前置意图识别模块,会增加处理时间
intent_llm: intent_llm:
type: intent_llm type: intent_llm
# 意图识别使用function_call,缺点:需要所选择的LLM支持function_call,优点:按需调用工具、速度快
# 新手使用function_call,建议使用:AliLLM,并把的model_name设置为:qwen-max
function_call:
type: function_call
Memory: Memory:
mem0ai: mem0ai:
@ -341,18 +349,6 @@ module_test:
# 本地音乐播放配置 # 本地音乐播放配置
music: music:
music_commands:
- "来一首歌"
- "唱一首歌"
- "播放音乐"
- "来点音乐"
- "背景音乐"
- "放首歌"
- "播放歌曲"
- "来点背景音乐"
- "我想听歌"
- "我要听歌"
- "放点音乐"
music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件 music_dir: "./music" # 音乐文件存放路径,将从该目录及子目录下搜索音乐文件
music_ext: # 音乐文件类型,p3格式效率最高 music_ext: # 音乐文件类型,p3格式效率最高
- ".mp3" - ".mp3"

View file

@ -20,13 +20,13 @@ FunctionCallConfig = [
"type": "function", "type": "function",
"function": { "function": {
"name": "play_music", "name": "play_music",
"description": "当用户想播放音乐时调用", "description": "唱歌、听歌、播放音乐方法。比如用户说播放音乐,参数为:random,比如用户说播放两只老虎,参数为:两只老虎",
"parameters": { "parameters": {
"type": "object", "type": "object",
"properties": { "properties": {
"song_name": { "song_name": {
"type": "string", "type": "string",
"description": "要播放的歌曲名称,如果没有指定具体歌名则为'random'" "description": "歌曲名称,如果没有指定具体歌名则为'random'"
} }
}, },
"required": ["song_name"] "required": ["song_name"]

View file

@ -91,7 +91,12 @@ class ConnectionHandler:
self.is_device_verified = False # 添加设备验证状态标志 self.is_device_verified = False # 添加设备验证状态标志
self.music_handler = _music self.music_handler = _music
self.close_after_chat = False # 是否在聊天结束后关闭连接 self.close_after_chat = False # 是否在聊天结束后关闭连接
self.use_function_call_mode = self.config.get("use_function_call_mode", False) # 是否使用function calling模式,开启后可以通过函数调用处理意图 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): async def handle_connection(self, ws):
try: try:
@ -227,7 +232,7 @@ class ConnectionHandler:
future = asyncio.run_coroutine_threadsafe(self.memory.query_memory(query), self.loop) future = asyncio.run_coroutine_threadsafe(self.memory.query_memory(query), self.loop)
memory_str = future.result() memory_str = future.result()
self.logger.bind(tag=TAG).info(f"记忆内容: {memory_str}") self.logger.bind(tag=TAG).debug(f"记忆内容: {memory_str}")
llm_responses = self.llm.response( llm_responses = self.llm.response(
self.session_id, self.session_id,
self.dialogue.get_llm_dialogue_with_memory(memory_str) self.dialogue.get_llm_dialogue_with_memory(memory_str)

View file

@ -2,16 +2,17 @@ from config.logger import setup_logging
import json import json
from core.handle.sendAudioHandle import send_stt_message from core.handle.sendAudioHandle import send_stt_message
from core.utils.dialogue import Message from core.utils.dialogue import Message
from core.handle.functionCallConfig import FunctionCallConfig from config.functionCallConfig import FunctionCallConfig
import asyncio import asyncio
from enum import Enum from enum import Enum
TAG = __name__ TAG = __name__
logger = setup_logging() logger = setup_logging()
class Action(Enum): class Action(Enum):
NOTFOUND = (0, "没有找到函数") NOTFOUND = (0, "没有找到函数")
NONE = (1, "啥也不干") NONE = (1, "啥也不干")
RESPONSE = (2, "直接回复") RESPONSE = (2, "直接回复")
REQLLM = (3, "调用函数后再请求llm生成回复") REQLLM = (3, "调用函数后再请求llm生成回复")
@ -19,20 +20,23 @@ class Action(Enum):
self.code = code self.code = code
self.message = message self.message = message
class ActionResponse: class ActionResponse:
def __init__(self, action : Action, result, response): def __init__(self, action: Action, result, response):
self.action = action # 动作类型 self.action = action # 动作类型
self.result = result # 动作产生的结果 self.result = result # 动作产生的结果
self.response = response # 直接回复的内容 self.response = response # 直接回复的内容
def get_functions(): def get_functions():
"""获取功能调用配置""" """获取功能调用配置"""
return FunctionCallConfig return FunctionCallConfig
def handle_llm_function_call(conn, function_call_data): def handle_llm_function_call(conn, function_call_data):
try: try:
function_name = function_call_data["name"] function_name = function_call_data["name"]
if function_name == "handle_exit_intent": if function_name == "handle_exit_intent":
# 处理退出意图 # 处理退出意图
try: try:
@ -42,30 +46,34 @@ def handle_llm_function_call(conn, function_call_data):
return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye) return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response=say_goodbye)
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"处理退出意图错误: {e}") logger.bind(tag=TAG).error(f"处理退出意图错误: {e}")
elif function_name == "play_music": elif function_name == "play_music":
# 处理音乐播放意图 # 处理音乐播放意图
try: try:
args = json.loads(function_call_data["arguments"]) song_name = "random"
song_name = args.get("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 "随机播放音乐" music_intent = f"播放音乐 {song_name}" if song_name != "random" else "随机播放音乐"
# 执行音乐播放命令 # 执行音乐播放命令
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() future.result()
return ActionResponse(action=Action.RESPONSE, result="退出意图已处理", response="还想听什么歌?") 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}")
else: else:
return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="") return ActionResponse(action=Action.NOTFOUND, result="没有找到对应的函数", response="")
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"处理function call错误: {e}") logger.bind(tag=TAG).error(f"处理function call错误: {e}")
return None return None
async def handle_user_intent(conn, text): async def handle_user_intent(conn, text):
""" """
Handle user intent before starting chat Handle user intent before starting chat
@ -80,19 +88,19 @@ async def handle_user_intent(conn, text):
# 检查是否有明确的退出命令 # 检查是否有明确的退出命令
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
logger.bind(tag=TAG).info(f"分析用户意图: {text}") logger.bind(tag=TAG).info(f"分析用户意图: {text}")
# 使用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)
@ -113,15 +121,15 @@ async def analyze_intent_with_llm(conn, text):
if not hasattr(conn, 'intent') or not conn.intent: if not hasattr(conn, 'intent') or not conn.intent:
logger.bind(tag=TAG).warning("意图识别服务未初始化") logger.bind(tag=TAG).warning("意图识别服务未初始化")
return None return None
# 创建对话历史记录 # 创建对话历史记录
dialogue = conn.dialogue dialogue = conn.dialogue
dialogue.put(Message(role="user", content=text)) dialogue.put(Message(role="user", content=text))
try: try:
intent_result = await conn.intent.detect_intent(dialogue.dialogue) intent_result = await conn.intent.detect_intent(dialogue.dialogue)
logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}") logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
# 尝试解析JSON结果 # 尝试解析JSON结果
try: try:
intent_data = json.loads(intent_result) intent_data = json.loads(intent_result)
@ -130,10 +138,10 @@ async def analyze_intent_with_llm(conn, text):
except json.JSONDecodeError: except json.JSONDecodeError:
# 如果不是JSON格式,尝试直接获取意图文本 # 如果不是JSON格式,尝试直接获取意图文本
return intent_result.strip() return intent_result.strip()
except Exception as e: except Exception as e:
logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}") logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
return None return None
@ -142,21 +150,21 @@ 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 # 如果正在播放音乐,可以关了 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)
return True return True
# 处理播放音乐意图 # 处理播放音乐意图
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) await conn.music_handler.handle_music_command(conn, intent)
return True return True
# 其他意图处理可以在这里扩展 # 其他意图处理可以在这里扩展
# 默认返回False,表示继续常规聊天流程 # 默认返回False,表示继续常规聊天流程
return False return False

View file

@ -15,7 +15,7 @@ logger = setup_logging()
def _extract_song_name(text): def _extract_song_name(text):
"""从用户输入中提取歌名""" """从用户输入中提取歌名"""
for keyword in ["听", "播放", "放", "唱"]: for keyword in ["播放音乐"]:
if keyword in text: if keyword in text:
parts = text.split(keyword) parts = text.split(keyword)
if len(parts) > 1: if len(parts) > 1:
@ -36,6 +36,7 @@ def _find_best_match(potential_song, music_files):
best_match = music_file best_match = music_file
return best_match return best_match
class MusicManager: class MusicManager:
def __init__(self, music_dir, music_ext): def __init__(self, music_dir, music_ext):
self.music_dir = Path(music_dir) self.music_dir = Path(music_dir)
@ -55,23 +56,20 @@ class MusicManager:
music_files.append(str(file.relative_to(self.music_dir))) music_files.append(str(file.relative_to(self.music_dir)))
return music_files return music_files
class MusicHandler: class MusicHandler:
def __init__(self, config): def __init__(self, config):
self.config = config self.config = config
self.music_related_keywords = []
if "music" in self.config: if "music" in self.config:
self.music_config = self.config["music"] self.music_config = self.config["music"]
self.music_dir = os.path.abspath( self.music_dir = os.path.abspath(
self.music_config.get("music_dir", "./music") # 默认路径修改 self.music_config.get("music_dir", "./music") # 默认路径修改
) )
self.music_related_keywords = self.music_config.get("music_commands", [])
self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3")) self.music_ext = self.music_config.get("music_ext", (".mp3", ".wav", ".p3"))
self.refresh_time = self.music_config.get("refresh_time", 60) self.refresh_time = self.music_config.get("refresh_time", 60)
else: else:
self.music_dir = os.path.abspath("./music") self.music_dir = os.path.abspath("./music")
self.music_related_keywords = ["来一首歌", "唱一首歌", "播放音乐", "来点音乐", "背景音乐", "放首歌",
"播放歌曲", "来点背景音乐", "我想听歌", "我要听歌", "放点音乐"]
self.music_ext = (".mp3", ".wav", ".p3") self.music_ext = (".mp3", ".wav", ".p3")
self.refresh_time = 60 self.refresh_time = 60
@ -100,13 +98,9 @@ class MusicHandler:
logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}") logger.bind(tag=TAG).info(f"找到最匹配的歌曲: {best_match}")
await self.play_local_music(conn, specific_file=best_match) await self.play_local_music(conn, specific_file=best_match)
return True return True
# 检查是否是通用播放音乐命令 # 检查是否是通用播放音乐命令
if any(cmd in clean_text for cmd in self.music_related_keywords): await self.play_local_music(conn)
await self.play_local_music(conn) return True
return True
return False
async def play_local_music(self, conn, specific_file=None): async def play_local_music(self, conn, specific_file=None):
"""播放本地音乐文件""" """播放本地音乐文件"""
@ -117,26 +111,18 @@ class MusicHandler:
# 确保路径正确性 # 确保路径正确性
if specific_file: if specific_file:
music_path = os.path.join(self.music_dir, specific_file)
if not os.path.exists(music_path):
logger.bind(tag=TAG).error(f"指定的音乐文件不存在: {music_path}")
return
selected_music = specific_file selected_music = specific_file
music_path = os.path.join(self.music_dir, specific_file)
else: else:
if time.time() - self.scan_time > self.refresh_time:
# 刷新音乐文件列表
self.music_files = MusicManager(self.music_dir, self.music_ext).get_music_files()
self.scan_time = time.time()
logger.bind(tag=TAG).debug(f"刷新的音乐文件列表: {self.music_files}")
if not self.music_files: if not self.music_files:
logger.bind(tag=TAG).error("未找到MP3音乐文件") logger.bind(tag=TAG).error("未找到MP3音乐文件")
return return
selected_music = random.choice(self.music_files) selected_music = random.choice(self.music_files)
music_path = os.path.join(self.music_dir, selected_music) music_path = os.path.join(self.music_dir, selected_music)
if not os.path.exists(music_path):
logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}") if not os.path.exists(music_path):
return logger.bind(tag=TAG).error(f"选定的音乐文件不存在: {music_path}")
return
text = f"正在播放{selected_music}" text = f"正在播放{selected_music}"
await send_stt_message(conn, text) await send_stt_message(conn, text)
conn.tts_first_text_index = 0 conn.tts_first_text_index = 0

View file

@ -29,7 +29,7 @@ class IntentProvider(IntentProviderBase):
prompt = ( prompt = (
"你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n" "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
f"{', '.join(intent_list)}\n" f"{', '.join(intent_list)}\n"
"如果是播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n" "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
"如果听不出具体歌名,可以返回'随机播放音乐'。\n" "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
"只需要返回意图结果的json,不要解释。" "只需要返回意图结果的json,不要解释。"
"返回格式如下:\n" "返回格式如下:\n"

View file

@ -21,10 +21,6 @@ class WebSocketServer:
has_memory_cfg = self.config.get("Memory") and memory_cls_name in self.config["Memory"] has_memory_cfg = self.config.get("Memory") and memory_cls_name in self.config["Memory"]
memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {} memory_cfg = self.config["Memory"][memory_cls_name] if has_memory_cfg else {}
intent_cls_name = self.config["selected_module"].get("Intent", "nointent") # 默认使用nointent
has_intent_cfg = self.config.get("Intent") and intent_cls_name in self.config["Intent"]
intent_cfg = self.config["Intent"][intent_cls_name] if has_intent_cfg else {}
"""创建处理模块实例""" """创建处理模块实例"""
return ( return (
vad.create_instance( vad.create_instance(
@ -56,7 +52,13 @@ class WebSocketServer:
), ),
MusicHandler(self.config), MusicHandler(self.config),
memory.create_instance(memory_cls_name, memory_cfg), memory.create_instance(memory_cls_name, memory_cfg),
intent.create_instance(intent_cls_name, intent_cfg), intent.create_instance(
self.config["selected_module"]["Intent"]
if not 'type' in self.config["Intent"][self.config["selected_module"]["Intent"]]
else
self.config["Intent"][self.config["selected_module"]["Intent"]]["type"],
self.config["Intent"][self.config["selected_module"]["Intent"]]
),
) )
async def start(self): async def start(self):