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:
Switch the endpoint. Requests move from
/v1/chat/completionsto/v1/responses.Switch the read path. Results come out of a typed
outputarray instead ofchoices[0].message.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 |
|---|---|---|
|
|
|
| Top-level |
|
|
| Leaving |
|
| The word output moves into the field name |
| None | Responses returns one generation per request; there is no |
|
| The definition shape is unchanged; where the call and its result appear is not |
|
| Same flag, completely different event shape |
|
| Responses stores responses by default; pass |
| Same names | Semantics unchanged |
The smallest possible change looks like this:
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.contentclient.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:
{
"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.
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:
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:
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
**previous_response_id**— the server keeps the context, and each subsequent turn passes the previous response ID. Remember thatinstructionsis not inherited, so a stable instruction prefix has to be resent every turn.Conversations API — the conversation becomes a durable object, which suits long-running sessions.
Replay Items yourself — append the previous turn's
outputto the nextinput, 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 stayshttps://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 carrycall_id; structured output moved totext.format.Storage decided explicitly —
store: falsewhere 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.
Related reading
Claude Sonnet 4.6 API Guide — the Anthropic-side model choice guide.
Video Generation API Guide — Veo 3.1 through a single OpenAI-compatible endpoint.
Advanced Claude Code Techniques — sub-agents, MCP, and cost optimization.
All CodeGateway posts — browse the full library.
