UNIT是百度推出的智能对话定制和服务平台,搭载业界领先的需求理解、对话控制及底层的自然语言处理、知识挖掘等核心技术,可以让您的产品快速拥有对话交互能力。
2020年新冠疫情的爆发后,UNIT及时推出了疫情问答预置技能,利用AI技术,极大地方便了开发者开发疫情相关信息查询、咨询等技能,可支持一键获取技能,接入公众号、小程序、硬件产品、虚拟服务机器人等众多产品形态。下面来看如何通过百度小程序实现疫情信息的自动问答功能。
1 添加“疫情问答”预置技能
1.1进入UNIT主页,点击“进入UNIT”,https://ai.baidu.com/unit/home
1.2 点击“我的技能”选项卡,在预置技能处点击“获取技能”。此处生成的技能ID在后续程序中调用。
1.3 选中“疫情问答”,在右侧可以输入对话,初步测试。点击“获取该技能”,即可将该技能加入到我的技能。
2 百度小程序注册
2.1打开百度小程序官网,注册账号并登陆:
https://smartprogram.baidu.com/developer/index.html
注意:目前不支持人工开发者入驻小程序平台,需要注册企业类型账号才可以
2.2 进入开发者平台管理中心,新建小程序:
2.3 进入“开发设置”中,获取APP ID
2.4 配置服务器
3百度小程序开发过程
3.1下载并安装百度开发者工具:
https://smartprogram.baidu.com/docs/develop/tutorial/install/
3.2小程序开发流程参考开发文档:https://smartprogram.baidu.com/docs/develop/tutorial/startdevelop/
3.3创建项目
在根目录的全局配置文件app.json中增加:"pages/contact/contact" ,会自动创建相关页面文件,结构如下:
contact.js:功能逻辑模块
contact.css:页面样式文件
contact.swan:页面布局文件
contact.json:页面配置文件
4 调用UNIT接口,获得回答
4.1 首先要在控制台创建应用,调用UNIT接口,“获取API Key/Secret Key”。
接口文档地址:https://ai.baidu.com/docs#/UNIT-v2-API/top
请求URL: https://aip.baidubce.com/rpc/2.0/unit/bot/chat
4.2核心代码
const app = getApp(); var api = require('../../utils/get_token.js'); const recorderManager = swan.getRecorderManager(); const fs = swan.getFileSystemManager(); var inputVal = ''; var msgList = []; var windowWidth = swan.getSystemInfoSync().windowWidth; var windowHeight = swan.getSystemInfoSync().windowHeight; var keyHeight = 0; var that; var chatListData = []; var filePath; /** * 获取token */ //header文件 var content_type = "application/json"; //client_id 为官网获取的AK, client_secret 为官网获取的SK var client_id = '*****************'; var client_secret = '***************'; var tts_token = ''; /** * 初始化数据 */ function initData(that) { inputVal = ''; //获取TTS_token that.read_token(client_id, client_secret, content_type); } Page({ /** * 页面的初始数据 */ data: { // 自定义欢迎语的语料 defaultCorpus: '', // 用户输入 askWord: '', // 发送按钮disable sendButtDisable: true, // 用户信息 userInfo: {}, // 对话信息 chatList: [], // 对话滚动标志 scrolltop: '', toView: '', // 用户Logo,如果用户不授权,则使用默认图像 userLogoUrl: '/res/image/user_default.png', keyboard: '', scrollHeight: '92vh', inputBottom: 0, value: '', focus: true, hasResult: false, showEmptyResult: false, blur: true }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { initData(this); }); that = this; // 取得用户信息,把用户头像放入用户Logo中 app.getUserInfo(function (userInfo) { var aUrl = userInfo.avatarUrl; if (aUrl != null) { that.setData({ userLogoUrl: aUrl }); } }); // 自定义欢迎语 // this.sendRequest(this.data.defaultCorpus); that.addChat('万众一心,抗击疫情。您可以这样问我:最新确诊病例?', 'l'); }, /** * 生命周期函数--监听页面显示 */ onShow: function () { swan.setPageInfo({ title: '智子问答', keywords: '智能,问答,冠状病毒,肺炎', description: '新型冠状病毒相关信息智能问答', success: res => { console.log('setPageInfo success', res); }, fail: err => { console.log('setPageInfo fail', err); } }) }, /** * 页面相关事件处理函数--监听用户下拉动作 */ onPullDownRefresh: function () {}, /** * 页面上拉触底事件的处理函数 */ onReachBottom: function () {}, /** * 获取聚焦 */ focus: function (e) { keyHeight = e.detail.height; this.setData({ scrollHeight: windowHeight - keyHeight + 'px' }); this.setData({ toView: 'msg-' + (msgList.length - 1), inputBottom: keyHeight + 'px' }); //计算msg高度 // calScrollHeight(this, keyHeight); }, //失去聚焦(软键盘消失) blur: function (e) { this.setData({ scrollHeight: '90vh', inputBottom: 0 }); this.setData({ toView: 'msg-' + (msgList.length - 1) }); }, // 监听用户输入 Typing: function (e) { var inputVal = e.detail.value; var buttDis = true; if (inputVal.length != 0) { var buttDis = false; } that.setData({ sendButtDisable: buttDis }); }, searchFocus(e) { this.setData({ focus: true }); }, searchInput(e) { const value = e.detail.value; this.setData({ value, component: [], api: [], hasResult: false, showEmptyResult: false }); if (!value) { this.resetResult(); return false; } if (value.length === 1 && /[a-zA-Z]/.test(value)) { this.resetResult(); return false; } }, searchConfirm(e) { const value = this.getData('value').replace(/\s/gi, ''); that.addChat(value, 'r'); // 请求函数 that.sendRequest(value); if (value) { this.setData({ showEmptyResult: true, hasHistory: true }); } }, searchBlur(e) { this.setData({ focus: false }); }, searchClear() { this.setData({ value: '', hasResult: false, showEmptyResult: false }); }, // 调用语义接口 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); // that.voiceAnalysis(word); }, // 发送UNIT网络请求 sendRequest(corpus) { that.read_token(client_id, client_secret, content_type); console.log("ok!! tts_token:", tts_token); app.NLIRequest(corpus, { 'success': function (res) { if (res.status == "error") { swan.showToast({ title: '返回数据有误!' }); return; } that.NLIProcess(res); }, 'fail': function (res) { swan.showToast({ title: '请求失败!' }); return; } }); }, // 处理语义(拿到回答) NLIProcess: function (res) { var nlires = JSON.parse(res); var nliArray = nlires.result.response.action_list[0].say; // var nliArray = nlires.result; // console.log(nliArray); that.addChat(nliArray, 'l'); that.tts(nliArray); 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 }); } }, switchInputType: function () { this.setData({ keyboard: !this.data.keyboard }); }, // 获取token read_token: function (client_id, client_secret, content_type) { api.get_token(client_id, client_secret, content_type, { 'success': function (res) { var resData = JSON.parse(res); tts_token = resData.access_token; // console.log("[Console log]access_token:" + tts_token); return; }, 'fail': function (res) { swan.showToast({ title: '请求token失败!' }); return; } }); }, });
5 测试效果
测试效果如图,响应速度快,回复数据准确,支持疫情实时数据和疫情科普知识的问答,可支持的问答范围主要是关于新冠病毒科普、消毒/隔离方法、疫情相关政策查询、感染症状、快递和外卖的防疫、防传染辟谣、家有老人/儿童/孕妇的防疫问答等知识类型。更多问答知识还在持续更新中。
百度小程序目前还只支持企业开发者
百度小程序 智子问答,已上线