Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Chat with AI</title>
- <style>
- :root {
- --primary-color: #007bff;
- --secondary-color: #28a745;
- --background-color: #f8f9fa;
- --border-color: #dee2e6;
- }
- body {
- font-family: Arial, sans-serif;
- margin: 0;
- padding: 20px;
- background-color: var(--background-color);
- }
- #chat {
- max-width: 600px;
- margin: auto;
- }
- #messages {
- border: 1px solid var(--border-color);
- padding: 10px;
- height: 300px;
- overflow-y: scroll;
- margin-bottom: 10px;
- background-color: white;
- }
- .message {
- margin: 10px 0;
- padding: 5px;
- border-radius: 5px;
- }
- .user { background-color: var(--primary-color); color: white; }
- .assistant { background-color: var(--secondary-color); color: white; }
- .system { color: gray; font-style: italic; }
- input, textarea, button {
- width: 100%;
- margin-bottom: 10px;
- padding: 5px;
- box-sizing: border-box;
- }
- button {
- background-color: var(--primary-color);
- color: white;
- border: none;
- padding: 10px;
- cursor: pointer;
- }
- button:hover {
- opacity: 0.8;
- }
- @media (max-width: 600px) {
- body {
- padding: 10px;
- }
- }
- </style>
- </head>
- <body>
- <div id="chat">
- <header>
- <h1>Chat with AI</h1>
- </header>
- <main>
- <fieldset>
- <legend>AI Configuration</legend>
- <input type="text" id="aiName" placeholder="Enter AI name">
- <textarea id="aiProfile" rows="4" placeholder="Define AI's identity and response style"></textarea>
- <button id="setAndClearBtn">Set and Clear</button>
- </fieldset>
- <div id="messages"></div>
- <input type="text" id="userInput" placeholder="Type your message">
- <button id="sendBtn">Send</button>
- </main>
- </div>
- <script>
- const ENDPOINT_URL = "http://localhost:5000/v1/chat/completions";
- const MAX_TOKENS = 4096;
- const OPENAI_API_KEY = ""; // Optional: Add your OpenAI API key here if using OpenAI's API directly
- const TEMPERATURE = 0.7; // Optional: Set the temperature for the model's responses (0.0 to 1.0)
- let conversationHistory = [];
- let aiName = localStorage.getItem('aiName') || "AI";
- let aiProfile = localStorage.getItem('aiProfile') || "You are a helpful assistant.";
- const getTokenCount = (messages) => messages.reduce((acc, message) => acc + message.content.split(' ').length, 0);
- const sanitizeInput = (input) => {
- const temp = document.createElement('div');
- temp.textContent = input;
- return temp.innerHTML;
- };
- const setAndClear = () => {
- aiName = sanitizeInput(document.getElementById("aiName").value) || "AI";
- aiProfile = sanitizeInput(document.getElementById("aiProfile").value) || "You are a helpful assistant.";
- localStorage.setItem('aiName', aiName);
- localStorage.setItem('aiProfile', aiProfile);
- const systemMessage = `Your name is ${aiName}. ${aiProfile}`;
- conversationHistory = [{ role: "system", content: systemMessage }];
- document.getElementById("messages").innerHTML = '';
- displayMessage(`Session started with ${aiName}`, "system");
- };
- const sendMessage = async () => {
- const userInput = sanitizeInput(document.getElementById("userInput").value);
- if (!userInput) return;
- document.getElementById("userInput").value = '';
- displayMessage(userInput, "user");
- document.getElementById("sendBtn").disabled = true;
- conversationHistory.push({ role: "user", content: userInput });
- while (getTokenCount(conversationHistory) > MAX_TOKENS) {
- if (conversationHistory.length > 1) {
- conversationHistory.splice(1, 1);
- } else {
- break;
- }
- }
- const payload = {
- model: "gpt-4",
- messages: conversationHistory
- };
- if (typeof TEMPERATURE !== 'undefined') {
- payload.temperature = TEMPERATURE;
- }
- try {
- const headers = { "Content-Type": "application/json" };
- if (OPENAI_API_KEY) {
- headers["Authorization"] = `Bearer ${OPENAI_API_KEY}`;
- }
- const response = await fetch(ENDPOINT_URL, {
- method: "POST",
- headers: headers,
- body: JSON.stringify(payload)
- });
- if (response.ok) {
- const responseData = await response.json();
- const reply = responseData.choices[0].message.content;
- conversationHistory.push({ role: "assistant", content: reply });
- displayMessage(reply, "assistant");
- } else {
- throw new Error('API response was not ok');
- }
- } catch (error) {
- displayMessage(`Error: ${error.message}`, "system");
- } finally {
- document.getElementById("sendBtn").disabled = false;
- }
- };
- const displayMessage = (message, role) => {
- const messagesDiv = document.getElementById("messages");
- const messageElement = document.createElement("div");
- messageElement.classList.add("message", role);
- messageElement.textContent = role === "assistant" ? `${aiName}: ${message}` :
- role === "user" ? `You: ${message}` : message;
- messagesDiv.appendChild(messageElement);
- messagesDiv.scrollTop = messagesDiv.scrollHeight;
- };
- document.addEventListener("DOMContentLoaded", () => {
- setAndClear();
- document.getElementById("setAndClearBtn").addEventListener("click", setAndClear);
- document.getElementById("sendBtn").addEventListener("click", sendMessage);
- document.getElementById("userInput").addEventListener("keydown", (event) => {
- if (event.key === 'Enter') sendMessage();
- });
- });
- </script>
- </body>
- </html>
Advertisement
Add Comment
Please, Sign In to add comment