Rasa阈值实现咨询:意图置信度低于阈值时触发指定动作的方案
实现Rasa低置信度意图分支处理的落地方案
1. 基础配置:开启置信度校验和触发规则
- 首先在
config.yml的pipeline中添加FallbackClassifier,设置你需要的置信度阈值(示例为0.6):
pipeline: # 保留你原有的其他NLU组件 - name: FallbackClassifier threshold: 0.6 # 低于该置信度的意图会标记为nlu_fallback ambiguity_threshold: 0.1 # 可选配置,多个最高置信度意图差值小于该值也触发fallback
- 接着在
rules.yml中配置低置信度触发的自定义处理动作,替代默认的兜底回复:
rules: - rule: Low confidence intent handler steps: - intent: nlu_fallback - action: action_low_confidence_processor
2. 核心逻辑实现:自定义处理动作
在actions/actions.py中编写action_low_confidence_processor,实现API调用、条件判断、流程分支的全逻辑:
from typing import Dict, Any, List, Text from rasa_sdk import Action, Tracker from rasa_sdk.executor import CollectingDispatcher from rasa_sdk.events import FollowupAction, UserUttered import requests class ActionLowConfidenceProcessor(Action): def name(self) -> Text: return "action_low_confidence_processor" def run(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict[Text, Any]) -> List[Dict[Text, Any]]: # 获取原始识别到的最高置信度意图、用户输入、实体信息 latest_msg = tracker.latest_message original_intent = latest_msg["intent"]["name"] original_confidence = latest_msg["intent"]["confidence"] user_input = latest_msg.get("text") entities = latest_msg.get("entities", []) # 调用你指定的业务API,可根据需要传参 try: api_resp = requests.post( "你的指定API地址", json={ "user_input": user_input, "detected_intent": original_intent, "confidence": original_confidence, "entities": entities }, timeout=3 # 建议加超时避免服务阻塞 ).json() except Exception as e: # API调用异常时可以自定义兜底逻辑 dispatcher.utter_message(text="当前服务繁忙,请稍后再试") return [] # 按你的预设条件做分支判断 # 示例条件:API返回需要执行自定义动作 if api_resp.get("need_custom_action"): return [FollowupAction("action_your_custom_business")] # 条件不满足则恢复执行原始意图的处理流程 else: # 构造UserUttered事件强制Rasa按原意图处理,跳过置信度校验 return [ UserUttered( text=user_input, parse_data={ "intent": {"name": original_intent, "confidence": 1.0}, "entities": entities, "text": user_input } ) ]
3. 可选优化点
- 如果你的业务场景中意图和动作是一一绑定的,不需要重新走完整的对话流程,可以直接用
FollowupAction("对应原始意图的动作名")替代上面的UserUttered事件,性能更高 - 置信度阈值可以放到环境变量或者自定义配置文件中统一管理,避免硬编码
- 可以在API调用前增加二次校验逻辑,比如高频输入、敏感词过滤等前置判断
内容的提问来源于stack exchange,提问作者Ali
相关产品推荐
相关产品推荐

