# -*- coding: utf-8 -*- """ 意图分类 —— 使用 LLM Agent 推理用户意图,替代关键词匹配 """ import re import asyncio from api.prompts import _INTENT_CLASSIFY_PROMPT from api.chat_model import get_chat_model async def classify_intent(message: str, filename: str | None = None) -> str: """使用 LLM Agent 推理用户意图,替代关键词匹配。 用轻量级模型调用做意图分类,支持两种路由: - "review" → 配风计划审查管线 - "dialog" → 通风对话助手(统一处理数据解读、需风量计算等) Args: message: 用户消息文本 filename: 可选,上传的附件文件名(用于辅助意图判断) Returns: "review" / "dialog" """ try: model = get_chat_model() # 构建附件信息行 attachment_info = f"附件文件名:{filename}" if filename else "(无附件)" prompt = _INTENT_CLASSIFY_PROMPT.format( message=message[:500], # 截断防过长 attachment_info=attachment_info, ) # 在 executor 中运行同步 invoke,避免阻塞事件循环 loop = asyncio.get_event_loop() result = await loop.run_in_executor( None, lambda: model.invoke([{"role": "user", "content": prompt}]) ) raw = result.content if hasattr(result, "content") else str(result) raw = raw.strip().lower() # 提取第一个有效词 match = re.search(r'(review|dialog)', raw) if match: return match.group(1) except Exception as e: print(f"[意图分类] Agent 分类失败,回退到 dialog: {e}") return "dialog"