1 需求分析
UNIT 是专业的对话系统定制化训练平台,不管是 app 、 web、 H5还是小程序 ,都可以轻松对接。小程序开发门槛很低,非常容易上手,跟UNIT进行对接,一两天就能搭建一个机器人助理,来尝试一下。
2 小程序开发过程
2.1注册小程序
注册地址:https://mp.weixin.qq.com/cgi-bin/registermidpage?action=index&lang=zh_CN
注册成功后在开发->开发者ID里找到AppID,这是开发小程序所需要的身份标识。然后填写服务器域名,需要用到的均要填上,如下图。
2.2 小程序的配置已基本完成,下一步需要下载开发工具了,下载地址是:
https://developers.weixin.qq.com/miniprogram/dev/devtools/download.html
2.3小程序开发文档,也是要看一看的:https://developers.weixin.qq.com/miniprogram/dev/framework/
2.4小程序开发界面
此处需要填入注册时带到的APPID。
2.5程序总体结构如下:
3 创建UNIT应用
3.1.进入UNIT主页,首先创建自己的机器人,命名为小智。
https://ai.baidu.com/unit/home
3.2.点击“我的技能”选项卡,点击“添加预置技能”
3.3选中“会议室预定”,在右侧可以输入对话,初步测试。点击“获取该技能”,即可将该技能加入到我的技能。
3.4点击“我的机器人”选项卡,然后点击“添加技能”,将预置技能加入到自己的机器人。
3.5可以看到机器人技能管理下已经加入了“会议室预定”技能,此处的技能ID在程序中会用到。
3.6点击机器人下方的“对话”,即可对机器人进行测试,以预定会议室为例,可以看出,技能能够根据用户输入开展多轮对话,自动询问必填槽位(会议时间)。
3.7首先要在控制台创建UNIT应用,获取API接口。点击“发布上线”,点击“获取API Key/Secret Key”。
3.8点击“创建应用”,输入应用名:个人助理小智,此处获得的AK、SK在程序中会用到。
3.9 接口API
程序中用到的API接口文档地址:
https://ai.baidu.com/docs#/UNIT-v2-API/top
请求URL:
由于目前为测试,采用沙盒环境:【不区分机房】https://aip.baidubce.com/rpc/2.0/unit/bot/chat
请求示例代码:
var https = require('https');
var qs = require('querystring');
var param = qs.stringify({
'access_token': '你的access_token'
});
var options = {
hostname: 'aip.baidubce.com',
path: '/rpc/2.0/unit/bot/chat?' + param,
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
}
};
var req = https.request(
options,
function (res) {
// 在标准输出中查看运行结果
res.pipe(process.stdout);
}
);
var postData = {
'log_id': '7758521',
'version': '2.0',
'request': {
'user_id': '88888',
'query_info': {
'asr_candidates': [],
'type': 'TEXT',
'source': 'KEYBOARD'
},
'bernard_level': 1,
'updates': '',
'query': '你好',
'client_session': '{"client_results":"", "candidate_options":[]}'
},
'bot_session': '',
'bot_id': '你的技能ID'
};
// 携带数据发送https请求
req.write(JSON.stringify(postData));
req.end();
4.程序实现
4.1.在根目录的app.json文件夹中增加:"pages/contact/contact"
会自动创建相关文件夹和相关文件。小程序默认进去即是contact页面
{
"pages": [
"pages/contact/contact",
"pages/index/index",
"pages/logs/logs"
],
"window": {
"backgroundTextStyle": "light",
"navigationBarBackgroundColor": "#fff",
"navigationBarTitleText": "WeChat",
"navigationBarTextStyle": "black"
},
"sitemapLocation": "sitemap.json"
}
4.2 app.js 中添加UNIT API调用代码:用来发送语义的API请求。
NLIRequest: function (corpus, arg) { // corpus是要发送的对话;arg是回调方法
var that = this;
// appkey
var appkey = that.globalData.NLPAppkey;
// appsecret
var appSecret = that.globalData.NLPAppSecret;
var api = "nli";
var timestamp = new Date().getTime();
// MD5签名
// var sign = md5.md5(appSecret + "api=" + api + "appkey=" + appkey + "timestamp=" + //timestamp + appSecret);
var rqJson = {
"bot_session": "",
"log_id": "7758521",
"request": {
"bernard_level": 0,
"client_session": "{\"client_results\":\"\", \"candidate_options\":[]}",
"query": corpus,
"query_info": {
"asr_candidates": [],
"source": "KEYBOARD",
"type": "TEXT"
},
"updates": "",
"user_id": "88888"
},
"bot_id": "64050",
"version": "2.0"
};
var rq = JSON.stringify(rqJson);
var nliUrl = that.globalData.NLPUrl;
// cusid是用来实现上下文的,可以自己随意定义内容,要够长够随机
var cusid = that.globalData.NLPCusid;
console.log("[Console log]:NLIRequest(),URL:" + nliUrl);
wx.request({
url: nliUrl,
data: rq,
header: { 'content-type': 'application/x-www-form-urlencoded' },
method: 'POST',
success: function (res) {
var resData = res.data;
console.log("[Console log]:NLIRequest() success...");
console.log("[Console log]:Result:");
console.log(resData);
var nli = JSON.stringify(resData);
// 回调函数,解析数据
typeof arg.success == "function" && arg.success(nli);
},
fail: function (res) {
console.log("[Console log]:NLIRequest() failed...");
console.error("[Console log]:Error Message:" + res.errMsg);
typeof arg.fail == "function" && arg.fail();
},
complete: function () {
console.log("[Console log]:NLIRequest() complete...");
typeof arg.complete == "function" && arg.complete();
}
})
},
4.3修改功能实现模块contact.js:主要用来控制页面的动态显示和需要的网络请求发送。
// 监听用户输入
Typing: function (e) {
var inputVal = e.detail.value;
var buttDis = true;
if (inputVal.length != 0) {
var buttDis = false;
}
that.setData({
sendButtDisable: buttDis,
})
},
// 调用语义接口
sendChat: function (e) {
let word = e.detail.value.ask_word ? e.detail.value.ask_word : e.detail.value;
that.addChat(word, 'r');
that.setData({
askWord: '',
sendButtDisable: true,
});
// 请求函数
that.sendRequest(word);
},
// 发送网络请求
sendRequest(corpus) {
app.NLIRequest(corpus, {
'success': function (res) {
if (res.status == "error") {
wx.showToast({
title: '返回数据有误!',
})
return;
}
that.NLIProcess(res);
},
'fail': function (res) {
wx.showToast({
title: '请求失败!',
})
return;
}
});
},
// 处理语义(拿到回答)
NLIProcess: function (res) {
var nlires = JSON.parse(res);
var nliArray = nlires.result.response.action_list[0].say;
console.log(nliArray);
that.addChat(nliArray, 'l');
return;
},
// 显示回答,并滚动到最新位置
addChat: function (word, orientation) {
that.addChatWithFlag(word, orientation, true);
},
// 显示回答并选择是否滚动到最新位置(true为是,false为否)
addChatWithFlag: function (word, orientation, scrolltopFlag) {
let ch = { 'text': word, 'time': new Date().getTime(), 'orientation': orientation };
chatListData.push(ch);
var charlenght = chatListData.length;
if (scrolltopFlag) {
that.setData({
chatList: chatListData,
scrolltop: "roll" + charlenght,
});
} else {
that.setData({
chatList: chatListData,
});
}
},
4.4修改页面样式文件contact.wxss
/* pages/contact/contact.wxss */
page {
background-color: #f1f1f1;
}
.inputRoom {
width: 100vw;
height: 16vw;
border-top: 1px solid #cdcdcd;
background-color: #f1f1f1;
position: fixed;
bottom: 0;
display: flex;
align-items: center;
z-index: 20;
}
input {
width: 76vw;
height: 9.33vw;
background-color: #fff;
border-radius: 40rpx;
margin-left: 2vw;
padding: 0 3vw;
font-size: 28rpx;
color: #444;
}
.leftMsg {
font-size: 35rpx;
color: #444;
line-height: 7vw;
padding: 2vw 2.5vw;
background-color: #fff;
margin-left: -1.6vw;
border-radius: 10rpx;
z-index: 10;
}
.rightMsg {
font-size: 35rpx;
color: #444;
line-height: 7vw;
padding: 2vw 2.5vw;
background-color: #96EB6A;
margin-right: -6.6vw;
border-radius: 10rpx;
z-index: 10; text-align: right;padding-right: 60rpx;
}
.avatar-imgl{
width: 11vw;
height: 11vw;
border-radius: 10rpx;
background-color: rgb(212, 61, 119);
}
.avatar-imgr{
width: 11vw;
height: 11vw;
border-radius: 10rpx;
background-color: rgb(16, 26, 165);
}
.message{
position: fixed;
bottom:0;
width: 100%;
}
.ask-input-word{
position: fixed;
bottom:0;
width: 100%;
display: block;
height: 80rpx;
padding: 10rpx 10rpx;
background-color: #fff;
border-top: 2rpx solid #eee;
border-bottom: 2rpx solid #eee;
z-index:3;
}
.ask-input-word input{
float:left;
width: 66%;
height: 100%;
line-height: 80rpx;
border-bottom: 1rpx solid #ccc;
padding:0 10rpx;
font-size: 35rpx;
color: #666;
}
.ask-input-word view{
display: inline-block;
width: 80rpx;
height: 80rpx;
line-height: 80rpx;
font-size: 60rpx;
text-align: center;
color: #999;
border: 1rpx solid #ccc;
border-radius: 50%;
margin-left: 10rpx;
}
.sendMessage button {
float: right;
font-size: 55rpx;
}
5.结果测试
请问有全部代码可以学习参考一下吗?正在做一个项目,实在是太需要了!查找了很多资料,您的这篇特别贴切!!谢谢谢谢!!!
这个有意思。真方便
请问,有源码可以学习下吗?
这个只是请求示例代码,说明而已,不在程序中
这个只是请求示例代码,说明而已,不在程序中
这个是以前的哦
你这个疫情的没审核通过?
同问
3.9 接口API这段代码是放在app.js还是contact.js里面?
我在GITHUB上也主要是搜索代码
没用过,有空研究一下
有没有源码分享,学习下。
可以放到GITHUB上
有源码吗 ?
已经升级
很期待,感谢分享
敬请期待……
后续更新语音版
审核程序太严苛了