Building Your First AI Chatbot — A Python Tutorial for Beginners

You do not need a machine learning degree to build a working chatbot. This tutorial walks through two real, runnable versions: a simple rule-based chatbot using pure Python, and an upgraded version that calls an LLM API for open-ended responses. By the end you will have working code and understand exactly what each piece does.

Step 1: A Simple Rule-Based Chatbot

The simplest chatbot matches keywords in user input to predefined responses. No dependencies needed beyond core Python.

# rule_based_bot.py
def get_response(user_input):
    text = user_input.lower()

    if "hello" in text or "hi" in text:
        return "Hey there! How can I help you today?"
    elif "hours" in text or "timing" in text:
        return "We're open Monday to Saturday, 9 AM to 6 PM."
    elif "price" in text or "cost" in text:
        return "Our plans start at ₹499/month. Want details on a specific plan?"
    elif "bye" in text:
        return "Goodbye! Have a great day."
    else:
        return "Sorry, I didn't understand that. Could you rephrase?"

print("Bot: Hi! Type 'bye' to exit.")
while True:
    user_input = input("You: ")
    if "bye" in user_input.lower():
        print("Bot:", get_response(user_input))
        break
    print("Bot:", get_response(user_input))

This works for a narrow, predictable use case (FAQ bots) but breaks down quickly once users phrase things in ways you did not anticipate.

Step 2: Add Intent Matching with a Classifier

Instead of hardcoded `if/elif` checks, train a lightweight classifier on sample phrases per intent — this generalizes much better to varied phrasing.

# intent_bot.py
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.svm import SVC

training_data = [
    ("hi there", "greeting"), ("hello", "greeting"), ("good morning", "greeting"),
    ("what are your hours", "hours"), ("when are you open", "hours"),
    ("how much does it cost", "price"), ("what's the pricing", "price"),
    ("bye", "goodbye"), ("see you later", "goodbye"),
]

responses = {
    "greeting": "Hey there! How can I help you today?",
    "hours": "We're open Monday to Saturday, 9 AM to 6 PM.",
    "price": "Our plans start at ₹499/month.",
    "goodbye": "Goodbye! Have a great day.",
}

texts, labels = zip(*training_data)
vectorizer = TfidfVectorizer()
X = vectorizer.fit_transform(texts)

model = SVC(kernel="linear", probability=True)
model.fit(X, labels)

def get_response(user_input):
    X_input = vectorizer.transform([user_input])
    intent = model.predict(X_input)[0]
    return responses.get(intent, "Sorry, I didn't understand that.")

print(get_response("what time do you open"))  # -> hours response

Step 3: Upgrade to an LLM-Powered Chatbot

For genuinely open-ended conversation, call an LLM API instead of matching intents. This handles phrasing you never anticipated.

# llm_bot.py
import os
from anthropic import Anthropic

client = Anthropic(api_key=os.environ["ANTHROPIC_API_KEY"])

conversation_history = []

def get_response(user_input):
    conversation_history.append({"role": "user", "content": user_input})
    response = client.messages.create(
        model="claude-3-5-haiku-20241022",
        max_tokens=300,
        system="You are a helpful customer support assistant for a small SaaS company.",
        messages=conversation_history,
    )
    reply = response.content[0].text
    conversation_history.append({"role": "assistant", "content": reply})
    return reply

print("Bot: Hi! Ask me anything. Type 'bye' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() == "bye":
        break
    print("Bot:", get_response(user_input))

Keeping `conversation_history` and passing it back on every call is what gives the bot memory of earlier turns in the conversation — without it, every message would be treated as a fresh, context-free question.

Choosing the Right Approach for Your Project

  • Rule-based — best for a narrow, predictable FAQ bot with a handful of fixed intents and zero API cost
  • Intent classifier — best when you have more varied phrasing but still a fixed, known set of possible intents
  • LLM API-based — best when conversations are open-ended, or when you need the bot to handle questions you cannot fully anticipate in advance

Frequently Asked Questions

What is the easiest way to build a chatbot in Python?

The easiest way is to start with a rule-based chatbot using simple keyword matching or the Python NLTK library, then progress to an API-based chatbot that calls an LLM API for open-ended responses once you understand the basic request-response loop.

Do I need machine learning knowledge to build a basic chatbot?

No. A rule-based or intent-matching chatbot can be built with basic Python and string matching, no machine learning required. ML or an LLM API becomes useful only when you want the chatbot to handle open-ended, unscripted conversation.

Which Python libraries are commonly used for chatbots?

Common choices are NLTK for basic text processing and pattern matching, scikit-learn for a lightweight intent classifier, and the requests library or an official SDK to call an LLM API such as OpenAI or Anthropic for more natural, open-ended responses.

Explore More Free AI Dev Tools

Dev Brains AI offers free tools for regex, SQL, cron, JSON, and Base64 generation — plus an AI Error Explainer to decode confusing stack traces in seconds.

Related articles