Chat GPT实用案例——VUE+Chat GPT实现聊天功能教程
首先,我们需要确定所需功能和技术栈:
- 前端框架:Vue.js
- 聊天机器人:Chat GPT API
- 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文件,并编写以下代码:
<template><div class="container"><h3>简单CSS样式</h3><div class="row pt-4"><div class="col-md"><!-- 用户输入 --><label for="">User Input</label><input type="text" placeholder="" v-model='userInput' @keyup.enter='sendMsg()'class='form-control'></div><!-- 工作区域 --><div class="col-md border-left py-2 px-5 h-100 overflow-y-auto text-center"> <!-- 聊天内容列表--><ul ref='dialogue' style='list-style-type: none;width:auto;margin-top:auto; margin-bottom:auto;' ><!--<li><strong>会话开始</strong></li>--></ul></div></div></div>
</template><script lang=js>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);}, }
}</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.
*
*/
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 seedconst 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 seedconst 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聊天界面。
祝您编码愉快!如果有任何问题,请随时联系我。