Using ChatGPT in your browser is very different from building with it in code. By connecting Python to OpenAI, you move from just using AI to actually creating with it. You can automate tasks, quickly summarise lots of documents, or make your own assistants. In this article, I’ll show you step-by-step how to connect Python to OpenAI.
Connecting Python to OpenAI
Before we start coding, let’s make sure we understand the process. Think of the OpenAI API as a smart remote consultant:
- Your Python Script is the manager (You).
- The API Key is your ID badge. It proves you are who you say you are and that you have permission (credits) to ask for help.
- The Request is the specific brief you send the consultant (“Write a poem,” “Fix this bug,” “Analyse this sentiment”).
- The Response is the consultant’s work returned to you.
Before version 1.0.0 of the library, we would send requests without much structure. Now, we create a specific Client and use a dedicated channel to make sure everything is secure and reliable.
Step 1: The Setup
Create your project folder. Open your terminal (or Command Prompt) and run:
mkdir openai-project
cd openai-project
Next, create a virtual environment. This keeps your project clean:
# Windows
python -m venv venv
venv\Scripts\activate
# Mac/Linux
python3 -m venv venv
source venv/bin/activate
Now, install the library. We need the official OpenAI library:
pip install openai
Step 2: Getting Your API Key
You cannot skip this step:
- Go to the platform: openai.com.
- Sign up or Log in.
- Navigate to Dashboard > API Keys.
- Click Create new secret key.
- Copy it immediately.
You will never see it again after you close that window.
Step 3: The Code
Create a file called app.py and add the following code. This example uses the latest OpenAI Python Client (version 1.0.0 or newer):
import os
from openai import OpenAI
# 1. Instantiate the client
# ideally, use: client = OpenAI(api_key=os.environ.get("OPENAI_API_KEY"))
# For learning purposes ONLY, you can paste your key below if env vars aren't set.
client = OpenAI(
api_key="YOUR_OPENAI_API_KEY_HERE"
)
print("Consultant is thinking...")
# 2. Create the chat completion (The Request)
response = client.chat.completions.create(
model="gpt-4o-mini", # The "brain" we are asking (cost-effective)
messages=[
{"role": "system", "content": "You are a poetic assistant."},
{"role": "user", "content": "Explain recursion in a haiku."}
]
)
# 3. Extract and print the answer (The Response)
print("\n--- AI Response ---")
print(response.choices[0].message.content)In this code, client = OpenAI(…) starts the connection and checks your credentials. If your key is incorrect, the script will stop at this point. You can think of this step as dialing a phone number.
The client.chat.completions.create(…) function is the main part of the code. We use chat.completions because newer models like GPT-4 work through chat, not just simple text completion.
The model = “gpt-4o-mini” is the AI model we are using:
- gpt-4o: Smart, but expensive.
- gpt-4o-mini: Fast, cheap, and excellent for most tasks.
The messages=[…] part is the conversation history. It’s a list of dictionaries.
The response.choices[0].message.content gives you a detailed object with extra information like tokens used and the model name. We look at the choices list, take the first answer, check the message, and then get the text content.
Handling the Errors
Sometimes things go wrong. The API could be unavailable, or you might run out of credits. Here’s how professional engineers write code to avoid crashes:
from openai import OpenAI, APIError
client = OpenAI()
try:
response = client.chat.completions.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": "Hello!"}]
)
print(response.choices[0].message.content)
except APIError as e:
# This runs if OpenAI returns an error (e.g., 401 Unauthorized, 429 Rate Limit)
print(f"OpenAI connection failed: {e}")If you get a RateLimitError, it means you are sending requests too quickly. Instead of retrying right away, wait for 2 seconds, then 4, then 8 before trying again.
Closing Thoughts
Connecting Python to OpenAI is a basic skill for modern AI work. However, what matters most is the logic you create with it.
A Python script can loop through a thousand customer reviews. It can read a PDF and quiz you on it. It can write code to fix its own errors.
Today, you learned how to give your Python script some intelligence. Next, you’ll need to learn how to guide it to do what you want.
If you found this article helpful, follow me on Instagram for daily AI tips and practical learning. Also, check out my latest book, Hands-On GenAI, LLMs & AI Agents. It’s a step-by-step guide to help you get job-ready in today’s AI world.





