intentHandler.py 11 KB

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