const chatInput = document.querySelector(".chat-input textarea"); const sendChatBtn = document.querySelector(".chat-input span"); const chatbox = document.querySelector(".chatbox"); let userMessage; const API_KEY = "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"; let createChatLi = (message, className) => { // Create a chat <li> element with the passed message and className const chatLi = document.createElement("li"); chatLi.classList.add("chat", className); let chatContent = className === "outgoing" ? `<p>${message}</p>` : ` <span class="material-symbols-outlined"> smart_toy </span><p>${message}</p>`; chatLi.innerHTML = chatContent; return chatLi; } const generateResponse = (incomingChatLi) => { const API_URL = "https://api.openai.com/v1/chat/completions"; const messageElement = incomingChatLi.querySelector("p"); const requestOption = { method: "POST", headers: { "Content-Type" : "application/json", "Authorization": `Bearer ${API_KEY}` }, body: JSON.stringify({ model: "gpt-3.5-turbo", messages: [{role: "user", content: userMessage}] }) } // Send POST request to API, get response fetch(API_URL, requestOption).then(res => res.json()).then(data => { messageElement.textContent = data.choices[0].message.content; }).catch((error) => { messageElement.textContent = "Oops! Something went horribly wrong. Please try again."; }) } const handleChat = () => { userMessage = chatInput.value.trim(); if(!userMessage) return; // Append the user's message to the chatbox chatbox.appendChild(createChatLi(userMessage, "outgoing")); setTimeout(() => { const incomingChatLi = createChatLi("...", "incoming") chatbox.appendChild(incomingChatLi); generateResponse(incomingChatLi); },600); } sendChatBtn.addEventListener("click", handleChat)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter