To build an AI chatbot in Python: (1) call a large language model through its Python SDK or HTTP API, (2) keep a list of messages so the bot remembers the conversation, (3) add your own knowledge with retrieval-augmented generation (embed your documents, retrieve relevant chunks, include them in the prompt), (4) optionally give it tools via function calling, (5) wrap it in a FastAPI back end with a simple web page, and (6) test it with a set of real questions, add guardrails, and deploy it with logging and cost limits.
Chatbots are the most popular first AI project for good reason: they're useful, they touch every part of modern AI engineering, and you can make a working version quickly and then keep improving it. This tutorial builds one in stages. Each stage works on its own, so you can stop at any point with something you can show. You need basic Python (functions, lists, dictionaries); if you're not there yet, start with learning Python from scratch.
How do AI chatbots work today?
Older chatbots matched keywords to scripted replies. Modern ones send the conversation to a large language model, which predicts a helpful reply token by token. Your code's job is everything around the model: what you send it (instructions, history, retrieved facts), what it's allowed to do (tools), and how you check and deliver the answer.
| Stage | What you add | What you learn |
|---|---|---|
| 1. Single reply | One API call with a system instruction | APIs, keys, prompts |
| 2. Conversation | Message history | Context windows, token limits |
| 3. Your knowledge | RAG over your documents | Chunking, embeddings, vector search |
| 4. Actions | Tools / function calling | Structured outputs, agents |
| 5. Interface | FastAPI + web page, streaming | Back-end and front-end basics |
| 6. Production | Tests, guardrails, logging, deployment | LLMOps, security, cost |
Stage 1: How do you get a first reply from a model?
Pick a model provider (hosted APIs from several companies, or an open-weight model running locally with a tool such as Ollama). Create an API key and store it in an environment variable, never in your code. Then the core of every chatbot looks like this, in provider-neutral pseudocode:
import os
client = ProviderClient(api_key=os.environ["LLM_API_KEY"])
reply = client.chat(
model="your-chosen-model",
system="You are a helpful study assistant. Answer clearly and briefly.",
messages=[{"role": "user", "content": "Explain overfitting in two sentences."}],
max_tokens=300,
)
print(reply.text)
Every provider's SDK has a near-identical shape: a model name, a system instruction, a list of messages with roles, and a limit on output length. Read your provider's quick-start for the exact function names.
Stage 2: How do you give the chatbot memory?
Models don't remember anything between calls. "Memory" is simply sending the conversation so far with each request:
history = []
while True:
user = input("You: ")
if user.lower() in {"quit", "exit"}:
break
history.append({"role": "user", "content": user})
reply = client.chat(model=MODEL, system=SYSTEM, messages=history, max_tokens=500)
history.append({"role": "assistant", "content": reply.text})
print("Bot:", reply.text)
Conversations grow, and every token you send costs time and money and must fit in the model's context window. Common strategies: keep only the last N turns, summarise older turns into a short note, or store facts about the user separately and include only what's relevant.
Calculated: turn number × 150 tokens (system prompt not included). Total tokens over a 20-turn chat add up to 31,500 (150 × 1+2+…+20), which is why trimming or summarising history matters.
Stage 3: How do you make it answer from your own documents?
This is retrieval-augmented generation (RAG), and it's what turns a general bot into a useful assistant for a college, a clinic or a company.
- Load documents: PDFs, web pages, FAQs, policies.
- Chunk them: split into passages of a few hundred words with a little overlap, keeping headings as context.
- Embed: convert each chunk into a vector with an embedding model (embeddings explained).
- Store: save vectors and text in an index such as FAISS, Chroma or PostgreSQL with pgvector.
- Retrieve: embed each question and fetch the most similar chunks (often 3–8).
- Generate: include those chunks in the prompt with an instruction: "Answer only from the sources below. If the answer isn't there, say you don't know. Cite the source."
def answer(question):
chunks = index.search(embed(question), k=5)
sources = "\n\n".join(f"[{c.id}] {c.text}" for c in chunks)
prompt = f"Sources:\n{sources}\n\nQuestion: {question}"
return client.chat(model=MODEL, system=RAG_RULES,
messages=[{"role": "user", "content": prompt}]).text
Quality depends far more on chunking, retrieval and instructions than on clever prompts. Improve it by adding keyword search alongside vector search (hybrid search), re-ranking results and testing with real questions. Framework choices are compared in LangChain vs LlamaIndex vs custom code.
Stage 4: How do you let the chatbot take actions?
With function calling, you describe tools (name, purpose, input schema) and the model can respond with a request to call one, for example get_class_schedule(date) or check_order_status(order_id). Your code runs the function, sends the result back, and the model writes the final answer. Rules that keep this safe:
- Validate every argument the model sends, exactly as you would validate user input.
- Give tools the minimum permissions they need; read-only where possible.
- Require human confirmation for anything that spends money, sends messages or deletes data.
- Cap the number of tool calls per question to avoid loops.
Once a bot plans multiple steps with tools, it's an agent; see how to build AI agents.
Stage 5: How do you give it a web interface?
Wrap your chat function in an API with FastAPI: a POST /chat endpoint that takes a message and a conversation ID and returns the reply. Store conversations in a database (PostgreSQL or MongoDB). Build a small front end with HTML and JavaScript, or React. Stream tokens to the browser with server-sent events or WebSockets so answers appear as they're generated, which makes the bot feel much faster.
Stage 6: How do you test and harden it before real users?
| Area | What to do |
|---|---|
| Evaluation set | Collect 50–100 real questions with expected answers; run them after every change and track the pass rate |
| Grounding | Check answers cite retrieved sources; test questions whose answer isn't in the documents |
| Prompt injection | Treat user text and retrieved documents as data, not instructions; test with hostile inputs (prompt injection explained) |
| Privacy | Don't log personal data unnecessarily; mask it; follow India's DPDP Act 2023 |
| Limits | Rate-limit users, cap output tokens, set budget alerts |
| Fallbacks | Friendly message on errors or timeouts; human handoff for sensitive topics |
These practices are the heart of LLMOps. Also read why AI hallucinates so you know what you're guarding against.
How do you deploy the chatbot?
- Put secrets in environment variables on the server.
- Package the app with Docker so it runs the same everywhere.
- Deploy to a cloud VM, a container service or a platform that runs Python apps; put it behind HTTPS.
- Add logging (request ID, latency, tokens, cost, errors) and a simple dashboard.
- Set up CI to run your evaluation set before each release (CI/CD for ML).
For the infrastructure side, read cloud computing for AI engineers.
Which chatbot projects make a strong portfolio?
- College or coaching assistant that answers from the prospectus, timetable and rules, with citations.
- Indian-language help bot that answers government-scheme FAQs in Hindi, Bengali, Tamil or another language, with careful source grounding.
- Developer docs assistant over an open-source project's documentation.
- Small business order bot with tools for menu lookup and order status (with confirmations).
- Study buddy that quizzes you from your own notes and tracks weak topics.
Document your evaluation results and limitations in the README: that's what impresses reviewers. More ideas in Python projects for beginners.
What skills does this project build?
Mapped from the six stages in this article to the published curriculum phases. Bar length shows how many of the six stages use each area.
How does Program Zero teach you to build chatbots and assistants?
In Program Zero you don't just call an API: you understand every layer. Phase 1 teaches Python and working with APIs and JSON; Phase 3 databases; Phase 4 REST APIs, auth and real-time WebSockets; Phase 8 builds tokenizers, transformers and a GPT-style model from scratch; Phase 9 covers serving and optimisation; Phase 10 deployment; and Phase 11 prompt injection and guardrails. The final capstone includes a RAG-enabled application with a UI. Live classes Monday to Friday 9:00–10:30 PM IST, recorded, with Saturday projects and a Sunday doubt session.
Go from a ten-line bot to a production assistant you fully understand. See the generative AI and LLM course, the AI agents course and the full curriculum, then book your seat for the batch starting 9 January 2027. Seats are limited.
What's the summary?
An AI chatbot in Python is an LLM call plus the engineering around it: message history for memory, RAG for your own knowledge, tools for actions, a FastAPI back end and web UI, and tests, guardrails and logging for production. Build it in stages, measure quality with a real question set, and you'll have one of the most useful portfolio projects in AI.