AightBits

Simple HTML5 Chat Bot Using OpenAI API

Aug 6th, 2024 (edited)
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
HTML 6.96 KB | Source Code | 0 0
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>Chat with AI</title>
  7.     <style>
  8.         :root {
  9.             --primary-color: #007bff;
  10.             --secondary-color: #28a745;
  11.             --background-color: #f8f9fa;
  12.             --border-color: #dee2e6;
  13.         }
  14.  
  15.         body {
  16.             font-family: Arial, sans-serif;
  17.             margin: 0;
  18.             padding: 20px;
  19.             background-color: var(--background-color);
  20.         }
  21.  
  22.         #chat {
  23.             max-width: 600px;
  24.             margin: auto;
  25.         }
  26.  
  27.         #messages {
  28.             border: 1px solid var(--border-color);
  29.             padding: 10px;
  30.             height: 300px;
  31.             overflow-y: scroll;
  32.             margin-bottom: 10px;
  33.             background-color: white;
  34.         }
  35.  
  36.         .message {
  37.             margin: 10px 0;
  38.             padding: 5px;
  39.             border-radius: 5px;
  40.         }
  41.  
  42.         .user { background-color: var(--primary-color); color: white; }
  43.         .assistant { background-color: var(--secondary-color); color: white; }
  44.         .system { color: gray; font-style: italic; }
  45.  
  46.         input, textarea, button {
  47.             width: 100%;
  48.             margin-bottom: 10px;
  49.             padding: 5px;
  50.             box-sizing: border-box;
  51.         }
  52.  
  53.         button {
  54.             background-color: var(--primary-color);
  55.             color: white;
  56.             border: none;
  57.             padding: 10px;
  58.             cursor: pointer;
  59.         }
  60.  
  61.         button:hover {
  62.             opacity: 0.8;
  63.         }
  64.  
  65.         @media (max-width: 600px) {
  66.             body {
  67.                 padding: 10px;
  68.             }
  69.         }
  70.     </style>
  71. </head>
  72. <body>
  73.     <div id="chat">
  74.         <header>
  75.             <h1>Chat with AI</h1>
  76.         </header>
  77.         <main>
  78.             <fieldset>
  79.                 <legend>AI Configuration</legend>
  80.                 <input type="text" id="aiName" placeholder="Enter AI name">
  81.                 <textarea id="aiProfile" rows="4" placeholder="Define AI's identity and response style"></textarea>
  82.                 <button id="setAndClearBtn">Set and Clear</button>
  83.             </fieldset>
  84.             <div id="messages"></div>
  85.             <input type="text" id="userInput" placeholder="Type your message">
  86.             <button id="sendBtn">Send</button>
  87.         </main>
  88.     </div>
  89.  
  90.     <script>
  91.         const ENDPOINT_URL = "http://localhost:5000/v1/chat/completions";
  92.         const MAX_TOKENS = 4096;
  93.         const OPENAI_API_KEY = ""; // Optional: Add your OpenAI API key here if using OpenAI's API directly
  94.         const TEMPERATURE = 0.7; // Optional: Set the temperature for the model's responses (0.0 to 1.0)
  95.         let conversationHistory = [];
  96.         let aiName = localStorage.getItem('aiName') || "AI";
  97.         let aiProfile = localStorage.getItem('aiProfile') || "You are a helpful assistant.";
  98.  
  99.         const getTokenCount = (messages) => messages.reduce((acc, message) => acc + message.content.split(' ').length, 0);
  100.  
  101.         const sanitizeInput = (input) => {
  102.             const temp = document.createElement('div');
  103.             temp.textContent = input;
  104.             return temp.innerHTML;
  105.         };
  106.  
  107.         const setAndClear = () => {
  108.             aiName = sanitizeInput(document.getElementById("aiName").value) || "AI";
  109.             aiProfile = sanitizeInput(document.getElementById("aiProfile").value) || "You are a helpful assistant.";
  110.             localStorage.setItem('aiName', aiName);
  111.             localStorage.setItem('aiProfile', aiProfile);
  112.            
  113.             const systemMessage = `Your name is ${aiName}. ${aiProfile}`;
  114.             conversationHistory = [{ role: "system", content: systemMessage }];
  115.            
  116.             document.getElementById("messages").innerHTML = '';
  117.             displayMessage(`Session started with ${aiName}`, "system");
  118.         };
  119.  
  120.         const sendMessage = async () => {
  121.             const userInput = sanitizeInput(document.getElementById("userInput").value);
  122.             if (!userInput) return;
  123.  
  124.             document.getElementById("userInput").value = '';
  125.             displayMessage(userInput, "user");
  126.             document.getElementById("sendBtn").disabled = true;
  127.  
  128.             conversationHistory.push({ role: "user", content: userInput });
  129.  
  130.             while (getTokenCount(conversationHistory) > MAX_TOKENS) {
  131.                 if (conversationHistory.length > 1) {
  132.                     conversationHistory.splice(1, 1);
  133.                 } else {
  134.                     break;
  135.                 }
  136.             }
  137.  
  138.             const payload = {
  139.                 model: "gpt-4",
  140.                 messages: conversationHistory
  141.             };
  142.  
  143.             if (typeof TEMPERATURE !== 'undefined') {
  144.                 payload.temperature = TEMPERATURE;
  145.             }
  146.  
  147.             try {
  148.                 const headers = { "Content-Type": "application/json" };
  149.                
  150.                 if (OPENAI_API_KEY) {
  151.                     headers["Authorization"] = `Bearer ${OPENAI_API_KEY}`;
  152.                 }
  153.  
  154.                 const response = await fetch(ENDPOINT_URL, {
  155.                     method: "POST",
  156.                     headers: headers,
  157.                     body: JSON.stringify(payload)
  158.                 });
  159.  
  160.                 if (response.ok) {
  161.                     const responseData = await response.json();
  162.                     const reply = responseData.choices[0].message.content;
  163.                     conversationHistory.push({ role: "assistant", content: reply });
  164.                     displayMessage(reply, "assistant");
  165.                 } else {
  166.                     throw new Error('API response was not ok');
  167.                 }
  168.             } catch (error) {
  169.                 displayMessage(`Error: ${error.message}`, "system");
  170.             } finally {
  171.                 document.getElementById("sendBtn").disabled = false;
  172.             }
  173.         };
  174.  
  175.         const displayMessage = (message, role) => {
  176.             const messagesDiv = document.getElementById("messages");
  177.             const messageElement = document.createElement("div");
  178.             messageElement.classList.add("message", role);
  179.             messageElement.textContent = role === "assistant" ? `${aiName}: ${message}` :
  180.                                          role === "user" ? `You: ${message}` : message;
  181.             messagesDiv.appendChild(messageElement);
  182.             messagesDiv.scrollTop = messagesDiv.scrollHeight;
  183.         };
  184.  
  185.         document.addEventListener("DOMContentLoaded", () => {
  186.             setAndClear();
  187.             document.getElementById("setAndClearBtn").addEventListener("click", setAndClear);
  188.             document.getElementById("sendBtn").addEventListener("click", sendMessage);
  189.             document.getElementById("userInput").addEventListener("keydown", (event) => {
  190.                 if (event.key === 'Enter') sendMessage();
  191.             });
  192.         });
  193.     </script>
  194. </body>
  195. </html>
Advertisement
Add Comment
Please, Sign In to add comment