How to Build an AI Chatbot in Python

If you need a Python help-desk bot that still knows the customer’s name three messages later, keep every message in a list and send that list to the AI model on each turn. That one habit separates an AI chatbot from a one-off API call.

Most first attempts forget everything, because each API call starts from zero. The fix is about 70 lines of plain Python.

In this tutorial, I’ll show you how to build an AI chatbot in Python with the openai package: a persona, memory across turns, history trimming, /reset and /quit commands, and error handling that doesn’t crash.

Everything ran for real on Python Python 3.12.5, openai 3.61.0 and gpt-6-luna, OpenAI’s lowest-cost model right now. Screenshots are real VS Code runs.

What You Need for a Python AI Chatbot

You need Python 3.9 or newer, VS Code and an OpenAI API key with billing turned on. My first AI agent tutorial covers the setup in detail, so here’s the short version.

  1. Create a folder named chatbot and open it in VS Code with File > Open Folder.
  2. Open View > Terminal and run pip install openai python-dotenv, ideally inside a Python virtual environment.
  3. Create a .env file there with one line, OPENAI_API_KEY=paste-your-key-here, and keep it out of Git (why keys belong in environment variables).
  4. Run each file below with python file_name.py in that terminal.

The Sample Python Chatbot: Sam from Pine Street Cycles

Our running sample is Sam, the help-desk bot for Pine Street Cycles, a made-up bike shop in Boise, Idaho. The prompt holds hours, prices and one tricky rule: no e-bike motor repairs.

Save this as shop_prompt.py in the chatbot folder. The other files load it with a plain import, as in importing a Python file from the same directory:

SYSTEM_PROMPT = """You are Sam, the help-desk assistant for Pine Street
Cycles, a bike shop in Boise, Idaho.
Shop facts:
- Hours: Monday-Saturday 9 AM-6 PM, closed Sunday.
- Basic tune-up $89.00, full overhaul $189.00, flat fix $15.00.
- Rentals: hybrid bike $35.00 a day, e-bike $65.00 a day.
- We don't repair e-bike motors or batteries.
Rules: plain text, no Markdown, two sentences at most.
If you don't know, say so and give the shop phone (208) 555-0147.
Never make up prices or policies."""

Method 1: Send One Message with a System Prompt

Start with one call. It proves your key works and tests the persona on a job Sam should refuse.

Save this as hello_bot.py next to shop_prompt.py and run python hello_bot.py in the VS Code terminal:

from dotenv import load_dotenv
from openai import OpenAI

from shop_prompt import SYSTEM_PROMPT

load_dotenv()                  # reads OPENAI_API_KEY from .env
client = OpenAI()

response = client.responses.create(
    model="gpt-6-luna",
    instructions=SYSTEM_PROMPT,      # the persona and shop facts
    input="Can you fix the motor on my e-bike?",
)
print("Bot:", response.output_text)
print("Tokens:", response.usage.total_tokens)

Output:

Bot: Sorry, Pine Street Cycles doesn’t repair e-bike motors. You can call us at (208) 555-0147 if you’d like to ask about other options.
Tokens: 250
VS Code running a Python AI chatbot's first OpenAI call with a bike shop system prompt and printing the reply and token count
Sam turns down the e-bike motor job and gives the shop phone. That call used 250 tokens.

How does this work?

instructions carries the persona and shop facts; input carries the customer’s message. response.output_text is the reply, and response.usage counts the tokens you pay for.

Instructions apply only to the call that sends them, so send them every turn.

Why a Python Chatbot Without History Forgets You

Now send two messages in a Python for loop, the way most first chatbots do. Same prompt file, but each call only gets the newest message.

Save this as no_memory.py and run it in the VS Code terminal:

from dotenv import load_dotenv
from openai import OpenAI

from shop_prompt import SYSTEM_PROMPT

load_dotenv()
client = OpenAI()

for text in ["Hi, I'm Maria. I ride a Trek hybrid.",
             "What's my name, and what do I ride?"]:
    response = client.responses.create(
        model="gpt-6-luna",
        instructions=SYSTEM_PROMPT,
        input=text,                  # only this one message is sent
    )
    print("You:", text)
    print("Bot:", response.output_text)

Output:

You: Hi, I'm Maria. I ride a Trek hybrid.
Bot: Hi Maria! How can we help with your Trek hybrid?
You: What's my name, and what do I ride?
Bot: I don’t know your name or what you ride. Call Pine Street Cycles at (208) 555-0147 if you need help with anything else.
VS Code output of a Python chatbot loop without history that cannot recall the customer's name on the second turn
The second call never saw Maria’s first message.

How does this work?

The API keeps no memory between calls from Python unless you ask it to. Each request is a fresh conversation.

Method 2: Keep Conversation History in a Python List (Recommended)

Here’s the real chatbot. It adds each customer line and each reply to a list, then sends the whole list every time.

Save this as chat.py in the same folder. To chat with it yourself, run python chat.py in the VS Code terminal and type at the You: prompt:

import openai
from dotenv import load_dotenv
from openai import OpenAI

from shop_prompt import SYSTEM_PROMPT

load_dotenv()
client = OpenAI()
MODEL = "gpt-6-luna"
MAX_HISTORY_CHARS = 4000        # rough budget: about 1,000 tokens


def trim_history(history, limit=MAX_HISTORY_CHARS):
    dropped = 0
    while (len(history) > 2
           and sum(len(m["content"]) for m in history) > limit):
        del history[:2]
        dropped += 1
    return dropped


def ask_model(history, model=MODEL):
    try:
        response = client.responses.create(
            model=model, instructions=SYSTEM_PROMPT, input=history)
    except openai.APIConnectionError:
        return None, "I can't reach OpenAI. Check your connection."
    except openai.RateLimitError:
        return None, "Too many requests right now. Try again soon."
    except openai.APIStatusError as err:
        return None, f"OpenAI error {err.status_code}. Check MODEL."
    return response, None


def chat_loop(ask=input, model=MODEL, limit=MAX_HISTORY_CHARS,
              show_tokens=False):
    history = []
    while True:
        try:
            text = ask("You: ").strip()
        except (EOFError, KeyboardInterrupt):
            break
        if not text:
            continue
        if text == "/quit":
            print("Bot: Thanks for stopping by. Ride safe!")
            break
        if text == "/reset":
            history.clear()
            print("Bot: Fresh start. What can I help with?")
            continue
        history.append({"role": "user", "content": text})
        dropped = trim_history(history, limit)
        if dropped:
            print(f"   [trimmed {dropped} old exchange(s)]")
        response, error = ask_model(history, model)
        if error:
            history.pop()              # forget the turn that failed
            print("Bot:", error)
            continue
        reply = response.output_text
        history.append({"role": "assistant", "content": reply})
        print("Bot:", reply)
        if show_tokens:
            print(f"   [{len(history)} messages, "
                  f"{response.usage.total_tokens} tokens]")


def fake_user(turns):
    """Feed scripted lines instead of typing (for demos)."""
    turns = iter(turns)
    def ask(prompt):
        text = next(turns, None)
        if text is None:
            raise EOFError          # out of lines: end like Ctrl+Z
        print(prompt + text)
        return text
    return ask


if __name__ == "__main__":
    print("Pine Street Cycles help desk. Type /reset or /quit.")
    chat_loop()

I can’t type into a screenshot run, so the demo feeds scripted lines through fake_user() instead of reading user input. It prints each line as if you typed it.

Save this as demo_memory.py next to chat.py and run python demo_memory.py:

from chat import chat_loop, fake_user

chat_loop(show_tokens=True, ask=fake_user([
    "Hi, I'm Maria. How much is an e-bike for the day?",
    "What was my name again?",
]))

Output:

You: Hi, I'm Maria. How much is an e-bike for the day?
Bot: Hi Maria, an e-bike rental is $65.00 for the day.
   [2 messages, 182 tokens]
You: What was my name again?
Bot: Your name is Maria.
   [4 messages, 222 tokens]
VS Code run of a Python AI chatbot with conversation history recalling the customer's name and e-bike rental price
Sam still knows Maria’s name on the next turn.

How does this work?

Each turn appends a user message, sends the full list through ask_model(), then appends the reply with the assistant role. That list is the memory, and the while loop keeps going until /quit or Ctrl+C.

The token count climbs (182, 222) because every turn resends the older messages. Long chats get pricier per call, which is why the next step matters.

Pro Tip: keep the system prompt out of the list, so trimming can never delete the persona.

Trim Chatbot History to Stay Under a Limit

Every model has a context window, and you pay for every history token again each turn. trim_history() in chat.py drops the oldest customer-plus-Sam pair until the text fits. It’s just len() inside sum().

To see it fire, the demo shrinks the budget to 60 characters. Same chat module, same customer, two questions.

Save this as demo_trim.py and run it in the VS Code terminal:

from chat import chat_loop, fake_user

chat_loop(limit=60, show_tokens=True, ask=fake_user([  # tiny budget
    "Hi, I'm Maria. Are you open on Sunday?",
    "What was my name again?",
]))

Output:

You: Hi, I'm Maria. Are you open on Sunday?
Bot: Hi Maria, Pine Street Cycles is closed on Sundays.
   [2 messages, 196 tokens]
You: What was my name again?
   [trimmed 1 old exchange(s)]
Bot: I don’t know your name from this conversation. You can reach Pine Street Cycles at (208) 555-0147.
   [2 messages, 239 tokens]
VS Code run of a Python chatbot trimming old exchanges from its history once the 60 character limit is reached
Old exchanges get trimmed, and Maria’s name is gone.

How does this work?

The check runs after the new message goes in, so the current question survives. Deleting two items keeps the turns in order.

About four characters make one token in English. I start at 4,000 characters and raise it if your users notice the bot for