Building an AI chatbot might sound intimidating, but with the right tools and guidance, you can have a working prototype up and running in under an hour. This guide will walk you through everything from setting up your environment to deploying a production-ready chatbot.
What We're Building
By the end of this tutorial, you'll have a fully functional AI chatbot that can:
- Understand and respond to natural language queries
- Maintain conversation context across multiple exchanges
- Handle errors gracefully with user-friendly messages
- Run entirely in the browser with a beautiful UI
Prerequisites
Before we dive in, make sure you have:
- Basic knowledge of HTML, CSS, and JavaScript
- A Mollyra AI account (free tier is perfect for learning)
- Node.js installed on your machine (optional, for local development)
- A code editor like VS Code
Getting Your API Key
Sign up at mollyra.com and navigate to your dashboard. Click "Create API Key", give it a name like "chatbot-dev", and copy the key. Keep it safe - never expose it in client-side code!
Step 1: Set Up the Project Structure
Create a new folder for your project and set up a basic HTML file with the chatbot interface:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chatbot</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="chat-container">
<div class="chat-header">
<h3>AI Assistant</h3>
</div>
<div class="chat-messages" id="messages"></div>
<form class="chat-input" id="chatForm">
<input type="text" id="userInput" placeholder="Type your message..." required>
<button type="submit">Send</button>
</form>
</div>
<script src="chatbot.js"></script>
</body>
</html>
Step 2: Create the Chat Interface
Now let's style our chatbot to look professional and modern:
.chat-container {
max-width: 600px;
margin: 2rem auto;
background: var(--bg-card);
border-radius: var(--radius-lg);
border: 1px solid var(--border-default);
overflow: hidden;
}
.chat-header {
padding: 1rem 1.5rem;
background: var(--bg-dark-secondary);
border-bottom: 1px solid var(--border-default);
}
.chat-messages {
height: 400px;
overflow-y: auto;
padding: 1.5rem;
}
.message {
margin-bottom: 1rem;
padding: 1rem;
border-radius: var(--radius-md);
}
.message.user {
background: var(--purple-primary);
margin-left: 20%;
}
.message.assistant {
background: var(--bg-dark-secondary);
margin-right: 20%;
}
Step 3: Implement the Chat Logic
The core of our chatbot is the JavaScript that handles the conversation:
const API_KEY = 'YOUR_MOLLYRA_API_KEY';
const API_URL = 'https://api.mollyra.ai/v1/chat/completions';
const chatForm = document.getElementById('chatForm');
const messagesContainer = document.getElementById('messages');
const userInput = document.getElementById('userInput');
let conversationHistory = [
{
role: 'system',
content: 'You are a helpful AI assistant. Keep responses concise but informative.'
}
];
chatForm.addEventListener('submit', async (e) => {
e.preventDefault();
const userMessage = userInput.value.trim();
if (!userMessage) return;
// Add user message to UI
addMessage(userMessage, 'user');
userInput.value = '';
// Add to history
conversationHistory.push({
role: 'user',
content: userMessage
});
// Get AI response
try {
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'mollyra-x',
messages: conversationHistory,
stream: false
})
});
const data = await response.json();
const assistantMessage = data.choices[0].message.content;
conversationHistory.push({
role: 'assistant',
content: assistantMessage
});
addMessage(assistantMessage, 'assistant');
} catch (error) {
addMessage('Sorry, something went wrong. Please try again.', 'assistant');
}
});
function addMessage(text, sender) {
const messageDiv = document.createElement('div');
messageDiv.className = `message ${sender}`;
messageDiv.textContent = text;
messagesContainer.appendChild(messageDiv);
messagesContainer.scrollTop = messagesContainer.scrollHeight;
}
Security Note
For production applications, never expose your API key in client-side JavaScript. Always call the API from a backend server where you can securely store your credentials.
Step 4: Add Advanced Features
Once you have the basics working, consider adding these enhancements:
Streaming Responses
Instead of waiting for the complete response, stream tokens as they arrive for a more dynamic experience:
const response = await fetch(API_URL, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${API_KEY}`
},
body: JSON.stringify({
model: 'mollyra-x',
messages: conversationHistory,
stream: true
})
});
const reader = response.body.getReader();
const decoder = new TextDecoder();
let assistantMessage = '';
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = JSON.parse(line.slice(6));
if (data.choices[0].delta.content) {
assistantMessage += data.choices[0].delta.content;
// Update UI with streaming content
}
}
}
}
Conversation Context Management
To prevent your conversation history from growing infinitely, implement context management:
const MAX_CONTEXT_MESSAGES = 20;
function manageContext() {
if (conversationHistory.length > MAX_CONTEXT_MESSAGES + 1) {
// Keep system message and last N messages
const systemMessage = conversationHistory[0];
const recentMessages = conversationHistory.slice(-MAX_CONTEXT_MESSAGES);
conversationHistory = [systemMessage, ...recentMessages];
}
}
Step 5: Deploy Your Chatbot
Ready to share your creation? Here are some easy deployment options:
- GitHub Pages: Free hosting for static sites
- Vercel: Fast deployment with serverless functions
- Netlify: Drag-and-drop deployment
- Your own server: Full control over the infrastructure
Next Steps
Congratulations! You've built your first AI chatbot. But this is just the beginning. Here are some ideas for what to build next:
- Add file upload support for document analysis
- Implement multi-language support
- Build a customer support chatbot with your knowledge base
- Create a code assistant that understands your codebase
Want to Build Something Amazing?
Join thousands of developers building AI-powered applications with Mollyra AI. Get started with our free tier today.