// Get DOM elements const chatWindow = document.getElementById("chat-window"); const userInput = document.getElementById("user-input"); // Define API endpoint and token const apiUrl = "https://api.openai.com/v1/chat/completions"; const apiKey = "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"; // get the api key // Function to send user input to the ChatGPT API async function sendMessage(message) { const response = await fetch(apiUrl, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${apiKey}`, }, body: JSON.stringify({ messages: [ { role: "system", content: "You are the user" }, { role: "user", content: message }, ], model: "text-davinci-002", }), }); const data = await response.json(); return data.choices[0].message.content; } // Function to generate ai response using ChatGPT async function getResponse() { const userInputValue = userInput.value; if (userInputValue.trim() !== "") { displayMessage(userInputValue, "user"); const response = await sendMessage(userInputValue); displayMessage(response, "bot"); userInput.value = ""; } } // for display massage function displayMessage(message, sender) { const messageElement = document.createElement("div"); messageElement.classList.add("message", sender); messageElement.innerText = message; chatWindow.appendChild(messageElement); chatWindow.scrollTop = chatWindow.scrollHeight; } // get listen from input :0 userInput.addEventListener("keypress", function (event) { if (event.key === "Enter") { getResponse(); } }); // Initial greeting from the bot displayMessage("Hello, how can I help you today?", "bot");