# ============================================================================= # 企微IT智能服务台 — 阶段5 自动化 意图识别 # ============================================================================= # 说明:调用 Dify 识别员工诉求命中哪个自动化场景;Dify 未配置时走关键词兜底, # 保证 P0 四个场景在无真实 Dify 环境下也能跑通闭环。 # ============================================================================= from __future__ import annotations import logging from typing import Any, Dict, Optional from app.integrations.dify import DifyClient, get_dify_client from app.integrations.factory import build_dify_client logger = logging.getLogger(__name__) class IntentRouter: """意图识别路由器。""" def __init__(self, db: Any = None, audit: Any = None): self.db = db self.audit = audit async def detect(self, description: str, employee_id: str = "") -> Dict[str, Any]: """识别意图,返回 {scenario_key, confidence, raw, error}。 优先走 Dify;若 Dify 未配置或调用失败,使用关键词兜底。 """ client: Optional[DifyClient] = None try: client = await build_dify_client(audit=self.audit) except Exception as e: # noqa: BLE001 logger.warning(f"构建 Dify 客户端失败,转关键词兜底: {e}") if client is None: fb = DifyClient._fallback_intent(description) fb["error"] = "dify_not_configured" return fb try: return await client.detect_intent(description, employee_id) except Exception as e: # noqa: BLE001 logger.warning(f"Dify 意图识别异常,转关键词兜底: {e}") fb = DifyClient._fallback_intent(description) fb["error"] = str(e) return fb