Club.noww.in
Calling the OpenAI API from Python takes about ten lines once the package and key are in place. Most beginner trouble comes from the setup around them.
Quick answer: run pip install openai python-dotenv, put OPENAI_API_KEY in a .env file, then call client.responses.create() with a model and an input, and print response.output_text.
from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() response = client.responses.create(model="gpt-6-luna", input="Hi!") print(response.output_text)In this tutorial, I’ll walk you through the Python OpenAI API from a clean install to text you can tune: the key, the first call, reading the response, picking a model, and three settings that change what you get back.
I ran each script for real on Python Python 3.12.5, openai 3.61.0 and gpt-6-luna, OpenAI’s most efficient model right now. The screenshots are real VS Code and Command Prompt runs.
What You Need Before Calling the OpenAI API from Python
- Python 3.10 or newer. The current openai package won’t install on older versions (install a newer Python next to the old one).
- An OpenAI platform account with API credits. A ChatGPT subscription doesn’t include API usage; billing is separate.
- An API key from the API keys page of your OpenAI dashboard. Copy it once; you can’t view it again later.
- VS Code (or any editor) and a terminal.
Our running sample is Harbor Lane Coffee, a made-up coffee shop in Portland, Maine. Every Python script below asks the model to write menu copy, a tagline or a welcome note for it.
Step 1: Install the openai Package in a Python Virtual Environment
A virtual environment keeps the OpenAI packages away from your other Python projects. If venvs are new to you, my Python virtual environments tutorial explains them.
First, a tiny script that proves the install worked. (My Python packages tutorial explains pip itself.) Here’s how to set it up:
- Create a folder named openai-demo and open it in VS Code with File > Open Folder.
- Create a file named check_setup.py in that folder and paste the code below into it.
- Open Command Prompt (or View > Terminal in VS Code) and go to the folder with the cd command.
- Type the four commands from the next block, one per line, pressing Enter after each.
Type these in Command Prompt inside the openai-demo folder. On macOS or Linux, activate with source .venv/bin/activate instead:
python -m venv .venv .venv\Scripts\activate pip install -q openai python-dotenv python check_setup.py
A fresh venv, a quiet pip install and the check script reporting openai 3.61.0.The -q flag only hides pip’s download list, and the pip upgrade notice is harmless.
Important: install and run from the same activated venv. Mixing them up is the classic cause of ModuleNotFoundError after pip install. Teams often pin the version too, as in pip install a specific version.
Step 2: Store Your OpenAI API Key in a .env File
Never paste your key into a Python file. Code gets shared, pushed to GitHub and pasted into chats, and a leaked key can run up charges fast.
Create a file named .env in the openai-demo folder (VS Code: File > New File). Add one line, with your real key after the equals sign:
OPENAI_API_KEY=sk-...your-key...If the folder is a Git repo, add .env to your .gitignore file so the key never gets committed:
.envload_dotenv() copies that line into the process environment, and OpenAI() reads OPENAI_API_KEY from there on its own. My Python environment variables tutorial covers os.environ in more depth.
Step 3: Make Your First Python OpenAI API Call
The Responses API is OpenAI’s recommended API for new projects, so that’s what we use here. One call sends a model name and your input, and you get a response object back.
Save this as first_call.py in the openai-demo folder and run python first_call.py in the VS Code terminal:
from dotenv import load_dotenv from openai import OpenAI load_dotenv() # copies OPENAI_API_KEY from .env client = OpenAI() # finds the key on its own response = client.responses.create( model="gpt-6-luna", input="Write one sentence for a coffee shop menu about " "our Maple Pecan Cold Brew ($5.75).", ) print(response.output_text)Output:
Smooth, slow-steeped cold brew with warm maple sweetness and toasted pecan notes — $5.75.
One Responses API call, one sentence of menu copy.How does this work? OpenAI() builds a client with your key. responses.create() sends the request and waits, and output_text joins every text piece of the reply into one Python string.
Run it twice and you’ll get two different sentences. That’s normal: the model samples words, so text generation isn’t repeatable by default. The same code also runs in a Jupyter notebook cell.
Step 4: Read output_text, usage and status from the Response
The response holds more than text. Same client, a shorter prompt, and a few more print() lines show what comes back.
Save this as read_response.py and run it in the VS Code terminal:
from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() response = client.responses.create( model="gpt-6-luna", input="Suggest a name for a fall latte. Name only.", ) usage = response.usage print("Text: ", response.output_text) print("Model: ", response.model) print("Status: ", response.status) print("Items: ", [item.type for item in response.output]) print("Input: ", usage.input_tokens, "tokens") print("Output: ", usage.output_tokens, "tokens") print("Reasoning:", usage.output_tokens_details.reasoning_tokens, "of the output tokens")Output:
Text: Maple Ember Latte Model: gpt-6-luna Status: completed Items: ['reasoning', 'message'] Input: 17 tokens Output: 31 tokens Reasoning: 21 of the output tokens
This call used 17 input and 31 output tokens, 21 of them reasoning.How does this work? response.output is a Python list of items. gpt-6-luna is a reasoning model, so a reasoning item comes before the message item that holds the text.
You pay for input and output tokens, and reasoning tokens count as output even though you never see them. Always check status: completed means the reply is whole.
Step 5: Choose an OpenAI Model for Your Python Script
The model name is a plain string, so switching models means changing one word. Which names can your key use? Ask the API: listing models costs nothing, and sorted() puts the IDs in order.
Save this as list_models.py and run it in the VS Code terminal:
from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() # listing models is free: no tokens are used names = sorted(m.id for m in client.models.list() if m.id.startswith("gpt-6")) print(len(names), "GPT-6 models on this account:") for i in range(0, len(names), 3): # three per line print(" ", ", ".join(names[i:i + 3]))Output:
11 GPT-6 models on this account: gpt-6-astra, gpt-6-astra-healthcare, gpt-6-luna gpt-6-sol, gpt-6.1-sol, gpt-6.1-sol-healthcare gpt-6.1-terra, gpt-6.2-astra, gpt-6.2-astra-healthcare gpt-6.2-sol, gpt-6.2-sol-healthcare
11 GPT-6 model IDs showed up for my key.Here’s how I’d choose among them for Python text generation:
| gpt-6-luna | Most efficient, high-volume tasks | Learning, short text, scripts that run often |
| gpt-6.1-terra | Fast, natural writing, visual reasoning | Polished copy or images in the input |
| gpt-6.2-sol | Everyday work and agents at scale | Multi-step tasks and tool calls |
| gpt-6.2-astra | Hardest problems, top quality | Complex reasoning where cost matters less |
I start every Python project on gpt-6-luna and move up only when the output isn’t good enough. Bigger models cost more per token.
Step 6: Shape Generated Text with Instructions
instructions is the system prompt: the role, tone and rules the model follows for that request. Your input stays the actual task.
Same Maple Pecan Cold Brew request, sent twice: once bare, once with our menu-copy rules.
Save this as instructions_demo.py and run it in the VS Code terminal:
import textwrap from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() MODEL = "gpt-6-luna" ASK = "Describe our Maple Pecan Cold Brew ($5.75)." STYLE = ("You write menu copy for Harbor Lane Coffee in " "Portland, Maine. One sentence, under 20 words, " "friendly, no emojis.") plain = client.responses.create(model=MODEL, input=ASK) styled = client.responses.create( model=MODEL, instructions=STYLE, input=ASK) for label, r in [("Without", plain), ("With", styled)]: words = len(r.output_text.split()) print(f"{label} instructions: {words} words") print(textwrap.shorten(r.output_text, 150), "\n")Output:
Without instructions: 13 words Smooth cold brew with cozy maple sweetness and rich, nutty pecan notes. **$5.75** With instructions: 17 words Smooth cold brew with cozy maple sweetness and toasted pecan notes, served chilled for a refreshing treat.
Without instructions: 13 words. With them: 17.How does this work? With no rules, the model guessed the format and wrapped its 13 words in Markdown bold. The instructions set the shop, the length and the tone, so the reply came back as 17 words of plain menu copy.
textwrap.shorten() only trims long text so it fits the screen, much like getting the first N characters of a string. Put the rules you always want in instructions, and keep the input for the task itself.
Pro Tip: instructions apply only to the call that sends them. In a multi-turn chat, pass them on every request.
Step 7: Set the OpenAI Temperature in Python
temperature sets how adventurous the word choices are: low values stay safe and similar, high values vary more. My first try on gpt-6-luna failed, and the error is worth seeing.
Save this as temperature_demo.py and run it in the VS Code terminal:
import openai from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() MODEL = "gpt-6-luna" ASK = "Write a five-word tagline for Harbor Lane Coffee." try: # default reasoning effort is medium client.responses.create(model=MODEL, input=ASK, temperature=0.2) except openai.BadRequestError as err: print("Error 400:", err.body["message"]) for temp in (0.2, 1.5): for _ in range(3): r = client.responses.create( model=MODEL, input=ASK, temperature=temp, reasoning={"effort": "none"}, # needed here ) print(f"temperature={temp}:", r.output_text)Output:
Error 400: Unsupported parameter: 'temperature' is not supported with this model. temperature=0.2: Your neighborhood, brewed with care daily. temperature=0.2: Harbor Lane Coffee: Your Daily Coastal Escape. temperature=0.2: Harbor Lane Coffee: Your Daily Coastal Escape. temperature=1.5: Your Harbor Lane, brewed beautifully daily. temperature=1.5: Your calm, cozy corner by the harbor. temperature=1.5: Find your calm, one cup at a time.
Temperature fails at the default effort, then works with effort set to none.How does this work? In my test, gpt-6-luna rejected temperature with a 400 error until I added reasoning={"effort": "none"}. With reasoning off, the for loop ran three calls per setting.
My run gave 2 different taglines out of 3 at 0.2 and 3 at 1.5. Test it on longer prompts too.
For product copy I stay between 0.2 and 1.0. Higher values read more creative, but they drift off-brand sooner.
Step 8: Cap OpenAI Output Length with max_output_tokens
max_output_tokens caps how many tokens the model may generate. The minimum is 16; I got a 400 error at 10. Same rewards-member welcome note, three different settings:
Save this as max_tokens_demo.py and run it in the VS Code terminal:
import textwrap from dotenv import load_dotenv from openai import OpenAI load_dotenv() client = OpenAI() ASK = ("Write a three-sentence welcome note for new " "Harbor Lane Coffee rewards members.") for effort, limit in [("medium", 16), ("none", 16), ("none", 200)]: r = client.responses.create( model="gpt-6-luna", input=ASK, max_output_tokens=limit, reasoning={"effort": effort}, ) used = r.usage.output_tokens why = r.incomplete_details.reason if r.incomplete_details else "-" print(f"{effort}/{limit}: {r.status}, {used} tokens, reason={why}") print(" text:", repr(textwrap.shorten(r.output_text, 60)))Output:
medium/16: incomplete, 16 tokens, reason=max_output_tokens text: '' none/16: incomplete, 16 tokens, reason=max_output_tokens text: 'Welcome to Harbor Lane Coffee Rewards—we’re glad [...]' none/200: completed, 48 tokens, reason=- text: 'Welcome to Harbor Lane Coffee Rewards—we’re delighted [...]'
At the default effort, a 16-token cap returned no text at all.How does this work? The cap counts reasoning tokens too. At the default medium effort, all 16 went to thinking, so the status was incomplete and the text was empty, even though I paid for those tokens.
With effort none, the same 16 tokens gave the start of the note, then stopped. At 200 it finished. If you see incomplete, read incomplete_details.reason before trusting the text.
Python OpenAI API Settings Cheat Sheet
Every Python OpenAI API setting from the steps above, on one screen:
| model | Picks the model | gpt-6-luna is the cheapest place to start |
| input | Your prompt: a string or a list of messages | A plain string is enough for one-off text |
| instructions | System-style rules for this call | Plain one-sentence copy, no Markdown |
| temperature | Randomness, 0 to 2 | 400 error unless reasoning effort is none |
| max_output_tokens | Cap on generated tokens, reasoning included | Minimum 16; a tiny cap can return empty text |
| reasoning | Effort: none, low, medium (default), high and up | none = faster, cheaper, allows temperature |
Errors You’ll See with the Python OpenAI API
Three mistakes cover most first-day Python failures, and I reproduced all three without spending credits. The script catches each SDK error class, like catching multiple exceptions in Python.
Save this as errors_demo.py and run it in the VS Code terminal:
import os import openai from dotenv import load_dotenv from openai import OpenAI load_dotenv() # 1. No key at all (as if the .env file were missing) saved = os.environ.pop("OPENAI_API_KEY") try: OpenAI() except openai.OpenAIError as err: print("1.", type(err).__name__) print(" ", str(err)[:72]) os.environ["OPENAI_API_KEY"] = saved # 2. A wrong key (a typo when you paste it) try: bad = OpenAI(api_key="sk-not-a-real-key") bad.responses.create(model="gpt-6-luna", input="Hi") except openai.AuthenticationError as err: print("2.", type(err).__name__, err.status_code) print(" ", err.body["message"][:72]) # 3. A model name with a typo try: OpenAI().responses.create(model="gpt6-luna", input="Hi") except openai.NotFoundError as err: print("3.", type(err).__name__, err.status_code) print(" ", err.body["message"][:72])Output:
1. OpenAIError Missing credentials. Please pass an `api_key`, `workload_identity`, `adm 2. AuthenticationError 401 Incorrect API key provided: sk-not-a*****-key. You can find your API key 3. NotFoundError 404 The model `gpt6-luna` does not exist or you do not have access to it.
Missing key, wrong key and a typo in the model name.- OpenAIError (no key): raised by OpenAI() itself. Check the .env file name, its folder and that load_dotenv() runs first.
- AuthenticationError 401: the key is wrong, revoked or has a stray space. Create a new key if you’re unsure.
- NotFoundError 404: the model name has a typo, or your account can’t use it. Copy the ID from list_models.py.
RateLimitError 429: too many requests or no credits
A 429 means you sent too much too fast, or your credits or spend limit ran out. The SDK already retries some errors twice; you can raise that. Here’s the pattern I use, saved in a script like rate_limit_demo.py:
import openai from openai import OpenAI client = OpenAI(max_retries=5) # default is 2 retries try: response = client.responses.create( model="gpt-6-luna", input="Write a tagline.") print(response.output_text) except openai.RateLimitError as err: print("429 from OpenAI:", err.body["message"]) print("Slow down, or check credits and limits.")If waiting doesn’t fix a 429, it’s billing: add credits or raise the limit in your dashboard.
Is the Chat Completions API Still OK to Use in Python?
Yes, Chat Completions still works, and many older Python tutorials use client.chat.completions.create(). For new code I use the Responses API, because new OpenAI features show up there first.
openai.ChatCompletion.create in an old example is pre-1.0 SDK code that fails on today’s package.
After Your First OpenAI API Call in Python
The Python OpenAI API gets more useful once a script remembers context. My AI chatbot in Python tutorial adds conversation history, and building your first AI agent lets the model call your functions.
Later posts cover streaming replies as they’re written, function calling, structured outputs and a deeper Responses API tour. They’re all collected on the Python AI agents hub page.
A few more Python projects to try with what you just learned:
- A speech-to-text converter in Python
- Text to speech in Python
- Make a Python script executable
- Constants in Python
Python OpenAI API: Quick Answers
Is the OpenAI API free to use from Python?
No. The openai package is free, but every API call uses tokens billed to your platform account. A ChatGPT Plus plan doesn’t cover API calls.
Which Python version does the openai package need?
Python 3.10 or newer for current releases. I used Python Python 3.12.5 with openai 3.61.0.
Where should I keep my OpenAI API key in Python?
In a .env file loaded with python-dotenv, or in a system environment variable. Never hard-code it in a .py file or commit it to Git.
Why is response.output_text empty?
Usually max_output_tokens was too low and reasoning used it all. Check response.status and incomplete_details, then raise the cap or lower the reasoning effort.
Can I set temperature on gpt-6-luna?
In my test, only with reasoning effort set to none. At the default effort the API returned a 400 Unsupported parameter error.
How do I install the OpenAI library in Python?
Activate a virtual environment and run pip install openai python-dotenv. The OpenAI developer quickstart shows the same first call in other languages too.












English (US)