模块rodas方法"/>
python json模块rodas方法
作者 | Alfian Losari
来源 | Medium
编辑| 代码医生团队
对于使用Google的Dialogflow的开发人员来说,创建基于Chatbot的机器学习应用程序变得更加容易。根据谷歌:
Dialogflow是一个端到端的开发套件,用于为网站,移动应用程序,流行的消息传递平台和物联网设备构建对话界面。开发人员可以使用它来构建能够在用户和企业之间进行自然和丰富交互的界面(例如,聊天机器人)。它由机器学习提供支持,以识别用户所说的意图和背景,允许对话界面提供高效和准确的响应。
在本文中,我们将使用Dialogflow构建一个Chatbot库存跟踪应用程序,为简单起见,我们将使用Firebase实时数据库来存储我们的产品描述和库存数量。我们将使用Dialogflow履行webhook,它将触发Google Cloud功能并根据操作处理响应。该应用程序将使用Flutter,因此它可以在iOS和Android上运行。可以访问项目GitHub存储库。
我们将建立什么
产品的Dialogflow实体:实体将为用户操作/意图提供特定的上下文。
Dialogflow意图产品描述和产品数量。意图表示用户想要询问的特定操作。
Firebase实时数据库:我们将包含库存中描述和数量的产品数据存储在数据库中,以便Fullfillment webhook可以查询用户搜索内容并提供响应。
使用Google Cloud功能的Dialogflow Fulfillment Webhook:webhook将获取请求查询操作和参数,然后根据用户操作,查询数据库中的描述或数量。
Flutter Project,移动前端应用程序:该应用程序显示用户的聊天列表UI,提供用户询问的输入,然后显示和说出响应。
设置Dialogflow
在开始之前,请转到Dialogflow网站,单击右上角的Go to console。您需要使用Google帐户登录并授权才能使用Dialogflow。
登录后,我们需要创建新的代理。代理是我们将用于与我们的应用程序通信的Chatbot。为机器人提供所需的名称,确保将代理与Google Project相关联。您可以在此。我们需要这样做,以便我们可以利用Firebase功能实现webhook实现。
Dialogflow使用intent和实体来识别用户想要的内容和用户语句的上下文,因此bot可以将用户请求映射到操作。
一个意图代表之间有什么用户说,应该由你的软件采取什么行动的映射。
实体是用于从自然语言输入中提取参数值的强大工具。您希望从用户的请求获得的任何重要数据都将具有相应的实体。
一个动作对应步伐当一个特定的目的已经由用户输入触发您的应用程序将耗时。
默认情况下,Dialogflow提供2个默认意图,默认欢迎意图和默认回退意图。
创建产品实体
单击左侧面板上的添加实体,将实体命名为Products,选中允许自动扩展。我们将使用Dialogflow预构建的系统实体来处理将产品名称关联到实体中的问题。
创建产品描述意图
单击左侧面板上的添加意图,然后命名意图产品描述。此意图将在他们询问有关产品的详细信息/描述时处理用户操作。单击Training Phrases选项卡,然后在下面输入培训短语表达式,确保选择产品名称并将其与我们之前创建的Products Entity相关联。我提供了用户在想要获取产品信息时可能会问的各种变体。
单击Action和Parameters,然后添加product_description作为Intent操作。单击Fulfillment并确保为此意图启用webhook调用。
创建产品数量意图
像以前一样,单击左侧面板上的添加意图,然后命名意图产品数量。当用户询问产品是否可用或是否有库存时,此意图将处理用户操作。单击Training Phrases选项卡,然后在下面输入培训短语表达式,确保选择产品名称并将其与我们之前创建的Products Entity相关联。我提供了用户在询问产品是否可用或有库存时可能会询问的各种变体。
单击Action和Parameters,然后添加product_quantity作为Intent操作。单击Fulfillment并确保为此意图启用webhook调用。
将产品数据存储在Firebase实时数据库中
在Firebase中创建一个新项目或使用您已有的项目。我们将产品库存数据存储在实时数据库中。下面是我们将使用的架构和虚拟数据。产品父母拥有包含描述,名称和库存的产品子代。当我们在数据库中查询特定产品名称时,将使用子项的键。为简单起见,我们使用Firebase数据库,如果您想要更复杂的查询和聚合,可以使用自己的Postgres或MongoDB数据库。
Webhook Fulfillment Implementaion
为了实现意图动作响应,我们将使用webhook到Google Cloud Function,使用Dialogflow内联编辑器编辑和部署我们的webhook到GCP。确保为Inline Editor启用开关。如果需要,您还可以提供自定义webhook端点。
单击package.json选项卡并粘贴下面的依赖项。
{
"name": "dialogflowFirebaseFulfillment",
"description": "This is the default fulfillment for a Dialogflow agents using Cloud Functions for Firebase",
"version": "0.0.1",
"private": true,
"license": "Apache Version 2.0",
"author": "Google Inc.",
"engines": {
"node": "~6.0"
},
"scripts": {
"start": "firebase serve --only functions:dialogflowFirebaseFulfillment",
"deploy": "firebase deploy --only functions:dialogflowFirebaseFulfillment"
},
"dependencies": {
"actions-on-google": "2.0.0-alpha.4",
"firebase-admin": "^5.11.0",
"firebase-functions": "^1.0.0",
"dialogflow": "^0.1.0",
"dialogflow-fulfillment": "0.3.0-beta.3"
}
}
在firebase函数https onRequest处理程序内的index.js中,我们收到包含Dialogflow的queryResult的请求体,我们可以从查询结果中访问intent动作。我们还可以从查询结果中访问Products实体参数。我们初始化Firebase管理模块,以便我们可以使用它来访问我们的Firebase实时数据库。
我们检查操作是否等于product_description,然后此实现必须来自产品描述意图,对于产品数量意图相同。然后,我们使用从Products实体的查询结果中检索的product参数为产品的子项执行Firebase查询。然后,我们返回包含fullfillmentText键的响应json,其中包含库存数量描述的值。
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp();
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
const db = admin.database();
const action = request.body.queryResult.action;
if (action === 'product_description') {
const product = request.body.queryResult.parameters.Products.trim();
const ref = db.ref(`products/${product.toLowerCase()}/description`);
ref.once('value').then((snapshot) => {
const result = snapshot.val();
if (result === null) {
response.json({
fulfillmentText: `Product does not exists in inventory`
});
return;
}
response.json({
fulfillmentText: `Here is the description of ${product}: ${result}`,
source: action
});
}).catch((err) => {
response.json({
fulfillmentText: `I don't know what is it`
});
})
} else if (action === 'product_quantity') {
const product = request.body.queryResult.parameters.Products.trim();
const ref = db.ref(`products/${product.toLowerCase()}`);
ref.once('value').then((snapshot) => {
const result = snapshot.val();
if (result === null) {
response.json({
fulfillmentText: `Product does not exists in inventory`
});
return;
}
if (!result.stock) {
response.json({
fulfillmentText: `Currently ${product} is out of stock`,
source: action
});
} else {
response.json({
fulfillmentText: `We have ${result.stock} ${product} in stock`,
source: action
});
}
}).catch((err) => {
response.json({
fulfillmentText: `I don't know what is it`
});
})
} else {
response.json({
fulfillmentText: `I don't know what is it`
});
}
});
这就是Dialogflow的实现,请确保使用提供的部署按钮部署webhook。您可以使用Dialogflow网站中的右侧面板测试意图和响应。接下来,我们将使用Flutter构建移动应用程序。
构建Flutter应用程序
Flutter应用程序使用多个依赖项,例如:
flutter_dialogflow:flutter_dialogflow可以很容易地将对话流与Victor Alfonso Rodas的Flutter项目集成。
tts:Alex Blount的文字转语音插件。
这是我们的pubscpec.yaml依赖项:
dependencies:
flutter:
sdk: flutter
flutter_dialogflow: ^0.0.1
tts: ^1.0.1
在main.dart文件中。我们创建一个Stateful Widget,其中包含要显示的ChatMessage Stateless Widget数组和一个TextController,供用户输入他们想要发送到Chatbot的消息。
当用户点击send按钮时,使用handleSubmit方法,将以查询文本作为参数调用Response方法。使用flutter_dialogflow依赖项,我们初始化通过Dialogflow API令牌的Dialogflow对象,可以在Web控制台中检索令牌。然后我们调用传递查询的sendQuery方法。收到响应后,我们实例化传递messageResponse的新ChatMessage对象,并将其添加到setState方法内的ChatMessage数组中,以触发包含响应的新渲染。我们还使用tts包Tts对象讲话方法将响应消息传递给trigget文本到语音的响应。
import 'package:flutter/material.dart';
import 'package:flutter_dialogflow/flutter_dialogflow.dart';
import 'package:tts/tts.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget{
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Alf Chatbot',
theme: new ThemeData(
primarySwatch: Colors.indigo,
),
home: new MyHomePage(title: 'Alf Chatbot'),
debugShowCheckedModeBanner: false,
);
}
}
class MyHomePage extends StatefulWidget{
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
/* .dart */
class _MyHomePageState extends State{
final List _messages = [];
final TextEditingController _textController = new TextEditingController();
Widget _buildTextComposer() {
return new IconTheme(
data: new IconThemeData(color: Theme.of(context).accentColor),
child: new Container(
margin: const EdgeInsets.symmetric(horizontal: 8.0),
child: new Row(
children: [
new Flexible(
child: new TextField(
controller: _textController,
onSubmitted: _handleSubmitted,
decoration:
new InputDecoration.collapsed(hintText: "Send a message"),
),
),
new Container(
margin: new EdgeInsets.symmetric(horizontal: 4.0),
child: new IconButton(
icon: new Icon(Icons.send),
onPressed: () => _handleSubmitted(_textController.text)),
),
],
),
),
);
}
void Response(query) async {
_textController.clear();
Dialogflow dialogflow =Dialogflow(token: "Enter API KEY Here");
AIResponse response = await dialogflow.sendQuery(query);
ChatMessage message = new ChatMessage(
text: response.getMessageResponse(),
name: "Alf the Bot",
type: false,
);
Tts.speak(response.getMessageResponse());
setState(() {
_messages.insert(0, message);
});
}
void _handleSubmitted(String text) {
_textController.clear();
ChatMessage message = new ChatMessage(
text: text,
name: "Me",
type: true,
);
setState(() {
_messages.insert(0, message);
});
Response(text);
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Column(children: [
new Flexible(
child: new ListView.builder(
padding: new EdgeInsets.all(8.0),
reverse: true,
itemBuilder: (_, int index) => _messages[index],
itemCount: _messages.length,
)),
new Divider(height: 1.0),
new Container(
decoration: new BoxDecoration(color: Theme.of(context).cardColor),
child: _buildTextComposer(),
),
]),
);
}
}
class ChatMessage extends StatelessWidget{
ChatMessage({this.text, this.name, this.type});
final String text;
final String name;
final bool type;
List otherMessage(context) {
return [
new Container(
margin: const EdgeInsets.only(right: 16.0),
child: new CircleAvatar(child: new Image.asset("img/placeholder.png")),
),
new Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
new Text(this.name, style:new TextStyle(fontWeight:FontWeight.bold )),
new Container(
margin: const EdgeInsets.only(top: 5.0),
child: new Text(text),
),
],
),
),
];
}
List myMessage(context) {
return [
new Expanded(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
new Text(this.name, style: Theme.of(context).textTheme.subhead),
new Container(
margin: const EdgeInsets.only(top: 5.0),
child: new Text(text),
),
],
),
),
new Container(
margin: const EdgeInsets.only(left: 16.0),
child: new CircleAvatar(child: new Text(this.name[0])),
),
];
}
@override
Widget build(BuildContext context) {
return new Container(
margin: const EdgeInsets.symmetric(vertical: 10.0),
child: new Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: this.type ? myMessage(context) : otherMessage(context),
),
);
}
}
结论
这就是我们构建了一个利用机器学习的Chatbot应用程序。机器学习,人工智能技术的时代已经来临,我们作为开发人员几乎没有触及我们可以使用这些技术来构建可以赋予人们生活能力的应用程序。在计算机视觉和自然语言处理方面有很多进步,例如Dialogflow,作为开发人员,我们可以利用它来创建解决人员和业务问题的产品。快乐的飘飘,敬请期待!
关于图书
《深度学习之TensorFlow:入门、原理与进阶实战》和《Python带我起飞——入门、进阶、商业实战》两本图书是代码医生团队精心编著的 AI入门与提高的精品图书。配套资源丰富:配套视频、QQ读者群、实例源码。 深度学习之TensorFlow读者群,① 群聊号码:40016981 ② 群聊号码:786252868 让python带我起飞读者群,群聊号码:274962708
点击“阅读原文”图书配套视频
更多推荐
python json模块rodas方法
发布评论