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文件,并编写以下代码:
简单CSS样式
-
<!--
- 会话开始 -->
接下来是 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
