Rasa Stack:创建支持上下文的人工智能助理和聊天机器人教程
相关概念
Rasa Stack 是一组开放源码机器学习工具,供开发人员创建支持上下文的人工智能助理和聊天机器人:
• Core = 聊天机器人框架包含基于机器学习的对话管理
• NLU = 用于自然语言理解的库包含意图识别和实体提取
NLU 和 Core 是独立的。您可以使用没有 Core 的 NLU,反之亦然。我们建议两者都使用。
让我们从一个例子开始。想象一下你已经建立了一个人工智能助理来预约医生。在谈话开始时,你问你的用户你在找什么?他们回答我需要94301的家庭医生。现在是 Rasa Stack 开始工作的时候了:
rasa-ecosystem.png
1. NLU根据您之前的训练数据了解用户的信息:
• 意图分类:根据预先定义的意图解释含义(例如:我需要94301中的一个GP是一个寻找医生意图的置信度是93%)
• 实体提取:识别结构化数据(例如:gp 是医生类型和 94301 是一个邮政编码)
2. Core 决定本次对话接下来会发生什么。它是基于机器学习的对话管理,根据 NLU 的输入、对话历史和您的训练数据预测下一个最佳行动。(例如:Core 有87%的信心,预约是下一个最佳操作,与用户确认是否希望更改主要联系信息)。
尝试一下
原文链接可以直接交互,译文只能展示流程,交互效果请查看最后的原文链接体验。
本教程将向您展示构建机器人所需的不同部分。您可以在文档中直接运行代码,而无需安装任何东西,也可以安装 Rasa Core 并在本地计算机上的 Jupyter notebook 中运行示例!如果您想在本地运行这个,请转到步骤3:首先开始构建来安装 Rasa Stack 。
目标
你将建立一个友好的聊天机器人,它会问你做得怎么样,并发送一张有趣的图片给你,让你在悲伤时振作起来。
mood_bot.png
使用 RASA NLU 教 bot 了解用户输入
1. 创建 NLU 案例
你首先要教你的助手理解你的信息。为此,您将训练 NLU 模型,该模型将以简单的文本格式接收输入并提取结构化数据。这种称为意图的结构化数据将帮助bot理解您的消息。
您要做的第一件事是定义bot应该理解的用户消息。您将通过定义意图并提供一些用户表达意图的方法来实现这一点。
运行下面的代码单元将 RASA NLU 训练示例保存到文件nlu.md:
nlu_md = """## intent:greet- hey- hello- hi- good morning- good evening- hey there## intent:goodbye- bye- goodbye- see you around- see you later## intent:mood_affirm- yes- indeed- of course- that sounds good- correct## intent:mood_deny- no- never- I don't think so- don't like that- no way- not really## intent:mood_great- perfect- very good- great- amazing- wonderful- I am feeling very good- I am great- I'm good## intent:mood_unhappy- sad- very sad- unhappy- bad- very bad- awful- terrible- not very good- extremely sad- so sad"""%store nlu_md > nlu.mdprint("The data has been successfully saved inside the nlu.md file! You can move on to the next step!")## intent:greet
- hey
- hello
- hi
- good morning
- good evening
- hey there
## intent:goodbye
- bye
- goodbye
- see you around
- see you later
## intent:mood_affirm
- yes
- indeed
- of course
- that sounds good
- correct
## intent:mood_deny
- no
- never
- I don't think so
- don't like that
- no way
- not really
## intent:mood_great
- perfect
- very good
- great
- amazing
- wonderful
- I am feeling very good
- I am great
- I'm good
## intent:mood_unhappy
- sad
- very sad
- unhappy
- bad
- very bad
- awful
- terrible
- not very good
- extremely sad
- so sad
"""
%store nlu_md > nlu.md
print("The data has been successfully saved inside the nlu.md file! You can move on to the next step!")
2. 定义NLU模型配置
NLU模型配置定义如何训练NLU模型以及如何从文本输入中提取特征。在本例中,您将使用一个预定义的 TensorFlow_Embedding Pipeline,您可以在这里了解更多信息。
下面的代码块将把NLU模型配置保存到名为 nlu_config.yml 的文件中。
nlu_config = """language: enpipeline: tensorflow_embedding"""%store nlu_config > nlu_config.ymlprint("The configuration has been successfully stored inside the nlu_config.yml file. You can now move on to the next step!")3.训练 NLU 模型现在您拥有训练 NLU 模型所需的所有组件。运行下面的单元,该单元将调用 rasa.nlu 模型,传递先前定义的 nlu.md 和 nlu_config.yml 文件,并将模型保存在 models/current/nlu 目录中。from rasa_nlu.model import Metadata, Interpreterimport jsondef pprint(o): # small helper to make dict dumps a bit prettier print(json.dumps(o, indent=2))interpreter = Interpreter.load('./models/current/nlu')pprint(interpreter.parse(u"Hello"))
%store nlu_config > nlu_config.yml
print("The configuration has been successfully stored inside the nlu_config.yml file. You can now move on to the next step!")
3.训练 NLU 模型
现在您拥有训练 NLU 模型所需的所有组件。运行下面的单元,该单元将调用 rasa.nlu 模型,传递先前定义的 nlu.md 和 nlu_config.yml 文件,并将模型保存在 models/current/nlu 目录中。
from rasa_nlu.model import Metadata, Interpreter
import json
def pprint(o):
# small helper to make dict dumps a bit prettier
print(json.dumps(o, indent=2))
interpreter = Interpreter.load('./models/current/nlu')
pprint(interpreter.parse(u"Hello"))
4. 测试模型
现在,您可以测试模型,看看机器人是否能理解您。下面的代码块将加载您刚刚培训的模型,并返回消息hello的意向分类结果。您也可以通过编辑hello字符串对不同的消息进行测试:
from rasa_nlu.model import Metadata, Interpreterimport jsondef pprint(o): # small helper to make dict dumps a bit prettier print(json.dumps(o, indent=2))interpreter = Interpreter.load('./models/current/nlu')pprint(interpreter.parse(u"Hello"))import Metadata, Interpreter
import json
def pprint(o):
# small helper to make dict dumps a bit prettier
print(json.dumps(o, indent=2))
interpreter = Interpreter.load('./models/current/nlu')
pprint(interpreter.parse(u"Hello"))
使用 Rasa Core 指导机器人做出响应
5. 写故事
在这个阶段,您将教您的聊天机器人使用 Rasa Core 响应您的消息。 Rasa Core 将训练对话管理模型,并预测机器人应如何在对话的特定状态下做出响应。
Rasa Core 模型以训练“故事”的形式从真实的会话数据中学习。故事是用户和机器人之间的真实对话,其中用户输入表示为意图和机器人的响应被表示为动作名称。下面是一个简单对话的例子:用户向我们的机器人打招呼,机器人向我们打招呼。这就是它看起来像一个故事:
## story1* greet - utter_greet# story1
* greet
- utter_greet
故事以 ## 开头 跟随着的是名字(可选)。以 * 开头的行是用户发送的消息。虽然您不写实际的消息,但它代表了用户的意图。以 - 开头的行是您的bot所采取的操作。在这种情况下,我们的所有操作都只是发送回用户的消息,比如说问候语,但是一般来说,一个操作可以做任何事情,包括调用API和与外部世界交互。
运行下面的单元格将示例故事保存在名为'stories.md'的文件中:
stories_md = """## happy path* greet - utter_greet* mood_great - utter_happy## sad path 1* greet - utter_greet* mood_unhappy - utter_cheer_up - utter_did_that_help* mood_affirm - utter_happy## sad path 2* greet - utter_greet* mood_unhappy - utter_cheer_up - utter_did_that_help* mood_deny - utter_goodbye## say goodbye* goodbye - utter_goodbye"""%store stories_md > stories.mdprint("The training stories have been successfully saved inside the stories.md file. You can move on to the next step!")## happy path
* greet
- utter_greet
* mood_great
- utter_happy
## sad path 1
* greet
- utter_greet
* mood_unhappy
- utter_cheer_up
- utter_did_that_help
* mood_affirm
- utter_happy
## sad path 2
* greet
- utter_greet
* mood_unhappy
- utter_cheer_up
- utter_did_that_help
* mood_deny
- utter_goodbye
## say goodbye
* goodbye
- utter_goodbye
"""
%store stories_md > stories.md
print("The training stories have been successfully saved inside the stories.md file. You can move on to the next step!")
6. 定义域
接下来我们需要做的就是定义一个域。这个域定义了你的机器人所处的世界——它应该得到什么样的用户输入,它应该能够预测什么样的动作,如何响应以及存储什么样的信息。下面是我们的bot的一个示例域,您将写入名为domain.yml的文件:
domain_yml = """intents: - greet - goodbye - mood_affirm - mood_deny - mood_great - mood_unhappyactions:- utter_greet- utter_cheer_up- utter_did_that_help- utter_happy- utter_goodbyetemplates: utter_greet: - text: "Hey! How are you?" utter_cheer_up: - text: "Here is something to cheer you up:" image: "https://i.imgur.com/nGF1K8f.jpg" utter_did_that_help: - text: "Did that help you?" utter_happy: - text: "Great carry on!" utter_goodbye: - text: "Bye""""%store domain_yml > domain.ymlprint("The domain has been successfully saved inside the domain.yml file. You can move on to the next step!")"
intents:
- greet
- goodbye
- mood_affirm
- mood_deny
- mood_great
- mood_unhappy
actions:
- utter_greet
- utter_cheer_up
- utter_did_that_help
- utter_happy
- utter_goodbye
templates:
utter_greet:
- text: "Hey! How are you?"
utter_cheer_up:
- text: "Here is something to cheer you up:"
image: "https://i.imgur.com/nGF1K8f.jpg"
utter_did_that_help:
- text: "Did that help you?"
utter_happy:
- text: "Great carry on!"
utter_goodbye:
- text: "Bye"
"""
%store domain_yml > domain.yml
print("The domain has been successfully saved inside the domain.yml file. You can move on to the next step!")
那么不同的部分意味着什么呢?
intents:你希望用户说的话。见Rasa NLU
actions:你的机器人能做和说的事情
templates:模板字符串用于bot可以说的内容
这是怎么结合起来的?Rasa Core的工作是在对话的每个步骤中选择要执行的正确操作。简单的操作只是向用户发送一条消息。这些简单的操作是域中的操作,从 utter_ 开始。他们只会根据模板部分中的模板回复一条消息。有关如何构建更有趣的操作,请参见自定义操作。
7. 训练对话模型
下一步是在我们的例子中训练一个神经网络。要执行此操作,请运行下面的命令。此命令将调用Rasa Core 训练功能,将域和故事文件传递给它,并将训练后的模型存储到models/dialogue目录中。此命令的输出将包括每个训练阶段的训练结果。
!python -m rasa_core.train -d domain.yml -s stories.md -o models/dialogueprint("Finished training! You can move on to the next step!")o models/dialogue
print("Finished training! You can move on to the next step!")
8. 和你的机器人聊天
就这样!现在你已经拥有了开始与机器人交互所需的一切!让我们使用下面的命令启动您的完整bot,包括rasa core和rasa nlu模型!
如果您没有运行上面的单元,这将不起作用!
import IPythonfrom IPython.display import clear_output, HTML, displayfrom rasa_core.agent import Agentfrom rasa_core.interpreter import RasaNLUInterpreterimport timeinterpreter = RasaNLUInterpreter('models/current/nlu')messages = ["Hi! you can chat in this window. Type 'stop' to end the conversation."]agent = Agent.load('models/dialogue', interpreter=interpreter)def chatlogs_html(messages): messages_html = "" for m in messages: if m.endswith('.jpg'): messages_html += "<img src={}, alt='Tiger pub'></img>".format(m) else: messages_html += "<p>{}</p>".format(m) chatbot_html = """<div class="chat-window" {}</div>""".format(messages_html) return chatbot_htmlwhile True: clear_output() display(HTML(chatlogs_html(messages))) time.sleep(0.3) a = input() messages.append(a) if a == 'stop': break responses = agent.handle_message(a) for r in responses: key = 'image' if 'image' in r.keys() else 'text' messages.append(r.get(key))
from IPython.display import clear_output, HTML, display
from rasa_core.agent import Agent
from rasa_core.interpreter import RasaNLUInterpreter
import time
interpreter = RasaNLUInterpreter('models/current/nlu')
messages = ["Hi! you can chat in this window. Type 'stop' to end the conversation."]
agent = Agent.load('models/dialogue', interpreter=interpreter)
def chatlogs_html(messages):
messages_html = ""
for m in messages:
if m.endswith('.jpg'):
messages_html += "<img src={}, alt='Tiger pub'></img>".format(m)
else:
messages_html += "<p>{}</p>".format(m)
chatbot_html = """<div class="chat-window" {}</div>""".format(messages_html)
return chatbot_html
while True:
clear_output()
display(HTML(chatlogs_html(messages)))
time.sleep(0.3)
a = input()
messages.append(a)
if a == 'stop':
break
responses = agent.handle_message(a)
for r in responses:
key = 'image' if 'image' in r.keys() else 'text'
messages.append(r.get(key))
祝贺你!你刚刚从头开始构建了一个机器人,完全由机器学习提供动力。为什么不玩耍上面的代码呢?
教你的机器人更好地理解你。添加更多的NLU数据,重新导入NLU模型并重新启动bot。
添加更多的故事以提供更多关于您的bot应该如何工作的示例。然后重新训练 Rasa Core 模型来尝试它!
编辑域中的响应模板,重新导入模型并查看结果!
现在,您已经准备好构建自己的机器人了!立即安装并立即运行。
英文原文:https://rasa.com/docs/get_started_step1/
欢迎关注磐创博客资源汇总站:
http://docs.panchuang.net/
欢迎关注PyTorch官方中文教程站:
http://pytorch.panchuang.net/
Rasa Stack:创建支持上下文的人工智能助理和聊天机器人教程的更多相关文章
- 【python】使用python十分钟创建个人聊天机器人教程
以青云客和图灵机器人接口示范python创建个人聊天机器人教程 一.以青云客聊天机器人为例示范get请求 官方网址:http://api.qingyunke.com/ 1.接入指引 请求地址 http ...
- 创建支持复杂脚本Complex Scripts的WINCE6.0系统
如果要创建支持复杂脚本(Complex Scripts)的系统,我们需要完成下面一系列步骤来确保系统包含所有需要支持的具体区域设置 (locale–specific). 1. 选择intern ...
- WCF技术剖析之五:利用ASP.NET兼容模式创建支持会话(Session)的WCF服务
原文:WCF技术剖析之五:利用ASP.NET兼容模式创建支持会话(Session)的WCF服务 在<基于IIS的WCF服务寄宿(Hosting)实现揭秘>中,我们谈到在采用基于IIS(或者 ...
- 【ASP.NET Web API教程】2.1 创建支持CRUD操作的Web API
原文 [ASP.NET Web API教程]2.1 创建支持CRUD操作的Web API 2.1 Creating a Web API that Supports CRUD Operations2.1 ...
- Docker创建支持ssh服务的容器和镜像
原文链接:Docker创建支持ssh服务的容器和镜像 1. 这里使用的centos作为容器,所以首先下载centos的images # sudo docker pull centos 2. 下载后执行 ...
- 深入学习JS执行--创建执行上下文(变量对象,作用域链,this)
一.介绍 本篇继上一篇深入理解js执行--单线程的JS,这次我们来深入了解js执行过程中的执行上下文. 本篇涉及到的名词:预执行,执行上下文,变量对象,活动对象,作用域链,this等 二.预执行 在上 ...
- python类与对象-如何让对象支持上下文管理
如何让对象支持上下文管理 问题举例 一个telnet客户端的类TelnetClient, 调用实例的connect(),login(),interact方法 启动客户端与服务器交互,交互完毕后需要调用 ...
- 原创:MVC 5 实例教程(MvcMovieStore 新概念版:mvc5.0,EF6.01) - 4、创建数据上下文和数据实体模型
说明:MvcMovieStore项目已经发布上线,想了解最新版本功能请登录 MVC影视(MvcMovie.cn) 进行查阅.如需转载,请注明出处:http://www.cnblogs.com/Dodu ...
- 利用docker创建支持centos的ssh镜像
创建docker镜像需要基础镜像,目前官方已提供了多种基础镜像,参见: https://hub.docker.com/explore/ 要想创建支持centos的ssh镜像,就需要以centos镜像为 ...
随机推荐
- [置顶]
Python 使用itchat 对微信好友数据进行简单分析
人生苦短,我用Python! Python 热度一直很高,我感觉这就是得益于拥有大量的包资源,极大的方便了开发人员的需求. 最近在一个微信公众号上看到一个调用微信 API 可以对微信好友进行简单数据分 ...
- JavaScript中prompt的使用
*/ * Copyright (c) 2016,烟台大学计算机与控制工程学院 * All rights reserved. * 文件名:text.js * 作者:常轩 * 微信公众号:Worldhel ...
- java.lang.SecurityException: class "javax.servlet.AsyncContext"'s signer information does not match signer information of other classes in the same package
最近在写个Http协议的压测挡板时,遇到以下错误. 2018-03-08 10:34:07.808:INFO:oejs.Server:jetty-8.1.9.v20130131 2018-03-08 ...
- linux lsof常用方法
lsof简介 lsof(list open files)是一个列出当前系统打开文件的工具,在linux环境下,任何事物都是以文件形式存在,通过文件不仅仅可以访问常规数据,还可以访问网络连接和硬件.系统 ...
- date成字符串
//获取当前时间 Date date=new Date(); System.out.println("当前date: "+date); //将时间转化成yyyy-MM-dd格式的字 ...
- 用jQuery怎么做到前后端分离
传统的web开发模式想必大家都知道,不管是jsp.asp.php或者一些魔板引擎开发,其实道理都是一样的,都是服务端渲染,原理是:浏览器发送一个get请求,服务器对应的返回前端一个html页面,由浏览 ...
- safari坑之 回弹
博客地址: https://www.seyana.life/post/20 今天在使用safari浏览博客的时候, 发现在拉至顶部并产生回弹之后,头部导航隐藏了, 除非在上拉的时候,刚好达到顶部而不超 ...
- 选择结构二switch选择结构
在上一章节我们讲解了if选择结构 本章我们学习 switch选择结构 还要知道if选择结构和switch结构的区别 为什么学习了if选择结构还要学习switch选择结构 以及 两种选择结构的运用 ...
- 【vue】---- 图片懒加载
1.作用 在图片较多的页面中,页面加载性能较差.使用图片懒加载可以让图片出现在可视区域时再进行加载,从而提高用户体验. 2.原理 设置img标签的src属性为空或统一的图片路径(如加载中样式),监听页 ...
- php中的进程
pcntl扩展:主要的进程扩展,完成进程创建于等待操作. posix扩展:完成posix兼容机通用api,如获取进程id,杀死进程等. sysvmsg扩展:实现system v方式的进程间通信之消息队 ...