Skip to content
Easy AI How-To

AdvancedChatGPTBuilding

Call the OpenAI Responses API in Python

The Responses API is how you call OpenAI's models from your own code. This guide goes from a first call to the four things most apps need: keeping a conversation going, streaming the reply, letting the model call your own function, and getting JSON back that matches a schema. You'll also see the token counts that decide what each call costs.

Time
About 30 minutes
Checked
Tools
OpenAI developer quickstart, OpenAI models, Conversation state, Function calling, Structured Outputs, OpenAI API pricing

If a button name on the screen does not match this guide, follow the action. These products rename buttons often. This is an advanced guide: it uses code, and each technical term is explained the first time it appears. Model names and prices change, so check the linked docs before you ship.

Steps

  1. Know what the Responses API is

    The Responses API is OpenAI's main way to call its models from code. You send an input (a string or a list of messages) and optional instructions, and you get back a response object. Its output is a list of items: the model's message, plus any tool calls or reasoning summaries. The Python library adds response.output_text, which joins all the text for you.

    OpenAI recommends Responses for all new projects. The older Chat Completions API still works, and the Assistants API was shut down on August 26, 2026, so skip any tutorial that starts with client.beta.assistants.

  2. Create a key and install the library

    In the OpenAI platform, add billing, then create a key under API keys. Then, in a new folder:

    python3 --version          # needs 3.10 or newer
    python3 -m venv .venv && source .venv/bin/activate
    pip install openai pydantic
    export OPENAI_API_KEY="your-key-here"
    

    The library reads OPENAI_API_KEY from the environment, so the key never goes in your code. Keep it out of Git, and set a monthly budget in the platform's limits settings before you start experimenting.

  3. Make your first call

    Save this as hello.py and run python hello.py.

    from openai import OpenAI
    
    MODEL = "gpt-6-luna"  # check the models page for current names
    client = OpenAI()
    
    response = client.responses.create(
        model=MODEL,
        instructions="You explain things in plain English, in three sentences or fewer.",
        input="What is an API, and why would I call one from Python?",
    )
    print(response.output_text)
    

    instructions is like a system prompt: it sets how the model behaves. input is the user's message. gpt-6-luna was OpenAI's lowest-cost current model when this was checked. Swap in gpt-6.1-sol or gpt-6-astra when you need more reasoning power.

  4. Look inside the response

    Before you build on it, print what came back:

    print("id:", response.id)
    for item in response.output:
        print("item:", item.type)
    u = response.usage
    print("input tokens:", u.input_tokens)
    print("output tokens:", u.output_tokens)
    print("  of which reasoning:", u.output_tokens_details.reasoning_tokens)
    
    • The GPT-6 models are reasoning models. They may think before answering, and those reasoning tokens are billed as output tokens. For simple tasks, add reasoning={"effort": "low"} to make calls faster and cheaper.
    • Don't read the text with response.output[0].content[0].text. The first item is not always the message. Use output_text, or loop over output and look for type == "message".
  5. Keep a conversation going

    The API doesn't remember anything between calls unless you tell it to. The simplest way is to pass the previous response's id:

    first = client.responses.create(model=MODEL, input="Give me one tip for naming Python variables.")
    second = client.responses.create(
        model=MODEL,
        previous_response_id=first.id,
        input="Show me a before-and-after example of that tip.",
    )
    print(second.output_text)
    

    This works because OpenAI stores responses for 30 days by default. If you set store=False (for example, for sensitive data), the id can't be looked up later. In that case, keep the message list yourself and send the whole thing as input each time. Either way, you pay for the earlier turns as input tokens on every call.

  6. Stream the reply as it's written

    For a chat-style app, show words as they arrive instead of waiting for the whole answer:

    stream = client.responses.create(
        model=MODEL,
        input="Write a four-line poem about debugging.",
        stream=True,
    )
    for event in stream:
        if event.type == "response.output_text.delta":
            print(event.delta, end="", flush=True)
        elif event.type == "response.completed":
            print("\n[done]", event.response.usage.output_tokens, "output tokens")
    

    A stream is a series of typed events. You usually only need the text deltas and the final response.completed event.

  7. Let the model call your own function

    Function calling lets the model ask your code to do something, like look up data. You describe the function, run it when the model asks, and send the result back. Save this as tools.py:

    import json
    from datetime import date
    from openai import OpenAI
    
    MODEL = "gpt-6-luna"
    client = OpenAI()
    
    tools = [{
        "type": "function",
        "name": "days_until",
        "description": "Count the days from today until a date (YYYY-MM-DD).",
        "parameters": {
            "type": "object",
            "properties": {"target": {"type": "string", "description": "A date like 2026-12-25"}},
            "required": ["target"],
            "additionalProperties": False,
        },
        "strict": True,
    }]
    
    def days_until(target: str) -> str:
        return str((date.fromisoformat(target) - date.today()).days)
    
    messages = [{"role": "user", "content": "How many days until 2026-12-25?"}]
    response = client.responses.create(model=MODEL, tools=tools, input=messages)
    
    messages += response.output  # keep the model's tool call (and reasoning) in the history
    for item in response.output:
        if item.type == "function_call" and item.name == "days_until":
            args = json.loads(item.arguments)
            messages.append({
                "type": "function_call_output",
                "call_id": item.call_id,
                "output": days_until(**args),
            })
    
    final = client.responses.create(model=MODEL, tools=tools, input=messages)
    print(final.output_text)
    

    The model never runs your code. It returns a function_call item with JSON arguments, your script runs days_until, and the second call gives the model the result so it can answer. "strict": True makes the arguments match your schema exactly. If you want the model to keep calling tools until it's done, wrap the two calls in a loop with a maximum number of rounds. That's the agent loop from the first-agent guide.

  8. Get JSON back that matches a schema

    When your code needs fields, not prose, use Structured Outputs with a Pydantic model:

    from pydantic import BaseModel
    
    class Recipe(BaseModel):
        name: str
        minutes: int
        ingredients: list[str]
    
    response = client.responses.parse(
        model=MODEL,
        input="A quick vegetarian pasta for two.",
        text_format=Recipe,
    )
    recipe = response.output_parsed
    print(recipe.name, recipe.minutes, recipe.ingredients)
    

    output_parsed is a real Recipe object, so there's no JSON cleanup and no guessing at keys.

  9. Check the cost and the answer

    Open the Usage page in the OpenAI platform and confirm that today's calls cost what you expected: tokens times the price on the models page. Then reread one answer from each step and check one fact yourself. The API is as confident as ChatGPT is when it's wrong. Before anything runs on a schedule, add max_output_tokens to cap long answers, and log response.usage on every call.

Tips

  • Keep the model name in one constant. Model names change often, and OpenAI's models page lists the current ones.

  • Built-in tools work the same way as your functions. Add {"type": "web_search"} to tools for answers from the live web, which is billed per search call on top of tokens.

  • Want to try agents without paying per call? The first-agent guide uses a Claude subscription login, and OpenAI's Codex CLI works with a ChatGPT sign-in. Use the API when you build something other people will use.

  • If you see a 429 error, you hit a rate limit or ran out of credit. Wait and retry, or check billing. The library already retries a few times on its own.

Common questions

Does my ChatGPT Plus subscription cover API calls?

No. ChatGPT plans and the API are billed separately. The API needs its own billing on the OpenAI platform, and you pay for the tokens you use.

Should I use Responses or Chat Completions?

Use Responses for new code. It's what OpenAI recommends, it has the built-in tools, and reasoning models work better with it. Chat Completions is still supported if you already have code on it.

Can I use the same code with other providers?

Often, yes. xAI's API accepts the same client.responses.create call when you point the library at xAI's address, as the Grok X Search guide shows. Model names and tools differ, so check each provider's docs.

Is my data used for training?

OpenAI says API data isn't used to train its models by default. Responses are still stored for 30 days unless you set store=False, so don't send secrets you couldn't share with a vendor.

Free newsletter

Learn AI by doing, one how-to at a time

New how-tos across all of AI: everyday tools, RAG, agents, local models, and taking a proof of concept to production. Each one is something you can try yourself, because the best way to learn AI is by doing it. Free, and you can unsubscribe in one click.

Subscribe free

Opens our sign-up page on beehiiv. Privacy