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:
By the end of this tutorial, you'll have a fully functional chat app with a simple interface to communicate with an AI!
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.
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>
#display
div will hold the chat history.#options
div will hold the form to submit messages.Now that we have a basic layout, let's dynamically create the chat window and input form using JavaScript.
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.#options
container, while the chat history will be placed in the #display
.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.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.YOUR_API_KEY
with your actual API key from OpenAI (or another AI provider).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.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:
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!