0


Chat GPT实用案例——VUE+Chat GPT实现聊天功能教程

首先,我们需要确定所需功能和技术栈:

  1. 前端框架:Vue.js
  2. 聊天机器人:Chat GPT API
  3. CSS框架:Bootstrap or 自主设计

在开始编写代码之前,请确认 Chat GPT API 服务已经配置好, 并且您已获得了API密钥或者token。

接下来是 Vue.js项目初始化:

# 安装vue-clinpminstall -g vue-cli 

# 创建一个基于webpack模板新项目(chatbot)
vue init webpack chatbot

# 进入到目录cd chatbot && npm install# 添加chat-gpt依赖库yarnadd @huggingface/chatapi-basic

然后打开package.json文件,在scripts中添加一些scripts命令:

"build":"node build/build.js","lint":"eslint --ext .js,.vue src","start":"node server/index.js",// 开始服务器监听请求

server/index.js 文件为聊天机器人Node代理类(实现跨域+GPT-API调用),具体请参考源码。(下方直接复制源码代码)

编辑聊天界面,在chatbot/src/components目录下新建Chat.vue文件,并编写以下代码:

<template><divclass="container"><h3>简单CSS样式</h3><divclass="row pt-4"><divclass="col-md"><!-- 用户输入 --><labelfor="">User Input</label><inputtype="text"placeholder=""v-model='userInput'@keyup.enter='sendMsg()'class='form-control'></div><!-- 工作区域 --><divclass="col-md border-left py-2 px-5 h-100 overflow-y-auto text-center"><!-- 聊天内容列表--><ulref='dialogue'style='list-style-type: none;width:auto;margin-top:auto;margin-bottom:auto;'><!--<li><strong>会话开始</strong></li>--></ul></div></div></div></template><scriptlang=js>exportdefault{name:"BaseChat",data(){return{chatData:[],userInput:'',sessionId:''}},mounted(){this.init()// 初始化sessionId},methods:{init:asyncfunction(){const ans =awaitthis.$axios.get('/api/session')this.sessionId =(ans.data).id;},// 发送消息到后端API(接受GPT回复)sendMsg:asyncfunction(){//添加用户发送信息到对话框列表中if(this.userInput!=""){awaitthis.updateDialogue('Me',this.userInput);}//获取ai的回答并将其添加到对话框列表中let response =awaitthis.getResponse();awaitthis.updateDialogue('AI',response);},asyncgetResponse(){let without_space_input =this.userInput.trim();//调用前端Chat GPT API const ans =await axios.post('/api/chat/text',{message:without_space_input,sessionId:this.sessionId});return ans.data.message;},updateDialogue:function(user,message){const ulTags=this.$refs.dialogue ;var newli = document.createElement("li");var newText=document.createTextNode(message);if(user=='Me'){
                 newli.style="text-align:right; color:green";}else{
                newli.style="color:blue";}
           

          ulTags.appendChild(newli).appendChild(newText);},}}</script><style>.container{width:100%;height:50vh;}</style>

接下来是 Chat 接口代理代码, 在server/index.js文件添加以下内容:

const express=require('express')const bodyParser=require('body-parser');const app=express();var config={key:"API-KEY",//API key token or Secret-API-keyengine:"davinci"};var sessionID=null;

app.use(express.static('../chatbot/dist/'))

app.use(bodyParser.json());

app.get('/hello',(req,res)=>{

   res.send("<h1>Hello World!</h1>");});/*
* 开始对话创建一个sesssion.
*
*/asyncfunctioncreate_session(){const api_url='https://api.openai.com/v1/engine/'+config.engine+'/completions';var headers={'Content-Type':'application/json',auth:`Bearer ${config.key}`};const prompt ="Hello openai";// Initial seedconst data={prompt:plug(prompt),max_tokens:300,temperature:0.8,n:1,presence_penalty:0,delay:false}let res =awaitfetch(api_url,{method:'POST',headers,body:JSON.stringify(data)}).then(response=> response.json())if(!('id'in res)){
      console.error("Error calling GPT API",res);thrownewError("Create Session Token request failed");}        
console.log("------------->>>",res.choices[0].text.replace(/[\r\n]+/gm,""));
         sessionID=res.id;return{success:true,id:(sessionID)};}
app.get('/api/session',(req,res)=>{(async()=>{const ans ={success:false};try{
          ans.success=true;
          ans["id"]=awaitcreate_session();// 返回目前在线最新对话的Api-Key和Session-Token.}catch(e){
      console.log(e);}

    res.status(200).json(ans);})()});/*
* Chat基础API,使用GPT模型实现聊天机器人功能。
*
*/const chat_message="Chat basic API functionality!";functionplug(text){//判断是否是列表let mcs=text.charAt(text.length-1)===';'if(mcs==true){ c='\n'}else{c=''}return text+c+chat_message;}
    
app.post('/api/chat/text',(req,res)=>{(async()=>{try{const message=req.body.message;//请求消息体的文本消息内容const api_url='https://api.openai.com/v1/engine/'+config.engine+'/completions';var headers={'Content-Type':'application/json',auth:`Bearer ${config.key}`};

    console.log(req.body)const prompt=[message]+"   ";// Initial seedconst data={prompt:plug(prompt),max_tokens:300,temperature:0.8,n:1,presence_penalty:0,delay:false}let res =awaitfetch(api_url,{method:'POST',headers,body:JSON.stringify(data)}).then(response=> response.json())if(!('choices'in res)){
        console.error("Error calling GPT API",res);thrownewError("Create Session Token request failed");}
            res.status(200).json({message:(res.choices[0].text)});}catch(e){
       console.log(e);}})()});

app.listen(9002,()=>{

console.log('listening port....9002')})

最后,运行命令node server/index.js启动服务器。 在浏览器中打开http://localhost:{port}/即可使用简单的Vue.ChatBot聊天界面。

祝您编码愉快!如果有任何问题,请随时联系我。

标签: gpt vue.js 前端

本文转载自: https://blog.csdn.net/weixin_43760048/article/details/130109415
版权归原作者 'Wu' 所有, 如有侵权,请联系我们删除。

“Chat GPT实用案例——VUE+Chat GPT实现聊天功能教程”的评论:

还没有评论