OpenAI Responses API 实战与 Assistants 迁移指南
迁移时先找所有依赖 assistant.instructions 的调用点。把上一轮 response.id 接上以后,系统指令不会自动继承,必须由应用在下一轮重新传入。
2026 年 8 月 26 日,OpenAI 正式关停了旧版 Assistants API,将多轮推理与会话状态统一收口到 Responses API(POST /v1/responses)与 Conversations API。本文基于截至 2026 年 11 月的 OpenAI Responses 迁移指南 与 Conversation State 文档,梳理原语映射、状态与 ZDR 边界、新模型工具传输前提,以及对齐原始 HTTP 协议的 TypeScript 错误分类与退避示例。
核心原语映射:普通调用告别 Run 轮询
旧版 Assistants API 要求依次创建 Assistant、向 Thread 追加消息、启动 Run 再循环轮询 run.status。迁移到 Responses + Conversations 体系后,四类核心资源的对应关系如下:
| 旧版 Assistants API | 新版 Responses / Conversations 体系 | 迁移后的工程变化 |
|---|---|---|
| Assistants | Prompts(控制台模板)或代码内联配置 | 指令、模型与工具配置可随应用代码版本化管理 |
| Threads | Conversations API | 统一承载消息、工具调用、结构化输出等异构条目 |
| Runs | Responses(POST /v1/responses) |
普通同步或流式调用不再轮询旧 Run;应用自定义工具的续接循环仍由调用方处理 |
| Run Steps | Items | 输入与输出统一抽象为类型化 Item 列表,便于审计与重放 |
如果还需要 OpenAI 托管的 Codex 执行 Harness 与可选沙箱环境,再评估处于公测(public beta)阶段的 OpenAI Agents API;只需推理与会话状态管理时,留在 Responses API 更轻量。
状态管理与 ZDR 边界:previous_response_id vs Conversations
脱离旧 Thread 后,官方提供两种服务端辅助状态模式,以及一种完全自管模式:
落地方案前必须核对三条硬边界:
previous_response_id与conversation互斥:同一次请求只能二选一。使用previous_response_id时,上一轮顶层instructions不会自动继承,必须在每一轮显式传入或通过 Prompt 模板指定。- Conversations 持久保存至显式删除:适合多设备共享或长周期上下文,但需要业务侧做好生命周期清理。
- 不要把
store: false简单等同于 ZDR:previous_response_id与 Conversations 均不支持零数据保留(ZDR)。如果希望不落服务端状态,应传store: false并由应用重放所需 Items;而 ZDR 属于组织或项目级数据控制开关,具体端点与功能的适用性必须逐项核对 OpenAI Data Controls。
新模型工具与传输前提
2026 年 9 月起陆续发布的 GPT-6 系列(gpt-6-astra、gpt-6-sol、gpt-6-luna)在 Responses API 下支持内置 Web Search、远程 MCP 与 Computer Use;但具体高级能力存在明确传输前提:
- 异步工具调用(
async: true):适用于由应用侧执行的 function / custom tools(详见 Async Tool Calling)。 - 运行中纠偏(Steering):需通过 Responses WebSocket 连接承载,而非普通单次 HTTP POST(详见 Steering Guide)。
- 提示词缓存与短期密钥:保持顶层
instructions前缀稳定有助于提升缓存命中率(见 GPT-5.5 最佳实践);项目级 API Key 支持配置到期时间,便于网关层定期轮换。
裸 HTTP 响应解析与已知状态码最小退避示例
直接用原生 fetch 调用 Create Response 接口 时,有两处极易写错:
- 原始 HTTP 回包没有顶层
output_text:response.output_text是官方 SDK 的聚合便利属性;裸 HTTP 返回的是outputItem 数组,需按type区分message(内含output_text或refusal)与function_call,同时检查status。 - 结构化区分硬额度错误与瞬时限流:根据 OpenAI Error Codes 与 Spend Limits,组织支出上限(
organization_spend_limit_exceeded)、项目支出上限(project_spend_limit_exceeded)、组织用量上限(organization_usage_limit_exceeded)与额度耗尽(insufficient_quota)属于不可重试错误,不能靠全文子串匹配,必须安全解析 JSON 中的error.code与error.type后直接终止;仅对瞬时429(如slow_down)和503(server_is_overloaded)按Retry-After(支持秒数与 HTTP 日期)加抖动退避。
下面给出一个覆盖上述协议细节的最小退避示例(注意:对于网络中断或超时后服务端是否已执行不明的 POST 请求,是否允许重放应由业务记录请求标识后单独决策):
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");
}如果项目已经引入官方 OpenAI TypeScript SDK,可直接使用 SDK 提供的 response.output_text 便利属性,同时保留对非 completed 状态、refusal 与硬额度错误码的显式分支处理。