intentHandler.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. import json
  2. import uuid
  3. import asyncio
  4. from typing import TYPE_CHECKING
  5. if TYPE_CHECKING:
  6. from core.connection import ConnectionHandler
  7. from core.utils.dialogue import Message
  8. from core.providers.tts.dto.dto import ContentType
  9. from core.handle.helloHandle import checkWakeupWords
  10. from plugins_func.register import Action, ActionResponse
  11. from core.handle.sendAudioHandle import send_stt_message
  12. from core.handle.reportHandle import enqueue_tool_report
  13. from core.utils.util import remove_punctuation_and_length
  14. from core.providers.tts.dto.dto import TTSMessageDTO, SentenceType
  15. TAG = __name__
  16. async def handle_user_intent(conn: "ConnectionHandler", text):
  17. # 预处理输入文本,处理可能的JSON格式
  18. try:
  19. if text.strip().startswith("{") and text.strip().endswith("}"):
  20. parsed_data = json.loads(text)
  21. if isinstance(parsed_data, dict) and "content" in parsed_data:
  22. text = parsed_data["content"] # 提取content用于意图分析
  23. conn.current_speaker = parsed_data.get("speaker") # 保留说话人信息
  24. except (json.JSONDecodeError, TypeError):
  25. pass
  26. # 检查是否有明确的退出命令
  27. _, filtered_text = remove_punctuation_and_length(text)
  28. if await check_direct_exit(conn, filtered_text):
  29. return True
  30. # 检查是否是唤醒词
  31. if await checkWakeupWords(conn, filtered_text):
  32. return True
  33. direct_function_call = match_direct_nav_command(filtered_text)
  34. if direct_function_call is not None:
  35. function_name, function_args = direct_function_call
  36. conn.logger.bind(tag=TAG).info(
  37. f"识别到直达导航命令: {filtered_text} -> {function_name}"
  38. )
  39. return await dispatch_function_call(
  40. conn,
  41. text,
  42. function_name,
  43. function_args,
  44. )
  45. if conn.intent_type == "function_call":
  46. # 使用支持function calling的聊天方法,不再进行意图分析
  47. return False
  48. # 使用LLM进行意图分析
  49. intent_result = await analyze_intent_with_llm(conn, text)
  50. if not intent_result:
  51. return False
  52. # 会话开始时生成sentence_id
  53. conn.sentence_id = str(uuid.uuid4().hex)
  54. # 处理各种意图
  55. return await process_intent_result(conn, intent_result, text)
  56. async def check_direct_exit(conn: "ConnectionHandler", text):
  57. """检查是否有明确的退出命令"""
  58. _, text = remove_punctuation_and_length(text)
  59. cmd_exit = conn.cmd_exit
  60. for cmd in cmd_exit:
  61. if text == cmd:
  62. conn.logger.bind(tag=TAG).info(f"识别到明确的退出命令: {text}")
  63. await send_stt_message(conn, text)
  64. await conn.close()
  65. return True
  66. return False
  67. async def analyze_intent_with_llm(conn: "ConnectionHandler", text):
  68. """使用LLM分析用户意图"""
  69. if not hasattr(conn, "intent") or not conn.intent:
  70. conn.logger.bind(tag=TAG).warning("意图识别服务未初始化")
  71. return None
  72. # 对话历史记录
  73. dialogue = conn.dialogue
  74. try:
  75. intent_result = await conn.intent.detect_intent(conn, dialogue.dialogue, text)
  76. return intent_result
  77. except Exception as e:
  78. conn.logger.bind(tag=TAG).error(f"意图识别失败: {str(e)}")
  79. return None
  80. def match_direct_nav_command(filtered_text: str):
  81. text = (filtered_text or "").strip()
  82. if not text:
  83. return None
  84. if text in {
  85. "开始录制路线",
  86. "开始记录路线",
  87. "录制路线",
  88. "开始记录",
  89. "开始记路线",
  90. }:
  91. return "nav_start_record", {}
  92. if text in {
  93. "结束录制",
  94. "停止录制",
  95. "结束记录",
  96. "停止记录",
  97. "录制结束",
  98. }:
  99. return "nav_stop_record", {}
  100. if text in {
  101. "开始预警",
  102. "开始播报",
  103. "开始领航",
  104. "开始导航",
  105. }:
  106. return "nav_start_run", {}
  107. if text in {
  108. "停止预警",
  109. "结束预警",
  110. "停止播报",
  111. "关闭预警",
  112. }:
  113. return "nav_stop_run", {}
  114. if text.startswith("标记"):
  115. if any(word in text for word in ("急转弯", "起转弯", "急弯")):
  116. return "nav_mark_hazard", {"hazard_type": "sharp_turn"}
  117. if "障碍" in text:
  118. return "nav_mark_hazard", {"hazard_type": "obstacle"}
  119. if any(word in text for word in ("大坑", "坑")):
  120. return "nav_mark_hazard", {"hazard_type": "bump"}
  121. if "跳台" in text:
  122. return "nav_mark_hazard", {"hazard_type": "jump"}
  123. if "陡坡" in text:
  124. return "nav_mark_hazard", {"hazard_type": "slope"}
  125. if "涉水" in text:
  126. return "nav_mark_hazard", {"hazard_type": "water"}
  127. return "nav_mark_hazard", {"hazard_type": "other"}
  128. return None
  129. async def dispatch_function_call(
  130. conn: "ConnectionHandler",
  131. original_text: str,
  132. function_name: str,
  133. function_args: dict | None = None,
  134. ):
  135. conn.sentence_id = str(uuid.uuid4().hex)
  136. function_args = function_args or {}
  137. function_args_json = json.dumps(function_args, ensure_ascii=False)
  138. function_call_data = {
  139. "name": function_name,
  140. "id": str(uuid.uuid4().hex),
  141. "arguments": function_args_json,
  142. }
  143. await send_stt_message(conn, original_text)
  144. conn.client_abort = False
  145. enqueue_tool_report(conn, function_name, function_args)
  146. def process_function_call():
  147. conn.dialogue.put(Message(role="user", content=original_text))
  148. tool_call_timeout = int(conn.config.get("tool_call_timeout", 30))
  149. try:
  150. result = asyncio.run_coroutine_threadsafe(
  151. conn.func_handler.handle_llm_function_call(conn, function_call_data),
  152. conn.loop,
  153. ).result(timeout=tool_call_timeout)
  154. except Exception as e:
  155. conn.logger.bind(tag=TAG).error(f"工具调用失败: {e}")
  156. result = ActionResponse(
  157. action=Action.ERROR,
  158. result="工具调用超时,请一会再试下哈",
  159. response="工具调用超时,请一会再试下哈",
  160. )
  161. if result:
  162. enqueue_tool_report(
  163. conn,
  164. function_name,
  165. function_args,
  166. str(result.result) if result.result else None,
  167. report_tool_call=False,
  168. )
  169. if result.action == Action.RESPONSE:
  170. text = result.response
  171. if text is not None:
  172. speak_txt(conn, text)
  173. elif result.action == Action.REQLLM:
  174. text = result.result
  175. conn.dialogue.put(Message(role="tool", content=text))
  176. llm_result = conn.intent.replyResult(text, original_text)
  177. if llm_result is None:
  178. llm_result = text
  179. speak_txt(conn, llm_result)
  180. elif result.action == Action.NOTFOUND or result.action == Action.ERROR:
  181. text = result.response if result.response else result.result
  182. if text is not None:
  183. speak_txt(conn, text)
  184. elif function_name != "play_music":
  185. text = result.response
  186. if text is None:
  187. text = result.result
  188. if text is not None:
  189. speak_txt(conn, text)
  190. conn.executor.submit(process_function_call)
  191. return True
  192. async def process_intent_result(
  193. conn: "ConnectionHandler", intent_result, original_text
  194. ):
  195. """处理意图识别结果"""
  196. try:
  197. # 尝试将结果解析为JSON
  198. intent_data = json.loads(intent_result)
  199. # 检查是否有function_call
  200. if "function_call" in intent_data:
  201. # 直接从意图识别获取了function_call
  202. conn.logger.bind(tag=TAG).debug(
  203. f"检测到function_call格式的意图结果: {intent_data['function_call']['name']}"
  204. )
  205. function_name = intent_data["function_call"]["name"]
  206. if function_name == "continue_chat":
  207. return False
  208. if function_name == "result_for_context":
  209. await send_stt_message(conn, original_text)
  210. conn.client_abort = False
  211. def process_context_result():
  212. conn.dialogue.put(Message(role="user", content=original_text))
  213. from core.utils.current_time import get_current_time_info
  214. current_time, today_date, today_weekday, lunar_date = (
  215. get_current_time_info()
  216. )
  217. # 构建带上下文的基础提示
  218. context_prompt = f"""当前时间:{current_time}
  219. 今天日期:{today_date} ({today_weekday})
  220. 今天农历:{lunar_date}
  221. 请根据以上信息回答用户的问题:{original_text}"""
  222. response = conn.intent.replyResult(context_prompt, original_text)
  223. speak_txt(conn, response)
  224. conn.executor.submit(process_context_result)
  225. return True
  226. function_args = {}
  227. if "arguments" in intent_data["function_call"]:
  228. function_args = intent_data["function_call"]["arguments"]
  229. if function_args is None:
  230. function_args = {}
  231. if isinstance(function_args, str):
  232. function_args = json.loads(function_args) if function_args else {}
  233. return await dispatch_function_call(
  234. conn,
  235. original_text,
  236. function_name,
  237. function_args if isinstance(function_args, dict) else {},
  238. )
  239. return False
  240. except json.JSONDecodeError as e:
  241. conn.logger.bind(tag=TAG).error(f"处理意图结果时出错: {e}")
  242. return False
  243. def speak_txt(conn: "ConnectionHandler", text):
  244. # 记录文本到 sentence_id 映射
  245. conn.tts.store_tts_text(conn.sentence_id, text)
  246. conn.tts.tts_text_queue.put(
  247. TTSMessageDTO(
  248. sentence_id=conn.sentence_id,
  249. sentence_type=SentenceType.FIRST,
  250. content_type=ContentType.ACTION,
  251. )
  252. )
  253. conn.tts.tts_one_sentence(conn, ContentType.TEXT, content_detail=text)
  254. conn.tts.tts_text_queue.put(
  255. TTSMessageDTO(
  256. sentence_id=conn.sentence_id,
  257. sentence_type=SentenceType.LAST,
  258. content_type=ContentType.ACTION,
  259. )
  260. )
  261. conn.dialogue.put(Message(role="assistant", content=text))