how-to-build-chatbot-using-openai

How how to built own multilingual AI Chatbot with Flask, OpenAI, and SQLite

In this post I am going to describe how to create a multilingual AI Chatbot with Flask, OpenAI, and SQLite step by step:

Here’s a step-by-step breakdown of how I developed a multilingual AI chatbot that:

Requirements

Install Requirements and Set Up the Environment

Before building the chatbot, ensure you have the necessary tools installed:

đź§° Tools Required

  • Python 3.1+

  • pip (Python package manager)

  • SQLite (comes built-in with Python)

  • VS Code (optional but recommended)

  • OpenAI API key

📦 Required Python Packages

Create a virtual environment and install required packages:

python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate

pip install flask openai

If you want to run and debug inside VS Code:

  • Install the Python extension in VS Code.
  • Add debugpy to enable debugging

    pip install debugpy
    

Add your OpenAI key as an environment variable: Environment variables: System variable: New and add following:

OPEN_AI_KEY= 'your open ai key'

How to find your OpenAI key?

  • Go to the OpenAI Platform and log in to your account.
  • Click on your profile icon in the top-right corner.
  • Select “View API Keys” from the dropdown menu.
  • Click “Create New Secret Key” to generate a new API key.
  • Copy the key and store it securely, as you won’t be able to view it again.

Add Open_AI_KEY in your code (chatbot.py)

client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))Install Sqlite

Steps to Install SQLite on Windows

  •  Go to the SQLite Download Page – https://a1.sqlite.org/download.html
  •  Download sqlite-tools-win-x64.zip (for 64-bit) or sqlite-tools-win-x86.zip (for 32-bit).
  •  Extract the Files:- Create a folder like C:\sqlite3\.
  • Extract the downloaded ZIP file into this folder.
  • Verify Installation:- Open Command Prompt (Win + R, type cmd, press Enter).
  • Navigate to the SQLite folder:cd C:\sqlite3\
  • Run:sqlite3 –version
  • cd C:\sqlite3\
  • sqlite3 –version
    If SQLite is installed correctly, it will display the version number.

Working with SQLite in Your Project:

SQLite is a simple, file-based database used in this project to store chat history.

How the DB Is Created

The chatbot automatically creates a file called chatbot.db in your project directory. This is done in the function:

def setup_database():
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chats (
                session_id TEXT,
                user_input TEXT,
                bot_response TEXT,
                timestamp TEXT,
                language TEXT
            )
        """)
        conn.commit()

SQLite Commands for Debugging or Manual Edits

Add SQLite to System PATH (Recommended)
If you want to run sqlite3 from anywhere in your terminal, follow these steps:

  • Open Environment Variables- Press Win + R, type sysem.cpl, and hit Enter.
  •  Go to Advanced → Environment Variables.
  • Edit the Path Variable- Under System Variables, find Path, click Edit.
  • Click New, then add :C:\sqlite3\

To interact with the database directly:

sqlite3 chatbot.db

Now you’re in the SQLite prompt. Here are some useful commands:

Command Description
.tables Show tables
SELECT * FROM chats; Show all chat history
DELETE FROM chats; Delete all chat history
.headers ON Show column names in SELECT results
.exit Exit the SQLite shell

Example: Delete rows where language is empty:

DELETE FROM chats WHERE language IS NULL OR language = '';

🔍 Where is Data Stored?

  • File name: chatbot.db
  • Table: chats

  • Columns: session_id, user_input, bot_response, timestamp, language

Implementation

Step 1: Set Up the Flask App and SQLite Database

We started with a basic Flask server and created a SQLite database to store each chat message, response, timestamp, and detected language.

app = Flask(__name__)

def setup_database():
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chats (
                session_id TEXT,
                user_input TEXT,
                bot_response TEXT,
                timestamp TEXT,
                language TEXT
            )
        """)
        conn.commit()

Step 2: Detect and Handle Simple Date/Time Questions Locally

Before calling OpenAI, we check for simple time/date questions and answer them directly, saving API costs.

def detect_datetime_question(user_input):
    text = user_input.lower()
    now = datetime.now()

    checks = {
        ("what time", "current time", "now", "time is it"): f"The current time is {now.strftime('%H:%M:%S')}.",
        ("what's the date", "what is the date", "current date", "today's date", "what date is it", "which date"): f"Today's date is {now.strftime('%Y-%m-%d')}.",
        ("which month", "what month", "current month", "month is this"): f"This month is {now.strftime('%B')}.",
        ("which day", "what day", "day is it", "current day", "today"): f"Today is {now.strftime('%A')}.",
        ("which year", "what year", "current year", "year is this"): f"This year is {now.strftime('%Y')}."
    }

    for keywords, answer in checks.items():
        if any(kw in text for kw in keywords):
            return answer
    return None

Step 3: Save Responses in Database

Each interaction (unless it’s cached) is saved into the database, along with the normalized input, timestamp,

# === Save Chat to Database ===
def save_to_db(session_id, user_input, bot_response, language):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO chats (session_id, user_input, bot_response, timestamp, language)
            VALUES (?, ?, ?, ?, ?)
        """, (session_id, normalized_input, bot_response, timestamp, language))
        conn.commit()
        conn.close()

Step 4: Reuse Cached Responses from DB (Avoid Unnecessary OpenAI Calls)

We normalize and store inputs to prevent redundant queries. If a user asks the same question, we reuse the stored answer

# === Fetch Last Bot Response for Reuse ===
def get_last_message(user_input):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT bot_response FROM chats
            WHERE user_input = ?
            ORDER BY ROWID DESC LIMIT 1
        """, (normalized_input,))
        result = cursor.fetchone()
    return result[0] if result else None

Step 5: we should validate the response form OpenAI (to avoid storing wrong data  to DB)

# === Validate AI Response ===
def is_valid_response(response: str) -> bool:
    if not response or not response.strip():
        return False
    invalid_keywords = ["something went wrong", "error:", "exception", "traceback",
                        "insufficient_quota", "no longer supported", "invalid request",
                        "you exceeded your quota"]
    return not any(err in response.lower() for err in invalid_keywords)

Step 6: Check conversation history

We need this function to show history of conversation with chatbot.

def get_conversation_history(session_id):
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT user_input, bot_response, timestamp, language
            FROM chats
            WHERE session_id = ?
            ORDER BY timestamp ASC
        """, (session_id,))
        return cursor.fetchall()

Step 7:  Home page to show the user input and chatbot respons

# === Home Page ===
@app.route("/", methods=["GET"])
def home():
    session_id = request.cookies.get("session_id") or str(uuid.uuid4())
    html = """
        <html><head><style>
        body { font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }
        input[type="text"] { width: 80%; padding: 10px; }
        button { padding: 10px 15px; margin-top: 10px; }
        </style></head><body>
        <h2>Chatbot</h2>
        <form action="/chat" method="post">
            <input type="text" name="message" placeholder="Type your message" required>
            <button type="submit">Send</button>
        </form>
        <form action="/history" method="get">
            <button type="submit">Show History</button>
        </form>
        </body></html>
    """
    response = make_response(html)
    response.set_cookie("session_id", session_id, max_age=60 * 60 * 24 * 7)
    return response

Step 8: Chat Handler as front end to call backend to send request to OpenAI

This function is as a front end (html) to call backend function: chatbot_response()

# === Chat Handler ===
@app.route("/chat", methods=["POST"])
def chat():
    session_id = request.cookies.get("session_id") or str(uuid.uuid4())
    user_input = request.form.get("message", "")
    if not user_input:
        return redirect("/")

    bot_reply = chatbot_response(session_id, user_input)
    html = f"""
        <html><head><style>
        body {{ font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }}
        .user {{ color: #0066cc; font-weight: bold; }}
        .bot {{ color: #009933; }}
        .chat-box {{ border-bottom: 1px solid #ccc; padding: 10px 0; }}
        button {{ padding: 10px 15px; margin-top: 10px; }}
        </style></head><body>
        <h2>Chatbot</h2>
        <div class="chat-box">
            <div class="user">You: {user_input}</div>
            <div class="bot">Bot: {bot_reply}</div>
        </div>
        <form action="/" method="get"><button type="submit">New Question</button></form>
        <form action="/history" method="get"><button type="submit">Show History</button></form>
        </body></html>
    """
    response = make_response(html)
    response.set_cookie("session_id", session_id, max_age=60 * 60 * 24 * 7)
    return response

Step 9: To create a history UI.

# === History Page ===
@app.route("/history", methods=["GET"])
def history():
    session_id = request.cookies.get("session_id")
    if not session_id:
        return redirect("/")

    history = get_conversation_history(session_id)
    history_html = ""
    for user_input, bot_response, timestamp, language in history:
        lang_display = language.upper() if language else "??"
        history_html += f"""
            <div class="chat-box">
                <div><strong>[{timestamp}] [{lang_display}]</strong></div>
                <div class="user">You: {user_input}</div>
                <div class="bot">Bot: {bot_response}</div>
            </div>
        """

    html = f"""
        <html><head><style>
        body {{ font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }}
        .user {{ color: #0066cc; font-weight: bold; }}
        .bot {{ color: #009933; }}
        .chat-box {{ border-bottom: 1px solid #ccc; padding: 10px 0; }}
        button {{ padding: 10px 15px; margin-top: 10px; }}
        </style></head><body>
        <h2>Chat History</h2>
        {history_html}
        <form action="/" method="get"><button type="submit">New Question</button></form>
        </body></html>
    """
    return html

Help function: looks_like_datetime_response to check if Response is like a date time+

def looks_like_datetime_response(response: str) -> bool:
    response = response.lower()

    # Regex: look for very specific datetime phrases or formats
    datetime_patterns = [
        r"\btoday is\b",
        r"\bcurrent date\b",
        r"\bthe date is\b",
        r"\bnow is\b",
        r"\btime is\b",
        r"\b\d{4}-\d{2}-\d{2}\b",  # e.g., 2025-05-17
        r"\b\d{1,2} (january|february|march|april|may|june|july|august|september|october|november|december) \d{4}\b",
        r"\bit's (monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b",
        r"\bthis month is\b",
        r"\bthe month is\b",
        r"\btoday\b",
        r"\bthis year\b",
        r"\bthis week\b"
    ]

    for pattern in datetime_patterns:
        if re.search(pattern, response):
            return True
    return False

Step 10:  The main function to ask OpenAI (With Language Detection)

We instruct OpenAI to detect the user’s language and return a JSON object with both the language and response.

# === Chatbot Main Logic ===
def chatbot_response(session_id, user_input):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))

    # Handle datetime Qs
    datetime_answer = detect_datetime_question(user_input)
    if datetime_answer:
        return datetime_answer

    # Return cached reply
    cached = get_last_message(normalized_input)
    if cached:
        return cached

    # Query OpenAI
    messages = [
    {
        "role": "system",
        "content": (
            "You are a helpful assistant. detect the language of the user input. "
            "respond to the input in the same language. "
            "Return the result in the following JSON format:\n\n"
            "{\n"
            '  "language": "<language_code>",\n'
            '  "response": "<your response in the same language>"\n'
            "}\n\n"
            "Use ISO 639-1 language codes (e.g., 'en', 'sv', 'tr', 'fa')."
        )
    },
    {
        "role": "user",
        "content": user_input
    }
]

    try: # Send request to OpenAI
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=0.7
        )
        reply = completion.choices[0].message.content
        data = json.loads(reply)
        response = data.get("response", "").strip()
        language = data.get("language", "").lower().strip()
    except Exception as e:
        logging.error(f"Failed to parse OpenAI response: {e}")
        response = reply.strip() if 'reply' in locals() else "Sorry, I don't have an answer right now."
        language = None

        if is_valid_response(response) \
       and not detect_datetime_question(user_input) \
       and not looks_like_datetime_response(response):

         save_to_db(session_id, normalized_input, response, language)
    return response

Step 11 : Full Code: chatbot.py

# chatbot.py — AI Chatbot with language detection, datetime handling, and SQLite chat history

from flask import Flask, request, make_response, redirect, session
import sqlite3
import uuid
import os
import json
import logging
import re
from datetime import datetime
from openai import OpenAI
from openai.types.chat import ChatCompletionMessage

# === Initialize Flask App ===
app = Flask(__name__)
app.secret_key = "your_secret_key_here"

# === Enable Logging ===
logging.basicConfig(level=logging.DEBUG)

# === Initialize OpenAI Client ===
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))

# === Set up SQLite Database ===
def setup_database():
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            CREATE TABLE IF NOT EXISTS chats (
                session_id TEXT,
                user_input TEXT,
                bot_response TEXT,
                timestamp TEXT,
                language TEXT
            )
        """)
        conn.commit() # Close the connection

setup_database()

# === Save Chat to Database ===
def save_to_db(session_id, user_input, bot_response, language):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            INSERT INTO chats (session_id, user_input, bot_response, timestamp, language)
            VALUES (?, ?, ?, ?, ?)
        """, (session_id, normalized_input, bot_response, timestamp, language))
        conn.commit() # Close the connection
        
# === Fetch Last Bot Response for Reuse ===
def get_last_message(user_input):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT bot_response FROM chats
            WHERE user_input = ?
            ORDER BY ROWID DESC LIMIT 1
        """, (normalized_input,))
        result = cursor.fetchone()
    return result[0] if result else None

# === Detect and Handle Simple Date/Time Questions ===
def detect_datetime_question(user_input):
    text = user_input.lower()
    now = datetime.now()

    checks = {
        ("what time", "current time", "now", "time is it"): f"The current time is {now.strftime('%H:%M:%S')}.",
        ("what's the date", "what is the date", "current date", "today's date", "what date is it", "which date"): f"Today's date is {now.strftime('%Y-%m-%d')}.",
        ("which month", "what month", "current month", "month is this"): f"This month is {now.strftime('%B')}.",
        ("which day", "what day", "day is it", "current day", "today"): f"Today is {now.strftime('%A')}.",
        ("which year", "what year", "current year", "year is this"): f"This year is {now.strftime('%Y')}."
    }

    for keywords, answer in checks.items():
        if any(kw in text for kw in keywords):
            return answer
    return None

# This function checks if the response from the OpenAI API is valid by looking for common error messages or keywords.
# This function checks if the response contains date/time-like content. It uses a list of keywords and regex patterns to identify such content.

import re
# This function checks if the response contains date/time-like content. It uses a list of keywords and regex patterns to identify such content.
def looks_like_datetime_response(response: str) -> bool:
    response = response.lower()

    # Regex: look for very specific datetime phrases or formats
    datetime_patterns = [
        r"\btoday is\b",
        r"\bcurrent date\b",
        r"\bthe date is\b",
        r"\bnow is\b",
        r"\btime is\b",
        r"\b\d{4}-\d{2}-\d{2}\b",  # e.g., 2025-05-17
        r"\b\d{1,2} (january|february|march|april|may|june|july|august|september|october|november|december) \d{4}\b",
        r"\bit's (monday|tuesday|wednesday|thursday|friday|saturday|sunday)\b",
        r"\bthis month is\b",
        r"\bthe month is\b",
        r"\btoday\b",
        r"\bthis year\b",
        r"\bthis week\b"
    ]

    for pattern in datetime_patterns:
        if re.search(pattern, response):
            return True
    return False


# === Validate AI Response ===
def is_valid_response(response: str) -> bool:
    if not response or not response.strip():
        return False
    invalid_keywords = ["something went wrong", "error:", "exception", "traceback",
                        "insufficient_quota", "no longer supported", "invalid request",
                        "you exceeded your quota"]
    return not any(err in response.lower() for err in invalid_keywords)

# === Chatbot Main Logic ===
def chatbot_response(session_id, user_input):
    normalized_input = user_input.lower().translate(str.maketrans('', '', re.escape('!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~')))

    # Handle datetime Qs
    datetime_answer = detect_datetime_question(user_input)
    if datetime_answer:
        return datetime_answer

    # Return cached reply
    cached = get_last_message(normalized_input)
    if cached:
        return cached

    # Query OpenAI
    messages = [
    {
        "role": "system",
        "content": (
            "You are a helpful assistant. detect the language of the user input. "
            "respond to the input in the same language. "
            "Return the result in the following JSON format:\n\n"
            "{\n"
            '  "language": "<language_code>",\n'
            '  "response": "<your response in the same language>"\n'
            "}\n\n"
            "Use ISO 639-1 language codes (e.g., 'en', 'sv', 'tr', 'fa')."
        )
    },
    {
        "role": "user",
        "content": user_input
    }
]

    try: # Send request to OpenAI
        completion = client.chat.completions.create(
            model="gpt-3.5-turbo",
            messages=messages,
            temperature=0.7
        )
        reply = completion.choices[0].message.content
        data = json.loads(reply)
        response = data.get("response", "").strip()
        language = data.get("language", "").lower().strip()
    except Exception as e:
        logging.error(f"Failed to parse OpenAI response: {e}")
        response = reply.strip() if 'reply' in locals() else "Sorry, I don't have an answer right now."
        language = None

    if is_valid_response(response) \
        and not detect_datetime_question(user_input) \
        and not looks_like_datetime_response(response):
        save_to_db(session_id, normalized_input, response, language)

    return response

# === Fetch Chat History for a Session ===
def get_conversation_history(session_id):
    with sqlite3.connect("chatbot.db") as conn:
        cursor = conn.cursor()
        cursor.execute("""
            SELECT user_input, bot_response, timestamp, language
            FROM chats
            WHERE session_id = ?
            ORDER BY timestamp ASC
        """, (session_id,))
        return cursor.fetchall()

# === Home Page ===
@app.route("/", methods=["GET"])
def home():
    session_id = request.cookies.get("session_id") or str(uuid.uuid4())
    html = """
        <html><head><style>
        body { font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }
        input[type="text"] { width: 80%; padding: 10px; }
        button { padding: 10px 15px; margin-top: 10px; }
        </style></head><body>
        <h2>Chatbot</h2>
        <form action="/chat" method="post">
            <input type="text" name="message" placeholder="Type your message" required>
            <button type="submit">Send</button>
        </form>
        <form action="/history" method="get">
            <button type="submit">Show History</button>
        </form>
        </body></html>
    """
    response = make_response(html)
    response.set_cookie("session_id", session_id, max_age=60 * 60 * 24 * 7)
    return response

# === Chat Handler ===
@app.route("/chat", methods=["POST"])
def chat():
    session_id = request.cookies.get("session_id") or str(uuid.uuid4())
    user_input = request.form.get("message", "")
    if not user_input:
        return redirect("/")

    bot_reply = chatbot_response(session_id, user_input)
    html = f"""
        <html><head><style>
        body {{ font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }}
        .user {{ color: #0066cc; font-weight: bold; }}
        .bot {{ color: #009933; }}
        .chat-box {{ border-bottom: 1px solid #ccc; padding: 10px 0; }}
        button {{ padding: 10px 15px; margin-top: 10px; }}
        </style></head><body>
        <h2>Chatbot</h2>
        <div class="chat-box">
            <div class="user">You: {user_input}</div>
            <div class="bot">Bot: {bot_reply}</div>
        </div>
        <form action="/" method="get"><button type="submit">New Question</button></form>
        <form action="/history" method="get"><button type="submit">Show History</button></form>
        </body></html>
    """
    response = make_response(html)
    response.set_cookie("session_id", session_id, max_age=60 * 60 * 24 * 7)
    return response

# === History Page ===
@app.route("/history", methods=["GET"])
def history():
    session_id = request.cookies.get("session_id")
    if not session_id:
        return redirect("/")

    history = get_conversation_history(session_id)
    history_html = ""
    for user_input, bot_response, timestamp, language in history:
        lang_display = language.upper() if language else "??"
        history_html += f"""
            <div class="chat-box">
                <div><strong>[{timestamp}] [{lang_display}]</strong></div>
                <div class="user">You: {user_input}</div>
                <div class="bot">Bot: {bot_response}</div>
            </div>
        """

    html = f"""
        <html><head><style>
        body {{ font-family: Arial; max-width: 600px; margin: auto; padding: 20px; }}
        .user {{ color: #0066cc; font-weight: bold; }}
        .bot {{ color: #009933; }}
        .chat-box {{ border-bottom: 1px solid #ccc; padding: 10px 0; }}
        button {{ padding: 10px 15px; margin-top: 10px; }}
        </style></head><body>
        <h2>Chat History</h2>
        {history_html}
        <form action="/" method="get"><button type="submit">New Question</button></form>
        </body></html>
    """
    return html

# === Run Server with Debug Support ===
if __name__ == "__main__":
    import debugpy
    debugpy.listen(("0.0.0.0", 5678))
    print("Waiting for debugger connection...")
    app.run(debug=True, use_reloader=False, use_debugger=False)

 

How to Run This Chatbot Project

Whether you’re using Visual Studio Code, the command line, or want to deploy it online, here’s how to run your chatbot locally and beyond.

Option 1: Run in Visual Studio Code (VS Code)

Prerequisites:

  • Python 3.1+

  • A valid OpenAI API Key

  • VS Code installed (with Python extension)

âś… Step-by-Step:

  1. Clone or create your chatbot project folder
    Place the chatbot.py file and requirements.txt (if you have one) in a folder.

  2. Open VS Code
    Open the folder in VS Code using File > Open Folder.

  3. Create a virtual environment (recommended):
    Open the VS Code terminal (Ctrl + backtick or Terminal > New Terminal) and run:

    bash
    python -m venv venv
  4. Activate the virtual environment:

    • Windows:

      bash
      venv\Scripts\activate
    • Mac/Linux:

      <span class="hljs-built_in">source</span> venv/bin/activate
  5. Install required packages:

    pip install flask openai
  6. Set your OpenAI API key:
    Create a .env file or set the environment variable in the terminal:

    export OPENAI_KEY= your_API_key here #macOS/Linux
    set OPEN_API_KEY= your _API_key here #windows
  7.  Run the App

    python chatbot.py
  8. View the chatbot:
    Open your browser and go to http://127.0.0.1:5000

how-to-build-chatbot-using-openai_1.png

UI of sending request to OpenAI

Option 2: Run via Command Line

If you don’t use VS Code, the same steps apply in any terminal (e.g., Command Prompt, Terminal, PowerShell):

python chatbot.py

Make sure your environment variables and dependencies are set as described above.

Option 3: Run on Replit (Free Cloud IDE)

Replit is great for quick demos:

  1. Go to https://replit.com

  2. Create a new Python project

  3. Upload your chatbot.py

  4. Add your OpenAI API key in Secrets as OPENAI_API_KEY

  5. Run the project

Note: SQLite will work, but Replit resets data after each session unless you upgrade or save state elsewhere.

Option 4: Deploy to Render, Railway, or Heroku

You can deploy this Flask app to the web using platforms like:

Just create a requirements.txt and optionally a Procfile:

# requirements.txt
flask
openai
# Procfile
web: python chatbot.py

Set environment variables (OPENAI_API_KEY) in their dashboard and deploy!

Testing Tips

You can test various scenarios like:

  • “What is the time now?” → Local time response

  • “Vad är klockan now?” → Response in Swedish

  • “Where is Tokyo?” → OpenAI-generated answer with language tag

  • “Same question again” → Cached response, no second API call

Write your question and press to Send button then you see the following:

how-to-build-chatbot-using-openai_2.png
Display of UI for question and Response

Display of UI for question and Response

Show history of chatbot Request and response from OpenAI.  If you press to the Show history button  then all  historic is taken from DB and presented on the UI as follow:

how-to-build-chatbot-using-openai_3.png

As seen all historic is shown with date time request, user input and response from OpenAI.

All Source code is on my Github

Conclusion

In this project, we’ve successfully developed a multilingual AI chatbot using Python, Flask, OpenAI’s GPT API, and SQLite for persistent chat history. Step by step, we implemented and refined key features including:

  • Language detection and response in the user’s language via JSON-structured prompts.

  • Chat history caching with SQLite to prevent repeated OpenAI API calls for the same question.

  • Handling of date and time questions instantly without external API requests.

  • Displaying conversation history with timestamps and language metadata in a user-friendly UI.

  • Avoiding duplicate storage and skipping invalid or low-value responses.

Throughout the development, we kept the system lightweight, reliable, and expandable. The chatbot now serves as an intelligent and responsive assistant that adapts its output based on language and context.

This project is a practical example of combining AI with classic web development tools to deliver real value. Whether you’re building your own chatbot, exploring OpenAI’s API, or designing simple AI interfaces, this walkthrough provides a solid foundation to build upon.

My next post is: How to Release AI Chatbot on Render

This post is part of  AI (Artificial Intelligence) step by step

Back to home page