Skip to content

How to Build Your Own Chatbot With Python

Build a functional, stateful Python chatbot with streaming and a web interface using OpenAI and Anthropic. Master memory, error handling, and production UI.

Tuan Tran Van
6 min read
Contents (10 sections)
  1. Step 1 — Set up your Python environment and API key
  2. Step 2 — Make your first API call and confirm it works
  3. Step 3 — Give the chatbot conversation memory (for members)
  4. Step 4 — Stream the reply so it appears as it is generated (for members)
  5. Step 5 — Put the chatbot behind a Streamlit web interface (for members)
  6. Step 6 — Handle errors, retries and token cost (for members)
  7. Choosing a UI framework and when to move to an agent SDK (for members)
  8. Troubleshooting common errors (for members)
  9. What to do next (for members)
  10. References (for members)

You are going to build a stateful chatbot with Python. By the end you will have a working system that streams replies in real time and runs behind a web interface.

You need Python 3.10 or higher, a terminal, and an API key from either OpenAI or Anthropic.

A chatbot written in Python answering a user in real time

Step 1 — Set up your Python environment and API key

Isolate the project's dependencies in a virtual environment:

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

Your prompt changes to include (chatbot_env) once the environment is active. Then install the SDKs and the environment loader:

bash
pip install openai anthropic python-dotenv

Create a .env file in the project root and put your keys in it:

env
OPENAI_API_KEY=your_openai_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here

The provider console page where you create a new API key for the project

Step 2 — Make your first API call and confirm it works

Pick one — skip the other.

OpenAI Variant

This snippet uses the Responses API with gpt-5.6. It takes an input parameter rather than the legacy messages array.

python
from openai import OpenAI
from dotenv import load_dotenv
import os
 
load_dotenv()
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
 
response = client.responses.create(
    model="gpt-5.6",
    input=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "How do I print a list in Python?"}
    ]
)
 
print(response.output_text)

Anthropic Variant

This one uses the Anthropic Messages API with claude-opus-5.

python
import os
from anthropic import Anthropic
 
client = Anthropic(api_key=os.environ.get("ANTHROPIC_API_KEY"))
 
message = client.messages.create(
    max_tokens=1024,
    messages=[{"role": "user", "content": "What is Python?"}],
    model="claude-opus-5",
)
 
for block in message.content:
    if block.type == "text":
        print(block.text)

A coherent text response in your terminal means the key and the SDK both work.

Share this article