Node.js、Socket.IO和GPT-4構(gòu)建AI聊天機(jī)器人的項(xiàng)目實(shí)踐
由 GPT-4 等先進(jìn)人工智能技術(shù)提供支持的聊天機(jī)器人可以顯著提高用戶參與度、提供即時(shí)幫助并提升整體用戶體驗(yàn)。在本教程中,將構(gòu)建一個(gè)利用 Node.js、Socket.IO 和 GPT-4 API 強(qiáng)大功能的 AI 聊天機(jī)器人應(yīng)用程序。通過分步指南,將了解如何創(chuàng)建無縫的實(shí)時(shí)聊天機(jī)器人體驗(yàn),從而改變網(wǎng)站并給訪問者留下深刻印象。
要使用 GPT-4 創(chuàng)建一個(gè)提供聊天機(jī)器人功能的完整 Node.js Web 應(yīng)用程序,需要一個(gè) Express 服務(wù)器,使用 Socket.IO 進(jìn)行實(shí)時(shí)通信,并使用 HTML 提供一個(gè)簡單的前端, CSS 和 JavaScript 文件。
代碼倉庫:https://github.com/QuintionTang/ai-chatbot
設(shè)置項(xiàng)目并安裝依賴項(xiàng)
在深入研究聊天機(jī)器人的實(shí)施之前,需要先設(shè)置項(xiàng)目并安裝必要的依賴項(xiàng)。在下面將引導(dǎo)完成創(chuàng)建項(xiàng)目結(jié)構(gòu)、安裝所需的 Node.js 包并確保順利的開發(fā)體驗(yàn)。
第 1 步:為項(xiàng)目創(chuàng)建一個(gè)目錄并進(jìn)入到該目錄
執(zhí)行以下命令在第一步中創(chuàng)建一個(gè)新的項(xiàng)目目錄:
mkdir ai-chatbot cd ai-chatbot
第 2 步:初始化項(xiàng)目并安裝所需的包
接下來,在項(xiàng)目文件夾中創(chuàng)建一個(gè) package.json 文件,并確保安裝了所有需要的依賴項(xiàng):
npm init -y npm install express socket.io openai dotenv
第 3 步:創(chuàng)建一個(gè) .env 文件來存儲(chǔ) OpenAI API 密鑰:
OPENAI_API_THISKEY=your_openai_api_key
實(shí)現(xiàn)服務(wù)器邏輯
下面開始創(chuàng)建服務(wù)器端邏輯。
第 4 步:為服務(wù)器創(chuàng)建一個(gè)文件:service.js
require("dotenv").config(); const express = require("express"); const http = require("http"); const socketIO = require("socket.io"); const { Configuration, OpenAIApi } = require("openai"); const app = express(); const server = http.createServer(app); const io = socketIO(server); const port = process.env.PORT || 3001; // OpenAI API 配置 const configuration = new Configuration({ ? ? apiKey: process.env.OPENAI_API_THISKEY, }); const openai = new OpenAIApi(configuration); // 靜態(tài)文件目錄 app.use(express.static("public")); io.on("connection", (socket) => { ? ? console.log("New user connected"); ? ? // Initialize the conversation history ? ? const conversationHistory = []; ? ? socket.on("sendMessage", async (message, callback) => { ? ? ? ? try { ? ? ? ? ? ? // Add the user message to the conversation history ? ? ? ? ? ? conversationHistory.push({ role: "user", content: message }); ? ? ? ? ? ? const completion = await openai.createChatCompletion({ ? ? ? ? ? ? ? ? model: "gpt-4", ? ? ? ? ? ? ? ? messages: conversationHistory, ? ? ? ? ? ? }); ? ? ? ? ? ? const response = completion.data.choices[0].message.content; ? ? ? ? ? ? // Add the assistant's response to the conversation history ? ? ? ? ? ? conversationHistory.push({ role: "assistant", content: response }); ? ? ? ? ? ? socket.emit("message", response); ? ? ? ? ? ? callback(); ? ? ? ? } catch (error) { ? ? ? ? ? ? console.error(error); ? ? ? ? ? ? callback("Error: Unable to connect to the chatbot"); ? ? ? ? } ? ? }); ? ? socket.on("disconnect", () => { ? ? ? ? console.log("User disconnected"); ? ? }); }); server.listen(port, () => { ? ? console.log(`Server is running on port ${port}`); });
上述代碼片段是使用 GPT-4 API、Express 和 Socket.IO 的 Node.js 聊天機(jī)器人 Web 應(yīng)用程序的主要服務(wù)器端代碼。
- dotenv 導(dǎo)入并配置為從 .env 文件加載環(huán)境變量。
- 導(dǎo)入必要的模塊,例如express、http、socket.io和 openai
- 創(chuàng)建一個(gè) Express 應(yīng)用程序、一個(gè) HTTP 服務(wù)器和一個(gè) Socket.IO 服務(wù)器,服務(wù)器偵聽指定端口(來自環(huán)境變量或默認(rèn)為 3001)。
- OpenAI API 使用提供的 API 密鑰進(jìn)行配置。
- public 目錄設(shè)置為 Express 應(yīng)用程序的靜態(tài)文件目錄。
- 連接事件監(jiān)聽器被添加到 Socket.IO 服務(wù)器。當(dāng)新用戶連接時(shí):
- 記錄用戶的連接。
- 一個(gè)名為 conversationHistory 的空數(shù)組被初始化以存儲(chǔ)對(duì)話歷史記錄。
- 事件監(jiān)聽器 sendMessage 被添加到連接的套接字。當(dāng)用戶發(fā)送消息時(shí):用戶的消息被添加到數(shù)組中 conversationHistory。GPT-4 API 請(qǐng)求以對(duì)話歷史記錄作為輸入。聊天機(jī)器人的響應(yīng)從 API 結(jié)果中提取并添加到數(shù)組中 conversationHistory 。最后,聊天機(jī)器人的響應(yīng)通過事件發(fā)回給用戶 message。如果出現(xiàn)錯(cuò)誤,則會(huì)向用戶發(fā)送錯(cuò)誤消息。
- disconnect事件偵聽器被添加到已連接的套接字中,以在用戶斷開連接時(shí)進(jìn)行記錄。
- 服務(wù)器啟動(dòng),一條日志消息表明它正在指定端口上運(yùn)行。
第 5 步:創(chuàng)建一個(gè)目錄 public 并在其中創(chuàng)建 index.html、styles.css 和 script.js 文件:
mkdir public cd public touch index.html styles.css script.js
前端部分
以下 HTML 代碼表示聊天機(jī)器人 Web 應(yīng)用程序的主頁。它提供基本結(jié)構(gòu),包括聊天機(jī)器人前端所需的 CSS 和 JavaScript 文件,需要插入到 index.html 中:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>AI Chatbot</title> <meta name="keywords" content="GPT、AI、ChatGPT、Docker、Vue、angular、ember、ChatGPT、Html、WEB Point" /> <meta name="description" content="An AI chatbot full stack project driven by GPT-4,used node.js、express、socke.io" /> <meta http-equiv="content-language" content="en" /> <meta name="author" content="https://github.com/QuintionTang" /> <link rel="stylesheet" href="styles.css" /> </head> <body> <div id="chat-container"> <div id="messages"></div> <form id="message-form"> <input type="text" id="message-input" placeholder="Type your message" autocomplete="off" /> <button type="submit">Send</button> </form> </div> <script src="/socket.io/socket.io.js"></script> <script src="script.js"></script> </body> </html>
第 7 步:將以下 CSS 代碼添加到 styles.css 文件中
body { ? ? font-family: Arial, sans-serif; ? ? display: flex; ? ? justify-content: center; ? ? align-items: center; ? ? height: 100vh; ? ? margin: 0; ? ? background-color: #262e35; ? ? -webkit-text-size-adjust: 100%; ? ? -webkit-tap-highlight-color: rgba(0, 0, 0, 0); } *, :after, :before { ? ? box-sizing: border-box; } #chat-container { ? ? border-radius: 5px; ? ? display: flex; ? ? line-height: 1.5; ? ? width: 100%; ? ? height: 100vh; ? ? flex-direction: column; } #messages { ? ? overflow-y: auto; ? ? padding: 1.5rem !important; ? ? height: calc(100vh - 91px); } #message-form { ? ? display: flex; ? ? padding: 1.5rem !important; ? ? border-top: 1px solid #36404a; } #message-input { ? ? flex-grow: 1; ? ? border: 1px solid #36404a; ? ? border-radius: 5px; ? ? border-radius: 0.4rem; ? ? font-size: 0.875rem; ? ? min-height: calc(1.5em + 1rem + 6px); ? ? background-color: rgb(54, 64, 74); ? ? padding: 0.5rem 1rem; ? ? color: #fff; } button { ? ? background-color: #007bff; ? ? border-radius: 0.4rem; ? ? color: white; ? ? border: none; ? ? border-radius: 5px; ? ? padding: 0.5rem 1rem; ? ? padding: 6px 12px; ? ? margin-left: 5px; ? ? cursor: pointer; } button:hover { ? ? background-color: #0056b3; } .ctext-wrap { ? ? display: flex; ? ? margin-bottom: 10px; ? ? background-color: #7269ef; ? ? border-radius: 8px 8px 8px 8px; ? ? color: #fff; ? ? padding: 12px 20px; ? ? position: relative; }
第 8 步:將以下 JavaScript 代碼添加到 script.js 文件中
const socket = io(); const messageForm = document.getElementById("message-form"); const messageInput = document.getElementById("message-input"); const messages = document.getElementById("messages"); function displayMessage(role, message) { ? ? const div = document.createElement("div"); ? ? div.innerHTML = `<p><b>${ ? ? ? ? role === "user" ? "You" : "Assistant" ? ? }:</b> ${message}</p>`; ? ? messages.appendChild(div); ? ? messages.scrollTop = messages.scrollHeight; } messageForm.addEventListener("submit", (e) => { ? ? e.preventDefault(); ? ? const message = messageInput.value; ? ? displayMessage("user", message); // ? ? socket.emit("sendMessage", message, (error) => { ? ? ? ? if (error) { ? ? ? ? ? ? return alert(error); ? ? ? ? } ? ? ? ? messageInput.value = ""; ? ? ? ? messageInput.focus(); ? ? }); }); socket.on("message", (message) => { ? ? displayMessage("assistant", message); });
- Socket.IO 客戶端實(shí)例是使用該變量創(chuàng)建io()并分配給該socket變量的。
- DOM 元素,例如消息表單、消息輸入字段和消息容器,使用getElementById
- displayMessage函數(shù)定義為在消息容器中創(chuàng)建和顯示聊天消息。它以消息發(fā)送者的角色(用戶或助理)和消息內(nèi)容作為參數(shù),使用格式化消息創(chuàng)建一個(gè)新元素,將div其附加到消息容器,并將容器滾動(dòng)到底部。
- 事件偵聽器添加到消息表單以處理表單提交:默認(rèn)的表單提交行為被阻止使用e.preventDefault()。從輸入字段中檢索用戶的消息并使用該displayMessage函數(shù)顯示。該sendMessage事件通過帶有用戶消息的 Socket.IO 客戶端發(fā)出,并提供錯(cuò)誤回調(diào)函數(shù)。如果有錯(cuò)誤,它會(huì)顯示為警報(bào)。否則,輸入字段被清除,焦點(diǎn)返回到輸入字段。
- 事件偵聽器添加到 Socket.IO 客戶端以處理 message 事件:當(dāng)從服務(wù)器接收到一條消息(聊天機(jī)器人的響應(yīng))時(shí),displayMessage 將使用角色 助手 調(diào)用該函數(shù),并將接收到的消息顯示在聊天中。
測(cè)試應(yīng)用程序
測(cè)試是為了驗(yàn)證邏輯,下面來測(cè)試一下。
第 9 步:通過運(yùn)行啟動(dòng)服務(wù)器
node service.js
現(xiàn)在,可以在瀏覽器中訪問 http://localhost:3000 并與 GPT-4 聊天機(jī)器人進(jìn)行交互。聊天機(jī)器人將回復(fù)消息,可以與其進(jìn)行對(duì)話。
如上所見:聊天機(jī)器人知道對(duì)話的上下文并提供考慮了對(duì)話歷史的答案。
結(jié)論
到此使用 Node.js、Socket.IO 和 GPT-4 API 成功構(gòu)建了 AI 支持的聊天機(jī)器人 Web 應(yīng)用程序。憑借其上下文感知功能和實(shí)時(shí)交互,聊天機(jī)器人可以滿足當(dāng)今用戶不斷變化的期望。
隨著繼續(xù)開發(fā)和完善聊天機(jī)器人,可能性是無限的。可以進(jìn)一步自定義聊天機(jī)器人的功能、外觀以及與其他服務(wù)的集成以滿足特定需求。
到此這篇關(guān)于Node.js、Socket.IO和GPT-4構(gòu)建AI聊天機(jī)器人的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)Node.js AI聊天機(jī)器人內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Node.js五大應(yīng)用性能技巧小結(jié)(必須收藏)
本篇文章主要介紹了Node.js五大應(yīng)用性能技巧小結(jié)(必須收藏),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家2017-08-08express中創(chuàng)建 websocket 接口及問題解答
本文主要介紹了express中創(chuàng)建 websocket 接口及問題解答,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2022-05-05如何優(yōu)雅地在Node應(yīng)用中進(jìn)行錯(cuò)誤異常處理
這篇文章主要介紹了如何優(yōu)雅地在Node應(yīng)用中進(jìn)行錯(cuò)誤處理,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2019-11-11Node.js操作Firebird數(shù)據(jù)庫教程
這篇文章主要為大家分享了Node.js操作Firebird數(shù)據(jù)庫教程,思路清晰便于大家理解,感興趣的小伙伴們可以參考一下2016-03-03基于promise.js實(shí)現(xiàn)nodejs的promises庫
promise是JavaScript實(shí)現(xiàn)優(yōu)雅編程的一個(gè)非常不錯(cuò)的輕量級(jí)框架。該框架可以讓你從雜亂的多重異步回調(diào)代碼中解脫出來,并把精力集中到你的業(yè)務(wù)邏輯上。2014-07-07Linux環(huán)境部署node服務(wù)并啟動(dòng)詳細(xì)步驟
最近用node.js開發(fā)了一個(gè)web項(xiàng)目,下面這篇文章主要給大家介紹了關(guān)于Linux環(huán)境部署node服務(wù)并啟動(dòng)的詳細(xì)步驟,文中通過圖文以及示例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05快速搭建Node.js(Express)用戶注冊(cè)、登錄以及授權(quán)的方法
這篇文章主要介紹了快速搭建Node.js(Express)用戶注冊(cè)、登錄以及授權(quán),小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-05-05