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
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
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 optionalinstructions, and you get back a response object. Itsoutputis a list of items: the model's message, plus any tool calls or reasoning summaries. The Python library addsresponse.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.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_KEYfrom 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.Make your first call
Save this as
hello.pyand runpython 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)instructionsis like a system prompt: it sets how the model behaves.inputis the user's message.gpt-6-lunawas OpenAI's lowest-cost current model when this was checked. Swap ingpt-6.1-solorgpt-6-astrawhen you need more reasoning power.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. Useoutput_text, or loop overoutputand look fortype == "message".
- 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
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 asinputeach time. Either way, you pay for the earlier turns as input tokens on every call.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.completedevent.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_callitem with JSON arguments, your script runsdays_until, and the second call gives the model the result so it can answer."strict": Truemakes 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.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_parsedis a realRecipeobject, so there's no JSON cleanup and no guessing at keys.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_tokensto cap long answers, and logresponse.usageon 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"}totoolsfor 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.
More guides
BeginnerChatGPTEveryday
Plan a week of meals
Give free ChatGPT your people, your time, and foods to skip. Get a 7-day plan and a shopping list you can edit.
About 10 minutes using ChatGPT
BeginnerChatGPTWriting
Write a social media caption
Ask free ChatGPT for three short captions from what really happened, then post one yourself.
About 6 minutes using ChatGPT
BeginnerChatGPTWriting
Make a message sound kinder
Paste a blunt draft into free ChatGPT and get a kinder version that does not add apologies or new facts.
About 6 minutes using ChatGPT