欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js、Socket.IO和GPT-4構建AI聊天機器人的項目實踐

 更新時間:2023年05月31日 09:10:03   作者:天行無忌  
本文主要介紹了Node.js、Socket.IO和GPT-4構建AI聊天機器人的項目實踐,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧

由 GPT-4 等先進人工智能技術提供支持的聊天機器人可以顯著提高用戶參與度、提供即時幫助并提升整體用戶體驗。在本教程中,將構建一個利用 Node.js、Socket.IO 和 GPT-4 API 強大功能的 AI 聊天機器人應用程序。通過分步指南,將了解如何創(chuàng)建無縫的實時聊天機器人體驗,從而改變網(wǎng)站并給訪問者留下深刻印象。

要使用 GPT-4 創(chuàng)建一個提供聊天機器人功能的完整 Node.js Web 應用程序,需要一個 Express 服務器,使用 Socket.IO 進行實時通信,并使用 HTML 提供一個簡單的前端, CSS 和 JavaScript 文件。

代碼倉庫:https://github.com/QuintionTang/ai-chatbot

設置項目并安裝依賴項

在深入研究聊天機器人的實施之前,需要先設置項目并安裝必要的依賴項。在下面將引導完成創(chuàng)建項目結構、安裝所需的 Node.js 包并確保順利的開發(fā)體驗。

第 1 步:為項目創(chuàng)建一個目錄并進入到該目錄

執(zhí)行以下命令在第一步中創(chuàng)建一個新的項目目錄:

mkdir ai-chatbot
cd ai-chatbot

第 2 步:初始化項目并安裝所需的包

接下來,在項目文件夾中創(chuàng)建一個 package.json 文件,并確保安裝了所有需要的依賴項:

npm init -y 
npm install express socket.io openai dotenv

第 3 步:創(chuàng)建一個 .env 文件來存儲 OpenAI API 密鑰:

OPENAI_API_THISKEY=your_openai_api_key

實現(xiàn)服務器邏輯

下面開始創(chuàng)建服務器端邏輯。

第 4 步:為服務器創(chuàng)建一個文件: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 聊天機器人 Web 應用程序的主要服務器端代碼。

  • dotenv 導入并配置為從 .env 文件加載環(huán)境變量。
  • 導入必要的模塊,例如express、http、socket.io和 openai
  • 創(chuàng)建一個 Express 應用程序、一個 HTTP 服務器和一個 Socket.IO 服務器,服務器偵聽指定端口(來自環(huán)境變量或默認為 3001)。
  • OpenAI API 使用提供的 API 密鑰進行配置。
  • public 目錄設置為 Express 應用程序的靜態(tài)文件目錄。
  • 連接事件監(jiān)聽器被添加到 Socket.IO 服務器。當新用戶連接時:
    • 記錄用戶的連接。
    • 一個名為 conversationHistory 的空數(shù)組被初始化以存儲對話歷史記錄。
    • 事件監(jiān)聽器 sendMessage 被添加到連接的套接字。當用戶發(fā)送消息時:用戶的消息被添加到數(shù)組中 conversationHistory。GPT-4 API 請求以對話歷史記錄作為輸入。聊天機器人的響應從 API 結果中提取并添加到數(shù)組中 conversationHistory 。最后,聊天機器人的響應通過事件發(fā)回給用戶 message。如果出現(xiàn)錯誤,則會向用戶發(fā)送錯誤消息。
  • disconnect事件偵聽器被添加到已連接的套接字中,以在用戶斷開連接時進行記錄。
  • 服務器啟動,一條日志消息表明它正在指定端口上運行。

第 5 步:創(chuàng)建一個目錄 public 并在其中創(chuàng)建 index.html、styles.css 和 script.js 文件:

mkdir public
cd public
touch index.html styles.css script.js

前端部分

以下 HTML 代碼表示聊天機器人 Web 應用程序的主頁。它提供基本結構,包括聊天機器人前端所需的 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 客戶端實例是使用該變量創(chuàng)建io()并分配給該socket變量的。
  • DOM 元素,例如消息表單、消息輸入字段和消息容器,使用getElementById
  • displayMessage函數(shù)定義為在消息容器中創(chuàng)建和顯示聊天消息。它以消息發(fā)送者的角色(用戶或助理)和消息內(nèi)容作為參數(shù),使用格式化消息創(chuàng)建一個新元素,將div其附加到消息容器,并將容器滾動到底部。
  • 事件偵聽器添加到消息表單以處理表單提交:默認的表單提交行為被阻止使用e.preventDefault()。從輸入字段中檢索用戶的消息并使用該displayMessage函數(shù)顯示。該sendMessage事件通過帶有用戶消息的 Socket.IO 客戶端發(fā)出,并提供錯誤回調(diào)函數(shù)。如果有錯誤,它會顯示為警報。否則,輸入字段被清除,焦點返回到輸入字段。
  • 事件偵聽器添加到 Socket.IO 客戶端以處理 message 事件:當從服務器接收到一條消息(聊天機器人的響應)時,displayMessage 將使用角色 助手 調(diào)用該函數(shù),并將接收到的消息顯示在聊天中。

測試應用程序

測試是為了驗證邏輯,下面來測試一下。

第 9 步:通過運行啟動服務器

node service.js

現(xiàn)在,可以在瀏覽器中訪問 http://localhost:3000 并與 GPT-4 聊天機器人進行交互。聊天機器人將回復消息,可以與其進行對話。

如上所見:聊天機器人知道對話的上下文并提供考慮了對話歷史的答案。

結論

到此使用 Node.js、Socket.IO 和 GPT-4 API 成功構建了 AI 支持的聊天機器人 Web 應用程序。憑借其上下文感知功能和實時交互,聊天機器人可以滿足當今用戶不斷變化的期望。
隨著繼續(xù)開發(fā)和完善聊天機器人,可能性是無限的。可以進一步自定義聊天機器人的功能、外觀以及與其他服務的集成以滿足特定需求。

到此這篇關于Node.js、Socket.IO和GPT-4構建AI聊天機器人的項目實踐的文章就介紹到這了,更多相關Node.js AI聊天機器人內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論