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

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

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

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

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

# 安装vue-cli
npm install -g vue-cli 

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

# 进入到目录cd chatbot && npm install

# 添加chat-gpt依赖库
yarn add @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文件,并编写以下代码:

  
      

简单CSS样式

    <!--
  • 会话开始
  • -->
export default { name: "BaseChat", data(){ return{ chatData:[], userInput:'', sessionId:'' } }, mounted () { this.init() // 初始化sessionId }, methods:{ init : async function (){ const ans = await this.$axios.get('/api/session') this.sessionId =(ans.data).id; }, // 发送消息到后端API(接受GPT回复) sendMsg:async function(){ //添加用户发送信息到对话框列表中 if(this.userInput!=""){ await this.updateDialogue('Me',this.userInput); } //获取ai的回答并将其添加到对话框列表中 let response = await this.getResponse(); await this.updateDialogue('AI',response); }, async getResponse(){ 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); }, } } .container{ width:100%; height:50vh; }

接下来是 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-key
	engine : "davinci"
};

var sessionID=null;

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

app.use(bodyParser.json());

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

   res.send("

Hello World!

"); }); /* * 开始对话创建一个sesssion. * */ async function create_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 seed const data= { prompt: plug(prompt), max_tokens: 300,temperature:0.8,n :1 ,presence_penalty :0,delay :false } let res = await fetch(api_url,{method:'POST',headers,body: JSON.stringify(data)}) .then(response => response.json()) if(!('id' in res)){ console.error("Error calling GPT API",res); throw new Error("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"]=await create_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!"; function plug(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 seed const data= { prompt: plug(prompt), max_tokens: 300, temperature:0.8,n :1 ,presence_penalty :0,delay :false } let res = await fetch(api_url,{method:'POST',headers,body: JSON.stringify(data)}) .then(response => response.json()) if(!('choices' in res)){ console.error("Error calling GPT API",res); throw new Error("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聊天界面。

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

本文来自网络,不代表协通编程立场,如若转载,请注明出处:https://net2asp.com/6d49aa294a.html