首先,我們需要確定所需功能和技術(shù)棧:
- 前端框架:Vue.js
- 聊天機(jī)器人:Chat GPT API
- CSS框架:Bootstrap or 自主設(shè)計
在開始編寫代碼之前,請確認(rèn) Chat GPT API 服務(wù)已經(jīng)配置好, 并且您已獲得了API密鑰或者token。
接下來是 Vue.js項目初始化:
# 安裝vue-cli
npm install -g vue-cli
# 創(chuàng)建一個基于webpack模板新項目(chatbot)
vue init webpack chatbot
# 進(jìn)入到目錄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", // 開始服務(wù)器監(jiān)聽請求
server/index.js 文件為聊天機(jī)器人Node代理類(實現(xiàn)跨域+GPT-API調(diào)用),具體請參考源碼。(下方直接復(fù)制源碼代碼)
編輯聊天界面,在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>
<!-- 工作區(qū)域 -->
<div class="col-md border-left py-2 px-5 h-100 overflow-y-auto text-center">
<!-- 聊天內(nèi)容列表-->
<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;
},
// 發(fā)送消息到后端API(接受GPT回復(fù))
sendMsg:async function(){
//添加用戶發(fā)送信息到對話框列表中
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();
//調(diào)用前端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文件添加以下內(nèi)容:
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("<h1>Hello World!</h1>");
});
/*
* 開始對話創(chuàng)建一個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基礎(chǔ)API,使用GPT模型實現(xiàn)聊天機(jī)器人功能。
*
*/
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;//請求消息體的文本消息內(nèi)容
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')
})
最后,運(yùn)行命令node server/index.js啟動服務(wù)器。 在瀏覽器中打開http://localhost:{port}/即可使用簡單的Vue.ChatBot聊天界面。文章來源:http://www.zghlxwxcb.cn/news/detail-444439.html
祝您編碼愉快!如果有任何問題,請隨時聯(lián)系我。文章來源地址http://www.zghlxwxcb.cn/news/detail-444439.html
到了這里,關(guān)于Chat GPT實用案例——VUE+Chat GPT實現(xiàn)聊天功能教程的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!