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 相关文章推荐
Stop SQL Server
Jun 21 Javascript
深入理解JavaScript系列(12) 变量对象(Variable Object)
Jan 16 Javascript
JavaScript中switch语句的用法详解
Jun 03 Javascript
基于jquery animate操作css样式属性小结
Nov 27 Javascript
jQuery下拉菜单的实现代码
Nov 03 Javascript
简单实现js浮动框
Dec 13 Javascript
利用JavaScript实现拖拽改变元素大小
Dec 14 Javascript
十大 Node.js 的 Web 框架(快速提升工作效率)
Jun 30 Javascript
js构造函数创建对象是否加new问题
Jan 22 Javascript
React中使用async validator进行表单验证的实例代码
Aug 17 Javascript
javascript中的event loop事件循环详解
Dec 14 Javascript
详解JS函数防抖
Jun 05 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
模拟xcopy的函数
2006/10/09 PHP
php使用fopen创建utf8编码文件的方法
2014/10/31 PHP
php命令行(cli)下执行PHP脚本文件的相对路径的问题解决方法
2015/05/25 PHP
php实现给一张图片加上水印效果
2016/01/02 PHP
PHP上传图片类显示缩略图功能
2016/06/30 PHP
thinkPHP框架实现生成条形码的方法示例
2018/06/06 PHP
PHP与以太坊交互详解
2018/08/24 PHP
arguments对象
2006/11/20 Javascript
jquery实现鼠标滑过小图时显示大图的方法
2015/01/14 Javascript
基于jQuery实现的扇形定时器附源码下载
2015/10/20 Javascript
JavaScript引用类型Object常见用法实例分析
2018/08/08 Javascript
vue iview多张图片大图预览、缩放翻转
2019/07/13 Javascript
通过微信公众平台获取公众号文章的方法示例
2019/12/25 Javascript
js+canvas绘制图形验证码
2020/09/21 Javascript
[53:21]2014 DOTA2国际邀请赛中国区预选赛5.21 DT VS LGD-CDEC
2014/05/22 DOTA
[01:15]《辉夜杯》北京网鱼队巡礼
2015/10/26 DOTA
[10:18]2018DOTA2国际邀请赛寻真——Fnatic能否笑到最后?
2018/08/14 DOTA
[49:11]完美世界DOTA2联赛PWL S3 INK ICE vs DLG 第二场 12.20
2020/12/23 DOTA
Python 内置函数complex详解
2016/10/23 Python
Django基于ORM操作数据库的方法详解
2018/03/27 Python
Python 分享10个PyCharm技巧
2019/07/13 Python
Python3.6+selenium2.53.6自动化测试_读取excel文件的方法
2019/09/06 Python
使用 css3 实现圆形进度条的示例
2017/07/05 HTML / CSS
详解HTML5中CSS外观属性
2020/09/10 HTML / CSS
Html5+CSS3+EL表达式问题小结
2020/12/19 HTML / CSS
爱尔兰灯和灯具网上商店:Lights.ie
2018/03/26 全球购物
与世界上最好的跑步专业品牌合作:Fleet Feet
2019/03/22 全球购物
Ajax的优点和缺点
2014/11/21 面试题
十佳青年个人事迹材料
2014/01/28 职场文书
旷课检讨书1000字
2014/02/14 职场文书
2014年教师党员自我评价范文
2014/09/22 职场文书
2015年防汛工作总结
2015/05/15 职场文书
暑假生活随笔
2015/08/15 职场文书
2016年5月份红领巾广播稿
2015/12/21 职场文书
pytorch中F.avg_pool1d()和F.avg_pool2d()的使用操作
2021/05/22 Python
用php如何解决大文件分片上传问题
2021/07/07 PHP