OpenAI Responses API 实战完全指南:下一代 AI 应用接口架构与迁移策略

深度解析 OpenAI Responses API 的架构设计、内置工具(Web Search、File Search、Computer Use)与 Chat Completions 的核心差异,含完整代码示例、性能对比与生产级迁移方案。

开发者效率 2026-06-10 18 分钟

2025 年 3 月,OpenAI 发布了 Responses API,这个被官方称为「Chat Completions API 的下一代继任者」的接口在发布一年后已经被超过 60% 的 OpenAI 企业客户采用。它不再是简单的「发消息、收回复」模式,而是将工具调用(Tool Use)、多轮对话状态管理、内置搜索能力整合到一个统一的 API 中。如果你还在用 Chat Completions API 拼接 function calling 逻辑,那么是时候了解 Responses API 如何将你的代码量减少 50% 以上了。

🔍 一、Responses API 架构解析:为什么 Chat Completions 不够用了

1.1 Chat Completions 的设计局限

Chat Completions API 自 2023 年发布以来一直是 OpenAI 的核心接口,但在构建复杂 AI 应用时,它的设计暴露了几个关键问题:

❌ Chat Completions 的痛点:

  • ⚠️ 工具调用需要开发者自己管理 tool_choice、parallel_tool_calls 等复杂参数
  • ⚠️ 多轮对话的上下文(messages 数组)需要客户端自行维护和拼接
  • ⚠️ 内置能力(搜索、文件检索)需要通过外部服务实现
  • ⚠️ Agent 场景需要多轮 API 调用循环,代码复杂度高
// ❌ Chat Completions 的工具调用:需要手动管理多轮循环
// 传统方式:开发者需要自己处理 tool_call → 执行 → 再调用 的完整循环
async function chatWithTools(userMessage) {
  const messages = [{ role: 'user', content: userMessage }];
  
  while (true) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages,
      tools: myTools,
      tool_choice: 'auto'
    });
    
    const choice = response.choices[0];
    
    // 需要手动检查是否有 tool_call
    if (choice.finish_reason === 'tool_calls') {
      messages.push(choice.message);
      
      // 需要手动执行每个 tool_call
      for (const toolCall of choice.message.tool_calls) {
        const result = await executeTool(toolCall);
        messages.push({
          role: 'tool',
          tool_call_id: toolCall.id,
          content: JSON.stringify(result)
        });
      }
      // 继续循环,再次调用 API
      continue;
    }
    
    return choice.message.content;
  }
}

1.2 Responses API 的架构革新

Responses API 从根本上重新设计了交互模型。它的核心理念是:API 本身就是一个有状态的 Agent 运行时

✅ Responses API 的核心改进:

  • ✅ 内置 Web Search、File Search、Computer Use 等工具,无需外部集成
  • ✅ 服务端管理对话状态,通过 previous_response_id 链式调用
  • ✅ 原生支持多步工具调用循环,API 自动处理 tool_call → execute → continue
  • ✅ 结构化的输出(output items),每一步操作都可追踪
// ✅ Responses API:简洁、声明式的工具调用
// API 自动处理工具调用循环,开发者只需声明工具和消息
const response = await openai.responses.create({
  model: 'gpt-4o',
  input: '帮我搜索今天北京的天气,然后总结成一句话',
  tools: [
    { type: 'web_search_preview' }  // 内置工具,无需自己实现
  ]
});

// 直接获取最终结果,无需手动管理中间步骤
console.log(response.output_text);
// → "今天北京晴转多云,气温 22-31°C,适合外出。"

💡 **提示:**Responses API 的 tools 参数支持自定义函数工具和内置工具的混合使用,这意味着你可以在同一个请求中同时使用 Web Search 和你自己的业务 API。

1.3 核心概念对比

特性 Chat Completions API Responses API
对话状态管理 客户端维护 messages 数组 服务端管理,通过 previous_response_id 链式调用
工具调用循环 需要开发者手动实现 while 循环 API 内置自动循环,一次调用完成
内置搜索工具 ❌ 不支持 ✅ Web Search、File Search 内置
Computer Use ❌ 不支持 ✅ 内置 computer_use 工具
输出格式 choices[].message 结构化 output items(text、tool_call 等)
流式响应 SSE chunks SSE events,支持 tool_call 进度
适用场景 简单对话、单次工具调用 Agent、多步推理、复杂工作流

🛠️ 二、Responses API 核心功能实战

2.1 Web Search:内置网页搜索能力

Web Search 是 Responses API 最实用的内置工具之一。它让模型能够实时搜索互联网并引用来源,无需你自己对接搜索 API。

// Web Search 实战:带来源引用的实时信息查询
import OpenAI from 'openai';

const openai = new OpenAI();

async function searchWithCitation(query) {
  const response = await openai.responses.create({
    model: 'gpt-4o',
    input: query,
    tools: [{
      type: 'web_search_preview',
      search_context_size: 'medium',  // low | medium | high
      user_location: {
        type: 'approximate',
        country: 'CN',
        city: 'Beijing'
      }
    }]
  });

  // 提取文本内容
  const textOutput = response.output.find(item => item.type === 'message');
  const answer = textOutput?.content[0]?.text || '';

  // 提取搜索来源(带 URL 和标题)
  const searchResults = response.output
    .filter(item => item.type === 'web_search_call')
    .flatMap(item => item.results || []);

  return {
    answer,
    sources: searchResults.map(r => ({
      title: r.title,
      url: r.url,
      snippet: r.snippet
    }))
  };
}

// 使用示例
const result = await searchWithCitation('2026 年最流行的 JavaScript 框架是什么?');
console.log(result.answer);
console.log('来源:', result.sources.map(s => s.url));

⚠️ **警告:**Web Search 的 search_context_size 参数直接影响成本和延迟。low 约消耗 300 tokens 上下文,high 约消耗 2000 tokens。在批量查询场景中,建议先用 low 测试,再根据质量需求调整。

2.2 File Search:向量化文档检索

File Search 工具内置了向量存储(Vector Store)和检索能力,你可以上传文档,模型会自动进行语义搜索和问答。

// File Search 实战:上传文档并进行语义问答
import OpenAI from 'openai';
import fs from 'fs';

const openai = new OpenAI();

async function setupAndSearch() {
  // 第一步:创建向量存储
  const vectorStore = await openai.vectorStores.create({
    name: 'product-docs'
  });

  // 第二步:上传文件到向量存储
  const file = await openai.files.create({
    file: fs.createReadStream('./product-manual.pdf'),
    purpose: 'assistants'
  });

  await openai.vectorStores.files.create(vectorStore.id, {
    file_id: file.id
  });

  // 等待文件处理完成(向量化索引)
  await openai.vectorStores.poll(vectorStore.id);

  // 第三步:使用 File Search 查询
  const response = await openai.responses.create({
    model: 'gpt-4o',
    input: '我们的产品支持哪些认证方式?请列出所有选项。',
    tools: [{
      type: 'file_search',
      vector_store_ids: [vectorStore.id],
      max_num_results: 5,
      ranking_options: {
        ranker: 'auto',       // auto | default-2024-11-15
        score_threshold: 0.5  // 过滤低相关性结果
      }
    }]
  });

  return response.output_text;
}

2.3 Computer Use:自动化浏览器操作

Computer Use 是 OpenAI 最具野心的内置工具,它让模型能够像人类一样操作计算机——点击按钮、输入文字、截屏分析。

// Computer Use 实战:自动化网页操作
// 注意:需要配合截图和坐标执行工具使用
const response = await openai.responses.create({
  model: 'computer-use-preview',
  input: [{
    role: 'user',
    content: '打开浏览器,访问 jsjson.com,点击 JSON 格式化工具'
  }],
  tools: [{
    type: 'computer_use_preview',
    display_width: 1920,
    display_height: 1080,
    environment: 'browser'  // browser | linux | mac | windows
  }],
  truncation: 'auto'
});

// 解析模型的操作指令
for (const item of response.output) {
  if (item.type === 'computer_call') {
    const action = item.action;
    
    switch (action.type) {
      case 'click':
        console.log(`点击坐标: (${action.x}, ${action.y})`);
        // 在这里执行实际的鼠标点击操作
        await performClick(action.x, action.y);
        break;
      case 'type':
        console.log(`输入文字: ${action.text}`);
        await performType(action.text);
        break;
      case 'screenshot':
        console.log('截屏请求');
        const screenshot = await takeScreenshot();
        // 将截屏结果作为下一步的输入
        break;
    }
  }
}

📌 **记住:**Computer Use 目前仍处于 Preview 阶段,适合自动化测试和 RPA 场景。在生产环境中使用时,务必添加人工审核环节,避免模型执行意外操作。

2.4 自定义函数工具:与你的业务系统集成

除了内置工具,Responses API 同样支持自定义函数工具,且语法比 Chat Completions 更简洁:

// 自定义函数工具实战:天气查询 + 数据库写入
const response = await openai.responses.create({
  model: 'gpt-4o',
  input: '查询上海今天的天气,然后把结果保存到数据库',
  tools: [
    // 内置工具
    { type: 'web_search_preview' },
    // 自定义函数工具
    {
      type: 'function',
      name: 'save_to_database',
      description: '将数据保存到数据库',
      parameters: {
        type: 'object',
        properties: {
          table: { type: 'string', description: '表名' },
          data: { type: 'object', description: '要保存的数据' }
        },
        required: ['table', 'data']
      },
      strict: true  // 启用严格模式,确保参数类型正确
    }
  ]
);

// Responses API 会自动处理工具调用循环
// 如果模型决定先搜索再保存,API 会自动执行多步操作
for (const item of response.output) {
  if (item.type === 'function_call' && item.name === 'save_to_database') {
    const args = JSON.parse(item.arguments);
    await db.insert(args.table, args.data);
  }
}

🚀 三、从 Chat Completions 迁移到 Responses API

3.1 迁移策略:渐进式替换

不建议一次性迁移所有代码。推荐按以下优先级逐步迁移:

优先级 场景 迁移理由
🔴 高 使用 Web Search 的场景 内置工具,代码量减少 80%
🔴 高 多步工具调用的 Agent 自动循环,无需手动管理
🟡 中 简单对话 + 单次工具调用 可以继续用 Chat Completions
🟢 低 纯文本对话(无工具) 两者差异不大,低优先级

3.2 代码迁移对比

// ❌ 迁移前:Chat Completions + 手动工具循环(约 40 行)
async function agentLoop(userInput) {
  const messages = [
    { role: 'system', content: '你是一个数据分析助手' },
    { role: 'user', content: userInput }
  ];
  
  while (true) {
    const response = await openai.chat.completions.create({
      model: 'gpt-4o',
      messages,
      tools: [
        { type: 'function', function: { name: 'query_db', parameters: dbSchema } },
        { type: 'function', function: { name: 'create_chart', parameters: chartSchema } }
      ]
    });
    
    const msg = response.choices[0].message;
    messages.push(msg);
    
    if (msg.tool_calls) {
      for (const tc of msg.tool_calls) {
        const result = await executeTool(tc.function.name, JSON.parse(tc.function.arguments));
        messages.push({ role: 'tool', tool_call_id: tc.id, content: JSON.stringify(result) });
      }
    } else {
      return msg.content;
    }
  }
}

// ✅ 迁移后:Responses API(约 20 行,减少 50%)
async function agentLoop(userInput) {
  const response = await openai.responses.create({
    model: 'gpt-4o',
    input: userInput,
    instructions: '你是一个数据分析助手',  // 替代 system message
    tools: [
      { type: 'function', name: 'query_db', parameters: dbSchema, strict: true },
      { type: 'function', name: 'create_chart', parameters: chartSchema, strict: true }
    ]
  );
  
  return response.output_text;
}

3.3 状态管理迁移

Chat Completions 需要客户端维护完整的 messages 数组,而 Responses API 使用服务端状态管理:

// ❌ Chat Completions:客户端维护状态
let messages = [{ role: 'system', content: '你是助手' }];

// 每次对话都要带上完整历史
messages.push({ role: 'user', content: '你好' });
let res1 = await openai.chat.completions.create({ model: 'gpt-4o', messages });
messages.push(res1.choices[0].message);

messages.push({ role: 'user', content: '继续' });
let res2 = await openai.chat.completions.create({ model: 'gpt-4o', messages });
// messages 数组会越来越大,Token 成本持续增长

// ✅ Responses API:服务端状态管理
let res1 = await openai.responses.create({
  model: 'gpt-4o',
  input: '你好'
});

let res2 = await openai.responses.create({
  model: 'gpt-4o',
  input: '继续',
  previous_response_id: res1.id  // 通过 ID 链式调用,服务端管理上下文
});

⚠️ 警告:previous_response_id 链式调用虽然方便,但服务端存储的响应数据有生命周期限制(通常为 30 天)。对于需要长期保存对话历史的场景,建议仍然在客户端备份关键数据。

3.4 流式响应迁移

// Responses API 流式响应:支持工具调用进度追踪
const stream = await openai.responses.create({
  model: 'gpt-4o',
  input: '帮我搜索最新的 TypeScript 6 特性并总结',
  tools: [{ type: 'web_search_preview' }],
  stream: true
});

for await (const event of stream) {
  switch (event.type) {
    case 'response.output_item.added':
      console.log('开始处理:', event.item.type);
      break;
    case 'response.output_item.done':
      if (event.item.type === 'web_search_call') {
        console.log('搜索完成,结果数:', event.item.results?.length);
      }
      break;
    case 'response.output_text.delta':
      process.stdout.write(event.delta);  // 实时输出文本
      break;
    case 'response.completed':
      console.log('\n完成,总 Token:', event.response.usage?.total_tokens);
      break;
  }
}

💰 四、成本对比与优化策略

4.1 成本结构对比

项目 Chat Completions (gpt-4o) Responses API (gpt-4o)
输入 Token $2.50 / 1M tokens $2.50 / 1M tokens
输出 Token $10.00 / 1M tokens $10.00 / 1M tokens
Web Search 需要外部 API(约 $0.01/次) 内置,按搜索上下文 Token 计费
File Search 需要自建向量数据库 内置,按存储 + 查询计费
状态存储 免费(客户端) 免费(30 天内)

4.2 成本优化实战

// 成本优化:合理使用 previous_response_id 避免重复输入
// 场景:长对话中,只发送增量内容而非完整历史

// ❌ 低效方式:每次都带完整上下文
// Token 消耗:O(n²) 增长

// ✅ 高效方式:使用 previous_response_id + 仅发送新消息
const optimizedResponse = await openai.responses.create({
  model: 'gpt-4o',
  input: '请用表格格式重新组织刚才的内容',  // 只发送新指令
  previous_response_id: previousId,           // 引用之前的上下文
  max_output_tokens: 2000                     // 限制输出长度
});

⚡ **关键结论:**对于超过 10 轮的长对话,使用 previous_response_id 链式调用比手动维护 messages 数组更节省 Token,因为 API 服务端会对历史上下文进行智能压缩。

✅ 最佳实践与避坑指南

推荐做法

  • 新项目直接使用 Responses API,除非有明确的兼容性要求
  • 混合使用内置工具和自定义工具,充分发挥平台能力
  • 使用 instructions 参数替代 system message,更清晰的职责分离
  • 启用 strict: true 确保自定义工具的参数类型安全
  • 使用流式响应提升用户体验,特别是 Web Search 等耗时操作

避免做法

  • 不要在简单对话场景强制使用 Responses API,Chat Completions 更轻量
  • 不要依赖 previous_response_id 存储关键业务数据,30 天后会过期
  • 不要在 Computer Use 场景中省略人工审核,模型可能执行意外操作
  • 不要忽略 max_output_tokens 设置,避免 Agent 循环产生过长输出

注意事项

  • ⚠️ Responses API 的 computer_use_preview 模型目前仅支持特定分辨率(推荐 1920x1080 或 1280x720)
  • ⚠️ Web Search 的搜索结果质量受 search_context_size 影响,建议根据场景选择 low/medium/high
  • ⚠️ File Search 的向量存储有容量限制(单个存储默认 1GB),大批量文档需要分片存储

🎯 总结

Responses API 代表了 AI API 从「对话接口」到「Agent 运行时」的范式转变。它的核心价值在于:

  1. 简化代码:内置工具和自动循环将 Agent 代码量减少 50% 以上
  2. 降低成本:服务端状态管理避免了重复发送完整历史上下文
  3. 增强能力:Web Search、File Search、Computer Use 开箱即用
  4. 提升可观测性:结构化的 output items 让每一步操作都可追踪

对于新项目,建议直接采用 Responses API;对于存量项目,可以按优先级逐步迁移使用了 Web Search 和多步工具调用的场景。Chat Completions API 不会被废弃,但 Responses API 无疑是未来的方向。

相关工具推荐:

📚 相关文章