mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-29 05:09:46 +01:00
2025-3-10-优化llm intent
This commit is contained in:
parent
69735207e6
commit
7e0dd7fad2
4 changed files with 86 additions and 29 deletions
|
|
@ -127,7 +127,7 @@ async def analyze_intent_with_llm(conn, text):
|
||||||
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(conn, dialogue.dialogue)
|
||||||
logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
|
logger.bind(tag=TAG).info(f"意图识别结果: {intent_result}")
|
||||||
|
|
||||||
# 尝试解析JSON结果
|
# 尝试解析JSON结果
|
||||||
|
|
|
||||||
|
|
@ -19,7 +19,7 @@ class IntentProviderBase(ABC):
|
||||||
logger.bind(tag=TAG).debug("Set LLM for intent provider")
|
logger.bind(tag=TAG).debug("Set LLM for intent provider")
|
||||||
|
|
||||||
@abstractmethod
|
@abstractmethod
|
||||||
async def detect_intent(self, dialogue_history: List[Dict]) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict]) -> str:
|
||||||
"""
|
"""
|
||||||
检测用户最后一句话的意图
|
检测用户最后一句话的意图
|
||||||
Args:
|
Args:
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,8 @@ class IntentProvider(IntentProviderBase):
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
self.llm = None
|
self.llm = None
|
||||||
self.promot = self.get_intent_system_prompt()
|
self.prompt1_classfy, self.prompt2_getmusicname = self.get_intent_system_prompt()
|
||||||
|
|
||||||
|
|
||||||
def get_intent_system_prompt(self) -> str:
|
def get_intent_system_prompt(self) -> str:
|
||||||
"""
|
"""
|
||||||
|
|
@ -20,42 +21,98 @@ class IntentProvider(IntentProviderBase):
|
||||||
格式化后的系统提示词
|
格式化后的系统提示词
|
||||||
"""
|
"""
|
||||||
intent_list = []
|
intent_list = []
|
||||||
for key, value in self.intent_options.items():
|
# for key, value in self.intent_options.items():
|
||||||
if key == "play_music":
|
# if key == "continue_chat":
|
||||||
intent_list.append(f"{value} [歌名]")
|
# """
|
||||||
else:
|
# "continue_chat": "1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等",
|
||||||
intent_list.append(value)
|
# "end_chat": "2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候",
|
||||||
|
# "play_music": "3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图"
|
||||||
prompt = (
|
# """
|
||||||
"你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
|
intent_list.append("1.继续聊天, 除了播放音乐和结束聊天的时候的选项, 比如日常的聊天和问候, 对话等")
|
||||||
f"{', '.join(intent_list)}\n"
|
# elif key == "end_chat":
|
||||||
"如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
|
intent_list.append("2.结束聊天, 用户发来如再见之类的表示结束的话, 不想再进行对话的时候")
|
||||||
"如果听不出具体歌名,可以返回'随机播放音乐'。\n"
|
# elif key == "play_music":
|
||||||
"只需要返回意图结果的json,不要解释。"
|
intent_list.append("3.播放音乐, 用户希望你可以播放音乐, 只用于播放音乐的意图")
|
||||||
"返回格式如下:\n"
|
prompt1_classfy = ("你是一个分类助手, 请根据以下的对话记录,判断用户的最后意图属于以下哪一类:\n"
|
||||||
"{intent: '用户意图'}"
|
"你可以使用的分类如下使用<begin><end>进行标记:\n"
|
||||||
)
|
"<begin>\n"
|
||||||
return prompt
|
f"{', '.join(intent_list)}\n"
|
||||||
|
"<end>\n"
|
||||||
|
"请你返回你的判断结果标号, 只使用一个数字作为返回结果, 下面是几个实际的示例\n"
|
||||||
|
"```"
|
||||||
|
"用户: 我想听一首可以让我激情澎湃的歌曲\n"
|
||||||
|
"3\n"
|
||||||
|
"```"
|
||||||
|
"用户: 我有点累了, 想休息一下, 再见\n"
|
||||||
|
"2\n"
|
||||||
|
"```"
|
||||||
|
"返回的结果只有一个数字, 没有其他的附加内容")
|
||||||
|
|
||||||
|
prompt2_getmusicname = ("用户发来消息, 请你根据他的消息分类出他想听的音乐的名字:\n"
|
||||||
|
"如果用户没有提供音乐的名字, 请返回随机播放音乐\n"
|
||||||
|
"请你返回你的判断结果, 只使用歌名作为返回结果, 下面是几个实际的示例\n"
|
||||||
|
"```\n"
|
||||||
|
"用户: 我想听静夜思\n"
|
||||||
|
"静夜思\n"
|
||||||
|
"```\n"
|
||||||
|
"用户: 我想听一首轻松的音乐\n"
|
||||||
|
"随机播放音乐\n"
|
||||||
|
"```\n"
|
||||||
|
"你可以使用的音乐的名字如下使用<begin><end>进行标记:\n")
|
||||||
|
# prompt = (
|
||||||
|
# "你是一个意图识别助手。你需要根据和用户的对话记录,重点分析用户的最后一句话,判断用户意图属于以下哪一类:\n"
|
||||||
|
# f"{', '.join(intent_list)}\n"
|
||||||
|
# "如果是唱歌、听歌、播放音乐,请指定歌名,格式为'播放音乐 [识别出的歌名]'。\n"
|
||||||
|
# "如果听不出具体歌名,可以返回'随机播放音乐'。\n"
|
||||||
|
# "只需要返回意图结果的json,不要解释。"
|
||||||
|
# "返回格式如下:\n"
|
||||||
|
# "{intent: '用户意图'}"
|
||||||
|
# )
|
||||||
|
return prompt1_classfy, prompt2_getmusicname
|
||||||
|
|
||||||
async def detect_intent(self, dialogue_history: List[Dict]) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict]) -> str:
|
||||||
if not self.llm:
|
if not self.llm:
|
||||||
raise ValueError("LLM provider not set")
|
raise ValueError("LLM provider not set")
|
||||||
|
|
||||||
# 构建用户最后一句话的提示
|
# 构建用户最后一句话的提示
|
||||||
msgStr = ""
|
msgStr = ""
|
||||||
for msg in dialogue_history:
|
# for msg in dialogue_history:
|
||||||
if msg.role == "user":
|
# if msg.role == "user":
|
||||||
msgStr += f"User: {msg.content}\n"
|
# msgStr += f"User: {msg.content}\n"
|
||||||
elif msg.role== "assistant":
|
# elif msg.role== "assistant":
|
||||||
msgStr += f"Assistant: {msg.content}\n"
|
# msgStr += f"Assistant: {msg.content}\n"
|
||||||
|
msgStr += f"{dialogue_history[-2].role}: {dialogue_history[-2].content}\n"
|
||||||
|
msgStr += f"{dialogue_history[-1].role}: {dialogue_history[-1].content}\n"
|
||||||
|
|
||||||
user_prompt = f"请分析用户的意图:\n{msgStr}"
|
user_prompt = f"请分析用户的意图:\n{msgStr}"
|
||||||
|
|
||||||
# 使用LLM进行意图识别
|
# 使用LLM进行意图识别
|
||||||
intent = self.llm.response_no_stream(
|
intent = self.llm.response_no_stream(
|
||||||
system_prompt=self.promot,
|
system_prompt=self.prompt1_classfy,
|
||||||
user_prompt=user_prompt
|
user_prompt=user_prompt
|
||||||
)
|
)
|
||||||
|
# 判断返回的是不是一个数字
|
||||||
|
intent = intent.strip()
|
||||||
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
|
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
|
||||||
return intent.strip()
|
if intent.isdigit():
|
||||||
|
# 处理不同选项
|
||||||
|
if int(intent) == 1:
|
||||||
|
return '{intent: "继续聊天"}'
|
||||||
|
elif int(intent) == 2:
|
||||||
|
return '{intent: "结束聊天"}'
|
||||||
|
elif int(intent) == 3:
|
||||||
|
|
||||||
|
print(conn.music_handler.music_files)
|
||||||
|
prompt = f"{self.prompt2_getmusicname}\n<begin>{conn.music_handler.music_files}\n<end>"
|
||||||
|
# logger.bind(tag=TAG).info(f"Prompt for getting music name: {prompt}")
|
||||||
|
intent = self.llm.response_no_stream(
|
||||||
|
system_prompt=prompt,
|
||||||
|
user_prompt=user_prompt
|
||||||
|
)
|
||||||
|
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
|
||||||
|
# 播放音乐 [识别出的歌名]
|
||||||
|
ret = '{intent: "播放音乐 ' + intent + '"}'
|
||||||
|
logger.bind(tag=TAG).info(f"Detected intent: {ret}")
|
||||||
|
return ret
|
||||||
|
logger.bind(tag=TAG).info(f"Detected intent: {intent}")
|
||||||
|
return {intent: "继续聊天"}
|
||||||
|
|
|
||||||
|
|
@ -6,7 +6,7 @@ TAG = __name__
|
||||||
logger = setup_logging()
|
logger = setup_logging()
|
||||||
|
|
||||||
class IntentProvider(IntentProviderBase):
|
class IntentProvider(IntentProviderBase):
|
||||||
async def detect_intent(self, dialogue_history: List[Dict]) -> str:
|
async def detect_intent(self, conn, dialogue_history: List[Dict]) -> str:
|
||||||
"""
|
"""
|
||||||
默认的意图识别实现,始终返回继续聊天
|
默认的意图识别实现,始终返回继续聊天
|
||||||
Args:
|
Args:
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue