# Call the OpenAI Responses API in Python

> Make your first OpenAI API call from Python with the Responses API, then keep a conversation going, stream the reply, call your own function, and get JSON back.

Level: Advanced
Tool: ChatGPT
Category: Building
Time: About 30 minutes
Checked: 2026-10-18
Tools: [OpenAI developer quickstart](https://developers.openai.com/api/docs/quickstart?language=python), [OpenAI models](https://developers.openai.com/api/docs/models), [Conversation state](https://developers.openai.com/api/docs/guides/conversation-state), [Function calling](https://developers.openai.com/api/docs/guides/function-calling), [Structured Outputs](https://developers.openai.com/api/docs/guides/structured-outputs), [OpenAI API pricing](https://developers.openai.com/api/docs/pricing)
HTML page: https://easyaihowtos.com/guides/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.

## What you need

- Python 3.10 or newer and a terminal (the current openai library requires 3.10+)
- An OpenAI API account with billing set up (API use is pay-as-you-go, separate from a ChatGPT Plus or Pro subscription)
- A few cents of API credit for the test calls

## 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:
```bash
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`.
```python
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:
```python
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:
```python
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:
```python
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`:
```python
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:
```python
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.

## FAQ

### 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.

---

This guide is from Easy AI How-To (https://easyaihowtos.com). It is independent of the tools named above. Screens and free-plan limits change, so check the date before you rely on a button name.
