Club.noww.in
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.
- Create a folder named chatbot and open it in VS Code with File > Open Folder.
- Open View > Terminal and run pip install openai python-dotenv, ideally inside a Python virtual environment.
- 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).
- 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
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.
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]
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]
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 forgetting.
Important: a trimmed fact, like the customer’s name, is gone for good. If something must survive, put it in the instructions.
Add /reset and /quit Commands to the Chatbot
Commands are string checks in chat_loop() that run before the API call, so they cost you nothing. The same loop can later sit behind Streamlit or FastAPI.
Save this demo as demo_commands.py and run it in the VS Code terminal:
from chat import chat_loop, fake_user chat_loop(ask=fake_user([ "Hi, I'm Maria. My hybrid has a flat tire.", "/reset", "What's my name?", ]))Output:
You: Hi, I'm Maria. My hybrid has a flat tire. Bot: We can fix a flat tire for $15.00. We’re open Monday–Saturday, 9 AM–6 PM. You: /reset Bot: Fresh start. What can I help with? You: What's my name? Bot: I don’t know your name. You can reach Pine Street Cycles at (208) 555-0147.
After /reset, Sam no longer knows Maria’s name.How does this work?
/reset calls history.clear(), which empties the list in place. /quit uses break, and /reset uses continue to skip the API call (Python break and continue).
Handle OpenAI API Errors Without Crashing
Networks drop and model names get typos. ask_model() in chat.py catches the SDK’s error classes and returns a friendly message instead of a traceback.
To test it, the demo passes a misspelled model name. Everything else is the same chat module.
Save this as demo_error.py and run it in the VS Code terminal:
from chat import chat_loop, fake_user # a typo in the model name, as it might happen in real code chat_loop(model="gpt-6-lunaa", ask=fake_user([ "Are you open on Saturday?", "/quit", ]))Output:
You: Are you open on Saturday? Bot: OpenAI error 404. Check MODEL. You: /quit Bot: Thanks for stopping by. Ride safe!
The bad model name returns a 404, and the loop keeps running.How does this work?
RateLimitError is a kind of APIStatusError, so the specific class comes first. The order rules are the same as in catching multiple exceptions in Python.
After a failure, history.pop() drops the unanswered message, so two user turns never sit in a row.
Stream the Chatbot Reply (Optional)
Streaming prints the reply as it’s written, so your chatbot feels faster. One flag turns it on.
Save this as stream_reply.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() stream = client.responses.create( model="gpt-6-luna", instructions=SYSTEM_PROMPT, input="Give me one tip for my first group ride.", stream=True, # events arrive as they're made ) chunks = 0 print("Bot: ", end="", flush=True) for event in stream: if event.type == "response.output_text.delta": print(event.delta, end="", flush=True) chunks += 1 elif event.type == "response.completed": tokens = event.response.usage.total_tokens print(f"\n [{chunks} chunks, {tokens} tokens]")Output:
Bot: Ride predictably: hold your line and signal turns or hazards early so others can anticipate your movements. [20 chunks, 207 tokens]
The reply arrives in small chunks.How does this work?
With stream=True, you get events: text in response.output_text.delta, usage in response.completed.
Which Way to Keep Chatbot Memory Should You Pick?
| Python list (this post) | You send the full history each turn | You want full control and easy trimming |
| previous_response_id | OpenAI chains the turns for you | Short chats; earlier input is still billed each turn |
| Conversations API | A stored conversation ID you pass to each call | Chats that must survive restarts |
For a first Python chatbot, I’d start with the list: you see exactly what the model gets.
Python Chatbot Gotchas I Hit
A Python chatbot this small still has a few traps. These showed up while I built Sam:
- Made-up answers: asked about a wait-while-you-wait flat fix, Sam admitted it didn’t know. Keep the “Never make up” rule.
- A budget that never fires: my first trim demo used 500 characters and never trimmed. Test with a tiny limit.
- Hard-coded keys: load them from .env, never from chat.py.
To keep a chat after the program closes, save the list with json.dumps() and load it on start. The Python AI agents series then teaches the bot to call tools.
More Python reading for chatbot builders:
- A speech-to-text converter in Python
- Text to speech in Python
- Append to a Python dictionary
- Python docstrings
AI Chatbot in Python: Common Questions
Do I need LangChain to build an AI chatbot in Python?
No. This chatbot uses only openai and python-dotenv. Frameworks add retrieval and tools later, on top of the same loop.
Which OpenAI model is best for a cheap Python chatbot?
Start with the smallest current model; I used gpt-6-luna. Model IDs change often, so check your platform account and pricing first.
How many tokens does a chatbot conversation use?
My single call used 250 tokens, and every run in this post together used about 1,296. Each turn costs a bit more because the history is resent.
How do I give my chatbot a personality?
Write a name, a job, the facts it may use and its rules into the system prompt, and pass it as instructions on every call.
How do I stop my Python chatbot from forgetting earlier messages?
Send the full history on every call and trim only the oldest turns. The OpenAI conversation state documentation covers manual history, previous_response_id and the Conversations API.












English (US)