Contents

OpenAI Responses API and Assistants Migration Guide

Start the migration by finding every call site that relies on assistant.instructions. Chaining previous_response_id carries conversation context forward, while the application must resend top-level instructions on every turn.

On August 26, 2026, OpenAI shut down the legacy Assistants API, consolidating multi-turn inference and conversation state on the Responses API (POST /v1/responses) and Conversations API (see Migration Guide and Conversation State Guide). A clean cutover comes down to mapping the old primitives, respecting ZDR and state boundaries, and parsing raw HTTP output Items and spend-limit errors accurately.

Resource Mapping: Leaving Run Polling Behind for Standard Calls

The legacy Assistants API required creating an Assistant, appending messages to a Thread, starting a Run, and polling run.status. The Responses + Conversations stack simplifies that model:

Legacy Assistants API Responses / Conversations Stack Practical Impact
Assistants Dashboard Prompts or inline code config Instructions, model IDs, and tools live in version control alongside application code
Threads Conversations API Tracks heterogeneous items (messages, tool calls, structured outputs)
Runs Responses (POST /v1/responses) Standard sync/stream calls no longer poll legacy Runs; custom application tool loops remain caller-managed
Run Steps Items Typed input and output items simplify auditing and replay

When you also need OpenAI’s managed Codex harness and optional execution sandboxes, evaluate the public-beta OpenAI Agents API; when your own backend owns execution, stay on Responses API.

State Modes and ZDR Boundaries

The Responses API supports two server-assisted state patterns plus a caller-managed mode:

flowchart LR Req["Multi-Turn Request"] --> Mode{"State Mode (Mutually Exclusive)"} Mode -->|"Turn Chaining / Dynamic Instructions"| Prev["previous_response_id Chaining"] Mode -->|"Long-Running / Multi-Device History"| Conv["Conversations API (conversation ID)"] Mode -->|"Caller-Managed History"| Self["store: false + App Replays Required Items"] Prev --> Resp["POST /v1/responses"] Conv --> Resp Self --> Resp Resp --> Out["Returns response.id & output Items"]

Verify three hard constraints before choosing a mode:

  1. previous_response_id and conversation are mutually exclusive: Pass one or the other, never both. With previous_response_id, top-level instructions do not inherit from the prior turn and must be supplied again (or referenced via a Prompt template).
  2. Conversations persist until deleted: Ideal for multi-device sessions, provided your application enforces retention cleanup.
  3. store: false is not by itself ZDR: Neither previous_response_id nor Conversations supports Zero Data Retention (ZDR). To avoid server-side state, pass store: false and replay required Items from your own database. ZDR is an organization/project-level data control whose eligibility must be verified per endpoint and feature in OpenAI Data Controls.

Newer Model Capabilities and Transport Prerequisites

The September 2026 GPT-6 models (gpt-6-astra, gpt-6-sol, gpt-6-luna) support built-in Web Search, remote MCP, and Computer Use on the Responses API, with specific transport prerequisites for advanced flows:

  • Async tool calling (async: true): Applies to application-executed function and custom tools (see Async Tool Calling).
  • Mid-turn steering: Runs over a Responses WebSocket session rather than a single HTTP POST (see Steering Guide).
  • Prompt caching and expiring keys: Keeping top-level instructions prefixes stable improves cache hits (see GPT-5.5 Best Practices), and project API keys support configurable expiration for automated gateway rotation.

Raw HTTP Parsing and Minimal Backoff for Known Status Codes

Two mistakes show up frequently when calling Create Response with raw fetch:

  1. Raw HTTP responses do not expose a top-level output_text field: response.output_text is an SDK convenience helper. Raw JSON returns an output Item array where message items hold output_text or refusal content parts alongside function_call items and a top-level status.
  2. Classify hard spend and quota errors structurally: Per OpenAI Error Codes and Spend Limits, organization_spend_limit_exceeded, project_spend_limit_exceeded, organization_usage_limit_exceeded, and insufficient_quota must fail fast—never rely on substring checks. Parse error.code and error.type safely, and back off with jitter (honoring numeric or HTTP-date Retry-After) only on transient 429 (slow_down) and 503 (server_is_overloaded) responses.

The minimal example below demonstrates HTTP status backoff and raw Item decoding (for ambiguous network drops or timeouts on POST, log request identifiers and define an explicit application-level replay policy):

interface ResponsesRequest {
  model: string;
  instructions: string;
  input: string | Array<Record<string, unknown>>;
  previous_response_id?: string;
  store?: boolean;
}

interface RawOutputContent {
  type: string;
  text?: string;
  refusal?: string;
}

interface RawOutputItem {
  type: string;
  content?: RawOutputContent[];
  name?: string;
  call_id?: string;
}

interface RawResponsePayload {
  id?: string;
  status?: string;
  output?: RawOutputItem[];
}

export interface ParsedResponse {
  id: string;
  status: string;
  texts: string[];
  refusals: string[];
  toolCalls: Array<{ name: string; callId: string }>;
}

const RESPONSES_URL = "https://api.openai.com/v1/responses";
const RETRYABLE_STATUS = new Set([429, 503]);
const NON_RETRYABLE_ERROR_CODES = new Set([
  "organization_spend_limit_exceeded",
  "project_spend_limit_exceeded",
  "organization_usage_limit_exceeded",
  "insufficient_quota",
]);

function parseRetryAfterMs(headerVal: string | null): number | null {
  if (!headerVal) return null;
  const seconds = Number(headerVal);
  if (Number.isFinite(seconds) && seconds > 0) {
    return seconds * 1000;
  }
  const dateMs = Date.parse(headerVal);
  if (!Number.isNaN(dateMs)) {
    return Math.max(0, dateMs - Date.now());
  }
  return null;
}

function isNonRetryableQuotaError(bodyText: string): boolean {
  try {
    const parsed = JSON.parse(bodyText) as {
      error?: { code?: unknown; type?: unknown };
    };
    const code = typeof parsed.error?.code === "string" ? parsed.error.code : "";
    const type = typeof parsed.error?.type === "string" ? parsed.error.type : "";
    return NON_RETRYABLE_ERROR_CODES.has(code) || NON_RETRYABLE_ERROR_CODES.has(type);
  } catch {
    return false;
  }
}

export function parseRawResponse(raw: RawResponsePayload): ParsedResponse {
  if (!raw.id || !raw.status || !Array.isArray(raw.output)) {
    throw new Error("Responses API protocol error: missing id, status, or output array");
  }

  const texts: string[] = [];
  const refusals: string[] = [];
  const toolCalls: Array<{ name: string; callId: string }> = [];

  for (const item of raw.output) {
    if (item.type === "message" && Array.isArray(item.content)) {
      for (const part of item.content) {
        if (part.type === "output_text" && typeof part.text === "string") {
          texts.push(part.text);
        } else if (part.type === "refusal" && typeof part.refusal === "string") {
          refusals.push(part.refusal);
        }
      }
    } else if (
      item.type === "function_call" &&
      typeof item.name === "string" &&
      typeof item.call_id === "string"
    ) {
      toolCalls.push({ name: item.name, callId: item.call_id });
    }
  }

  return { id: raw.id, status: raw.status, texts, refusals, toolCalls };
}

export async function callResponsesWithBackoff(
  req: ResponsesRequest,
  opts: { maxAttempts?: number; requestTimeoutMs?: number; totalDeadlineMs?: number } = {},
): Promise<ParsedResponse> {
  const apiKey = process.env.OPENAI_API_KEY;
  if (!apiKey) throw new Error("Missing OPENAI_API_KEY");

  const maxAttempts = opts.maxAttempts ?? 3;
  if (!Number.isInteger(maxAttempts) || maxAttempts < 1) {
    throw new RangeError(`maxAttempts must be a positive integer, got ${maxAttempts}`);
  }

  const requestTimeoutMs = opts.requestTimeoutMs ?? 30_000;
  const deadline = Date.now() + (opts.totalDeadlineMs ?? 60_000);

  for (let attempt = 0; attempt < maxAttempts; attempt++) {
    const remainingMs = deadline - Date.now();
    if (remainingMs <= 0) {
      throw new Error("Responses API total retry deadline exceeded");
    }

    const res = await fetch(RESPONSES_URL, {
      method: "POST",
      headers: {
        Authorization: `Bearer ${apiKey}`,
        "Content-Type": "application/json",
      },
      body: JSON.stringify(req),
      signal: AbortSignal.timeout(Math.min(requestTimeoutMs, remainingMs)),
    });

    const bodyText = await res.text();
    if (res.ok) {
      const raw = JSON.parse(bodyText) as RawResponsePayload;
      return parseRawResponse(raw);
    }

    const boundedSnippet = bodyText.slice(0, 240);
    if (
      !RETRYABLE_STATUS.has(res.status) ||
      isNonRetryableQuotaError(bodyText) ||
      attempt === maxAttempts - 1
    ) {
      throw new Error(`Responses API failed (${res.status}): ${boundedSnippet}`);
    }

    const retryAfterMs = parseRetryAfterMs(res.headers.get("retry-after"));
    const jitterMs = Math.floor(Math.random() * 250);
    const delayMs = retryAfterMs ?? 500 * 2 ** attempt + jitterMs;
    if (Date.now() + delayMs >= deadline) {
      throw new Error(`Responses API retry skipped due to deadline (${res.status})`);
    }
    await new Promise((resolve) => setTimeout(resolve, delayMs));
  }

  throw new Error("Unexpected retry termination");
}

If you use the official OpenAI TypeScript SDK, you can read response.output_text directly while keeping explicit handling for non-completed statuses, refusal parts, and non-retryable spend/quota error codes.

References