← Back to Blog

OpenAI Responses API Migration Tutorial for Python

(Unofficial)

This guide is independently community-maintained. It is not affiliated with, endorsed by, or sponsored by the vendor of the third-party tool it covers. All third-party trademarks are the property of their respective owners.

November 27, 2026
OpenAI Responses API Migration Tutorial for Python

OpenAI Responses API Migration Tutorial for Python

Migrating from Chat Completions to the Responses API is smaller than it sounds, and the official guidance makes it smaller still. OpenAI's migration guide (as-of 2026-10-29, Migrate to the Responses API) states that the Responses API is the newer API primitive, an evolution of Chat Completions, and that while Chat Completions remains supported, Responses is recommended for all new projects. So this is not a deadline migration — nothing breaks if you stay where you are. What you are deciding is whether to pick up Responses' features early: messages become typed Items so reasoning and tool calls each stand on their own, built-in tools such as web search, file search, code interpreter, image generation and remote MCP become available, and conversation state can be carried by previous_response_id or the Conversations API.

The mechanics are friendly. The gateway serves both /v1/chat/completions and /v1/responses behind the same OpenAI-compatible base URL, https://api.codegateway.dev/v1, and the key does not change. What changes is the endpoint, the request body, and the way you read the response. This guide is the Python side of that move: field mapping, the new response shape, tool calls with call_id, structured output, streaming events, state handling, and the errors worth preparing for.

The three things the migration actually changes

The official guide (as-of 2026-10-29, Migrate to the Responses API) frames the migration as three related changes, and it is worth keeping that framing because it makes the work easy to stage:

  1. Switch the endpoint. Requests move from /v1/chat/completions to /v1/responses.

  2. Switch the read path. Results come out of a typed output array instead of choices[0].message.

  3. Choose how state travels between turns. Either previous_response_id, the Conversations API, or replaying the previous Items yourself.

Everything else — authentication, retries, timeouts, logging — stays where it is.

Request body field mapping

Chat Completions

Responses

Notes

messages

input

input accepts a string or an array of Items; prior messages can be passed straight in

role=system / role=developer messages

Top-level instructions

instructions is not inherited through previous_response_id, so resend it each turn

response_format

text.format

Leaving response_format in a Responses request is a documented mistake

max_tokens / max_completion_tokens

max_output_tokens

The word output moves into the field name

n

None

Responses returns one generation per request; there is no n

tools (function type)

tools (function type)

The definition shape is unchanged; where the call and its result appear is not

stream=True

stream=True

Same flag, completely different event shape

store

store

Responses stores responses by default; pass store: false to opt out

temperature / top_p

Same names

Semantics unchanged

The smallest possible change looks like this:

python
import os
from openai import OpenAI

client = OpenAI(
base_url="https://api.codegateway.dev/v1",
api_key=os.environ["CG_KEY"],
)

# Before
completion = client.chat.completions.create(
model="gpt-6-astra",
messages=[{"role": "user", "content": "Explain in one sentence what an API gateway does."}],
)

# After
response = client.responses.create(
model="gpt-6-astra",
input="Explain in one sentence what an API gateway does.",
)
print(response.output_text) # replaces completion.choices[0].message.content

client.responses needs a reasonably recent version of the OpenAI Python SDK — older releases do not expose it, so upgrade to the latest. The model identifier to use is whatever the model catalog lists for your account; gpt-6-astra is a directory entry there.

What the response looks like now

The same question comes back in two different shapes. Chat Completions returns a chat.completion object with the text under choices[0].message.content. Responses returns a response object whose output is an array of Items, each with its own type:

json
{
"id": "resp_xxx",
"status": "completed",
"output": [
{ "type": "reasoning", "summary": [] },
{
"type": "message",
"role": "assistant",
"content": [{ "type": "output_text", "text": "An API gateway is…" }]
}
],
"usage": { "input_tokens": 42, "output_tokens": 88, "total_tokens": 130 }
}

Three things to internalise when you write the parsing code. output is an array, not a single object. The type on each element tells you whether it holds text, reasoning, or a tool call. And the text itself lives inside content. If you would rather not walk the array, the SDK exposes response.output_text as a convenience property that returns the concatenated text for you.

Tool calls: function_call and call_id

In Chat Completions the model returns an assistant message carrying tool_calls, and you reply with a tool message carrying tool_call_id. Responses splits that into two Item types. The model returns a function_call Item with a call_id and an arguments payload; you send back a function_call_output Item carrying the same call_id.

python
resp = client.responses.create(
model="gpt-6-astra",
input="What is the weather in Beijing?",
tools=[{
"type": "function",
"name": "get_weather",
"description": "Look up the weather for a city",
"parameters": {
"type": "object",
"properties": {"city": {"type": "string"}},
"required": ["city"],
},
}],
)

for item in resp.output:
if item.type == "function_call":
result = my_weather_tool(city=item.arguments["city"])
resp = client.responses.create(
model="gpt-6-astra",
previous_response_id=resp.id,
input=[{
"type": "function_call_output",
"call_id": item.call_id,
"output": result,
}],
)

Two traps here. The official guide (as-of 2026-10-29, Migrate to the Responses API) lists "returning a function result without the matching call_id" as a common mistake, so carry the identifier through verbatim. And when you continue with previous_response_id, the server already holds the function_call Item — you only send the function_call_output.

There is one more reason the official guidance pushes new work towards Responses. Chat Completions does not support tool calling when reasoning_effort is anything other than none, and the guidance goes further for models whose reasoning cannot be turned off at all — for those models, tool calling requires the Responses API. If your roadmap includes a newer reasoning model and tool calls, moving the endpoint is the part you cannot skip.

Structured output: response_format becomes text.format

This is the field that tends to get half-migrated. response_format does not belong in a Responses request; the structured-output configuration lives under text.format:

python
schema = {
"type": "object",
"properties": {
"city": {"type": "string"},
"high": {"type": "number"},
},
"required": ["city", "high"],
}

resp = client.responses.create(
model="gpt-6-astra",
input="What is the highest temperature in Beijing today?",
text={"format": {"type": "json_schema", "name": "weather", "schema": schema}},
)
print(resp.output_text)

Because text.format is nested rather than top-level, a partially migrated codebase tends to fail in a way that is easy to misread: the field is simply absent, and the model replies with prose instead of JSON. Check the nesting before you assume the schema is wrong.

Built-in tools instead of hand-rolled orchestration

Chat Completions has no built-in tool layer. Search, retrieval and code execution all have to be orchestrated by your own code. Responses ships hosted tools — web search, file search, code interpreter, image generation and remote MCP — and the model can call them within a single request.

The official guidance is to swap hand-built orchestration for the built-in tool whenever the built-in tool covers the case. Two practical notes on running this through a gateway: the availability of each built-in tool follows OpenAI's own documentation, and whether the gateway admits a given request depends on current support, so validate with a small request before you put it in front of real traffic. Tool usage is billed like any other consumption and shows up on the Dashboard usage page.

Streaming: from delta chunks to semantic events

Streaming is where the code changes most, because the frame format changes completely.

Chat Completions streams chat.completion.chunk objects on data: lines, with the text fragment in choices[0].delta, and ends with data: [DONE]. Responses streams semantic events: each SSE message carries the event type on the event: line and JSON on the data: line, with the type repeated inside the payload alongside a sequence_number. For text you care about response.created, response.output_text.delta and response.completed. Function-call arguments arrive on response.function_call_arguments.delta and .done. The stream can end on response.completed, or on response.failed, response.incomplete, or error.

The client has to dispatch on the event type rather than keep reading a delta field:

python
stream = client.responses.create(
model="gpt-6-astra",
input="Describe what an API gateway does in three sentences.",
stream=True,
)

for event in stream:
if event.type == "response.output_text.delta":
print(event.delta, end="", flush=True)
elif event.type in ("response.completed", "response.failed", "response.incomplete"):
break
print()

Keeping your old Chat Completions streaming parser is a documented mistake, and it fails quietly: you will read an empty response rather than get an exception, because the delta field simply never appears in the new frame shape.

Reading the result

The result of a Chat Completions call lives at response.choices[0].message.content. The result of a Responses call is an output array whose elements are Items — messages, reasoning, function calls — and the SDK's response.output_text property hands you the assembled text.

The trap is assuming output[0] is always text. When a response includes reasoning or a tool call, the array mixes item types, so dispatch on item.type instead of indexing blindly. Usage and billing follow the Dashboard usage page; the details are in the billing guide.

Three ways to carry conversation state

  1. **previous_response_id** — the server keeps the context, and each subsequent turn passes the previous response ID. Remember that instructions is not inherited, so a stable instruction prefix has to be resent every turn.

  2. Conversations API — the conversation becomes a durable object, which suits long-running sessions.

  3. Replay Items yourself — append the previous turn's output to the next input, and you own the context window entirely.

One storage detail to plan for: Responses stores each response by default, and if that is not acceptable, pass store: false explicitly. Chat Completions also stores by default for new accounts.

If you want a sense of how the platforms differ in practice, the Claude Code connection timeout troubleshooting guide and the Codex CLI setup guide both walk through client configuration on the same OpenAI-compatible base URL this migration keeps you on.

Errors to prepare for

400 from the validation layer. If the model is not one the gateway admits on this endpoint, the request is rejected at validation with a message pointing you back to /v1/chat/completions. This is a 400, and it is a routing answer rather than a transient fault.

503 service unavailable. Do not read this as "this model has no Responses route". The gateway rewrites upstream rate limiting into a 503 on this endpoint, so treat 503 as rate limiting first: back off and retry, then confirm the model is an OpenAI-family entry in the catalog before you migrate that flow to /v1/responses at all. The two gateway DeepSeek models are Workers AI native models and are not admitted on this endpoint, so migrating them is a 400 at validation rather than a 503.

400 for a missing **call_id**, or text that never appears. The first is the tool-result identifier; the second is usually a leftover Chat Completions streaming parser.

Empty or truncated output. Check max_output_tokens and confirm whether the request was billed on the usage page before retrying, so an automatic retry does not charge twice.

Rollout checklist

  • Endpoint moved to /v1/responses; base URL stays https://api.codegateway.dev/v1; the key does not change.

  • 503 treated as upstream rate limiting — back off and retry, and confirm the model is an OpenAI-family catalog entry before moving a flow onto this endpoint.

  • Model identifier taken from the model catalog; current rate from the pricing page and your Dashboard invoice.

  • Streaming parsing switched to dispatch on event.type; function results carry call_id; structured output moved to text.format.

  • Storage decided explicitly — store: false where responses must not be retained.

  • If you are not ready to move everything, put an environment flag in front of the client and run the same test cases against both endpoints, comparing outputs before you shift traffic.

  • Smart Routing is off by default and enabled per key when you want cross-vendor fallback.

Keep one key across the migration

If you have no OpenAI key, or you would rather not register with each vendor and attach a separate foreign card to each account, create one CodeGateway key: register, issue an sk-cg- key on the Dashboard API keys page, then top up on the Dashboard billing page. The same key works across models and across both endpoints, so migrating to the Responses API does not mean rotating credentials, and usage and cost stay on a single dashboard. Current rates are on the pricing page.

Author:CodeGateway Team

Solve API Key & Billing limits with CodeGateway

Lacking an official API key or facing overseas card payment issues? Create an sk-cg- key instantly. One key for Claude, GPT, Gemini, and DeepSeek: Claude and Gemini text models use the Anthropic Messages protocol (/v1/messages) — the OpenAI-compatible text endpoints do not accept them. Built-in smart routing and free trial credits included.

Sign up free