Build Your First AI Chatbot in Under 30 Minutes (Free)
Build Your First AI Chatbot in Under 30 Minutes (Free)
Developer coding on laptop with terminal open
You have used ChatGPT and Claude. Now you want to build your own AI chatbot. Maybe you want to create a customer support bot for your website, a study assistant, a creative writing partner, or just want to understand how it all works under the hood.
The great news: you can build a working AI chatbot in under 30 minutes, completely free. No paid subscriptions, no credit card required.
In this tutorial, we will build a simple but functional chatbot using Python, a free AI API, and basic web technologies. By the end, you will have a chatbot running locally that you can customize for any purpose.
What You Will Need
Before we start, make sure you have these (all free):
- •Python 3.8+ installed (download here)
- •A text editor -- VS Code is recommended (free)
- •A free API key from one of the providers below
- •Basic command line knowledge (we will guide you through everything)
- •About 30 minutes of your time
Never coded before? That is okay. We will explain every line of code. Just follow along step by step.
Step 1: Choose Your Free AI API (5 minutes)
Several providers offer free API access to powerful language models. Here are the best options in 2026:
Option A: Google Gemini API (Recommended for Beginners)
- •Free tier: 60 requests per minute, 1,500 requests per day
- •Sign up: ai.google.dev
- •Model: Gemini 1.5 Flash (fast and capable)
- •Best for: Beginners, generous free limits
Option B: OpenAI API
- •Free tier: $5 credit for new accounts (lasts a while for testing)
- •Sign up: platform.openai.com
- •Model: GPT-3.5 Turbo (affordable and fast)
- •Best for: Those who want GPT-powered responses
Option C: Hugging Face Inference API
- •Free tier: Generous free usage for open-source models
- •Sign up: huggingface.co
- •Model: Various open-source models (Mistral, Llama, etc.)
- •Best for: Those who prefer open-source
For this tutorial, we will use Google Gemini API because it has the most generous free tier and is the easiest to set up. The concepts apply to any provider.
Getting Your API Key
- 1Go to ai.google.dev
- 2Click "Get API Key"
- 3Sign in with your Google account
- 4Click "Create API Key"
- 5Copy the key and save it somewhere safe
> Important: Never share your API key publicly or commit it to a public GitHub repository. Treat it like a password.
Step 2: Set Up Your Project (3 minutes)
Open your terminal and run these commands:
mkdir my-chatbot
cd my-chatbot
python -m venv venv
Activate the virtual environment:
On Mac/Linux:
source venv/bin/activate
On Windows:
venv\Scripts\activate
Install the required packages:
pip install google-generativeai flask
That is it for setup. Two packages:
- •google-generativeai -- Google's official Python SDK for Gemini
- •flask -- A lightweight web framework to create a simple web interface
Step 3: Build the Backend (10 minutes)
Create a new file called app.py and add the following code:
import os
import google.generativeai as genai
from flask import Flask, request, jsonify, render_template_string
>
# Configure the API
genai.configure(api_key="YOUR_API_KEY_HERE")
>
# Initialize the model
model = genai.GenerativeModel('gemini-1.5-flash')
>
# Start a chat session
chat = model.start_chat(history=[])
>
# Create Flask app
app = Flask(__name__)
>
# System prompt - customize this to change your chatbot's personality
SYSTEM_PROMPT = """You are a helpful, friendly assistant.
You give concise, accurate answers.
If you do not know something, you say so honestly."""
>
@app.route('/')
def home():
return render_template_string(HTML_TEMPLATE)
>
@app.route('/chat', methods=['POST'])
def chat_endpoint():
user_message = request.json.get('message', '')
if not user_message:
return jsonify({'error': 'No message provided'}), 400
>
try:
response = chat.send_message(
f"{SYSTEM_PROMPT}\n\nUser: {user_message}"
)
return jsonify({'response': response.text})
except Exception as e:
return jsonify({'error': str(e)}), 500
>
if __name__ == '__main__':
app.run(debug=True, port=5000)
What This Code Does
- •Lines 1-3: Import the libraries we need
- •Line 5: Configure the Gemini API with your key
- •Line 7: Create a Gemini model instance (using the fast Flash model)
- •Line 9: Start a chat session that maintains conversation history
- •Lines 14-16: Define your chatbot's personality with a system prompt
- •Lines 18-20: Create a route that serves the web interface
- •Lines 22-33: Create an API endpoint that receives messages and returns AI responses
Step 4: Build the Frontend (8 minutes)
Add the HTML template to the same app.py file, above the Flask app initialization:
HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
<title>My AI Chatbot</title>
<style>
* { margin: 0; padding: 0; box-sizing: border-box; }
body { font-family: -apple-system, sans-serif;
background: #0a0a0a; color: #fff;
display: flex; justify-content: center;
align-items: center; min-height: 100vh; }
.chat-container { width: 100%; max-width: 600px;
height: 80vh; display: flex;
flex-direction: column;
border: 1px solid #333;
border-radius: 12px; overflow: hidden; }
.messages { flex: 1; overflow-y: auto; padding: 20px; }
.message { margin-bottom: 16px; padding: 12px 16px;
border-radius: 12px; max-width: 80%;
line-height: 1.5; }
.user { background: #2563eb; margin-left: auto; }
.bot { background: #1e1e1e; border: 1px solid #333; }
.input-area { display: flex; padding: 16px;
border-top: 1px solid #333; }
input { flex: 1; padding: 12px; border-radius: 8px;
border: 1px solid #333; background: #1e1e1e;
color: #fff; font-size: 16px; outline: none; }
button { margin-left: 8px; padding: 12px 24px;
background: #2563eb; color: #fff; border: none;
border-radius: 8px; cursor: pointer;
font-size: 16px; }
button:hover { background: #1d4ed8; }
</style>
</head>
<body>
<div class="chat-container">
<div class="messages" id="messages">
<div class="message bot">
Hello! I am your AI assistant. How can I help you?
</div>
</div>
<div class="input-area">
<input type="text" id="input"
placeholder="Type a message..."
onkeypress="if(event.key==='Enter')sendMessage()">
<button onclick="sendMessage()">Send</button>
</div>
</div>
<script>
async function sendMessage() {
const input = document.getElementById('input');
const msg = input.value.trim();
if (!msg) return;
addMessage(msg, 'user');
input.value = '';
const res = await fetch('/chat', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({message: msg})
});
const data = await res.json();
addMessage(data.response || data.error, 'bot');
}
function addMessage(text, type) {
const div = document.createElement('div');
div.className = 'message ' + type;
div.textContent = text;
document.getElementById('messages').appendChild(div);
div.scrollIntoView({behavior: 'smooth'});
}
</script>
</body>
</html>
"""
Step 5: Run Your Chatbot (2 minutes)
Make sure you have replaced YOUR_API_KEY_HERE with your actual Gemini API key, then run:
python app.py
Open your browser and go to http://localhost:5000. You should see your chatbot interface. Type a message and hit Enter or click Send.
Congratulations -- you just built an AI chatbot.
Step 6: Customize Your Chatbot (5+ minutes)
Now for the fun part. Here are ways to make your chatbot unique:
Change the Personality
Edit the SYSTEM_PROMPT variable to give your chatbot a different personality:
Customer Support Bot:
> SYSTEM_PROMPT = """You are a customer support agent for a software company. You are polite, patient, and solution-oriented. You help users troubleshoot issues and always offer to escalate to a human if you cannot resolve the problem."""
Study Assistant:
> SYSTEM_PROMPT = """You are a study tutor. You explain concepts simply with examples. When a student asks a question, you first check their understanding, then build on it. You use analogies and encourage curiosity."""
Creative Writing Partner:
> SYSTEM_PROMPT = """You are a creative writing assistant. You help with brainstorming story ideas, developing characters, writing dialogue, and giving constructive feedback on drafts. You are enthusiastic and encouraging."""
Add Conversation Memory
Our current setup already maintains conversation history within a session through the Gemini chat object. The chatbot remembers what you said earlier in the conversation.
Add Markdown Rendering
For better formatting, you can add a library like marked.js to render markdown in the chat responses, making code blocks, lists, and bold text display properly.
Going Further: Ideas to Explore
Once you have the basics working, here are exciting next steps:
1. Deploy It for Free
- •Render -- Free tier for web services
- •Railway -- Free tier with easy deployment
- •Vercel -- Perfect for serverless functions
- •PythonAnywhere -- Free Python hosting
2. Add a Knowledge Base
Make your chatbot an expert on specific content by loading documents:
> # Load your own content
> context = open('my_knowledge_base.txt').read()
> SYSTEM_PROMPT = f"""You are an expert assistant. Use this knowledge base to answer questions: {context}"""
3. Connect to a Database
Store conversation history in SQLite (built into Python) so users can resume conversations:
> import sqlite3
> db = sqlite3.connect('chat_history.db')
4. Add Voice Input
Use the browser's Web Speech API to add voice-to-text:
> const recognition = new webkitSpeechRecognition();
> recognition.onresult = (event) => {
> document.getElementById('input').value = event.results[0][0].transcript;
> };
5. Build a Telegram or Discord Bot
Integrate your AI with messaging platforms using their bot APIs:
Troubleshooting Common Issues
"ModuleNotFoundError: No module named 'google.generativeai'"
Make sure your virtual environment is activated and run the install command again.
"API key not valid"
Double-check that you copied the full API key. Regenerate it if needed.
"Rate limit exceeded"
You have hit the free tier limits. Wait a minute and try again, or switch to a different API provider.
"CORS error" in the browser console
This should not happen with our Flask setup, but if it does, install flask-cors:
> pip install flask-cors
What You Learned
In under 30 minutes, you have:
- •Set up a Python development environment
- •Connected to a state-of-the-art AI model via API
- •Built a web-based chat interface from scratch
- •Learned how to customize your chatbot's personality
- •Explored deployment and enhancement options
Tip: When working with AI APIs, you will deal with JSON data constantly. Our JSON Formatter is incredibly useful for inspecting API responses during development. And if you need to share screenshots of your chatbot for documentation, our Image Compressor can optimize them for web use.
Resources
- •Google AI for Developers -- Official Gemini documentation
- •OpenAI API Docs -- If you prefer using GPT models
- •Flask Documentation -- Learn more about the web framework
- •GitHub -- Host your chatbot code and collaborate with others
- •FreeApexGears AI Hub -- Discover more free AI tools and resources
- •FreeApexGears Tools -- Free developer tools to help with your projects
Happy building. The best way to learn AI is by building with it.