AI聊天-如何将消息发送给机器人 第4集

AI聊天-如何将消息发送给机器人

一、前言

上一篇我们讲解了如何让我们的消息发送框悬浮在固定位置,本编讲为大家讲解如何讲消息发送给机器人,这里需要用到http请求,后端需要提供对应的接口

二、源码资源

1、服务端代码已为大家准备好,请参考springboot的使用技巧
2、测试页面源码,请参考从零开始搭建AI聊天

三、实现思路

1、集成 sse客户端,并配置后端的服务请求地址

2、页面监听enter键,发送消息

3、讲返回的消息流拼接到dom并展示

四、重难度讲解

1、集成 sse客户端,并配置后端的服务请求地址

npm install eventsource

2、页面监听enter键

      <chat-send @sendMsg="sendMsg" ref="send"  @keydown.enter.native="sendText($event)"></chat-send>
    sendText(event){
      if (event.keyCode === 13) {
        this.$refs.send.sendMessages()
        return false
      }
    },

3、index组件最终源码

<template>
  <div class="container">
    <div class="aside">
      <div class="logo">logo区域</div>
      <div>聊天选择区域</div>
    </div>
    <div class="main-right">
      <div class="header">标题区域</div>
      <chat-main ref="main"></chat-main>
      <chat-send @sendMsg="sendMsg" ref="send"  @keydown.enter.native="sendText($event)"></chat-send>
    </div>
  </div>
</template>

<script>
import EventSource from 'eventsource';
import {setDeviceInfo} from "@/utils/storage";
import ChatMain from "@/components/chat-main";
import ChatSend from "@/components/chat-send";
import {chat} from "@/api/sse";
export default {
name: "index",
  components: {ChatSend, ChatMain},
  data(){
  return{
    deviceType:1, //1pc 2h5
    uid:123456
  }
  },
  mounted() {
    this.clientWidth()
    this.initSSE();
  },
  methods:{
    initSSE(){
      const url = `${process.env.VUE_APP_API_BASE_URL}/createSse`; // 替换为实际的SSE端点URL
      this.eventSource = new EventSource(url,{headers:{uid:this.uid}});
      this.eventSource.onmessage = (event) => {
        // 处理接收到的SSE数据

        let payload;
        try{
          payload =JSON.parse(event.data);
        }catch (error) {
          // console.error("内容报异常")
        }
        if(undefined!=payload){
          this.$refs.main.appendMsg(payload)
        }
      };
      this.eventSource.onerror = (error) => {
        // 处理连接错误
        console.error(error);
      };
    },
    sendMsg(textarea){
      if(null==this.eventSource){
        this.initSSE()
      }
      chat({question:textarea,uid:this.uid}).then(()=>{
        this.$refs.main.appendQ(textarea)
        this.$refs.send.echoQuestion()
      })
    },

    sendText(event){
      if (event.keyCode === 13) {
        this.$refs.send.sendMessages()
        return false
      }
    },
    clientWidth(){
      //监听宽度,判断是否关闭对应的菜单
      let deviceInfo = 'pc';
      this.deviceType = 1
      if(document.body.clientWidth>document.body.clientHeight){
        setDeviceInfo(deviceInfo);
      }else{
        deviceInfo = 'h5'
        this.deviceType = 2
        setDeviceInfo(deviceInfo);
      }
    },
  },
}
</script>

<style scoped>
.container{
  text-align: center;
  display: flex;
  justify-content: flex-start;
  align-items: center;
}
.aside{
  width: 13vw;
  height: calc(100vh);
  background: #f1f0f0;
}
.logo{
  width: 13vw;
  height: 12vh;
}
.main-right{
  width: 87vw;
  height: calc(100vh);
}
.header{
  width: 100%;
  height:7vh;
  background: white;
}


</style>

4、chat-main组件源码

<template>
  <div class="chat-main">
    <div class="chat-main-content" v-for="(item,index) in msgList" :key="index">
      <li>
        <span>{{item.createTime}}</span>
        <span style="width: 100%">{{item.question}}</span>
      </li>
      <li>
        <span style="display: flex;text-align: center">
          <img src="../asserts/image/gpt.png" width="36" height="36">
          <span style="padding-left: 10px">{{item.createTime}}</span>
        </span>
        <span>
          <markdown-it-vue :content="item.answer"  class="markdown-body"  :options="options"></markdown-it-vue>
        </span>
      </li>
    </div>
  </div>
</template>

<script>
import MarkdownItVue from 'markdown-it-vue'
import 'markdown-it-vue/dist/markdown-it-vue.css'
import {formatDate} from "@/utils/date";
export default {
name: "chat-main",
  components:{MarkdownItVue},
  data(){
  return{
    msgList:[],
    options: {
      markdownIt: {
        linkify: true,
        highlight:true
      },
      linkAttributes: {
        attrs: {
          target: '_blank',
          rel: 'noopener'
        }
      }
    }
  }
  },
  methods:{
    appendQ(question){
      let param = {id:2,groupId:"148",question:question,answer:"",createTime:this.formatDate(new Date())}
      this.msgList.push(param);
      this.msgIndex = this.msgList.length -1
    },
    appendMsg(data){
      if(data.content){
        this.msgList[this.msgIndex].answer+=data.content
      }
    },
    formatDate(time){
      return formatDate(time, 'yyyy-MM-dd hh:mm:ss')
    },
  }
}
</script>

<style scoped>
.chat-main{
  height: calc(90vh);
  text-align: center;
  width: 100%;
  overflow-y: auto;
}
.markdown-body{
  color: #0c0c0c !important;
  margin-left: 10px;
  border-radius: 5px;
  padding-top: 10px;
}
.chat-main-content li{
  list-style-type: none;
  line-height: 36px;
  /*border:solid 1px white;*/
  margin: auto;
}
li:nth-child(odd) {
  /* 设置奇数项样式 */
  margin-right: 1.5vw;
  text-align: right;
  display: flex;
  flex-direction: column;
}

li:nth-child(even) {
  /* 设置偶数项样式 */
  text-align: left;
  margin-left: 1.5vw;
}

</style>

5、chat-send源码

<template>
  <div class="chat-send">
    <div style="display: flex;justify-content: center;align-content: center;align-items: center">
    <input type="textarea" v-model="textarea" class="send-input" placeholder="  请输入您的问题 按 enter 即发送" />
      <span @click="sendMessages">
        <img src="./../asserts/image/send.png" width="48" height="48">
      </span>
    </div>
  </div>
</template>

<script>
export default {
name: "chat-send",
  data(){
  return{
    textarea:"",
  }
  },
  methods:{
    sendMessages(){
      if(this.textarea==''||this.textarea==null){
        return;
      }
      if(this.textarea.length>2000){
        open("问题过长,请将您的问题多次会话描述")
        return;
      }
      this.$emit("sendMsg",this.textarea,false)
    },
    echoQuestion(){
      this.textarea="";
    }
  }
}
</script>

<style scoped>

.chat-send{
  text-align: center;
  border-radius: 10px;
  left: 56%;
  top: 92%;
  position: absolute;
  transform: translate(-50%,-50%);
}
.chat-send input{
  height: 6vh;
  width: 40vw;
  border-radius: 10px;
  background: rgba(254,255,253,0.5)
}
.chat-send button{
  height: 3vh;
  width: 3vw;
  border-radius: 10px;
}
</style>

演示效果

在这里插入图片描述

五、总结

1、集成sse并初始化连接对象的过程中,需要注意请求头的传入形如一下

     this.eventSource = new EventSource(url,{headers:{uid:this.uid}});

请求头header的传入在实战项目中可以替换为token

2、对于键盘的监听 可以 采用一下事件进行监听

@keydown.enter.native="sendText($event)"

3、在追加文本信息的过程中需要用到,如:

   appendMsg(data){
      if(data.content){
        this.msgList[this.msgIndex].answer+=data.content
      }
    },

本编讲到这里,如果大佬有什么好的建议,欢迎在评论区留言,下编将为大家讲解,如何让我们的会话界面自动回到底部
最后大家请记得点赞收藏哦

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值