The OpenAI Responses API is now the default way to call GPT models from code. OpenAI recommends it for all new projects, and GPT-6.2 Astra and Sol only support tool calling through it.
This tutorial walks you through it in Python, from your first call to streaming, tools, memory, JSON output and migration. Every snippet uses the current official SDK and the parameter names from the OpenAI docs.
- Install:
pip install openai(we checked version 3.62.2, released 2 Dec 2026, which needs Python 3.10+). - Basic call:
client.responses.create(model="gpt-6.2-sol", input="..."), then readresponse.output_text. - Memory: chain turns with
previous_response_id, or keep a durable thread with the Conversations API. - Tools: built-in
web_search,file_searchandcode_interpreter, plus your own functions. - Price: GPT-6.2 Sol is $2 / $10 per 1M input / output tokens; GPT-6.2 Astra is $8 / $40.
What the Responses API Is and When to Use It
The Responses API is OpenAI’s main endpoint for generating text, at POST /v1/responses. It is the successor to Chat Completions and the replacement for the Assistants API, which shut down on 26 August 2026.
Instead of a messages list in and choices out, you send input and get back an output array of typed items. Those items can be messages, reasoning, tool calls or search results.
Here is what it gives you over Chat Completions:
- Built-in tools: web search, file search, code interpreter, computer use, image generation and remote MCP servers, with no extra glue code.
- Server-side memory: pass
previous_response_idor a conversation ID instead of resending the whole chat. - Better reasoning and caching: OpenAI’s migration guide cites 40% to 80% better cache use than Chat Completions in its internal tests.
- Required for new tools: GPT-6.2 Astra and Sol support Chat Completions, but tool calling needs the Responses API.
If you are brand new to the OpenAI SDK, our OpenAI API Python tutorial covers the basics first.
Prerequisites
- Python 3.10 or newer: the openai package 3.62.2 on PyPI lists
requires_python >=3.10. - An OpenAI API key: create one on the OpenAI platform. Our guide on how to get an OpenAI API key shows each screen.
- Credit on your account: the API is pay as you go and separate from a ChatGPT subscription.
- A terminal and editor: any editor works. VS Code is a good free choice.
Setup in 5 Steps
- Create a project folder. Run
mkdir responses-demoandcd responses-demo. - Make a virtual environment. Run
python3 -m venv .venv, then activate it withsource .venv/bin/activateon macOS or Linux, or.venv\Scripts\activateon Windows. - Install the SDK. Run
pip install openai pydantic. Check the version withpip show openai. This guide was checked against 3.62.2. - Set your key as an environment variable. On macOS or Linux run
export OPENAI_API_KEY="your_key_here". On Windows PowerShell runsetx OPENAI_API_KEY "your_key_here", then open a new terminal. - Test it. Save the first example below as
hello.pyand runpython hello.py. If you see a sentence, you are ready.
Warning: never paste your key into code or commit it to Git. The SDK reads OPENAI_API_KEY automatically, so OpenAI() needs no arguments.
Your First Call (Python and curl)
This is the smallest useful program. It sends one string and prints the text answer.
from openai import OpenAI
client = OpenAI() # reads OPENAI_API_KEY
response = client.responses.create(
model="gpt-6.2-sol",
input="Explain what an API is in two short sentences.",
)
print(response.output_text)
print(response.usage)
output_text is an SDK helper that joins all text parts of the output. The usage object shows input_tokens, output_tokens, total_tokens, plus input_tokens_details.cached_tokens and output_tokens_details.reasoning_tokens.
Adding instructions and reasoning effort
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-sol",
input=[
{"role": "developer", "content": "You are a friendly Python tutor. Answer in plain English."},
{"role": "user", "content": "What does a list comprehension do?"},
],
reasoning={"effort": "low"},
max_output_tokens=2000,
)
if response.status == "incomplete":
print("Stopped early:", response.incomplete_details.reason)
print(response.output_text)
A few rules from the docs matter here:
- Standing rules go in a developer message: since GPT-6.2, top-level
instructionsare appended afterinput. Put reusable rules in the firstdevelopermessage so they cache well. - Effort values: the API knows
none,minimal,low,medium,high,xhighandmax, but GPT-6.2 Astra and Sol rejectnone. OpenAI suggests starting withmedium. - Output cap:
max_output_tokensincludes reasoning tokens and has a minimum of 16. - No sampling knobs on GPT-6.2: the GPT-6.2 guide says to omit
temperature,top_pandtop_logprobs.
The same call with curl
curl https://api.openai.com/v1/responses \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-d '{
"model": "gpt-6.2-sol",
"input": "Explain what an API is in two short sentences."
}'
Streaming Responses
Streaming shows text as it is generated, which feels much faster in a chat UI. Set stream=True and loop over typed server-sent events.
from openai import OpenAI
client = OpenAI()
stream = client.responses.create(
model="gpt-6.2-sol",
input="Write a 4-line poem about Python.",
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\nTokens used:", event.response.usage.total_tokens)
elif event.type == "error":
print("\nStream error:", event)
The events you will use most are listed below.
| Event type | When it fires |
|---|---|
response.created |
Once, when the response starts |
response.output_text.delta |
Many times, each with a new text piece in event.delta |
response.function_call_arguments.delta |
While the model writes tool call arguments |
response.output_text.done |
When one text part is finished |
response.completed |
Once, with the full response and usage |
response.failed / error |
When something goes wrong |
Built-in Tools: Web Search, File Search, Code Interpreter
Built-in tools run on OpenAI’s side. You list them in tools and the model decides when to call them. The GPT-6.2 model pages list web search, file search, image generation, code interpreter, hosted shell, apply patch, skills, computer use, MCP and tool search.
Web search
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-sol",
tools=[{"type": "web_search"}],
input="What are the top 3 Python releases this year? Cite sources.",
)
print(response.output_text)
The answer comes back with URL citations as annotations on the text. Web search costs $10 per 1,000 calls, and the search content tokens are billed at your model’s rates.
Code interpreter
from openai import OpenAI
client = OpenAI()
response = client.responses.create(
model="gpt-6.2-sol",
tools=[{
"type": "code_interpreter",
"container": {"type": "auto", "memory_limit": "4g"},
}],
instructions="Write and run Python code to answer math questions.",
input="Solve 3x + 11 = 14 and show the code you ran.",
)
print(response.output_text)
Leave out memory_limit to get the default 1 GB container. A container expires after 20 minutes of no use, and its files and memory are lost, so download outputs right away.
File search
File search looks through files you upload into a vector store. You pass {"type": "file_search", "vector_store_ids": ["vs_..."]} in tools. It costs $2.50 per 1,000 calls, plus storage at $0.10 per GB per day after the first free GB.
Tip: set max_tool_calls to cap how many built-in tool calls one response can make. It is an easy guard against surprise web search bills.
Function Calling with Your Own Code
Function calling lets the model ask your code to do something, like check a database or call another API. The flow has three steps.
- Describe the function. Give a name, description and JSON Schema for the arguments.
- Read the call. The model returns a
function_callitem withname,arguments(a JSON string) andcall_id. - Send the result back. Add a
function_call_outputitem with the samecall_id, then call the API again.
import json
from openai import OpenAI
client = OpenAI()
def get_weather(city):
# Replace with a real weather API call
return f"It is 18 C and sunny in {city}."
tools = [{
"type": "function",
"name": "get_weather",
"description": "Get the current weather for a city.",
"strict": True,
"parameters": {
"type": "object",
"properties": {
"city": {"type": "string", "description": "City name, e.g. Paris"},
},
"required": ["city"],
"additionalProperties": False,
},
}]
input_list = [{"role": "user", "content": "What's the weather in Paris?"}]
response = client.responses.create(model="gpt-6.2-sol", tools=tools, input=input_list)
# Keep everything the model returned, including reasoning items
input_list += response.output
for item in response.output:
if item.type == "function_call" and item.name == "get_weather":
args = json.loads(item.arguments)
input_list.append({
"type": "function_call_output",
"call_id": item.call_id,
"output": get_weather(args["city"]),
})
final = client.responses.create(model="gpt-6.2-sol", tools=tools, input=input_list)
print(final.output_text)
Notice the function shape. In Chat Completions the name sat inside a nested function object. In the Responses API, name, description and parameters sit at the top level of the tool.
- tool_choice:
"auto"(default),"required","none", a specific function like{"type": "function", "name": "get_weather"}, or{"type": "allowed_tools", ...}for a subset. - parallel_tool_calls: set it to
Falseto get at most one tool call per turn. - Reasoning items: with reasoning models, pass back the reasoning items with your tool outputs. Appending
response.outputdoes this for you.
For a deeper dive into tool loops, see our OpenAI Agents SDK guide, which wraps this pattern for you.
Conversation State: previous_response_id vs Conversations
The model does not remember anything between calls on its own. The Responses API gives you three ways to keep context.
| Method | How it works | Best for |
|---|---|---|
| Manual | Append response.output and the next user message to your own list, resend it all |
Full control, store=False, zero data retention |
| previous_response_id | Pass the last response ID; the server adds the earlier turns | Simple chatbots and short sessions |
| Conversations API | Create a conversation object and pass its ID on every call | Long-lived threads across devices, jobs or days |
Chaining with previous_response_id
from openai import OpenAI
client = OpenAI()
first = client.responses.create(
model="gpt-6.2-sol",
input="Suggest a name for a Python cooking app.",
store=True,
)
print(first.output_text)
second = client.responses.create(
model="gpt-6.2-sol",
previous_response_id=first.id,
input="Make it shorter and more playful.",
)
print(second.output_text)
Using the Conversations API
from openai import OpenAI
client = OpenAI()
conversation = client.conversations.create()
for question in ["My name is Sam.", "What is my name?"]:
response = client.responses.create(
model="gpt-6.2-sol",
conversation=conversation.id,
input=[{"role": "user", "content": question}],
)
print(response.output_text)
print("Save this ID to continue later:", conversation.id)
Know these rules before you choose:
- Retention: stored responses are kept for 30 days by default. Conversation objects and their items are not subject to that 30-day limit.
- Billing: even with
previous_response_id, all earlier input tokens in the chain are billed as input tokens on every turn. - Not both:
previous_response_idcannot be combined withconversationin one request. - Long chats: the compaction feature (
context_management, or the/responses/compactendpoint) shrinks old context so you stay inside the window.
Note: GPT-6.2 drops earlier reasoning items if you edit the start of a conversation or switch models mid-chain. Keep the prefix unchanged to keep reasoning and prompt caching working.
Structured Output with Pydantic
Structured Outputs force the model to return JSON that matches your schema. With the Python SDK the easiest route is responses.parse plus a Pydantic model.
from openai import OpenAI
from pydantic import BaseModel
client = OpenAI()
class Invoice(BaseModel):
vendor: str
total: float
currency: str
items: list[str]
response = client.responses.parse(
model="gpt-6.2-sol",
input=[
{"role": "developer", "content": "Extract the invoice details."},
{"role": "user", "content": "Acme Ltd billed us 120.50 EUR for 2 keyboards and 1 mouse."},
],
text_format=Invoice,
)
invoice = response.output_parsed
print(invoice.vendor, invoice.total, invoice.currency)
print(invoice.items)
Without Pydantic, pass the schema yourself under text. Note the change from Chat Completions, where this lived in response_format.
text={
"format": {
"type": "json_schema",
"name": "invoice",
"strict": True,
"schema": {
"type": "object",
"properties": {
"vendor": {"type": "string"},
"total": {"type": "number"},
},
"required": ["vendor", "total"],
"additionalProperties": False,
},
}
}
The first request with a new schema is slower while the API processes it. You still need to handle refusals and incomplete responses. Our structured outputs guide compares this with Claude and Gemini.
Migrating from Chat Completions
Chat Completions is still supported, but most new features land in the Responses API first. Here is the mapping from OpenAI’s migration guide.
| Chat Completions | Responses API |
|---|---|
client.chat.completions.create |
client.responses.create |
messages=[...] |
input="..." or a list of items |
| System message | First developer message, or top-level instructions for one turn |
choices[0].message.content |
response.output_text |
max_tokens / max_completion_tokens |
max_output_tokens |
response_format |
text={"format": {...}} |
reasoning_effort="low" |
reasoning={"effort": "low"} |
Tool call in message.tool_calls |
function_call item in output |
role: "tool" message |
function_call_output item linked by call_id |
n=3 |
Not available; send separate requests |
| You manage history | previous_response_id or conversation |

A safe migration order looks like this:
- Swap simple calls first. Change the method, rename
messagestoinput, and readoutput_text. - Move system prompts. Put them in a first
developermessage so they stay cacheable. - Rewrite tool definitions. Flatten the
functionobject and switch tofunction_call_outputitems. - Update structured output. Move
response_formattotext.format, or useresponses.parse. - Decide on storage. Responses are stored by default. Set
store=Falseif you need no server-side copy.
Moving to the newest models too? Our GPT-6.2 API migration guide covers the model-specific changes.
Prices and a Worked Cost Example
The Responses API itself has no fee. You pay for model tokens and any built-in tool calls. These are standard rates per 1M tokens for requests up to 272K input tokens, from OpenAI’s pricing page.
| Model | Input | Cached input | Output |
|---|---|---|---|
gpt-6.2-astra |
$8.00 | $0.40 | $40.00 |
gpt-6.2-sol |
$2.00 | $0.10 | $10.00 |
gpt-6-luna |
$0.10 | $0.01 | $0.50 |
gpt-5.4-mini |
$0.75 | $0.075 | $4.50 |

Other costs to plan for:
- Long prompts: above 272K input tokens, input and cache rates double and output costs 1.5x.
- Cache writes: GPT-6.2 Sol lists $2.50 per 1M for a 30-minute cache write and $5.00 for a 12-hour write.
- Batch: 50% off standard rates. See our OpenAI Batch API tutorial.
- Background windows: 2-hour and 8-hour windows (public beta) cut token rates by 30% and 40% on eligible GPT-6.2 requests.
- Tools: web search $10 per 1K calls, file search $2.50 per 1K calls, code interpreter from $0.03 per 20-minute 1 GB session.
Worked example: a support bot on GPT-6.2 Sol
Say each request has 2,000 input tokens and 500 output tokens, and you handle 10,000 requests a day.
- Input: 20M tokens x $2 = $40.00
- Output: 5M tokens x $10 = $50.00
- Total: about $90 a day, or roughly $2,700 for a 30-day month.
If 1,500 of those input tokens are a fixed system prompt served from cache, the input bill drops to 15M x $0.10 + 5M x $2 = $11.50. The daily total falls to about $61.50, before small cache-write charges. Our prompt caching guide shows how to set this up.
Tip: the same job on gpt-6.2-astra costs four times as much. Start on Sol, and only move hard tasks to Astra.
Limits You Should Know
| Limit | Value |
|---|---|
| Context window (GPT-6.2 Astra and Sol) | 1,050,000 tokens |
| Max input tokens | 922,000 |
| Max output tokens | 128,000 |
| Knowledge cutoff | Astra: 18 May 2026; Sol: 1 Jun 2026 |
| Rate limit, Build tier | 5,000 RPM, 1M TPM |
| Rate limit, Launch tier | 10,000 RPM, 4M TPM |
| Rate limit, Grow tier | 15,000 RPM, 40M TPM |
| Stored response retention | 30 days (default; off with store=False) |
| Metadata | Up to 16 key-value pairs |
| Code interpreter idle timeout | 20 minutes |
| Generations per request | 1 (no n parameter) |
Rate limits are per model and depend on your account tier. Our LLM API rate limits guide explains how tiers work across providers.
Troubleshooting: Common Errors and Fixes
These are the errors from OpenAI’s error codes page, plus the Python exception class the SDK raises.
| Error | Python class | Fix |
|---|---|---|
| 401 “Incorrect API key provided” | AuthenticationError |
Check for typos or spaces, confirm the key’s project, or make a new key. |
| 401 “Invalid Authentication” | AuthenticationError |
Key revoked or from another org or project. Confirm the org ID or regenerate. |
| 403 “Country, region, or territory not supported” | PermissionDeniedError |
You are calling from an unsupported location. Check OpenAI’s supported countries list. |
| 429 “Rate limit reached for requests” | RateLimitError |
Wait for Retry-After, or use exponential backoff with jitter. |
429 credit_balance_exhausted or spend limit exceeded |
RateLimitError |
Add credit or raise the project or org limit. Retrying will not help. |
429 “Slow down” (slow_down) |
RateLimitError |
Your traffic rose too fast. Reduce, then ramp up slowly. |
| 400 bad request (wrong or unsupported parameter) | BadRequestError |
Read the message. Common causes: temperature on GPT-6.2, effort none, or both conversation and previous_response_id. |
| 503 “Model temporarily overloaded” | InternalServerError |
Follow Retry-After and retry. |
| Connection or timeout failure | APIConnectionError / APITimeoutError |
Check network, proxy and firewall, then retry. |
Problems that are not errors
- Empty
output_text: checkresponse.status. If it isincompletewith reasonmax_output_tokens, the model used the budget on reasoning. Raisemax_output_tokens; OpenAI suggests reserving 25,000 tokens when you start experimenting. - The model forgot the chat: you did not pass
previous_response_idorconversation, or the first call hadstore=False. - Tool loop errors about a missing call: every
function_call_outputneeds the exactcall_id, and the originalfunction_callitem must be in the input too. - Expired container: code interpreter containers die after 20 idle minutes. Start a new one.
import time
from openai import OpenAI, RateLimitError, APIConnectionError
client = OpenAI(max_retries=3) # the SDK already retries some errors
def ask(prompt):
for attempt in range(5):
try:
return client.responses.create(model="gpt-6.2-sol", input=prompt).output_text
except (RateLimitError, APIConnectionError) as err:
wait = 2 ** attempt
print(f"{type(err).__name__}, retrying in {wait}s")
time.sleep(wait)
raise RuntimeError("Gave up after 5 attempts")
print(ask("Say hi in French."))
For a longer list of fixes, see our OpenAI API errors guide.
Frequently Asked Questions
Is the Chat Completions API deprecated?
No. OpenAI says Chat Completions remains supported, but it recommends the Responses API for all new projects. GPT-6.2 tool calling only works in the Responses API.
What happened to the Assistants API?
The Assistants API shut down on 26 August 2026. OpenAI lists the Responses API and the Conversations API as its replacement.
Does previous_response_id save money?
Not directly. All earlier input tokens in the chain are still billed as input on each turn, but prompt caching can make repeated tokens much cheaper.
Can I stop OpenAI storing my responses?
Yes. Pass store=False on each request. You then need to manage conversation history yourself by resending the output items.
Which model should I start with?
OpenAI’s model page suggests GPT-6.2 Astra if you are unsure, but GPT-6.2 Sol costs a quarter as much and is built for everyday work and agents. Many apps start on Sol and send only the hardest tasks to Astra.
Why does my GPT-6.2 request fail with temperature set?
The GPT-6.2 guide says to omit temperature, top_p and top_logprobs in Responses requests. Remove them and use reasoning effort to tune behaviour instead.
Can I get several answers in one call like n=3?
No. The Responses API returns one generation per request, so send separate requests if you need multiple candidates.
Sources
- OpenAI: Migrate to the Responses API
- OpenAI: Conversation state
- OpenAI: Function calling
- OpenAI: Structured Outputs
- OpenAI: Streaming API responses
- OpenAI: Code Interpreter
- OpenAI: API pricing
- OpenAI: GPT-6.2 Sol model page
- OpenAI: Error codes
- OpenAI: Deprecations
- OpenAI API changelog
- PyPI: openai Python package




