Most chatbot tutorials either hide everything behind a no-code tool or dump a block of code with no explanation. This one sits in between: a step-by-step guide to building an AI chatbot with Python that you’ll actually understand. In about 100 lines, you’ll build a chatbot that runs in your terminal, remembers the conversation, keeps costs in check, handles common errors and keeps your API key out of your code.
Along the way you’ll see what’s really happening when you chat with an AI: what gets sent, what it costs and why the model doesn’t actually “remember” anything on its own.
What you need:
- A computer with Python 3.10 or newer. The current OpenAI Python library requires it.
- An OpenAI API account with a little prepaid credit. API billing is separate from a ChatGPT subscription.
- About 30 minutes, and basic comfort typing commands into a terminal.
If you’d rather not write code at all, no-code chatbot builders exist. This guide is for people who want to understand how chatbots work underneath, which also makes you much better at using the no-code tools.
How we tested this code: we ran automated tests offline, with OpenAI library version 3.60.0 and Python 3. They check the conversation history, the trimming, the handling of errors and cut-off replies, and the quit command, using a stand-in instead of the real API. We also had the official OpenAI library send its request to a local stand-in server to confirm the request is formatted correctly. We did not run a live conversation with OpenAI’s servers for this article. Part 2 of this series will add a live walkthrough with screenshots and a simple web interface.
How the chatbot works
Before writing code, it helps to see the whole picture.

The most important idea is this: the model has no memory between requests. Each time you send a message, your program sends the earlier messages along with it. That’s how the chatbot “remembers” what you said a minute ago. It’s also why longer conversations cost more, and why our program only sends the most recent part of the conversation.
If terms like “token” or “context window” are new to you, AI 101: Key Concepts for Beginners explains them in plain language.
Step 1: Set up a project folder
Check your Python version first. Open a terminal (on Windows, search for PowerShell; on a Mac, open Terminal) and run:
python --version
On Windows, if that doesn’t work, try py --version. On a Mac, try python3 --version. If you see a version below 3.10, or an error, install the latest version from python.org. On Windows, tick “Add python.exe to PATH” during installation.
Now create a folder for the project and a virtual environment, which keeps this project’s libraries separate from everything else on your computer:
mkdir my-chatbot
cd my-chatbot
python -m venv .venv
On a Mac, python often isn’t available, so use python3 -m venv .venv instead. Once the virtual environment is active, plain python works on every system.
Activate it. On Windows (PowerShell):
.venv\Scripts\Activate.ps1
On a Mac or Linux:
source .venv/bin/activate
You’ll see (.venv) at the start of your terminal line when it’s active. Run the activate command again any time you open a new terminal to work on this project.
Step 2: Install the OpenAI library
With the virtual environment active, run:
pip install openai
We tested this tutorial with version 3.60.0 of the library. Newer versions in the 3.x series should work the same way.
Step 3: Create an API key and store it safely
An API key is a password that lets your program use your OpenAI account, and anyone who has it can spend your credit. Three rules:
- Never put the key in your code. We’ll store it in an environment variable instead, and the OpenAI library reads it from there automatically.
- Never share it, including in screenshots, chat messages or AI tools.
- Limit the damage if it leaks. In your OpenAI account, create a separate project for experiments, and keep automatic credit recharge turned off.
To set it up:
- Sign in at platform.openai.com, add a small amount of prepaid credit in the billing settings, then go to API keys and create a new key. Copy it.
- Save it as an environment variable.
On Windows (PowerShell):
setx OPENAI_API_KEY "paste-your-key-here"
Then close the terminal and open a new one. The new variable isn’t visible in the window where you ran setx. Remember to go back to your project folder and activate the virtual environment again.
On a Mac or Linux:
export OPENAI_API_KEY="paste-your-key-here"
This lasts until you close the terminal. To make it permanent, add the same line to your shell’s startup file, such as ~/.zshrc on a Mac.
Step 4: Make your first API call
Before building the full chatbot, confirm that everything works. Create a file called hello.py in your project folder:
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY from your environment
response = client.responses.create(
model="gpt-6-luna",
input="Say hello in one short sentence.",
)
print(response.output_text)
Run it:
python hello.py
If you see a short greeting, your setup works. If you get an error, jump to Common errors and how to fix them below.
A note on the model name: gpt-6-luna is the lowest-cost model in OpenAI’s current lineup and plenty for a learning project. Model names change over time, so if you get a “model not found” error, check OpenAI’s models page for the current names and update the line.
Step 5: Build the AI chatbot with Python
Create a file called chatbot.py and paste in this code:
import os
import openai
from openai import OpenAI
# Settings you can change
MODEL = "gpt-6-luna" # a low-cost model; check OpenAI's models page for current names
SYSTEM_PROMPT = (
"You are a friendly assistant for beginners. "
"Keep answers short and clear. "
"If you are not sure about something, say so instead of guessing."
)
MAX_TURNS = 10 # how many recent exchanges to send, including the new message
MAX_OUTPUT_TOKENS = 1000 # upper limit per reply, including the model's hidden reasoning
REASONING_EFFORT = "low" # less internal "thinking" = faster and cheaper replies
def trim_history(history, max_turns=MAX_TURNS):
"""Keep the new message plus the exchanges just before it.
Each exchange is two messages (user + assistant), so this always
starts with a user message.
"""
return history[-(max_turns * 2 - 1):]
def ask(client, history, user_text):
"""Send the conversation so far plus the new message, and return the reply.
Returns None if the reply was cut off before any text came back.
"""
history.append({"role": "user", "content": user_text})
try:
response = client.responses.create(
model=MODEL,
instructions=SYSTEM_PROMPT,
input=trim_history(history),
max_output_tokens=MAX_OUTPUT_TOKENS,
reasoning={"effort": REASONING_EFFORT},
store=False, # don't keep this response in your OpenAI account's stored logs
)
except Exception:
history.pop() # remove the message that failed, so the history stays clean
raise
reply = response.output_text
if not reply:
history.pop() # nothing came back, so forget the unanswered message
return None
history.append({"role": "assistant", "content": reply})
if response.status == "incomplete":
reply += "\n(The reply was cut off. Raise MAX_OUTPUT_TOKENS for longer answers.)"
return reply
def main():
if not os.environ.get("OPENAI_API_KEY"):
print("No API key found. Set the OPENAI_API_KEY environment variable first.")
return
client = OpenAI() # reads the key from OPENAI_API_KEY automatically
history = []
print("Chatbot ready. Type 'quit' to stop.\n")
while True:
user_text = input("You: ").strip()
if user_text.lower() in {"quit", "exit"}:
print("Goodbye!")
break
if not user_text:
continue
try:
reply = ask(client, history, user_text)
except openai.AuthenticationError:
print("Error: your API key was rejected. Check that it was copied correctly.\n")
continue
except openai.RateLimitError:
print("Error: rate limit or no credit left. Wait a moment, or check your billing page.\n")
continue
except openai.NotFoundError:
print(f"Error: the model '{MODEL}' wasn't found. Check the model name.\n")
continue
except openai.APIConnectionError:
print("Error: couldn't reach OpenAI. Check your internet connection.\n")
continue
except openai.APIError as error:
print(f"Error from the API: {error}\n")
continue
if reply is None:
print("The reply was cut off before any text came back. Try again, or raise MAX_OUTPUT_TOKENS.\n")
continue
print(f"Bot: {reply}\n")
if __name__ == "__main__":
main()
What each part does
The settings at the top are the parts you’ll want to experiment with. SYSTEM_PROMPT is the chatbot’s standing instructions: its personality, tone and rules. It’s sent with every request through the instructions parameter, separately from the conversation. Everything in our prompt engineering guide applies here: the clearer these instructions, the more consistent the bot.
Two settings control cost. MAX_OUTPUT_TOKENS is an upper limit on each reply. It also covers the model’s hidden reasoning, which counts as output, so a single reply can never use more than 1,000 output tokens. REASONING_EFFORT controls how much the model “thinks” before answering. Luna’s default is medium. We use low, which is faster and cheaper and plenty for a simple chat. For harder questions you can raise it, at a higher cost.
history is a plain Python list of messages. Each message is a small dictionary with a role ("user" for you, "assistant" for the bot) and its content. This list is the chatbot’s entire memory, and it lives on your computer. OpenAI’s API can also keep conversation state on its servers for you, but managing it yourself shows exactly what’s being sent, and it works with the store=False setting described below.
trim_history decides how much of that memory is sent. With MAX_TURNS = 10, each request includes your new message plus the nine exchanges before it. Without a limit, every request would include the whole conversation, so long chats would get steadily more expensive and could eventually exceed the model’s context window. The trade-off: the bot forgets anything older than the limit.
ask does one round trip. It adds your message to the history, sends the instructions and recent history to the API, reads the reply from response.output_text and adds that reply to the history. If the request fails, it removes your message again, so the history doesn’t fill up with unanswered questions. It also handles replies that hit the MAX_OUTPUT_TOKENS limit. If no text came back at all, which can happen when the model spends its whole budget on reasoning, it returns nothing and the program tells you. If the text was cut off partway, it shows what arrived with a short note.
store=False tells OpenAI not to keep the response in your account’s stored logs, which it otherwise does for 30 days by default. It doesn’t mean nothing is kept: OpenAI says it may retain API data for up to 30 days for abuse monitoring. It just means you’re not adding stored conversations to your account that you don’t need.
main checks that an API key exists, then runs a loop: read what you type, send it, print the answer, repeat until you type quit. Each error gets its own plain-language message instead of a wall of technical text.
Step 6: Run it
python chatbot.py
You should see:
Chatbot ready. Type 'quit' to stop.
You:
Type a question and press Enter. To check that the memory works, tell it your name, ask something else, then ask “What’s my name?” Type quit when you’re done.
What it costs
The API charges per token, separately for the text you send (input) and the text the model writes (output). A token is a chunk of text, often a word or part of one. These are OpenAI’s listed prices on November 26, 2026:
| Model | Input (per 1 million tokens) | Output (per 1 million tokens) |
|---|---|---|
| gpt-6-luna | $0.10 | $0.50 |
| gpt-6.2-sol | $2.00 | $10.00 |
Here’s a rough estimate for one conversation of 10 exchanges, assuming short questions (about 30 tokens), replies of about 150 tokens and a short system prompt. Because each request re-sends the earlier messages, the input adds up to roughly 8,750 tokens, plus about 1,500 tokens of output.
- With gpt-6-luna, that’s about $0.0016, a fraction of a cent.
- With gpt-6.2-sol, it’s about $0.03.
These figures don’t include reasoning tokens, which Luna bills as output. With REASONING_EFFORT = "low" there are usually few of them, and MAX_OUTPUT_TOKENS = 1000 puts a ceiling on each reply: at Luna’s price, 1,000 output tokens cost $0.0005. Treat all of this as ballpark figures, not a quote. Your account’s Usage page shows exactly what you’ve spent, so check it after your first few conversations.
Common errors and how to fix them
| What you see | Likely cause | Fix |
|---|---|---|
| “No API key found” | The environment variable isn’t set in this terminal | On Windows, open a new terminal after running setx. On a Mac, run the export line again. |
| “your API key was rejected” (401) | The key is wrong, has extra spaces or was revoked | Copy the key again carefully, or create a new one. |
| “rate limit or no credit left” (429) | Too many requests at once, or your prepaid credit or spend limit has run out | Wait a minute and try again. If it continues, check your credit balance and limits in the billing settings. Retrying won’t help if the credit is used up. |
| “the model … wasn’t found” (404) | The model name is wrong or no longer available | Check OpenAI’s models page and update MODEL. |
| “couldn’t reach OpenAI” | Internet or firewall problem | Check your connection. On a work network, a firewall may block it. |
ModuleNotFoundError: No module named 'openai' | The library isn’t installed in the active environment | Activate the virtual environment, then run pip install openai again. |
| “running scripts is disabled on this system” (Windows) | PowerShell blocks the activation script | Use Command Prompt instead and run .venv\Scripts\activate.bat. |
| “The reply was cut off” | The reply hit the MAX_OUTPUT_TOKENS limit | Ask for a shorter answer, or raise MAX_OUTPUT_TOKENS (for example to 2000). |
Limits and safety
It can still be wrong. A chatbot built on the API has the same weaknesses as any chatbot: it can give confident answers that aren’t true. The instruction to admit uncertainty helps, but it doesn’t remove the problem.
Don’t put your key in a website. If you later turn this into a web page, the API key must stay on a server you control, never in code that runs in visitors’ browsers, where anyone can read it.
Be careful what you send. Everything you type is sent to OpenAI. Don’t paste passwords or other people’s private information into it.
Watch your spending. Keep auto-recharge off while you’re learning, and check the Usage page occasionally.
Where to go next
Some easy improvements to try on your own:
- Change
SYSTEM_PROMPTto give the bot a specific job, such as a study helper for one subject or a friendly Python tutor. - Lower
MAX_TURNSand watch how quickly the bot “forgets.” - Switch
MODELto a more capable model and compare the answers and the cost.
In Part 2, we’ll run this chatbot live with screenshots, add a simple web interface and share the full project code.
Sources
Checked as of November 26, 2026.