build ai chatbot python

Building AI Chatbots

๐Ÿ“˜ ai-automation-academy · Part 8 of 15 · Module 3 · Projects
A free, step-by-step course on buying, selling & trading domains. View the full series →
Building AI Chatbots
Key takeaways
  • A complete chatbot needs under 100 lines of Python
  • RAG with embeddings grounds responses in your data
  • Summary memory keeps context while controlling costs
  • Deploy free with Streamlit Cloud or Docker

Understanding build ai chatbot python is the foundation of this guide. Below we break it down step by step so you can act with confidence.

Chatbots are the most visible AI automation. This lesson builds a complete chatbot with conversation memory, streaming, and a web UI โ€” all in under 100 lines of Python.

You will use Streamlit for the frontend and OpenAI for the intelligence.

Build Ai Chatbot Python: Project Setup

๐Ÿ”ฌ Demo: Install Dependencies
pip install streamlit openai python-dotenv
echo "OPENAI_API_KEY=sk-your-key" > .env

Complete Chatbot Code

๐Ÿ”ฌ Demo: Full Working Chatbot (chatbot.py)
import streamlit as st
import openai
import os
from dotenv import load_dotenv

load_dotenv()
client = openai.OpenAI(api_key=os.environ["OPENAI_API_KEY"])

# Configuration
SYSTEM_PROMPT = """You are a helpful customer support agent for a SaaS product.
You are friendly, concise, and solution-oriented.
If you do not know the answer, say so honestly and offer to escalate.
Never make up product features or pricing."""

MAX_HISTORY = 20  # keep last 20 messages for context

st.set_page_config(page_title="AI Support Bot", page_icon="chat")
st.title("AI Support Bot")

# Initialize chat history
if "messages" not in st.session_state:
    st.session_state.messages = []

# Display chat history
for msg in st.session_state.messages:
    with st.chat_message(msg["role"]):
        st.markdown(msg["content"])

# Chat input
if prompt := st.chat_input("How can I help you?"):
    # Add user message
    st.session_state.messages.append({"role": "user", "content": prompt})
    with st.chat_message("user"):
        st.markdown(prompt)

    # Build messages for API
    api_messages = [{"role": "system", "content": SYSTEM_PROMPT}]
    api_messages += st.session_state.messages[-MAX_HISTORY:]

    # Stream the response
    with st.chat_message("assistant"):
        stream = client.chat.completions.create(
            model="gpt-4o-mini",
            messages=api_messages,
            stream=True
        )
        response = st.write_stream(stream)

    st.session_state.messages.append({"role": "assistant", "content": response})

Run it: streamlit run chatbot.py

Adding Knowledge Base (RAG)

๐Ÿ”ฌ Demo: Simple RAG with Embeddings
import numpy as np

# 1. Prepare your knowledge base
knowledge_base = [
    "Our product costs $29/month for the starter plan and $99/month for pro.",
    "We offer a 14-day free trial with no credit card required.",
    "Supported integrations include Slack, Jira, GitHub, and Notion.",
    "To reset your password, go to Settings > Security > Change Password.",
    "Our API rate limit is 1000 requests per minute on the pro plan.",
]

# 2. Create embeddings for the knowledge base
def embed_texts(texts: list[str]) -> list[list[float]]:
    response = client.embeddings.create(model="text-embedding-3-small", input=texts)
    return [item.embedding for item in response.data]

kb_embeddings = embed_texts(knowledge_base)

# 3. Search function
def search_knowledge(query: str, top_k: int = 3) -> list[str]:
    query_emb = embed_texts([query])[0]
    scores = [
        np.dot(query_emb, kb_emb) / (np.linalg.norm(query_emb) * np.linalg.norm(kb_emb))
        for kb_emb in kb_embeddings
    ]
    top_indices = np.argsort(scores)[-top_k:][::-1]
    return [knowledge_base[i] for i in top_indices if scores[i] > 0.3]

# 4. Inject into chatbot
def build_messages_with_rag(user_query: str, history: list) -> list:
    context = search_knowledge(user_query)
    system = SYSTEM_PROMPT
    if context:
        system += f"\n\nRelevant information:\n" + "\n".join(f"- {c}" for c in context)
    messages = [{"role": "system", "content": system}]
    messages += history[-MAX_HISTORY:]
    return messages

Explore Crypto Trading

Cryptocurrency trading is one of the fastest-growing financial markets โ€” open 24/7, globally accessible, and full of opportunity for those who learn the fundamentals first.

  • Trade spot, futures & copy-trading on one platform
  • Start with as little as $10 โ€” practice risk-free on the testnet
  • Built-in TradingView charts, grid bots & DCA tools

Free Crypto Trading Academy → ยท Domain Trading Academy →

Conversation Memory Strategies

Three approaches to managing chat history:

  • Window memory โ€” keep the last N messages (simple, used above)
  • Summary memory โ€” periodically summarize old messages into a compact form
  • Hybrid โ€” summarize old + keep recent N verbatim
๐Ÿ”ฌ Demo: Summary Memory Implementation
def summarize_history(messages: list[dict], keep_recent: int = 6) -> list[dict]:
    if len(messages) <= keep_recent:
        return messages

    old_messages = messages[:-keep_recent]
    recent_messages = messages[-keep_recent:]

    # Summarize old messages
    summary_resp = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Summarize this conversation in 2-3 sentences, preserving key facts and decisions."},
            {"role": "user", "content": str(old_messages)}
        ],
        max_tokens=200
    )
    summary = summary_resp.choices[0].message.content

    return [{"role": "system", "content": f"Previous conversation summary: {summary}"}] + recent_messages

WSOT 2026: Squad Leader Slots Are Open โ€” Up to $128,000 per Leader

Join Now

Deployment

Deploy your chatbot to the web:

# Option 1: Streamlit Community Cloud (free)
# Push to GitHub, connect at share.streamlit.io

# Option 2: Docker
# Dockerfile:
# FROM python:3.11-slim
# WORKDIR /app
# COPY requirements.txt .
# RUN pip install -r requirements.txt
# COPY . .
# EXPOSE 8501
# CMD ["streamlit", "run", "chatbot.py", "--server.port=8501"]

For production, add rate limiting, input sanitization, and usage logging.

When evaluating build ai chatbot python, start with the fundamentals: what problem it solves, who it serves, and how it compares to the alternatives buyers consider first.

Start with the fundamentals. Define who you are serving, the single outcome you want, and the budget you are comfortable committing before you compare any options.

A practical rule is to favour clarity over cleverness. The choice that is easiest to understand, spell, remember and act on tends to win over the long run.

Context changes the answer. What is optimal for a fast-moving startup is rarely optimal for an established brand, so weigh your own stage, market and ambitions.

Avoid the common mistakes: rushing the decision, copying competitors blindly, and ignoring the total cost of ownership beyond the very first year of use.

Think in terms of trade-offs rather than a single perfect answer. Every option trades memorability, cost, reach and flexibility in a slightly different mix.

Frequently asked questions

How do I prevent prompt injection?

Never put user input directly into system prompts. Use a separate user message. Validate and sanitize inputs. Set strict output formats.

What about using Claude instead of OpenAI?

Replace the openai client with anthropic and adjust the message format. The Streamlit streaming pattern works the same way.

How many concurrent users can this handle?

Streamlit handles about 20-50 concurrent users per instance. For more, deploy multiple instances behind a load balancer.

Free Courses โ€” Learn New Skills

No sign-up · No fees · Learn at your own pace

Start Trading

Trade crypto and premium domains โ€” digital assets with real opportunities.

Find your name on Atom

DominantBrand curates the best premium, brandable names from Atom.com — the marketplace with a free AI appraisal, a USPTO trademark check, and secure escrow. Every listing even ships with a designed logo.

Browse Domains