How to Build a Simple Chatbot With Python in One Hour
A chatbot is one of the best first projects in Python because you see results immediately: you type, it answers. It's also a project that scales with you, from a dozen lines of keyword matching to a bot backed by a large language model that remembers the conversation. A simple Python chatbot is a program that runs a loop, reads user input, decides on a response using rules or an AI model, and prints that response until the user chooses to quit.
Quick Answer: Spend 10 minutes on setup, 20 minutes building a rule-based bot with a loop and a dictionary of responses, 20 minutes upgrading it to call a large language model API with conversation history, and 10 minutes on error handling and testing. You'll finish with a working, extendable terminal chatbot.
What Kind of Chatbot Can You Build in an Hour?
In one focused hour, you can realistically build two versions of the same terminal chatbot. Version one is rule-based: it matches keywords in the user's message to predefined replies. It's fully predictable, runs offline, and costs nothing. Version two is LLM-powered: it sends the conversation to a hosted large language model through an API and prints the model's reply. It handles open-ended questions but needs an API key and an internet connection, and each request may cost a small amount depending on your provider.
You need to be comfortable with variables, strings, while loops, if statements, dictionaries, and functions. If any of those feel shaky, work through a structured 30-day Python learning plan first, then come back. This project will feel much smoother once loops and dictionaries are second nature.
Two terms will come up repeatedly. An intent is what the user wants, such as a greeting, asking for hours, or saying goodbye. Conversation history is the list of previous messages you send back to the model on every request, because LLM APIs are stateless: the model doesn't remember anything between calls unless you resend it. Understanding that single fact explains most "my chatbot forgot what I said" problems beginners run into.
The One-Hour Build Plan
Keep a timer running. The point isn't speed for its own sake; it's forcing you to ship a working version before polishing.
- Minutes 0 to 10: Setup. Confirm Python 3 is installed, create a project folder, and create a virtual environment with
python -m venv venv. Activate it and createbot.py. - Minutes 10 to 30: Rule-based bot. Write a loop that reads input, lowercases it, checks it against a dictionary of keywords, and prints a matching reply or a fallback message.
- Minutes 30 to 50: LLM upgrade. Install your provider's Python SDK, store your API key in an environment variable, and replace the keyword lookup with an API call that includes conversation history.
- Minutes 50 to 60: Harden and test. Add error handling for network failures, a way to quit, a cap on history length, and test with ten different messages, including empty input and very long input.
Here's the core of the rule-based version. Type it rather than pasting it; the act of typing builds the muscle memory you'll need for the next project.
RESPONSES = {
"hello": "Hi there! How can I help?",
"hours": "We're open 9am to 5pm, Monday to Friday.",
"price": "Plans start with a free tier. Ask me about features!",
}
def reply(message):
text = message.lower()
for keyword, answer in RESPONSES.items():
if keyword in text:
return answer
return "Sorry, I don't know that yet. Try asking about hours or price."
while True:
user = input("You: ").strip()
if user.lower() in ("quit", "exit"):
print("Bot: Goodbye!")
break
print("Bot:", reply(user)) This version already teaches the essential chatbot structure: input, decision, output, repeat. Everything in the LLM version is a change to the decision step.
Before moving on, spend two minutes improving the rule-based bot, because the improvement teaches a real lesson about text processing. Right now the order of the dictionary decides which reply wins when a message contains two keywords, such as "hello, what are your hours?" A small upgrade is to let each intent have several trigger words, for example a list containing "hello," "hi," and "hey," and to split the message into individual words with text.split() before checking. That prevents accidental matches inside longer words and makes adding synonyms trivial. If you have time, track which messages hit the fallback reply and print them when the program exits. That log tells you exactly which intents users actually need, which is how real support bots are improved over time.
Rule-Based vs. LLM-Powered: Which Should You Build?
Both approaches are legitimate, and many production bots combine them. The comparison below helps you decide which to emphasize for your use case.
| Factor | Rule-Based Bot | LLM-Powered Bot |
|---|---|---|
| Setup complexity | Standard library only | SDK install plus API key |
| Running cost | Free | Usually billed per token used |
| Handles unexpected questions | Poorly, falls back to a default | Well, generates fluent answers |
| Predictability | Fully predictable output | Can vary or be wrong |
| Works offline | Yes | No |
| Best for | FAQs, menus, learning fundamentals | Open conversation, tutoring, drafting |
A practical hybrid: check rules first for questions where the answer must be exact, like opening hours or refund policy, and send everything else to the model. That keeps critical facts accurate while still handling open-ended chat.
Upgrading to an LLM: Practitioner Notes
The upgrade is mostly about managing a list of messages. Each message is a dictionary with a role (system, user, or assistant) and content. The system message sets the bot's behavior; user and assistant messages form the history. Here's a minimal pattern using the OpenAI Python SDK, which reads your key from the OPENAI_API_KEY environment variable. Other providers' SDKs follow a very similar shape; check their documentation for exact method names and current model IDs.
from openai import OpenAI
client = OpenAI()
MODEL = "your-model-id"
history = [{"role": "system", "content": "You are a friendly, concise support bot."}]
while True:
user = input("You: ").strip()
if user.lower() in ("quit", "exit"):
break
if not user:
continue
history.append({"role": "user", "content": user})
try:
response = client.chat.completions.create(model=MODEL, messages=history)
answer = response.choices[0].message.content
except Exception as error:
print("Bot: Something went wrong:", error)
history.pop()
continue
history.append({"role": "assistant", "content": answer})
print("Bot:", answer)
history = history[:1] + history[-20:] Three practitioner details matter here. First, the API key never appears in the code; hard-coded keys end up on GitHub far more often than people expect. Second, on failure the code removes the user message it just added, so a retry doesn't send a duplicate. Third, the last line keeps the system message plus the twenty most recent messages, because sending an ever-growing history increases cost and eventually exceeds the model's context window.
The system message is the most underrated line in the program. A vague instruction like "You are a helpful assistant" produces vague, rambling answers. A specific one sets scope, tone, length, and boundaries: "You are a support assistant for a small bakery. Answer in two or three sentences. If asked about anything unrelated to the bakery, politely redirect. If you don't know an answer, say so instead of guessing." Test your bot with off-topic questions and tricky requests, then tighten the system message based on what goes wrong. This iterate-and-observe loop is the core of practical prompt engineering, and it costs nothing but a few test messages. Keep each version of the system message in a comment or a separate file so you can compare how changes affect behavior.
When something breaks during this step, and an authentication error, a wrong model name, or a missing package is very likely on your first try, read the error message before asking for help. Learning to debug errors with AI methodically instead of pasting fixes you don't understand will save you far more than an hour over the life of this project.
Common Mistakes When Building Your First Chatbot
Committing the API key. Putting the key in bot.py and pushing to GitHub is the most expensive beginner mistake. Use environment variables or a .env file listed in .gitignore, and revoke any key that was ever exposed.
Forgetting that the model is stateless. If you send only the latest message, the bot can't follow up on anything. Always send the history.
Unbounded history. The opposite problem: sending every message forever. Trim or summarize older messages.
Substring false matches in rule-based bots. Checking whether "hi" is in the text also matches "this" and "which." Split the message into words, or use word-boundary regular expressions, for more accurate matching.
No handling for empty input. Pressing Enter on an empty line sends a blank message. Skip it with a simple check.
Trusting the model with facts. LLMs can invent plausible but wrong answers. For business facts like prices or policies, answer from your own data rather than letting the model guess.
Testing Checklist and Next Steps
Before you call the project done, run through this checklist in your terminal. It takes about ten minutes and catches most issues.
Basic flow: greet the bot, ask two follow-up questions that depend on earlier messages, and confirm the LLM version remembers context.
Edge cases: send an empty message, a single character, a very long paragraph, and text with emojis or non-English characters. Nothing should crash.
Failure modes: temporarily unset your API key or disconnect from the internet. The bot should print a clear error and keep running rather than crashing with a traceback.
Exit behavior: confirm both "quit" and "exit" end the program cleanly, regardless of capitalization.
Code quality: move the reply logic into a function, add a short docstring, and make sure the key isn't anywhere in your files.
Once it passes, pick one extension that teaches something new. You could give the bot a web interface with Flask or Streamlit, load FAQ answers from a JSON file instead of hard-coding them, stream responses token by token, or add retrieval so the bot answers questions about a specific document. Each extension adds a skill employers recognize, such as web routing, file handling, streaming APIs, or retrieval-augmented generation.
Key Takeaways
- Every chatbot follows the same loop: read input, decide on a response, print it, and repeat until the user quits.
- A rule-based bot built with a dictionary and a loop teaches the fundamentals and runs offline at no cost.
- LLM APIs are stateless, so you must resend the conversation history with every request for the bot to remember context.
- Store API keys in environment variables, never in code, and trim history to control cost and context length.
- Hybrid bots that answer critical facts from rules and send open questions to a model combine accuracy with flexibility.
Frequently Asked Questions
Can a beginner really build a chatbot in one hour?
Yes, if you already know Python basics like loops, dictionaries, and functions. A rule-based bot takes about twenty minutes, and an LLM upgrade takes another twenty. Setup and testing fill the rest. Complete beginners should learn fundamentals first, or the hour will be spent on syntax instead.
Do I need machine learning knowledge to build a chatbot?
No. A rule-based bot needs only standard Python. An LLM-powered bot calls a hosted model through an API, so the machine learning happens on the provider's side. Understanding prompts, conversation history, and API errors matters far more than knowing how models are trained.
Is it free to build a chatbot with Python?
The rule-based version is completely free. LLM-powered versions usually require an API key from a provider, and most charge based on how much text you send and receive. Some providers offer free trial credits or free tiers, so check current pricing before building anything that handles heavy traffic.
Why does my chatbot forget what I said earlier?
Language model APIs don't store conversation state between requests. Your code must keep a list of previous messages and send it with every call. If you only send the latest message, the model has no context. Append both user and assistant messages to the history list.
How do I put my Python chatbot on a website?
Wrap the reply logic in a web framework. Streamlit offers a quick chat interface with very little code, while Flask or FastAPI give more control for building an API endpoint that a custom frontend can call. Keep the API key on the server, never in browser code.
Which Python library is best for chatbots?
For learning, start with the standard library for rule-based logic and your model provider's official SDK for the LLM version. As projects grow, frameworks such as LangChain or LlamaIndex help with retrieval and tool use, but they add complexity you don't need for a first bot.
Conclusion
The most valuable thing you'll take from this hour isn't the chatbot itself; it's understanding that every conversational AI product is built on the same simple loop plus careful management of context. Once you've written that loop yourself, frameworks and fancy interfaces stop feeling like magic and start feeling like layers you can reason about. Finish the testing checklist, push the code to GitHub without your API key, and add one meaningful extension. Then write up what you built and what you learned, because that is how you turn a small build into a portfolio piece that shows real problem-solving.




