关于 openai-responses
面向 OpenAI Responses API 开发者的 Agent 构建技能,介绍状态化对话、托管工具及 MCP 连接方式。
主要功能
- 01自动管理对话状态
- 02跨轮次保留推理状态
- 03托管代码、文件、网页和图像工具
- 04后台处理长时间任务
适用场景
- 01构建多轮 Agent 应用
- 02检索已上传文件
- 03使用 Python 分析数据
- 04通过 MCP 连接外部工具
MCP 相关
介绍如何通过 Responses API 连接 MCP 服务,包括服务标签、URL 和身份验证令牌。
安装
复制下面的命令,在终端中运行。
npx skills add https:/ / github.com/ ovachiever/ droid-tings --skill openai-responses安装后在 Claude Code 中输入/openai-responses确认已加载。
包含的文件
除 SKILL.md 外,安装时一起下载的参考资料和脚本。
README.md.claude-plugin/plugin.jsonreferences/built-in-tools-guide.mdmcp-integration-guide.mdmigration-guide.mdreasoning-preservation.mdresponses-vs-chat-completions.mdstateful-conversations.mdtop-errors.mdscripts/check-versions.shtemplates/background-mode.tsbasic-response.tscloudflare-worker.tscode-interpreter.tsfile-search.tsimage-generation.tsmcp-integration.tspackage.jsonstateful-conversation.tsweb-search.ts详细介绍
OpenAI Responses API
状态:已可用于生产环境 最后更新:2025-10-25 API 发布:2025 年 3 月 依赖项:[email protected]+(Node.js)或 fetch API(Cloudflare Workers)
什么是 Responses API?
Responses API(/v1/responses)是 OpenAI 于 2025 年 3 月推出的统一接口,用于构建 Agent 应用。它从根本上改变了你与 OpenAI 模型交互的方式,提供了有状态的对话以及结构化的推理和行动循环。
核心创新:保留推理状态
与 Chat Completions 在轮次之间丢弃推理不同,Responses 会让笔记本保持打开。模型逐步思考的过程会延续到下一轮,使 TAUBench 上的表现提升约 5%,并支持更好的多轮交互。
为什么选择 Responses,而不是 Chat Completions?
| 功能 | Chat Completions | Responses API | 优势 |
|---|---|---|---|
| 状态管理 | 手动(你负责跟踪历史记录) | 自动(对话 ID) | 代码更简单,出错风险更低 |
| 推理 | 轮次之间丢弃 | 在轮次之间保留 | 多轮表现更好 |
| 工具 | 客户端往返调用 | 服务端托管 | 延迟更低,代码更简单 |
| 输出格式 | 单条消息 | 多态(消息、推理、工具调用) | 调试信息更丰富,用户体验更好 |
| 缓存利用率 | 基准水平 | 提升 40-80% | 成本更低,响应更快 |
| MCP 支持 | 手动集成 | 内置 | 轻松连接外部工具 |
快速入门(5 分钟)
1. 获取 API 密钥
# Sign up at https://platform.openai.com/
# Navigate to API Keys section
# Create new key and save securely
export OPENAI_API_KEY="sk-proj-..."
这很重要,因为:
- 所有请求都需要 API 密钥
- 妥善保管(切勿提交到 git)
- 使用环境变量
2. 安装 SDK(Node.js)
npm install openai
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);
重要:
- 始终在服务端使用(切勿在客户端代码中暴露 API 密钥)
- 默认模型为
gpt-5(也可使用gpt-5-mini、gpt-4o等) input可以是字符串或消息数组
3. 或使用直接 API(Cloudflare Workers)
// No SDK needed - use fetch()
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);
为什么使用 fetch?
- 边缘环境中无需依赖项
- 可完全控制请求和响应
- 适用于 Cloudflare Workers、Deno、Bun
Responses 与 Chat Completions:完整对比
何时使用哪一种
在以下情况下使用 Responses API:
- ✅ 构建 Agent 应用(推理 + 行动)
- ✅ 需要在轮次之间保留推理状态
- ✅ 希望使用内置工具(Code Interpreter、File Search、Web Search)
- ✅ 使用 MCP 服务进行外部集成
- ✅ 实现具有自动状态管理功能的对话式 AI
- ✅ 对长时间运行的任务进行后台处理
- ✅ 需要多态输出(消息、推理、工具调用)
在以下情况下使用 Chat Completions:
- ✅ 简单的一次性文本生成
- ✅ 完全无状态的交互(无需保持对话连续性)
- ✅ 旧版集成(已有 Chat Completions 代码)
- ✅ 不使用工具的非常简单的用例
架构差异
Chat Completions 流程:
User Input → Model → Single Message → Done
(Reasoning discarded, state lost)
Responses API 流程:
User Input → Model (preserved reasoning) → Polymorphic Outputs
↓ (server-side tools)
Tool Call → Tool Result → Model → Final Response
(Reasoning preserved, state maintained)
性能优势
缓存利用率:
- Chat Completions:基准性能
- Responses API:缓存利用率提升 40-80%
- 结果:延迟更低 + 成本更低
推理性能:
- Chat Completions:轮次之间丢弃推理
- Responses API:在轮次之间保留推理
- 结果:TAUBench 上的表现提升 5%(GPT-5 使用 Responses 对比 Chat Completions)
有状态的对话
自动状态管理
Responses API 可以使用对话 ID自动管理对话状态。
创建对话
// Create conversation with initial message
const conversation = await openai.conversations.create({
metadata: { user_id: 'user_123' },
items: [
{
type: 'message',
role: 'user',
content: 'Hello!',
},
],
});
console.log(conversation.id); // "conv_abc123..."
使用对话 ID
// First turn
const response1 = await openai.responses.create({
model: 'gpt-5',
conversation: 'conv_abc123',
input: 'What are the 5 Ds of dodgeball?',
});
console.log(response1.output_text);
// Second turn - model remembers previous context
const response2 = await openai.responses.create({
model: 'gpt-5',
conversation: 'conv_abc123',
input: 'Tell me more about the first one',
});
console.log(response2.output_text);
// Model automatically knows "first one" refers to first D from previous turn
这很重要,因为:
- 无需手动跟踪历史记录
- 在轮次之间保留推理状态
- 自动管理上下文
- 降低上下文错误风险
手动状态管理(替代方案)
如果需要完全掌控,可以手动管理历史记录:
let history = [
{ role: 'user', content: 'Tell me a joke' },
];
const response = await openai.responses.create({
model: 'gpt-5',
input: history,
store: true, // Optional: store for retrieval later
});
// Add response to history
history = [
...history,
...response.output.map(el => ({
role: el.role,
content: el.content,
})),
];
// Next turn
history.push({ role: 'user', content: 'Tell me another' });
const secondResponse = await openai.responses.create({
model: 'gpt-5',
input: history,
});
适合使用手动管理的情况:
- 需要自定义历史记录清理逻辑
- 想以编程方式修改对话历史记录
- 实现自定义缓存策略
内置工具(服务端)
Responses API 包含服务端托管工具,可省去成本高昂的后端往返请求。
可用工具
| 工具 | 用途 | 使用场景 |
|---|---|---|
| Code Interpreter | 执行 Python 代码 | 数据分析、计算、图表 |
| File Search | 无需向量存储的 RAG | 搜索上传文件并获取答案 |
| Web Search | 实时网络信息 | 时事、事实核查 |
| Image Generation | DALL-E 集成 | 根据描述创建图像 |
| MCP | 连接外部工具 | Stripe、数据库、自定义 API |
Code Interpreter
在服务端执行 Python 代码,用于数据分析、计算和可视化。
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Calculate the mean, median, and mode of: 10, 20, 30, 40, 50',
tools: [{ type: 'code_interpreter' }],
});
console.log(response.output_text);
// Model writes and executes Python code, returns results
高级示例:数据分析
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Analyze this sales data and create a bar chart showing monthly revenue: [data here]',
tools: [{ type: 'code_interpreter' }],
});
// Check output for code execution results
response.output.forEach(item => {
if (item.type === 'code_interpreter_call') {
console.log('Code executed:', item.input);
console.log('Result:', item.output);
}
});
这样做的意义:
- 无需在本地运行 Python
- 沙盒执行环境
- 自动生成图表
- 可以处理上传的文件
File Search(无需向量存储的 RAG)
无需构建自己的 RAG 流水线,即可搜索上传的文件。
// 1. Upload files first (one-time setup)
const file = await openai.files.create({
file: fs.createReadStream('knowledge-base.pdf'),
purpose: 'assistants',
});
// 2. Use file search
const response = await openai.responses.create({
model: 'gpt-5',
input: 'What does the document say about pricing?',
tools: [
{
type: 'file_search',
file_ids: [file.id],
},
],
});
console.log(response.output_text);
// Model searches file and provides answer with citations
支持的文件类型:
- PDF、Word 文档、文本文件
- Markdown、HTML
- 代码文件(Python、JavaScript 等)
- 最大限制:每个文件 512MB
Web Search
获取网络上的实时信息。
const response = await openai.responses.create({
model: 'gpt-5',
input: 'What are the latest updates on GPT-5?',
tools: [{ type: 'web_search' }],
});
console.log(response.output_text);
// Model searches web and provides current information with sources
这样做的意义:
- 不受知识截止日期限制
- 自动引用来源
- 实时访问数据
- 无需外部搜索 API
Image Generation(DALL-E)
直接通过 Responses API 生成图像。
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Create an image of a futuristic cityscape at sunset',
tools: [{ type: 'image_generation' }],
});
// Find image in output
response.output.forEach(item => {
if (item.type === 'image_generation_call') {
console.log('Image URL:', item.output.url);
}
});
可用模型:
- DALL-E 3(默认)
- 多种尺寸和质量选项
MCP 服务集成
Responses API 内置了对 Model Context Protocol(MCP) 服务的支持,可连接外部工具。
什么是 MCP?
MCP 是一种开放协议,用于标准化应用程序向大模型提供上下文的方式。它支持:
- 连接外部 API(Stripe、数据库、CRM)
- 使用托管的 MCP 服务
- 构建自定义工具集成
基本 MCP 集成
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Roll 2d6 dice',
tools: [
{
type: 'mcp',
server_label: 'dice',
server_url: 'https://example.com/mcp',
},
],
});
// Model discovers available tools on MCP server and uses them
console.log(response.output_text);
使用身份验证的 MCP(OAuth)
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Create a $20 payment link',
tools: [
{
type: 'mcp',
server_label: 'stripe',
server_url: 'https://mcp.stripe.com',
authorization: process.env.STRIPE_OAUTH_TOKEN,
},
],
});
console.log(response.output_text);
// Model uses Stripe MCP server to create payment link
重要:
- API 不会存储授权令牌
- 每次请求都必须提供令牌
- 使用环境变量确保安全
多态输出:MCP 工具调用
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Roll 2d4+1',
tools: [
{
type: 'mcp',
server_label: 'dice',
server_url: 'https://dmcp.example.com',
},
],
});
// Inspect tool calls
response.output.forEach(item => {
if (item.type === 'mcp_call') {
console.log('Tool:', item.name);
console.log('Arguments:', item.arguments);
console.log('Output:', item.output);
}
if (item.type === 'mcp_list_tools') {
console.log('Available tools:', item.tools);
}
});
输出类型:
mcp_list_tools- 在服务上发现的工具mcp_call- 工具调用及结果message- 对用户的最终回复
推理保留
工作原理
与会丢弃推理内容的 Chat Completions 不同,Responses API 会在多轮对话中保留模型的内部推理状态。
形象地说:
- Chat Completions:模型有一本草稿簿,写下推理内容后,在回复前会撕掉这一页
- Responses API:模型会保持草稿簿打开,让先前的推理内容对下一轮可见
性能影响
TAUBench 结果(GPT-5):
- Chat Completions:基准分数
- Responses API:提升 5%(完全得益于保留推理)
这很重要,因为:
- 多轮问题解决能力更强
- 长对话更加连贯
- 逐步推理能力更佳
- 上下文错误更少
推理摘要(免费!)
Responses API 免费提供推理摘要。
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Solve this complex math problem: [problem]',
});
// Inspect reasoning
response.output.forEach(item => {
if (item.type === 'reasoning') {
console.log('Model reasoning:', item.summary[0].text);
}
if (item.type === 'message') {
console.log('Final answer:', item.content[0].text);
}
});
使用场景:
- 调试模型决策
- 用于合规的审计跟踪
- 了解模型的思考过程
- 构建透明的 AI 系统
后台模式(长时间运行的任务)
对于耗时超过标准超时限制的任务,请使用后台模式。
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Analyze this 500-page document and summarize key findings',
background: true,
tools: [{ type: 'file_search', file_ids: [fileId] }],
});
// Returns immediately with status
console.log(response.status); // "in_progress"
console.log(response.id); // Use to check status later
// Poll for completion
const checkStatus = async (responseId) => {
const result = await openai.responses.retrieve(responseId);
if (result.status === 'completed') {
console.log(result.output_text);
} else if (result.status === 'failed') {
console.error('Task failed:', result.error);
} else {
// Still running, check again later
setTimeout(() => checkStatus(responseId), 5000);
}
};
checkStatus(response.id);
适用场景:
- 处理大型文件
- 复杂计算
- 多步骤研究任务
- 分析大型数据集
超时限制:
- 标准模式:60 秒
- 后台模式:最长 10 分钟
多态输出
Responses API 会返回多种输出类型,而不是单条消息。
输出类型
| 类型 | 描述 | 示例 |
|---|---|---|
message | 面向用户的文本回复 | 最终答案、说明 |
reasoning | 模型的内部思考过程 | 分步推理摘要 |
code_interpreter_call | 代码执行 | Python 代码 + 结果 |
mcp_call | 工具调用 | 工具名称、参数、输出 |
mcp_list_tools | 可用工具 | MCP 服务中的工具定义 |
file_search_call | 文件搜索结果 | 匹配的片段、引用 |
web_search_call | 网络搜索结果 | URL、摘要 |
image_generation_call | 图像生成 | 图像 URL |
处理多态输出
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Search the web for the latest AI news and summarize',
tools: [{ type: 'web_search' }],
});
// Process different output types
response.output.forEach(item => {
switch (item.type) {
case 'reasoning':
console.log('Reasoning:', item.summary[0].text);
break;
case 'web_search_call':
console.log('Searched:', item.query);
console.log('Sources:', item.results);
break;
case 'message':
console.log('Response:', item.content[0].text);
break;
}
});
// Or use helper for text-only
console.log(response.output_text);
重要原因:
- 更易调试(查看所有步骤)
- 审计记录(跟踪所有工具调用)
- 更丰富的用户体验(向用户展示进度)
- 合规性(记录所有操作)
从 Chat Completions 迁移
重大变更
| 功能 | Chat Completions | Responses API | 迁移操作 |
|---|---|---|---|
| 端点 | /v1/chat/completions | /v1/responses | 更新 URL |
| 参数 | messages | input | 重命名参数 |
| 状态 | 手动(messages 数组) | 自动(conversation ID) | 使用 conversation ID |
| 工具 | 包含函数的 tools 数组 | 内置类型 + MCP | 更新工具定义 |
| 输出 | choices[0].message.content | output_text 或 output 数组 | 更新响应解析逻辑 |
| 流式传输 | data: {"choices":[...]} | 包含多种项目类型的 SSE | 更新流解析器 |
迁移示例
之前(Chat Completions):
const response = await openai.chat.completions.create({
model: 'gpt-5',
messages: [
{ role: 'system', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello!' },
],
});
console.log(response.choices[0].message.content);
之后(Responses):
const response = await openai.responses.create({
model: 'gpt-5',
input: [
{ role: 'developer', content: 'You are a helpful assistant.' },
{ role: 'user', content: 'Hello!' },
],
});
console.log(response.output_text);
主要差异:
chat.completions.create→responses.createmessages→inputsystem角色 →developer角色choices[0].message.content→output_text
何时迁移
现在迁移,如果你:
- ✅ 正在构建新应用
- ✅ 需要有状态的对话
- ✅ 使用 Agent 模式(推理 + 工具)
- ✅ 希望获得更好的性能(保留推理)
继续使用 Chat Completions,如果你:
- ✅ 只需进行简单的一次性生成
- ✅ 使用旧版集成
- ✅ 不需要状态管理
错误处理
常见错误及解决方案
1. 会话状态未持久化
错误:
Conversation state not maintained between turns
原因:
- 未使用 conversation ID
- 每轮使用不同的 conversation ID
解决方案:
// Create conversation once
const conv = await openai.conversations.create();
// Reuse conversation ID for all turns
const response1 = await openai.responses.create({
model: 'gpt-5',
conversation: conv.id, // ✅ Same ID
input: 'First message',
});
const response2 = await openai.responses.create({
model: 'gpt-5',
conversation: conv.id, // ✅ Same ID
input: 'Follow-up message',
});
2. MCP 服务连接失败
错误:
{
"error": {
"type": "mcp_connection_error",
"message": "Failed to connect to MCP server"
}
}
原因:
- 服务 URL 无效
- 授权令牌缺失或已过期
- 服务无响应
解决方案:
// 1. Verify URL is correct
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Test MCP',
tools: [
{
type: 'mcp',
server_label: 'test',
server_url: 'https://api.example.com/mcp', // ✅ Full URL
authorization: process.env.AUTH_TOKEN, // ✅ Valid token
},
],
});
// 2. Test server URL manually
const testResponse = await fetch('https://api.example.com/mcp');
console.log(testResponse.status); // Should be 200
// 3. Check token expiration
console.log('Token expires:', parseJWT(token).exp);
3. 代码解释器超时
错误:
{
"error": {
"type": "code_interpreter_timeout",
"message": "Code execution exceeded time limit"
}
}
原因:
- 代码运行时间超过 30 秒
解决方案:
// Use background mode for long-running code
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Process this large dataset',
background: true, // ✅ Extended timeout
tools: [{ type: 'code_interpreter' }],
});
// Poll for results
const result = await openai.responses.retrieve(response.id);
4. 图像生成速率限制
错误:
{
"error": {
"type": "rate_limit_error",
"message": "DALL-E rate limit exceeded"
}
}
原因:
- 图像生成请求过多
解决方案:
// Implement retry with exponential backoff
const generateImage = async (prompt, retries = 3) => {
try {
return await openai.responses.create({
model: 'gpt-5',
input: prompt,
tools: [{ type: 'image_generation' }],
});
} catch (error) {
if (error.type === 'rate_limit_error' && retries > 0) {
const delay = (4 - retries) * 1000; // 1s, 2s, 3s
await new Promise(resolve => setTimeout(resolve, delay));
return generateImage(prompt, retries - 1);
}
throw error;
}
};
5. 文件搜索相关性问题
问题:
- 文件搜索返回不相关的结果
解决方案:
// Use more specific queries
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Find sections about pricing in Q4 2024 specifically', // ✅ Specific
// NOT: 'Find pricing' (too vague)
tools: [{ type: 'file_search', file_ids: [fileId] }],
});
// Or filter results manually
response.output.forEach(item => {
if (item.type === 'file_search_call') {
const relevantChunks = item.results.filter(
chunk => chunk.score > 0.7 // ✅ Only high-confidence matches
);
}
});
6. 成本跟踪疑问
问题:
- 账单与预期不同
说明:
- Responses API 会对以下项目计费:输入 token + 输出 token + 工具使用 + 已存储的对话
- Chat Completions 仅对以下项目计费:输入 token + 输出 token
解决方案:
// Monitor usage
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Hello',
store: false, // ✅ Don't store if not needed
});
console.log('Usage:', response.usage);
// {
// prompt_tokens: 10,
// completion_tokens: 20,
// tool_tokens: 5,
// total_tokens: 35
// }
7. 未找到对话
错误:
{
"error": {
"type": "invalid_request_error",
"message": "Conversation conv_xyz not found"
}
}
原因:
- conversation ID 拼写错误
- 对话已删除
- 对话已过期(90 天)
解决方案:
// Verify conversation exists before using
const conversations = await openai.conversations.list();
const exists = conversations.data.some(c => c.id === 'conv_xyz');
if (!exists) {
// Create new conversation
const newConv = await openai.conversations.create();
// Use newConv.id
}
8. 工具输出解析失败
问题:
- 无法正确访问工具输出
解决方案:
// Use helper methods
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Search for AI news',
tools: [{ type: 'web_search' }],
});
// Helper: Get text-only output
console.log(response.output_text);
// Manual: Inspect all outputs
response.output.forEach(item => {
console.log('Type:', item.type);
console.log('Content:', item);
});
生产环境模式
成本优化
1. 使用对话 ID(缓存优势)
// ✅ GOOD: Reuse conversation ID
const conv = await openai.conversations.create();
const response1 = await openai.responses.create({
model: 'gpt-5',
conversation: conv.id,
input: 'Question 1',
});
// 40-80% better cache utilization
// ❌ BAD: New manual history each time
const response2 = await openai.responses.create({
model: 'gpt-5',
input: [...previousHistory, newMessage],
});
// No cache benefits
2. 不需要时禁用存储
// For one-off requests
const response = await openai.responses.create({
model: 'gpt-5',
input: 'Quick question',
store: false, // ✅ Don't store conversation
});
3. 尽可能使用较小的模型
// For simple tasks
const response = await openai.responses.create({
model: 'gpt-5-mini', // ✅ 50% cheaper
input: 'Summarize this paragraph',
});
速率限制处理
const createResponseWithRetry = async (params, maxRetries = 3) => {
for (let i = 0; i < maxRetries; i++) {
try {
return await openai.responses.create(params);
} catch (error) {
if (error.type === 'rate_limit_error' && i < maxRetries - 1) {
const delay = Math.pow(2, i) * 1000; // Exponential backoff
console.log(`Rate limited, retrying in ${delay}ms`);
await new Promise(resolve => setTimeout(resolve, delay));
} else {
throw error;
}
}
}
};
监控和日志记录
const monitoredResponse = async (input) => {
const startTime = Date.now();
try {
const response = await openai.responses.create({
model: 'gpt-5',
input,
});
// Log success metrics
console.log({
status: 'success',
latency: Date.now() - startTime,
tokens: response.usage.total_tokens,
model: response.model,
conversation: response.conversation_id,
});
return response;
} catch (error) {
// Log error metrics
console.error({
status: 'error',
latency: Date.now() - startTime,
error: error.message,
type: error.type,
});
throw error;
}
};
Node.js 与 Cloudflare Workers
Node.js 实现
import OpenAI from 'openai';
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
export async function handleRequest(input: string) {
const response = await openai.responses.create({
model: 'gpt-5',
input,
tools: [{ type: 'web_search' }],
});
return response.output_text;
}
优点:
- 完整的 SDK 支持
- 类型安全
- 流式处理辅助工具
缺点:
- 需要 Node.js 运行时
- 打包体积较大
Cloudflare Workers 实现
export default {
async fetch(request: Request, env: Env): Promise<Response> {
const { input } = await request.json();
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,
tools: [{ type: 'web_search' }],
}),
});
const data = await response.json();
return new Response(data.output_text, {
headers: { 'Content-Type': 'text/plain' },
});
},
};
优点:
- 无依赖项
- 边缘部署
- 冷启动更快
缺点:
- 需要手动构建请求
- 不使用自定义类型时不具备类型安全
始终要做 / 绝不要做
✅ 始终要做
-
在多轮交互中使用对话 ID
const conv = await openai.conversations.create(); // Reuse conv.id for all related turns -
处理多态响应中的所有输出类型
response.output.forEach(item => { if (item.type === 'reasoning') { /* log */ } if (item.type === 'message') { /* display */ } }); -
对长时间运行的任务使用后台模式
const response = await openai.responses.create({ background: true, // ✅ For tasks >30s ... }); -
为 MCP 服务提供授权令牌
tools: [{ type: 'mcp', authorization: process.env.TOKEN, // ✅ Required }] -
监控令牌用量以控制成本
console.log(response.usage.total_tokens);
❌ 绝不要做
-
绝不要在客户端代码中暴露 API 密钥
// ❌ DANGER: API key in browser const response = await fetch('https://api.openai.com/v1/responses', { headers: { 'Authorization': 'Bearer sk-proj-...' } }); -
绝不要假定输出只有一条消息
// ❌ BAD: Ignores reasoning, tool calls console.log(response.output[0].content); // ✅ GOOD: Use helper or check all types console.log(response.output_text); -
绝不要在不同用户之间重复使用对话 ID
// ❌ DANGER: User A sees User B's conversation const sharedConv = 'conv_123'; -
绝不要忽略错误类型
// ❌ BAD: Generic error handling try { ... } catch (e) { console.log('error'); } // ✅ GOOD: Type-specific handling catch (e) { if (e.type === 'rate_limit_error') { /* retry */ } if (e.type === 'mcp_connection_error') { /* alert */ } } -
后台任务的轮询间隔绝不要短于 1 秒
// ❌ BAD: Too frequent setInterval(() => checkStatus(), 100); // ✅ GOOD: Reasonable interval setInterval(() => checkStatus(), 5000);
参考资料
官方文档
- Responses API 指南:https://platform.openai.com/docs/guides/responses
- API 参考:https://platform.openai.com/docs/api-reference/responses
- MCP 集成:https://platform.openai.com/docs/guides/tools-connectors-mcp
- 博客文章(为什么选择 Responses API):https://developers.openai.com/blog/responses-api/
- 入门应用:https://github.com/openai/openai-responses-starter-app
Skill 资源
templates/- 可运行的代码示例references/responses-vs-chat-completions.md- 功能对比references/mcp-integration-guide.md- MCP 服务配置references/built-in-tools-guide.md- 工具使用模式references/stateful-conversations.md- 对话管理references/migration-guide.md- Chat Completions → Responsesreferences/top-errors.md- 常见错误和解决方案
后续步骤
- ✅ 阅读
templates/basic-response.ts- 简单示例 - ✅ 尝试
templates/stateful-conversation.ts- 多轮聊天 - ✅ 探索
templates/mcp-integration.ts- 外部工具 - ✅ 查看
references/top-errors.md- 避免常见问题 - ✅ 查看
references/migration-guide.md- 从 Chat Completions 迁移时参考
祝你使用 Responses API 开发顺利! 🚀