vue+AI智能机器人回复功能实现


Posted in Javascript onJuly 16, 2020

本文实例为大家分享了vue+AI智能机器人回复的具体代码,供大家参考,具体内容如下

操作步骤

  • 引入前端代码

前端代码是参考github上的一个开源项目,里面包括AI机器人回复和聊天室两个模块,这里只抽取出来一个AI机器人回复的前端,有兴趣的话,可以点击查看

  • 封装好代理与请求

因为第三方API的请求是外网的,存在跨域问题,所以要配置代理,配置如下:

文件:vue.config.js

const vueConfig = {
 //上面还有项目的其他配置
 
 devServer: {
 port: 8000,
 proxy: {
  '/ai': {
  target: 'http://openapi.tuling123.com/',
  changeOrigin: true,
  pathRewrite: {'^/ai': ''}
  }
 }
 },
}
module.exports = vueConfig

配完代理后,创建请求实例:

文件: request.js

// 创建AI机器人回复请求axios实例
const aiService = axios.create({
 //VUE_APP_AI_BASE_URL=/ai
 //baseURL: process.env.VUE_APP_AI_BASE_URL,
 baseURL: '/ai',
 timeout: 10000
})

……

export {
 aiService as aiAxios
}
  • 调用第三方AI机器人的API

第三方AI机器人有很多,笔者尝试过阿里和图灵两个,调用方式都差不多,但是阿里的有点小贵,所以这里以图灵的为示例:

aiAxios.post('/openapi/api/v2', {
 reqType: '0',
 perception: {
 inputText: {
  text: this.inputContent
 }
 },
 userInfo: {
 //图灵上注册后自己的机器人apikey
 apiKey: '****',
 //登录用户用账户ID
 userId: '123456'
 }
 }).then(res => {
 let text= res.data.results[0].values.text;
 this.msgs.push({
 date: moment().format('YYYY-MM-DD HH:mm:ss'),
 from: '智能机器人',
 content: text,
 self: false,
 avatarUrl: aiHeadImg
 })
 this.$refs.chattingContent.scrollTop = this.$refs.chattingContent.scrollHeight
 }).catch(err => {
 this.$message.info(err);
})

整体示例代码

<template lang="html">
 <transition name="slide-right">
 <div class="chatting">
 <!-- 聊天界面头部 -->
 <div class="chatting-header">
 <div class="chatting-back">
  <i class="icon-back"></i>
 </div>
 <div class="chatting-title">
  <h2>AI 智能机器人</h2>
 </div>
 <div class="chatting-menu">
  <i class="icon-menu"></i>
 </div>
 </div>
 <!-- 聊天内容区域 -->
 <div ref="chattingContent" id="chattingContent" class="chatting-content">
 <div v-for="item of msgs">
  <!--用户输入内容-->
  <div v-if="item.self" class="chatting-item self clearfix">
  <div class="msg-date">
  {{ item.date }}
  </div>
  <div class="msg-from">
  <span class="msg-author">{{ item.from}}</span>
  <img :src="item.avatarUrl" alt="">
  </div>
  <div class="msg-content">{{ item.content }}</div>
  </div>
  <!--AI回复内容-->
  <div v-else class="chatting-item other clearfix">
  <div class="msg-date">
  {{ item.date }}
  </div>
  <div class="msg-from">
  <img :src="item.avatarUrl" alt="">
  <span class="msg-author">{{ item.from }}</span>
  </div>
  <div class="msg-content">{{ item.content }}</div>
  </div>
 </div>
 </div>
 <!-- 输入区域 -->
 <div class="chatting-input">
 <input @keyup.enter="send" v-model.trim="inputContent" placeholder="与智能机器人聊些啥">
 <button @click="send">发送</button>
 </div>
 </div>
 </transition>

</template>

<script>
 import {aiAxios} from '../../../utils/request'
 import moment from 'moment'
 //下面两张头像自己从网上随便找两张
 import aiHeadImg from '../../../assets/web/pub/images/head-ai.svg'
 import clientHeadImg from '../../../assets/web/pub/images/pltx.png'

 export default {
 name: 'chatting',
 data() {
 return {
 msgs: localStorage.msgs_ai && JSON.parse(localStorage.msgs_ai) || [],
 inputContent: '',
 oContent: {}
 }
 },
 watch: {
 msgs(val) {
 localStorage.msgs_ai = JSON.stringify(val);
 }
 },

 mounted() {
 this.oContent = document.getElementById('chattingContent');
 setTimeout(() => {
 this.$refs.chattingContent.scrollTop = this.$refs.chattingContent.scrollHeight
 }, 0)
 },
 methods: {
 //发送消息
 send() {
 this.oContent.scrollTop = this.oContent.scrollHeight;
 if (this.inputContent === '') {
  return;
 }

 this.msgs.push({
  date: moment().format('YYYY-MM-DD HH:mm:ss'),
  from: this.userInfo.personname || '匿名',
  content: this.inputContent,
  self: true,
  avatarUrl: clientHeadImg
 });
 setTimeout(() => {
  this.$refs.chattingContent.scrollTop = this.$refs.chattingContent.scrollHeight
 }, 0)

 this.getClientRobotReply()
 this.inputContent = '';
 },
 //图灵AI机器人回复
 getClientRobotReply() {
 aiAxios.post('/openapi/api/v2', {
  reqType: '0',
  perception: {
  inputText: {
  text: this.inputContent
  }
  },
  userInfo: {
  //图灵上注册后自己的机器人apikey
  apiKey: '****',
  //登录用户用账户ID
  userId: '123456'
  }
 }).then(res => {
  let text= res.data.results[0].values.text;
  this.msgs.push({
  date: moment().format('YYYY-MM-DD HH:mm:ss'),
  from: '智能机器人',
  content: text,
  self: false,
  avatarUrl: aiHeadImg
  })
  this.$refs.chattingContent.scrollTop = this.$refs.chattingContent.scrollHeight
 }).catch(err => {
  this.$message.info(err);
 })
 }
 }
 }
</script>

<style lang="less" scoped>
 .chatting {
 display: flex;
 flex-direction: column;

 width: 100%;
 height: 100%;

 .chatting-header {
 display: flex;
 justify-content: space-between;
 align-items: center;
 height: 50px;
 width: 100%;
 background-color: #2196f3;
 color: white;
 padding-left: 10px;
 padding-right: 15px;

 .chatting-back {
 width: 30px;
 height: 30px;
 i.icon-back {
  /*background: url('../../common/icons/icon-group2.svg') no-repeat;*/
  background-size: contain;
 }
 }

 .chatting-title {
 i.icon-group {
  vertical-align: top;
  width: 30px;
  height: 30px;
  //background: url('./images/icon-group.svg') no-repeat;
  background-size: contain;
  margin-right: 3px;
 }
 }

 .chatting-menu {
 width: 30px;
 height: 30px;
 i.icon-menu {
  /*background: url('../../common/icons/icon-index.svg') no-repeat;*/
  background-size: contain;
 }
 }
 }

 .chatting-content {
 flex: 1;
 width: 100%;
 background-color: rgba(0, 0, 0, .1);
 overflow: auto;
 .chatting-item {
 padding: 10px;
 width: 100%;
 .msg-date {
  text-align: center;
  color: gray;
  font-size: 80%;
 }
 .msg-from {
  display: flex;
  align-items: center;
  span.loc {
  color: gray;
  font-size: 60%;
  margin-right: 5px;
  }
  .msg-author {
  font-size: 1.2rem;
  }
  img {
  width: 30px;
  height: 30px;
  border-radius: 15px;
  }
 }
 .msg-content {
  margin-top: 5px;
  background-color: white;
  width: 200px;
  padding: 6px 10px;
  border-radius: 10px;
 }
 }

 .chatting-item + .chatting-item {
 margin-top: 10px;
 }
 .self {
 .msg-from {
  display: flex;
  justify-content: flex-end;
  align-items: center;
  img {
  margin-left: 10px;
  }
 }

 .msg-content {
  float: right;
  word-wrap: break-word;
  word-break: break-all;
  margin-right: 10px;
 }


 }

 .other {
 .msg-from {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  img {
  margin-right: 10px;
  }
 }

 .msg-content {
  float: left;
  margin-left: 10px;
  word-wrap: break-word;
  word-break: break-all;
 }

 }

 .online {
 width: 200px;
 // max-width: 100%;
 margin: 3px auto;
 border-radius: 4px;
 text-align: center;
 background-color: #FFFDE7;
 }
 }

 .chatting-input {
 display: flex;
 height: 40px;
 width: 100%;
 input {
 flex: 1;
 padding-left: 10px;
 // padding-top: 10px;
 height: 100%;
 font-size: 1.3rem;
 }
 button {
 width: 60px;
 height: 100%;
 background-color: #2196f3;
 color: white;
 font-size: 1.2rem;
 }
 }
 }
</style>

关于vue.js组件的教程,请大家点击专题vue.js组件学习教程进行学习。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Javascript 相关文章推荐
基于jquery打造的百分比动态色彩条插件
Sep 19 Javascript
JavaScript 函数的执行过程
May 09 Javascript
jQuery实现鼠标滚动图片延迟加载效果附源码下载
Jun 28 Javascript
require.js中的define函数详解
Jul 10 Javascript
浅谈JS中的常用选择器及属性、方法的调用
Jul 28 Javascript
vue引入js数字小键盘的实现代码
May 14 Javascript
Angular中sweetalert弹框的基本使用教程
Jul 22 Javascript
原生js实现移动端Touch轮播图的方法步骤
Jan 03 Javascript
Vue 事件处理操作实例详解
Mar 05 Javascript
详解js获取video任意时间的画面截图
Apr 17 Javascript
微信小程序批量监听输入框对按钮样式进行控制的实现代码
Oct 12 Javascript
node.js 微信开发之定时获取access_token
Feb 07 Javascript
vue.js实现h5机器人聊天(测试版)
Jul 16 #Javascript
15个简单的JS编码标准让你的代码更整洁(小结)
Jul 16 #Javascript
通过实例解析vuejs如何实现调试代码
Jul 16 #Javascript
详解js中的几种常用设计模式
Jul 16 #Javascript
JS寄快递地址智能解析的实现代码
Jul 16 #Javascript
详解js中的原型,原型对象,原型链
Jul 16 #Javascript
详解Webpack4多页应用打包方案
Jul 16 #Javascript
You might like
用PHP来写记数器(详细介绍)
2006/10/09 PHP
php中删除字符串中最先出现某个字符的实现代码
2013/02/03 PHP
eAccelerator的安装与使用详解
2013/06/13 PHP
thinkPHP模板中函数的使用方法示例
2016/11/30 PHP
php获取数据库中数据的实现方法
2017/06/01 PHP
PHP PDOStatement::fetchObject讲解
2019/02/01 PHP
Tab页界面,用jQuery及Ajax技术实现
2009/09/21 Javascript
Ext JS添加子组件的误区探讨
2013/06/28 Javascript
javascript教程:关于if简写语句优化的方法
2014/05/17 Javascript
js操作滚动条事件实例
2015/01/29 Javascript
原生js制作简单的数字键盘
2015/04/24 Javascript
JS实现选定指定HTML元素对象中指定文本内容功能示例
2017/02/13 Javascript
js css3实现图片拖拽效果
2017/03/04 Javascript
使用JavaScript实现alert的实例代码
2017/07/06 Javascript
原生JavaScrpit中异步请求Ajax实现方法
2017/11/03 Javascript
使用iView Upload 组件实现手动上传图片的示例代码
2018/10/01 Javascript
javascript异步处理与Jquery deferred对象用法总结
2019/06/04 jQuery
jQuery层叠选择器用法实例分析
2019/06/28 jQuery
[04:28]DOTA2亚洲邀请赛小组赛第五日 TOP10精彩集锦
2015/02/03 DOTA
python实现批量转换文件编码(批转换编码示例)
2014/01/23 Python
python中使用iterrows()对dataframe进行遍历的实例
2018/06/09 Python
python中dict字典的查询键值对 遍历 排序 创建 访问 更新 删除基础操作方法
2018/09/13 Python
django之跨表查询及添加记录的示例代码
2018/10/16 Python
python怎么判断模块安装完成
2020/06/19 Python
AmazeUI 输入框组的示例代码
2020/08/14 HTML / CSS
前端H5 Video常见使用场景简介
2020/08/21 HTML / CSS
布里斯班女装时尚品牌:Adrift
2017/12/28 全球购物
建筑设计学生的自我评价
2014/01/16 职场文书
优秀大学生的自我评价
2014/01/16 职场文书
《美丽的小兴安岭》教学反思
2014/02/26 职场文书
老人祝寿主持词
2014/03/28 职场文书
个人对照检查材料思想汇报(四风问题)
2014/09/25 职场文书
房产电话营销开场白
2015/05/29 职场文书
使用golang编写一个并发工作队列
2021/05/08 Golang
springboot+WebMagic+MyBatis爬虫框架的使用
2021/08/07 Java/Android
Linux7.6二进制安装Mysql8.0.27详细操作步骤
2021/11/27 MySQL