OpenAI响应API openai-responses

OpenAI Responses API 是用于构建状态式人工智能代理应用的统一接口,支持推理状态保持、内置工具如代码解释器、文件搜索、网络搜索和图像生成,并集成MCP服务器。关键词:OpenAI响应API,状态式AI,代理应用,推理保持,内置工具,MCP集成。

AI智能体 0 次安装 0 次浏览 更新于 3/7/2026

name: openai-responses description: OpenAI 响应API 用于状态式代理应用,带有推理保持。用于MCP集成、内置工具、后台处理或从聊天完成迁移。

关键词:响应API,openai 响应,状态式 openai,openai mcp,代码解释器 openai,文件搜索 openai,网络搜索 openai,图像生成 openai,推理保持,代理工作流,对话状态,后台模式,聊天完成迁移,gpt-5,多态输出 license: MIT metadata: version: “2.0.0” last_verified: “2025-11-18” api_launch: “March 2025” sdk_version: “openai@5.19.1+” templates_included: 10 references_included: 8

OpenAI 响应API

状态: 生产就绪 | API 启动: 2025年3月 | SDK: openai@5.19.1+


快速开始 (5分钟)

Node.js

import OpenAI from 'openai';

const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const response = await openai.responses.create({
  model: 'gpt-5',
  input: 'What are the 5 Ds of dodgeball?',
});

console.log(response.output_text);

Cloudflare Workers

const response = await fetch('https://api.openai.com/v1/responses', {
  method: 'POST',
  headers: {
    'Authorization': `Bearer ${env.OPENAI_API_KEY}`,
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    model: 'gpt-5',
    input: 'Hello, world!',
  }),
});

const data = await response.json();
console.log(data.output_text);

加载 references/setup-guide.md 以获取包含状态式对话和内置工具的完整设置。


什么是响应API?

响应API (/v1/responses) 是OpenAI于2025年3月推出的用于代理应用的统一接口。关键创新: 在多个回合中保持推理状态(不像聊天完成那样丢弃),在TAUBench上提高多回合性能约5%。

为什么使用响应而非聊天完成? 自动状态管理、保持推理、服务器端工具、40-80%更好的缓存利用率,以及内置MCP支持。

加载 references/responses-vs-chat-completions.md 以获取完整比较和决策指南。


前3个关键规则

总是做 ✅

  1. 存储 conversation_id - 在回合之间保持状态(最关键)
  2. 使用环境变量 用于API密钥(永远不要硬编码)
  3. 处理多态输出 - 检查 output.type(消息、推理、函数调用)

永远不要做 ❌

  1. 永远不要忽略 conversation_id - 状态将丢失
  2. 永远不要假设单一输出类型 - 总是检查 output.type
  3. 永远不要混合聊天完成和响应 在同一对话中

加载 references/setup-guide.md 以获取完整规则和最佳实践。


前5个用例

用例1: 状态式对话

// 第一回合
const response1 = await openai.responses.create({
  model: 'gpt-5',
  input: '我最喜欢的颜色是蓝色。',
});

const conversationId = response1.conversation_id;

// 第二回合 - 模型记得
const response2 = await openai.responses.create({
  model: 'gpt-5',
  conversation_id: conversationId,
  input: '我最喜欢的颜色是什么?',
});
// 输出: "您最喜欢的颜色是蓝色。"

加载: references/stateful-conversations.md + templates/stateful-conversation.ts


用例2: 网络搜索代理

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '搜索网络获取最新AI新闻。',
  tools: {
    web_search: { enabled: true },
  },
});

加载: references/built-in-tools-guide.md + templates/web-search.ts


用例3: 代码解释器

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '计算从1到100的平方和。',
  tools: {
    code_interpreter: { enabled: true },
  },
});

加载: references/built-in-tools-guide.md + templates/code-interpreter.ts


用例4: 文件搜索 (RAG)

// 上传文件
const file = await openai.files.create({
  file: fs.createReadStream('document.pdf'),
  purpose: 'user_data',
});

// 搜索文件
const response = await openai.responses.create({
  model: 'gpt-5',
  input: '总结上传文档的关键点。',
  tools: {
    file_search: {
      enabled: true,
      file_ids: [file.id],
    },
  },
});

加载: references/built-in-tools-guide.md + templates/file-search.ts


用例5: MCP服务器集成

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '获取旧金山的天气。',
  tools: {
    mcp_servers: [
      {
        url: 'https://weather-mcp.example.com',
        tool_choice: 'auto',
      },
    ],
  },
});

加载: references/mcp-integration-guide.md + templates/mcp-integration.ts


内置工具

所有工具在服务器端运行:代码解释器(Python执行)、文件搜索(RAG)、网络搜索(实时)、图像生成(DALL-E)。

明确启用:

tools: {
  code_interpreter: { enabled: true },
  file_search: { enabled: true, file_ids: ['file-123'] },
  web_search: { enabled: true },
  image_generation: { enabled: true },
}

加载 references/built-in-tools-guide.md 以获取完整指南、示例和配置选项。


状态式对话

使用对话ID的自动状态管理消除了手动消息跟踪,保持推理,并将缓存利用率提高40-80%。

// 创建对话
const response1 = await openai.responses.create({
  model: 'gpt-5',
  input: '记住:我的名字是爱丽丝。',
});

// 继续对话
const response2 = await openai.responses.create({
  model: 'gpt-5',
  conversation_id: response1.conversation_id,
  input: '我的名字是什么?',
});

加载 references/stateful-conversations.md 以获取持久化模式(Node.js/Redis/KV)和生命周期管理。


从聊天完成迁移

快速更改:messagesinputsystem 角色 → developerchoices[0].message.contentoutput_text/v1/chat/completions/v1/responses

之前(聊天完成):

const messages = [{ role: 'user', content: '你好' }];
const response = await openai.chat.completions.create({
  model: 'gpt-4o',
  messages: messages,
});
messages.push(response.choices[0].message); // 手动历史

之后(响应API):

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '你好',
});

const response2 = await openai.responses.create({
  model: 'gpt-5',
  conversation_id: response.conversation_id, // 自动状态
  input: '后续问题',
});

加载 references/migration-guide.md 以获取完整迁移清单和工具迁移模式。


多态输出

响应可以返回多种输出类型(消息、推理、函数调用、图像)。处理每种类型或使用 output_text 便利属性。

for (const output of response.output) {
  if (output.type === 'message') {
    console.log('消息:', output.content);
  } else if (output.type === 'reasoning') {
    console.log('推理:', output.summary);
  } else if (output.type === 'function_call') {
    console.log('函数:', output.name, output.arguments);
  }
}

// 或使用便利属性
console.log(response.output_text);

加载 references/reasoning-preservation.md 以获取推理输出详细信息和调试模式。


后台模式

对于长时间运行任务(>60秒),使用 background: true 异步运行并轮询完成。

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '分析这份50页文档。',
  background: true,
});

// 轮询完成
const completed = await openai.responses.retrieve(response.id);

加载 templates/background-mode.ts 以获取完整轮询模式和指数退避。


前3个错误和解决方案

错误1: 会话状态未持久化

症状: 模型不记得先前回合。

原因: 未使用对话ID或每次创建新对话。

解决方案:

// ✅ 好: 重用对话ID
const conv = await openai.conversations.create();
const response1 = await openai.responses.create({
  model: 'gpt-5',
  conversation: conv.id, // 相同ID
  input: '问题1',
});
const response2 = await openai.responses.create({
  model: 'gpt-5',
  conversation: conv.id, // 相同ID - 记得先前
  input: '问题2',
});

错误2: MCP服务器连接失败

原因: 无效服务器URL、缺失/过期授权令牌。

解决方案:

const response = await openai.responses.create({
  model: 'gpt-5',
  input: '测试MCP',
  tools: [
    {
      type: 'mcp',
      server_url: 'https://mcp.stripe.com', // ✅ 完整HTTPS URL
      authorization: process.env.STRIPE_OAUTH_TOKEN, // ✅ 有效令牌
    },
  ],
});

预防: 使用环境变量存储秘密,实现令牌刷新逻辑,添加指数退避重试。


错误3: 代码解释器超时

原因: 代码运行超过30秒(标准模式限制)。

解决方案:

// ✅ 好: 使用后台模式处理长任务
const response = await openai.responses.create({
  model: 'gpt-5',
  input: '处理这个大数据集',
  background: true, // ✅ 最多10分钟
  tools: [{ type: 'code_interpreter' }],
});

// 轮询结果
let result = await openai.responses.retrieve(response.id);
while (result.status === 'in_progress') {
  await new Promise(r => setTimeout(r, 5000));
  result = await openai.responses.retrieve(response.id);
}

加载 references/top-errors.md 以获取所有8个错误、详细解决方案和预防策略。


何时加载参考

加载 references/setup-guide.md 当:

  • 首次使用响应API,需要完整Node.js或Cloudflare Workers设置
  • 想要生产部署清单和环境特定最佳实践
  • 故障排除设置问题或实现流式/后台模式

加载 references/responses-vs-chat-completions.md 当:

  • 决定使用响应还是聊天完成API
  • 理解性能基准(TAUBench结果、缓存利用率)
  • 评估迁移工作或比较成本结构

加载 references/migration-guide.md 当:

  • 从聊天完成API迁移,带有逐步清单
  • 需要代码比较示例(之前/之后模式)
  • 将工具从自定义函数迁移到内置/MCP

加载 references/built-in-tools-guide.md 当:

  • 使用代码解释器、文件搜索、网络搜索或图像生成
  • 需要工具配置选项、组合多个工具或故障排除

加载 references/mcp-integration-guide.md 当:

  • 集成外部MCP服务器或构建自定义MCP工具
  • 需要MCP配置示例或认证模式

加载 references/stateful-conversations.md 当:

  • 实现对话持久化与KV/Redis/数据库
  • 需要对话生命周期管理或元数据跟踪模式

加载 references/reasoning-preservation.md 当:

  • 想要访问模型推理以进行调试或透明度
  • 构建可审计AI系统或需要推理输出示例

加载 references/top-errors.md 当:

  • 遇到API错误(覆盖8个常见错误和解决方案)
  • 需要错误代码参考、预防策略或错误处理模式

生产清单

部署前:

  • [ ] API密钥安全存储(环境变量或秘密)
  • [ ] 错误处理实现(401, 429, 400, 500)
  • [ ] 速率限制处理(指数退避)
  • [ ] 对话ID持久化(数据库/KV)
  • [ ] 流式启用用于长响应
  • [ ] 工具明确启用
  • [ ] 多态输出处理

加载 references/setup-guide.md 以获取完整生产清单和平台特定考虑。


相关技能

  • openai-api - 经典聊天完成API
  • openai-agents - OpenAI代理SDK(响应的包装器)
  • claude-api - Claude API用于比较
  • ai-sdk-core - Vercel AI SDK(支持响应)

官方文档


有问题?问题?

  1. 检查 references/top-errors.md 以获取错误解决方案
  2. 回顾 references/setup-guide.md 以获取完整设置
  3. 参见 references/migration-guide.md 以获取聊天完成迁移
  4. templates/ 加载模板以获取工作示例