Day 2, 30 minutes · beginner
Why it matters
Make your first OpenAI Responses API call in Python, with the key kept out of your code and git, and read the answer, token counts and cost. The first call is where most beginners leak their key. They paste it into the script "just to test", and the script ends up on GitHub. The second trap is reading only the text of the answer, when the reply also tells you what it cost and whether it finished.
Today Hedda's helper gets its first code. You put the key where your script finds it and git never picks it up, send one question to the Responses API and look at everything that comes back: the answer, the list of output items, and the token counts. Then you ask a follow-up question that only makes sense with the first one. You finish with a safe project folder and two scripts that print their own cost.
The key goes in the environment
OpenAI's SDK (the official Python library, openai) reads the key from an environment variable called OPENAI_API_KEY. So your code never holds it. A variable set in one terminal disappears when you close it, so many people use a .env file: a plain text file with one setting per line. A small package called python-dotenv (not made by OpenAI) loads those lines as environment variables when the script starts.
The order matters:
.gitignorefirst, the list of files git must leave alone.- Check that git really ignores
.envwithgit check-ignore, before the file exists. - Only then write the key into
.env, and confirm withgit status.
If a key ever lands in a commit, ignoring it later does not help. Revoke the key on the API keys page and make a new one.
One call, many parts
The script calls client.responses.create with four settings:
- model:
gpt-6-luna, the model OpenAI's models page calls its most efficient. Model names change fast, so copy the name from the models page. - instructions: the standing rules for the helper. The docs say these take priority over the user's input.
- input: the visitor's question.
- reasoning and max_output_tokens: Luna thinks before it answers, and those thinking tokens (reasoning tokens) are billed as output. Effort
lowkeeps that small.max_output_tokenscaps everything the model writes, thinking included.
That cap has a catch. If the model reaches it, the reply has status incomplete, and the docs warn this can happen before any visible text is written, while you still pay for the tokens used. That is why the script checks the status first. If you see "Stopped early", raise the cap a little.
The reply is a response object. Three parts matter today:
- output: a list of items. Often a
reasoningitem and then amessageitem, but later you will see tool calls here too. The docs warn not to assume the text sits in the first item. - output_text: a shortcut in the SDK that joins all text from the message items. Use it to print the answer.
- usage:
input_tokens,output_tokens, and inside the output details thereasoning_tokens. This is what you pay for.
Conversation state
Each call stands on its own: the model remembers nothing between calls. To ask a follow-up, the model must see the earlier turn again. The docs give three ways:
- Send the history yourself: add the earlier output items to your next input list. Lesson 3 does this.
- previous_response_id: give the id of the last response and the API adds that turn for you.
follow_up.pydoes this. It works because responses are stored for 30 days by default. - The Conversations API: a stored conversation with its own id, for longer chats.
Two rules from the docs to remember. Top-level instructions only count for the call that sends them, so follow_up.py sends them again. And with previous_response_id, all earlier input in the chain is still billed as input tokens. Run the script and you will see the second call's input count grow. Long chats get expensive in this quiet way.
If you would rather not have responses stored, set store=False and send the history yourself.
The steps
- Set up the folder with a virtual environment and git.
- Write
.gitignore, check it, then write.env. - Install
openaiandpython-dotenv. - Write
config.pyandrules.py, the shared setup for the whole course. - Run
first_call.pyand read every printed line. - Run
follow_up.pyand compare the token counts.
Pick your tool below and follow the steps.
If something fails
- An error about the API key: the key is wrong, revoked or not loaded. Run the script from the project folder, where
.envis. - 429: a rate limit, a spend limit or no credit left. The error code says which one, for example
project_spend_limit_exceededorcredit_balance_exhausted. - An error about the model: the name may have changed. Check the models page.
Common mistakes
- Writing quotes or spaces in
.env. - Reading
output[0]and finding a reasoning item instead of text. - Setting
max_output_tokensso low that nothing visible comes back. - Opening a new terminal and forgetting to activate
.venvagain.
Deeper dive
Today's actions
Ticks are not saved without an accountDo it in OpenAI API
OpenAI API
- Set up a folder with its own virtual environment (a private set of Python packages for this project):
mkdir otterbrook-desk,cd otterbrook-desk,python -m venv .venv. Activate it withsource .venv/bin/activate(macOS, Linux) or.venv\Scripts\activate(Windows). Then rungit init. - Create
.gitignorewith these three lines. Then rungit check-ignore -v .env: it must print a line that names.gitignore. If it prints nothing, fix the file before you go on..env .venv/ __pycache__/ - Only now create
.envwith one line, your key in place of the fake text, no spaces and no quotes. Rungit status: the list it prints must not show.env.OPENAI_API_KEY=paste-your-key-here - Run
python --version(3.10 or newer is needed) and thenpip install openai python-dotenv. - Create
config.py: the one place that holds the model name and the client for every later script."""Shared setup for the Otterbrook front desk helper.""" from dotenv import load_dotenv from openai import OpenAI load_dotenv() # loads OPENAI_API_KEY from .env as an environment variable MODEL = "gpt-6-luna" # model names change: check the models page before you copy this client = OpenAI() # reads OPENAI_API_KEY from the environment: the key is never in code - Create
rules.pywith the standing rules of the front desk helper.RULES = ( "You answer questions for the front desk of Otterbrook Community Pool, a made-up swimming pool. " "Be warm and brief: at most 60 words per answer. " "When a price, a time or a free place is not known to you, say so " "and suggest calling the front desk. Never give medical advice." ) - Create
first_call.pyand runpython first_call.py. You should see an answer,status: completed, the type of every output item and three token counts.from config import MODEL, client from rules import RULES response = client.responses.create( model=MODEL, instructions=RULES, input="Can my seven year old join a swimming lesson on Saturday morning?", reasoning={"effort": "low"}, max_output_tokens=2000, ) if response.status == "incomplete": print("Stopped early:", response.incomplete_details.reason) print("ANSWER:", response.output_text) print("status:", response.status, "| id:", response.id) for item in response.output: print("output item:", item.type) usage = response.usage print("input tokens:", usage.input_tokens) print("output tokens:", usage.output_tokens) print("of which reasoning:", usage.output_tokens_details.reasoning_tokens) - Create
follow_up.pyand run it. The second question only makes sense with the first one, which the API adds for you. Compare the input tokens of the two calls.from config import MODEL, client from rules import RULES first = client.responses.create( model=MODEL, instructions=RULES, input="What should my daughter bring to her first swimming lesson?", reasoning={"effort": "low"}, max_output_tokens=2000, ) print("ANSWER 1:", first.output_text) second = client.responses.create( model=MODEL, instructions=RULES, # instructions count only for the call that sends them previous_response_id=first.id, # the API adds the first question and answer input="And what if she is afraid of the water?", reasoning={"effort": "low"}, max_output_tokens=2000, ) print("ANSWER 2:", second.output_text) print("input tokens, call 1:", first.usage.input_tokens) print("input tokens, call 2:", second.usage.input_tokens)
Note: The SDK reads OPENAI_API_KEY from the environment, and python-dotenv (not an OpenAI package) copies it there from .env. Responses are stored for 30 days by default and are needed for previous_response_id; store=False turns that off. Model names change: check the models page before you copy one.
Paid planNeeds prepaid API credit. The OpenAI API is billed per use, separately from any ChatGPT plan.
Create a free account to save your progress
Free, and no payment details. Your ticks and finished lessons are kept, on every device.
Create a free account I already have an accountCreate a free account to save your progress. Sign in or sign up