基于Rasa框架搭建中文机器人对话系统
Rasa是一个能用于构建机器人对话系统的框架,基于Rasa框架搭建机器人对话系统,可以使用于工业各类语音智能服务场景,如:远程医疗问诊、智能客户服务、保险产品销售、金融催收服务、手机智能助手等领域。支持基于规则、填槽和机器学习来构建对话系统。主要模块包括:NLU(意图识别和实体提取)和Core(基于模型及规则进行回复)。提供了搭建对话系统的脚手架。
常用命令有:
rasa init 创建项目
rasa train 训练NLU和Core模型
rasa run actions 启动动作服务(主要是自己写的动作,系统默认的动作,不需要单独启动)
rasa shell 启动对话机器人 (会自动启动默认动作服务)
涉及配置文件有:
config.yml 即对NLU和Core模型的配置
# Configuration for Rasa NLU.
# https://rasa.com/docs/rasa/nlu/components/
language: zhpipeline:
# # No configuration for the NLU pipeline was provided. The following default pipeline was used to train your model.
# # If you'd like to customize it, uncomment and adjust the pipeline.
# # See https://rasa.com/docs/rasa/tuning-your-model for more information.
# - name: WhitespaceTokenizer- name: JiebaTokenizer #支持中文- name: RegexFeaturizer- name: LexicalSyntacticFeaturizer- name: CountVectorsFeaturizer- name: CountVectorsFeaturizeranalyzer: char_wbmin_ngram: 1max_ngram: 4- name: DIETClassifierepochs: 100constrain_similarities: true- name: EntitySynonymMapper- name: ResponseSelectorepochs: 100constrain_similarities: true- name: FallbackClassifierthreshold: 0.3ambiguity_threshold: 0.1# Configuration for Rasa Core.
# https://rasa.com/docs/rasa/core/policies/
policies:
# # No configuration for policies was provided. The following default policies were used to train your model.
# # If you'd like to customize them, uncomment and adjust the policies.
# # See https://rasa.com/docs/rasa/policies for more information.- name: MemoizationPolicy- name: TEDPolicymax_history: 5epochs: 100constrain_similarities: true- name: RulePolicy
domain.yml 领域配置
version: '2.0'
config:store_entities_as_slots: true
session_config:session_expiration_time: 60carry_over_slots_to_new_session: true
intents:
- greet:use_entities: true
- deny:use_entities: true
- request_names:use_entities: true
- goodbye:use_entities: true
- affirm:use_entities: true
- mood_great:use_entities: true
- mood_unhappy:use_entities: true
- bot_challenge:use_entities: true
entities: []
slots:first_name:type: rasa.shared.core.slots.TextSlotinitial_value: nullauto_fill: trueinfluence_conversation: truelast_name:type: rasa.shared.core.slots.TextSlotinitial_value: nullauto_fill: trueinfluence_conversation: truename_spelled_correctly:type: rasa.shared.core.slots.BooleanSlotinitial_value: nullauto_fill: trueinfluence_conversation: truerequested_slot:type: rasa.shared.core.slots.UnfeaturizedSlotinitial_value: nullauto_fill: trueinfluence_conversation: false
responses:utter_greet:- text: 嗨,你好吗?utter_cheer_up:- image: https://i.imgur.com/nGF1K8f.jpgtext: '这是某些使你嗨起来的东西:'utter_did_that_help:- text: 这对你有帮助吗?utter_happy:- text: 好极了,继续!utter_goodbye:- text: 再见utter_iamabot:- text: 我是个机器人,由Rasa框架提供支持.utter_ask_first_name:- text: 你贵姓?utter_ask_last_name:- text: 你的名字?utter_ask_name_spelled_correctly:- buttons:- payload: /affirmtitle: 是- payload: /denytitle: 否text: 姓 {first_name} 拼写对了吗?utter_submit:- text: 好的,谢谢!utter_slots_values:- text: 我记住你了, {first_name} {last_name}!
actions:
- utter_greet
- utter_slots_values
- utter_submit
- validate_name_form
forms:name_form:first_name:- type: from_textlast_name:- type: from_text
e2e_actions: []
credentials.yml 证书配置,用于调用语音通道的接口
# This file contains the credentials for the voice & chat platforms
# which your bot is using.
# https://rasa.com/docs/rasa/messaging-and-voice-channelsrest:
# # you don't need to provide anything here - this channel doesn't
# # require any credentials#facebook:
# verify: "<verify>"
# secret: "<your secret>"
# page-access-token: "<your page access token>"#slack:
# slack_token: "<your slack token>"
# slack_channel: "<the slack channel>"
# slack_signing_secret: "<your slack signing secret>"#socketio:
# user_message_evt: <event name for user message>
# bot_message_evt: <event name for bot messages>
# session_persistence: <true/false>#mattermost:
# url: "https://<mattermost instance>/api/v4"
# token: "<bot token>"
# webhook_url: "<callback URL>"# This entry is needed if you are using Rasa X. The entry represents credentials
# for the Rasa X "channel", i.e. Talk to your bot and Share with guest testers.
rasa:url: "http://localhost:5002/api"
endpoints.yml 端点配置,如:机器人要使用的模型、动作、存储服务等。
# This file contains the different endpoints your bot can use.# Server where the models are pulled from.
# https://rasa.com/docs/rasa/model-storage#fetching-models-from-a-server#models:
# url: http://my-server.com/models/default_core@latest
# wait_time_between_pulls: 10 # [optional](default: 100)# Server which runs your custom actions.
# https://rasa.com/docs/rasa/custom-actions#action_endpoint:
# url: "http://localhost:5055/webhook"
action_endpoint:url: "http://localhost:5055/webhook"# Tracker store which is used to store the conversations.
# By default the conversations are stored in memory.
# https://rasa.com/docs/rasa/tracker-stores#tracker_store:
# type: redis
# url: <host of the redis instance, e.g. localhost>
# port: <port of your redis instance, usually 6379>
# db: <number of your database within redis, e.g. 0>
# password: <password used for authentication>
# use_ssl: <whether or not the communication is encrypted, default false>#tracker_store:
# type: mongod
# url: <url to your mongo instance, e.g. mongodb://localhost:27017>
# db: <name of the db within your mongo instance, e.g. rasa>
# username: <username used for authentication>
# password: <password used for authentication>
tracker_store:type: SQLdialect: sqlitedb: trackers.db# Event broker which all conversation events should be streamed to.
# https://rasa.com/docs/rasa/event-brokers#event_broker:
# url: localhost
# username: username
# password: password
# queue: queue
event_broker:type: SQLdialect: sqlitedb: events.db
names.txt 本案例使用的姓名列表。
孙悟空
猪八戒
唐三藏
沙悟净
诸葛青云
数据,主要包括:
nlu.yml 用于训练nlu模型的训练数据
version: "2.0"
nlu:
- intent: greetexamples: |- 你好- 上午好- 中午好- 嗨
- intent: goodbyeexamples: |- 再见- 回头见- 晚安
- intent: affirmexamples: |- 是的- 有- 当然- 听上去不错
- intent: denyexamples: |- 不- 不要- 没有- 没有- 我不喜欢
- intent: mood_greatexamples: |- 太好了- 感觉不错- 非常好
- intent: mood_unhappyexamples: |- 不开心- 感到沮丧- 不高兴- 不太好
- intent: bot_challengeexamples: |- 你是个机器人吗?- 你是人类吗?- 我是在和机器人讲话吗?- 我是在和人类讲话吗?
- intent: request_namesexamples: |- 我想告诉你姓名- 你知道我的姓名吗?
- lookup: namesexamples: |- 猪八戒- 孙悟空- 沙悟净- 唐三藏
rules.yml 规则,根据用户意图,进行具体的动作(包括查询、填槽、回复等)
version: "2.0"rules:- rule: Say goodbye anytime the user says goodbyesteps:- intent: goodbye- action: utter_goodbye- rule: Say 'I am a bot' anytime the user challengessteps:- intent: bot_challenge- action: utter_iamabot- rule: Activate formsteps:- intent: request_names- action: name_form- active_loop: name_form- rule: Submit formcondition:- active_loop: name_formsteps:- action: name_form- active_loop: null- slot_was_set:- requested_slot: null- action: utter_submit- action: utter_slots_values
stories.yml 故事情节,描述对话的流程
version: "2.0"stories:- story: happy pathsteps:- intent: greet- action: utter_greet- intent: mood_great- action: utter_happy- story: sad path 1steps:- intent: greet- action: utter_greet- intent: mood_unhappy- action: utter_cheer_up- action: utter_did_that_help- intent: affirm- action: utter_happy- story: sad path 2steps:- intent: greet- action: utter_greet- intent: mood_unhappy- action: utter_cheer_up- action: utter_did_that_help- intent: deny- action: utter_goodbye- story: interactive_story_1steps:- intent: greet- action: utter_greet- intent: request_names- action: name_form- active_loop: name_form- slot_was_set:- requested_slot: first_name- slot_was_set:- name_spelled_correctly: None- slot_was_set:- first_name: None- slot_was_set:- requested_slot: last_name- slot_was_set:- name_spelled_correctly: None- slot_was_set:- last_name: None- slot_was_set:- requested_slot: null- active_loop: null- action: utter_submit- action: utter_slots_values
下面举例创建mybot的过程:
1、使用rasa init 创建mybot项目,目录结果如下:
涉及的配置文件在上文已经逐一列出,下面看看自定义的action是如何写的,主要完成了输入验证的过程,默认的action是以utter_打头,系统默认支持。
actions.py
import yaml
import pathlib
from typing import Text, List, Any, Dict, Optionalfrom rasa_sdk import Tracker, FormValidationAction
from rasa_sdk.executor import CollectingDispatcher
from rasa_sdk.types import DomainDictnames = pathlib.Path("names.txt").read_text().split("\n")class ValidateNameForm(FormValidationAction):def name(self) -> Text:return "validate_name_form"async def required_slots(self,slots_mapped_in_domain: List[Text],dispatcher: "CollectingDispatcher",tracker: "Tracker",domain: "DomainDict",) -> Optional[List[Text]]:first_name = tracker.slots.get("first_name")if first_name is not None:if first_name not in names:return ["name_spelled_correctly"] + slots_mapped_in_domainreturn slots_mapped_in_domainasync def extract_name_spelled_correctly(self, dispatcher: CollectingDispatcher, tracker: Tracker, domain: Dict) -> Dict[Text, Any]:intent = tracker.get_intent_of_latest_message()return {"name_spelled_correctly": intent == "affirm"}def validate_name_spelled_correctly(self,slot_value: Any,dispatcher: CollectingDispatcher,tracker: Tracker,domain: DomainDict,) -> Dict[Text, Any]:"""Validate `first_name` value."""if tracker.get_slot("name_spelled_correctly"):return {"first_name": tracker.get_slot("first_name"), "name_spelled_correctly": True}return {"first_name": None, "name_spelled_correctly": None}def validate_first_name(self,slot_value: Any,dispatcher: CollectingDispatcher,tracker: Tracker,domain: DomainDict,) -> Dict[Text, Any]:"""Validate `first_name` value."""# If the name is super short, it might be wrong.print(f"姓 = {slot_value} 长度 = {len(slot_value)}")if len(slot_value) <=1:dispatcher.utter_message(text=f"姓太短了,你确定拼写对了?")return {"first_name": None}else:return {"first_name": slot_value}def validate_last_name(self,slot_value: Any,dispatcher: CollectingDispatcher,tracker: Tracker,domain: DomainDict,) -> Dict[Text, Any]:"""Validate `last_name` value."""# If the name is super short, it might be wrong.print(f"名字 = {slot_value} 长度 = {len(slot_value)}")if len(slot_value) <= 1:dispatcher.utter_message(text=f"名字太短了,你确定拼写对了?")return {"last_name": None}else:return {"last_name": slot_value}
2、启动自动定义的actions服务:
3、训练NLU和Core模型:
4、启动机器人进行对话
分期业务效果:
实际尝试:可以自动完成正常的分期业务流程,中间可以穿插其它的对话内容,如:分期时间长、手续费太贵、担心被套路等。
基于Rasa框架搭建中文机器人对话系统相关推荐
- 基于GitBook框架搭建技术文档平台
源宝导读:为了向用户更好的传递ERP开放平台的价值与技术知识,我们基于GitBook框架搭建了一个文档中心站点,本文将介绍此站点的设计与实现过程. 一.项目架构图 因为文档会涉及到很多的产品线,所以目 ...
- 第一章:基于 SpringBoot 快速搭建QQ机器人,并监听群事件
第一章:基于 SpringBoot 快速搭建QQ机器人 前言:知识与储备 这个QQ机器人能干什么? 第一步:搭建Maven项目环境 第二步:编写pom文件 第三步:编写启动类 第四步:创建配置文件 第 ...
- TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%)
TF之GD:基于tensorflow框架搭建GD算法利用Fashion-MNIST数据集实现多分类预测(92%) 目录 输出结果 实现代码 输出结果 Successfully downloaded t ...
- 基于 SSM 框架搭建的宠物领养系统
近年来,随着人们对于宠物领养.保护的意识日益提高,宠物领养市场逐渐走向规范化.高效化.而针对这一市场需求,基于 SSM 框架搭建的宠物领养系统应运而生. 一.关于 SSM 框架 SSM 是一个基于 S ...
- 基于SSM框架搭建的论坛系统
基于SSM框架搭建的论坛系统 页面展示: 主页 帖子页面 论坛数据库设计 SSM框架搭建 RootConfig.java WebConfig.java WebInit.java 配置po模型 User ...
- 基于Mirai框架的QQ机器人使用文档----郑大科协2021招新群
目录 1. 引言 1.1 编写目的 1.2 项目背景 1.3 参考链接 2. 使用说明 2.1 关于插件 2.2 自动功能 2.3 交互功能 2.4 插件链接 3. 出错与恢复 3.1 自动功能出错 ...
- 用Python开发基于Mirai框架的QQ机器人-1. 安装与搭建
首先,要安装mirai-console-loader,以下简称mcl,github仓库位置:mirai-console-loader. 下载解压后,用cmd进入mcl的目录,运行mcl就可以了,设置就 ...
- 基于SSM框架搭建的个人博客网站(可用于毕业设计)
项目背景 个人学习Spring+SpringMVC+MyBatis框架整合练习时搭建的一个网站. 使用的技术栈 Spring SpringMVC MyBatis 国际化框架 shrio校验框架 jsp ...
- YMP框架学习笔记(二)------基于YMP框架搭建WEB应用程序
2019独角兽企业重金招聘Python工程师标准>>> 大神的YMP框架:https://github.com/suninformation/ymateplatform.git 1. ...
最新文章
- java 连续打印_Java实现连续打印ABC
- 定义一个带参带返回值的方法,实现输出随机数数组
- Android Studio中统一管理版本号引用配置
- 【C 语言】文件操作 ( 写文本文件 | Qt 创建 C 语言命令行项目 )
- [CPP]--Unicode 字符编码
- tomcat下manager配置
- 最大流最小割经典例题_C/C++知识点之最大流最小割C++实现
- extjs--combox用法
- 如何拿到阿里算法校招offer
- 述 SQL 中的 distinct 和 row_number() over() 的区别及用法
- 英特尔“Beach”图片泄露 Optane SSD路线图成关注焦点
- [ZJOI2007]捉迷藏 (线段树,括号序列)
- 第一期:一款简单好用的屏幕画笔工具
- 快乐刷课---Tampermonkey下载使用
- 期货开户后需要银期转账绑定
- 【操作系统安全】_Win7Win8系列提权漏洞
- ros机器人gazebo仿真
- 青少年CTF--misc部分题解
- Adobe也封杀中国账号了,技术管理者如何做到有备无患
- 华为朗读屏幕怎么关闭
热门文章
- 数据分析 --- 五力模型 VS PEST(分析模型)VS SWOT分析法
- 是什么让你感受到了中年危机,如何应对即将到来的中年危机
- 气动和液压的差异点,可能会颠覆你的认知哦!
- 【AltiumDesigner专栏】01.05——ECAD-MCAD(一)
- 机器学习(多元线性回归模型逻辑回归)
- [翻译]跟我一起边译边学之Linux:致谢 Acknowledgments
- 百度关键词分析工具_百度网站关键词快排系统 - 网站被降权的原因分析
- IT人士获得老板青睐器重的五大秘决
- Idea导包正确还是显示标红(错误)
- 字节码:ASCII编码:单字节编码,ANSI编码:多字节编码,UNICODE编码:宽字节编码