Rasa中location slot无法获取实体值返回None的问题求助
Rasa框架中location Slot无法获取实体值的问题解决
一、Slot无法获取实体值的原因
- NLU配置文件完全错误:你的
nlu.yml里写的是actions.py的代码,完全不符合NLU数据的要求。NLU文件需要定义意图、实体的训练样本,没有正确的训练数据,Rasa根本识别不了inform意图和location实体,自然没法填充slot。 - 实体识别未生效:就算修复了NLU文件,如果训练样本不足或者格式错误,Rasa的实体识别模型没法从用户输入里正确提取
location实体,slot也会是空值。 - 意图匹配偏差:如果用户输入被误分类到了非
inform的意图,就算有实体,也会因为slot映射里指定了仅从inform意图取值,导致slot无法填充。
二、对话过程中提取Slot/Entity值的方法
1. 先修复核心错误:修正nlu.yml
nlu.yml必须包含意图和实体的训练样本,示例如下:
version: "3.1" nlu: - intent: greet examples: | - Hi - Hello - Hey there - intent: goodbye examples: | - Bye - See you later - Goodbye - intent: inform examples: | - 北京的天气怎么样 - 我想知道[上海](location)的天气 - [广州](location)今天气温多少
2. 确认Slot映射配置正确
你的domain.yml中slot映射配置没问题,可保持当前设置:
slots: location: type: text mappings: - type: from_entity entity: location intent: inform
3. 对话中提取值的具体方式
从Slot中获取
在动作代码里通过tracker.get_slot()直接读取slot值,和你现有代码一致:
location = tracker.get_slot("location")
直接从当前输入的实体中提取
如果需要跳过slot,直接获取当前用户输入里的实体,可使用以下代码:
# 获取当前消息中的所有实体 entities = tracker.latest_message.get("entities") # 筛选出location实体的值 location = next((e["value"] for e in entities if e["entity"] == "location"), None)
用表单自动收集Slot
如果需要主动询问用户获取location,可使用Rasa表单功能:
在domain.yml中添加表单定义:
forms: weather_form: required_slots: - location
再在rules.yml中添加触发规则:
rules: - rule: 激活天气查询表单 steps: - intent: inform - action: weather_form - active_loop: weather_form
Rasa会自动询问用户,直到收集到完整的location slot值。
4. 验证与测试
- 修复所有文件后,重新训练模型:
rasa train - 用
rasa shell启动对话测试,输入包含地点的语句,比如“北京的天气怎么样”,查看控制台输出的实体和slot是否正确填充。 - 如果实体识别不准确,增加更多NLU训练样本,或使用正则表达式实体、lookup表提升识别精度。
内容的提问来源于stack exchange,提问作者Munsif
相关产品推荐
相关产品推荐

