> Tiny Chat

A Pocket Size Bestie Built with JavaScript and an AI API.
Written by Mark VincentUpdated: September 2024

Welcome to Tiny Chat, a minimalist chat application where users can interact with an AI API. This app allows users to input messages, receive responses from the AI, and display a simple chat history. We'll use HTML, CSS, and JavaScript for the interface, and the backend will be powered by an AI API like OpenAI's GPT.

In this tutorial, you will learn how to:

  1. Set up a chat interface with HTML and CSS.
  2. Use JavaScript to manage the user input and display.
  3. Integrate an API to simulate a chatbot interaction.
  4. Display chat history in real-time.

By the end of this tutorial, you'll have a fully functional chat app with a simple interface to communicate with an AI!

Table of Contents

Overview

Tiny Chat is a straightforward web-based chat app where users can type messages, submit them, and receive AI-generated responses. We’ll use HTML for structure, CSS for styling, and JavaScript for the functionality. We will also use an external AI API (such as OpenAI) to simulate an intelligent chatbot.

Setup

What You'll Need

  1. A basic HTML structure for the app’s layout.
  2. CSS for styling the chat interface.
  3. JavaScript for interactivity and AI API integration.
  4. An AI API key from a service like OpenAI to get responses.

HTML Layout

First, ensure you have a container for the chat interface in your HTML file. Here’s a simple structure:

<div id="display"></div> <div id="options"></div>
  • The #display div will hold the chat history.
  • The #options div will hold the form to submit messages.

Create the Chat Interface

Now that we have a basic layout, let's dynamically create the chat window and input form using JavaScript.

Set Up Chat History and Form

We will use JavaScript to create the chat window and a form with an input field and a submit button. The chat history will display user and AI messages, and the input form will allow the user to send messages.

const generateChat = () => { // Create the chat history container const chatHistory = document.createElement('div'); chatHistory.id = 'chat-history'; chatHistory.style.border = '5px solid #FDD835'; // Create the form for adding new messages const chatForm = document.createElement('form'); chatForm.id = 'chat-form'; // Input field for user message const userInput = document.createElement('input'); userInput.id = 'user-input'; userInput.placeholder = 'Ask me anything...'; // Submit button const sendMsg = document.createElement('button'); sendMsg.id = 'send-message'; sendMsg.type = 'submit'; sendMsg.innerHTML = 'Send'; sendMsg.style.color = '#FDD835'; // Append input field and button to form chatForm.append(userInput); chatForm.append(sendMsg); // Append chat history and form to the main display const options = document.getElementById('options'); const display = document.getElementById('display'); display.append(chatHistory); options.append(chatForm); document.getElementById('profile').style.color = `#FDD835`; };
  • chatHistory: A dynamically created div where all chat messages will be displayed.
  • chatForm: A form containing an input field and a submit button for sending user messages.
  • The chat form will be appended to the #options container, while the chat history will be placed in the #display.

Handle User Input

Now that we have a form to capture user input, we need to handle the submission and display the user's message in the chat history.

We will listen for the form’s submit event, capture the message, and display it in the chat window. If the input field is empty, we will prevent submission.

let chatMessages = []; // To store all chat messages // Add a new message to the chat const addMessage = (text, sender) => { chatMessages.push({ text, sender }); // Add the message to the chat history renderChat(); // Re-render the chat window }; // Handle form submission chatForm.addEventListener('submit', async e => { e.preventDefault(); // Prevent the page from reloading const userMessage = userInput.value.trim(); // Get the user's message if (userMessage === '') return; // Do nothing if the input is empty addMessage(userMessage, 'user'); // Add user message to chat userInput.value = ''; // Clear the input field const aiResponse = await fetchAIResponse(userMessage); // Fetch the AI's response addMessage(aiResponse, 'ai'); // Add AI response to chat });
  • addMessage: Adds a new message to the chat history and triggers a re-render.
  • Form event listener: Captures the user’s input, adds it to the chat, clears the input field, and fetches a response from the AI API.

Connect to the AI API

Now that we have user input, we need to send it to the AI API and get a response. We'll use fetch to send the user’s message to the API and return a response.

const fetchAIResponse = async (message) => { try { const response = await fetch('https://api.openai.com/v1/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer YOUR_API_KEY` }, body: JSON.stringify({ model: 'text-davinci-003', prompt: message, max_tokens: 150 }) }); const data = await response.json(); // Parse the response return data.choices[0].text.trim(); // Return the AI’s response } catch (error) { console.error('Error fetching AI response:', error); return 'Sorry, something went wrong. Please try again later.'; } };
  • fetchAIResponse: Sends the user’s message to the AI API and returns the AI's response.
  • Replace YOUR_API_KEY with your actual API key from OpenAI (or another AI provider).

Render Chat History

Finally, we need to render the chat messages in the chat history. Each message (from the user or the AI) will be displayed in the chat window, and the window will scroll down to show the latest message.

const renderChat = () => { chatHistory.innerHTML = ''; // Clear chat history chatMessages.forEach(message => { const messageDiv = document.createElement('div'); messageDiv.classList.add(message.sender === 'user' ? 'user-message' : 'ai-message'); messageDiv.textContent = message.text; // Set the message text chatHistory.appendChild(messageDiv); // Append message to chat history }); chatHistory.scrollTop = chatHistory.scrollHeight; // Scroll to the latest message };
  • renderChat: Clears the chat history and re-renders all messages. It ensures that the chat window scrolls down to display the most recent message.

Conclusion

Congratulations! You've now built Tiny Chat, a simple chat app where users can interact with an AI. Here’s a recap of what we’ve covered:

  1. Creating the chat interface using JavaScript.
  2. Handling user input and displaying it in the chat window.
  3. Fetching responses from the AI API and rendering them in real-time.

With this foundation, you can extend Tiny Chat by adding features like saving chat history, customizing the user interface, or enhancing the chatbot’s capabilities.

Happy Hacking!