How to make your first OpenAI Responses API call in Python

Day 2, 30 minutes · beginner

Goal of this lessonKeep your key in a .env file that git ignores, make a first Responses API call, and read its output items, token usage and a follow-up turn.

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:

  1. .gitignore first, the list of files git must leave alone.
  2. Check that git really ignores .env with git check-ignore, before the file exists.
  3. Only then write the key into .env, and confirm with git 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 low keeps that small. max_output_tokens caps 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 reasoning item and then a message item, 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 the reasoning_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:

  1. Send the history yourself: add the earlier output items to your next input list. Lesson 3 does this.
  2. previous_response_id: give the id of the last response and the API adds that turn for you. follow_up.py does this. It works because responses are stored for 30 days by default.
  3. 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

  1. Set up the folder with a virtual environment and git.
  2. Write .gitignore, check it, then write .env.
  3. Install openai and python-dotenv.
  4. Write config.py and rules.py, the shared setup for the whole course.
  5. Run first_call.py and read every printed line.
  6. Run follow_up.py and 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 .env is.
  • 429: a rate limit, a spend limit or no credit left. The error code says which one, for example project_spend_limit_exceeded or credit_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_tokens so low that nothing visible comes back.
  • Opening a new terminal and forgetting to activate .venv again.

Deeper dive

Today's actions

Ticks are not saved without an account

Do it in OpenAI API

OpenAI API

  1. 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 with source .venv/bin/activate (macOS, Linux) or .venv\Scripts\activate (Windows). Then run git init.
  2. Create .gitignore with these three lines. Then run git 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__/
  3. Only now create .env with one line, your key in place of the fake text, no spaces and no quotes. Run git status: the list it prints must not show .env.
    OPENAI_API_KEY=paste-your-key-here
  4. Run python --version (3.10 or newer is needed) and then pip install openai python-dotenv.
  5. 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
  6. Create rules.py with 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."
    )
  7. Create first_call.py and run python 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)
  8. Create follow_up.py and 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.

Checked on 4 December 2026 · Source: OpenAI API docs: Developer quickstart (opens in a new tab)

Create a free account to save your progress. Sign in or sign up