OpenAI Responses API Status : Production Ready Last Updated : 2025-10-25 API Launch : March 2025 Dependencies : [email protected]+ (Node.js) or fetch API (Cloudflare Workers) --- What Is the Responses API? The Responses API ( ) is OpenAI's unified interface for building agentic applications, launched in March 2025. It fundamentally changes how you interact with OpenAI models by providing stateful conversations and a structured loop for reasoning and acting . Key Innovation: Preserved Reasoning State Unlike Chat Completions where reasoning is discarded between turns, Responses keeps the notebook o…

+ totalCost.toFixed(4));\n```\n\n**Prevention:**\n- Monitor `usage.tool_tokens` in responses\n- Set `store: false` for one-off requests\n- Track conversation count (storage costs)\n- Implement cost alerts\n\n---\n\n## Common Error Response Formats\n\n### Authentication Error\n```json\n{\n \"error\": {\n \"type\": \"authentication_error\",\n \"message\": \"Invalid API key\"\n }\n}\n```\n\n### Rate Limit Error\n```json\n{\n \"error\": {\n \"type\": \"rate_limit_error\",\n \"message\": \"Rate limit exceeded\",\n \"retry_after\": 5\n }\n}\n```\n\n### Invalid Request Error\n```json\n{\n \"error\": {\n \"type\": \"invalid_request_error\",\n \"message\": \"Conversation conv_xyz not found\"\n }\n}\n```\n\n### Server Error\n```json\n{\n \"error\": {\n \"type\": \"server_error\",\n \"message\": \"Internal server error\"\n }\n}\n```\n\n---\n\n## General Error Handling Pattern\n\n```typescript\nasync function handleResponsesAPI(input: string) {\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input,\n });\n\n return response.output_text;\n } catch (error: any) {\n // Handle specific errors\n switch (error.type) {\n case 'rate_limit_error':\n console.error('Rate limited, retry after:', error.retry_after);\n break;\n case 'mcp_connection_error':\n console.error('MCP server failed:', error.message);\n break;\n case 'code_interpreter_timeout':\n console.error('Code execution timed out, use background mode');\n break;\n case 'authentication_error':\n console.error('Invalid API key');\n break;\n default:\n console.error('Unexpected error:', error.message);\n }\n\n throw error; // Re-throw or handle\n }\n}\n```\n\n---\n\n## Prevention Checklist\n\n- [ ] Use conversation IDs for multi-turn interactions\n- [ ] Provide valid MCP server URLs and tokens\n- [ ] Use `background: true` for tasks > 30 seconds\n- [ ] Implement exponential backoff for rate limits\n- [ ] Use specific queries for file search\n- [ ] Use template literals for variable substitution\n- [ ] Update Chat Completions syntax to Responses syntax\n- [ ] Monitor `usage.tool_tokens` and conversation count\n\n---\n\n## Getting Help\n\nIf you encounter an error not covered here:\n\n1. Check official docs: https://platform.openai.com/docs/api-reference/responses\n2. Search OpenAI Community: https://community.openai.com\n3. Contact OpenAI Support: https://help.openai.com\n\n---\n\n**Last Updated**: 2025-10-25\n","content_type":"text/markdown; charset=utf-8","language":"markdown","size":11342,"content_sha256":"f3666d2f2c2e1e25fb01b6885e606b46e1d62dd41dee517e47cec98e46171fbc"},{"filename":"scripts/check-versions.sh","content":"#!/bin/bash\n\n# Check OpenAI SDK versions for Responses API compatibility\n# Minimum version: [email protected]\n\necho \"=== OpenAI Responses API - Version Checker ===\"\necho \"\"\n\n# Check if npm is installed\nif ! command -v npm &> /dev/null; then\n echo \"❌ npm not found. Please install Node.js and npm.\"\n exit 1\nfi\n\n# Check latest version\necho \"Checking latest openai package version...\"\nLATEST_VERSION=$(npm view openai version 2>/dev/null)\n\nif [ -z \"$LATEST_VERSION\" ]; then\n echo \"❌ Could not fetch latest version. Check internet connection.\"\n exit 1\nfi\n\necho \"📦 Latest version: $LATEST_VERSION\"\necho \"\"\n\n# Check if package.json exists\nif [ -f \"package.json\" ]; then\n echo \"Checking installed version...\"\n INSTALLED_VERSION=$(node -p \"require('./package.json').dependencies?.openai || require('./package.json').devDependencies?.openai\" 2>/dev/null)\n\n if [ ! -z \"$INSTALLED_VERSION\" ]; then\n # Remove ^ or ~ prefix\n INSTALLED_VERSION=$(echo $INSTALLED_VERSION | sed 's/[\\^~]//g')\n echo \"📦 Installed version: $INSTALLED_VERSION\"\n\n # Compare versions (simple string comparison for major.minor.patch)\n REQUIRED_VERSION=\"5.19.0\"\n\n # Extract major.minor.patch\n INSTALLED_MAJOR=$(echo $INSTALLED_VERSION | cut -d. -f1)\n INSTALLED_MINOR=$(echo $INSTALLED_VERSION | cut -d. -f2)\n INSTALLED_PATCH=$(echo $INSTALLED_VERSION | cut -d. -f3)\n\n REQUIRED_MAJOR=$(echo $REQUIRED_VERSION | cut -d. -f1)\n REQUIRED_MINOR=$(echo $REQUIRED_VERSION | cut -d. -f2)\n REQUIRED_PATCH=$(echo $REQUIRED_VERSION | cut -d. -f3)\n\n # Check compatibility\n if [ \"$INSTALLED_MAJOR\" -gt \"$REQUIRED_MAJOR\" ] || \\\n ([ \"$INSTALLED_MAJOR\" -eq \"$REQUIRED_MAJOR\" ] && [ \"$INSTALLED_MINOR\" -gt \"$REQUIRED_MINOR\" ]) || \\\n ([ \"$INSTALLED_MAJOR\" -eq \"$REQUIRED_MAJOR\" ] && [ \"$INSTALLED_MINOR\" -eq \"$REQUIRED_MINOR\" ] && [ \"$INSTALLED_PATCH\" -ge \"$REQUIRED_PATCH\" ]); then\n echo \"✅ Version is compatible with Responses API (>= $REQUIRED_VERSION)\"\n else\n echo \"❌ Version is too old for Responses API\"\n echo \" Required: >= $REQUIRED_VERSION\"\n echo \" Installed: $INSTALLED_VERSION\"\n echo \"\"\n echo \"To upgrade: npm install openai@latest\"\n exit 1\n fi\n else\n echo \"⚠️ openai package not found in dependencies\"\n echo \"\"\n echo \"To install: npm install openai\"\n fi\nelse\n echo \"⚠️ No package.json found\"\n echo \"\"\n echo \"To install: npm install openai\"\nfi\n\necho \"\"\necho \"=== Recommendations ===\"\necho \"\"\necho \"Minimum version for Responses API: [email protected]\"\necho \"Latest stable version: openai@$LATEST_VERSION\"\necho \"\"\necho \"To install/upgrade:\"\necho \" npm install openai@latest\"\necho \"\"\necho \"For Cloudflare Workers (no SDK needed):\"\necho \" Use native fetch API\"\necho \"\"\n","content_type":"application/x-sh; charset=utf-8","language":"bash","size":2905,"content_sha256":"7368ff263e5d286d5f5ba19df227429b99fef4ec90292110cf64d84078088f5a"},{"filename":"templates/background-mode.ts","content":"/**\n * Background Mode Example\n *\n * Demonstrates long-running tasks with background mode (up to 10 minutes).\n * Standard mode timeout: 60 seconds\n * Background mode timeout: 10 minutes\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicBackgroundMode() {\n console.log('=== Basic Background Mode ===\\n');\n\n // Start background task\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Analyze this 500-page document and provide a comprehensive summary',\n background: true, // ✅ Extended timeout\n });\n\n console.log('Task started:', response.id);\n console.log('Status:', response.status); // \"in_progress\"\n\n // Poll for completion\n let result = await openai.responses.retrieve(response.id);\n\n while (result.status === 'in_progress') {\n console.log('Still processing...');\n await new Promise((resolve) => setTimeout(resolve, 5000)); // Check every 5 seconds\n result = await openai.responses.retrieve(response.id);\n }\n\n if (result.status === 'completed') {\n console.log('\\nCompleted!');\n console.log('Result:', result.output_text);\n } else if (result.status === 'failed') {\n console.error('Task failed:', result.error);\n }\n}\n\nasync function backgroundWithCodeInterpreter() {\n console.log('=== Background Mode + Code Interpreter ===\\n');\n\n // Long-running data analysis\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Process this large dataset and generate detailed statistical analysis',\n background: true,\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Analysis started:', response.id);\n\n // Poll with progress updates\n let checks = 0;\n let result = await openai.responses.retrieve(response.id);\n\n while (result.status === 'in_progress') {\n checks++;\n console.log(`Check ${checks}: Still processing...`);\n await new Promise((resolve) => setTimeout(resolve, 10000)); // Check every 10 seconds\n result = await openai.responses.retrieve(response.id);\n }\n\n if (result.status === 'completed') {\n console.log(`\\nCompleted after ${checks} checks`);\n console.log('Analysis:', result.output_text);\n }\n}\n\nasync function backgroundWithFileSearch() {\n console.log('=== Background Mode + File Search ===\\n');\n\n // Upload large document\n const file = await openai.files.create({\n file: Buffer.from('Large document content...'),\n purpose: 'assistants',\n });\n\n // Long-running file analysis\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Read this entire document and extract all key insights, metrics, and action items',\n background: true,\n tools: [{ type: 'file_search', file_ids: [file.id] }],\n });\n\n console.log('File analysis started:', response.id);\n\n // Wait for completion\n const result = await waitForCompletion(response.id);\n console.log('Insights:', result.output_text);\n}\n\nasync function backgroundWithWebSearch() {\n console.log('=== Background Mode + Web Search ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Research the top 50 AI companies and create a comprehensive comparison report',\n background: true,\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Research started:', response.id);\n\n const result = await waitForCompletion(response.id);\n console.log('Report:', result.output_text);\n}\n\nasync function multipleBackgroundTasks() {\n console.log('=== Multiple Background Tasks ===\\n');\n\n // Start multiple tasks in parallel\n const task1 = openai.responses.create({\n model: 'gpt-5',\n input: 'Analyze Q1 financial data',\n background: true,\n tools: [{ type: 'code_interpreter' }],\n });\n\n const task2 = openai.responses.create({\n model: 'gpt-5',\n input: 'Research competitor landscape',\n background: true,\n tools: [{ type: 'web_search' }],\n });\n\n const task3 = openai.responses.create({\n model: 'gpt-5',\n input: 'Summarize customer feedback documents',\n background: true,\n tools: [{ type: 'file_search', file_ids: ['file_123'] }],\n });\n\n // Wait for all\n const [response1, response2, response3] = await Promise.all([task1, task2, task3]);\n\n console.log('All tasks started:');\n console.log('Task 1:', response1.id);\n console.log('Task 2:', response2.id);\n console.log('Task 3:', response3.id);\n\n // Wait for completion\n const result1 = await waitForCompletion(response1.id);\n const result2 = await waitForCompletion(response2.id);\n const result3 = await waitForCompletion(response3.id);\n\n console.log('\\nAll tasks completed!');\n console.log('Q1 Analysis:', result1.output_text);\n console.log('Competitor Research:', result2.output_text);\n console.log('Customer Feedback:', result3.output_text);\n}\n\nasync function backgroundWithStatusTracking() {\n console.log('=== Background Mode with Status Tracking ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Complex multi-step research task',\n background: true,\n });\n\n console.log('Task ID:', response.id);\n\n // Track status with detailed logging\n let previousStatus = '';\n let result = await openai.responses.retrieve(response.id);\n\n while (result.status === 'in_progress') {\n if (result.status !== previousStatus) {\n console.log(`Status changed: ${previousStatus} → ${result.status}`);\n previousStatus = result.status;\n }\n\n // Log additional info if available\n if (result.metadata) {\n console.log('Metadata:', result.metadata);\n }\n\n await new Promise((resolve) => setTimeout(resolve, 5000));\n result = await openai.responses.retrieve(response.id);\n }\n\n console.log('Final status:', result.status);\n}\n\nasync function handleBackgroundErrors() {\n console.log('=== Error Handling ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Long-running task',\n background: true,\n });\n\n try {\n const result = await waitForCompletion(response.id, {\n maxWaitTime: 5 * 60 * 1000, // 5 minutes max\n checkInterval: 5000,\n });\n\n console.log('Success:', result.output_text);\n } catch (error: any) {\n if (error.message === 'TIMEOUT') {\n console.error('Task exceeded maximum wait time');\n console.error('Task ID:', response.id);\n console.error('Check status later or increase timeout');\n } else if (error.status === 'failed') {\n console.error('Task failed:', error.error);\n } else {\n console.error('Unexpected error:', error);\n }\n }\n}\n\nasync function cancelBackgroundTask() {\n console.log('=== Cancel Background Task ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Long task',\n background: true,\n });\n\n console.log('Task started:', response.id);\n\n // Cancel after 10 seconds\n await new Promise((resolve) => setTimeout(resolve, 10000));\n\n try {\n await openai.responses.cancel(response.id);\n console.log('Task cancelled:', response.id);\n } catch (error: any) {\n console.error('Cancellation error:', error.message);\n }\n}\n\n// Helper function\nasync function waitForCompletion(\n responseId: string,\n options: { maxWaitTime?: number; checkInterval?: number } = {}\n): Promise\u003cany> {\n const { maxWaitTime = 10 * 60 * 1000, checkInterval = 5000 } = options;\n\n const startTime = Date.now();\n let result = await openai.responses.retrieve(responseId);\n\n while (result.status === 'in_progress') {\n if (Date.now() - startTime > maxWaitTime) {\n throw new Error('TIMEOUT');\n }\n\n await new Promise((resolve) => setTimeout(resolve, checkInterval));\n result = await openai.responses.retrieve(responseId);\n }\n\n if (result.status === 'failed') {\n throw result;\n }\n\n return result;\n}\n\n// Run examples\n// basicBackgroundMode();\n// backgroundWithCodeInterpreter();\n// multipleBackgroundTasks();\n// handleBackgroundErrors();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":7910,"content_sha256":"47628f8c9307577a04e1338fe3b165221189f42902b78a8beb3c86ac7aec53f8"},{"filename":"templates/basic-response.ts","content":"/**\n * Basic Response Example\n *\n * Simple text generation using the OpenAI Responses API.\n * This is the simplest way to use the Responses API.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicResponse() {\n // Simple text input\n const response = await openai.responses.create({\n model: 'gpt-5', // or 'gpt-5-mini', 'gpt-4o'\n input: 'What are the 5 Ds of dodgeball?',\n });\n\n // Get text output\n console.log(response.output_text);\n\n // Or inspect full output array\n response.output.forEach((item) => {\n console.log('Type:', item.type);\n if (item.type === 'message') {\n console.log('Content:', item.content);\n }\n });\n\n // Check usage\n console.log('Tokens used:', response.usage.total_tokens);\n}\n\nasync function basicResponseWithMessages() {\n // Using message array format (like Chat Completions)\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: [\n { role: 'developer', content: 'You are a helpful assistant.' },\n { role: 'user', content: 'Explain quantum computing in one sentence.' },\n ],\n });\n\n console.log(response.output_text);\n}\n\nasync function basicResponseWithOptions() {\n // With additional options\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Write a haiku about coding',\n store: false, // Don't store conversation (saves costs)\n temperature: 0.7, // Creativity level (0-2)\n });\n\n console.log(response.output_text);\n}\n\n// Run examples\nbasicResponse();\n// basicResponseWithMessages();\n// basicResponseWithOptions();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":1625,"content_sha256":"82a3fe9b5836fe7c7b417f1454d8fe6b9a895a3122acdc1e4a729ce04faa423c"},{"filename":"templates/cloudflare-worker.ts","content":"/**\n * Cloudflare Workers Example\n *\n * Demonstrates using the Responses API in Cloudflare Workers without the SDK.\n * Uses native fetch API for zero dependencies.\n */\n\nexport interface Env {\n OPENAI_API_KEY: string;\n}\n\nexport default {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n // Handle CORS preflight\n if (request.method === 'OPTIONS') {\n return new Response(null, {\n headers: {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'POST, GET, OPTIONS',\n 'Access-Control-Allow-Headers': 'Content-Type',\n },\n });\n }\n\n if (request.method !== 'POST') {\n return new Response('Method not allowed', { status: 405 });\n }\n\n try {\n const { input } = await request.json\u003c{ input: string }>();\n\n // Basic response\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n });\n\n return new Response(JSON.stringify(response), {\n headers: {\n 'Content-Type': 'application/json',\n 'Access-Control-Allow-Origin': '*',\n },\n });\n } catch (error: any) {\n return new Response(JSON.stringify({ error: error.message }), {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n });\n }\n },\n};\n\n// Helper: Create response\nasync function createResponse(apiKey: string, params: any) {\n const response = await fetch('https://api.openai.com/v1/responses', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify(params),\n });\n\n if (!response.ok) {\n const error = await response.json();\n throw new Error(error.error?.message || 'OpenAI API error');\n }\n\n return response.json();\n}\n\n// Example: Stateful conversation\nexport const conversationWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { conversationId, input } = await request.json\u003c{\n conversationId?: string;\n input: string;\n }>();\n\n // Create or use existing conversation\n let convId = conversationId;\n if (!convId) {\n const conv = await createConversation(env.OPENAI_API_KEY);\n convId = conv.id;\n }\n\n // Create response with conversation\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n conversation: convId,\n input,\n });\n\n return new Response(\n JSON.stringify({\n conversationId: convId,\n output: response.output_text,\n }),\n {\n headers: { 'Content-Type': 'application/json' },\n }\n );\n },\n};\n\n// Helper: Create conversation\nasync function createConversation(apiKey: string) {\n const response = await fetch('https://api.openai.com/v1/conversations', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${apiKey}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({}),\n });\n\n return response.json();\n}\n\n// Example: With MCP tools\nexport const mcpWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input } = await request.json\u003c{ input: string }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: env.STRIPE_OAUTH_TOKEN,\n },\n ],\n });\n\n return new Response(JSON.stringify(response), {\n headers: { 'Content-Type': 'application/json' },\n });\n },\n};\n\n// Example: With Code Interpreter\nexport const codeInterpreterWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input } = await request.json\u003c{ input: string }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n tools: [{ type: 'code_interpreter' }],\n });\n\n return new Response(JSON.stringify(response), {\n headers: { 'Content-Type': 'application/json' },\n });\n },\n};\n\n// Example: With File Search\nexport const fileSearchWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input, fileIds } = await request.json\u003c{\n input: string;\n fileIds: string[];\n }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n tools: [{ type: 'file_search', file_ids: fileIds }],\n });\n\n return new Response(JSON.stringify(response), {\n headers: { 'Content-Type': 'application/json' },\n });\n },\n};\n\n// Example: With Web Search\nexport const webSearchWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input } = await request.json\u003c{ input: string }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n tools: [{ type: 'web_search' }],\n });\n\n return new Response(JSON.stringify(response), {\n headers: { 'Content-Type': 'application/json' },\n });\n },\n};\n\n// Example: Background mode\nexport const backgroundWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input, responseId } = await request.json\u003c{\n input?: string;\n responseId?: string;\n }>();\n\n // Start background task\n if (input) {\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n background: true,\n });\n\n return new Response(\n JSON.stringify({\n responseId: response.id,\n status: response.status,\n }),\n {\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n // Check status\n if (responseId) {\n const response = await fetch(\n `https://api.openai.com/v1/responses/${responseId}`,\n {\n headers: {\n 'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n },\n }\n );\n\n const data = await response.json();\n\n return new Response(JSON.stringify(data), {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n\n return new Response('Invalid request', { status: 400 });\n },\n};\n\n// Example: Error handling\nexport const errorHandlingWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n try {\n const { input } = await request.json\u003c{ input: string }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n });\n\n return new Response(JSON.stringify(response), {\n headers: { 'Content-Type': 'application/json' },\n });\n } catch (error: any) {\n // Handle specific errors\n if (error.type === 'rate_limit_error') {\n return new Response(\n JSON.stringify({ error: 'Rate limit exceeded', retry_after: error.retry_after }),\n {\n status: 429,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n if (error.type === 'mcp_connection_error') {\n return new Response(\n JSON.stringify({ error: 'MCP server connection failed' }),\n {\n status: 502,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n\n // Generic error\n return new Response(\n JSON.stringify({ error: error.message || 'Internal error' }),\n {\n status: 500,\n headers: { 'Content-Type': 'application/json' },\n }\n );\n }\n },\n};\n\n// Example: Polymorphic outputs\nexport const polymorphicWorker = {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input } = await request.json\u003c{ input: string }>();\n\n const response = await createResponse(env.OPENAI_API_KEY, {\n model: 'gpt-5',\n input,\n tools: [{ type: 'code_interpreter' }, { type: 'web_search' }],\n });\n\n // Process different output types\n const processedOutput: any = {\n text: response.output_text,\n reasoning: [],\n toolCalls: [],\n };\n\n response.output.forEach((item: any) => {\n if (item.type === 'reasoning') {\n processedOutput.reasoning.push(item.summary[0].text);\n }\n if (item.type === 'code_interpreter_call') {\n processedOutput.toolCalls.push({\n type: 'code_interpreter',\n input: item.input,\n output: item.output,\n });\n }\n if (item.type === 'web_search_call') {\n processedOutput.toolCalls.push({\n type: 'web_search',\n query: item.query,\n results: item.results,\n });\n }\n });\n\n return new Response(JSON.stringify(processedOutput), {\n headers: { 'Content-Type': 'application/json' },\n });\n },\n};\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":8794,"content_sha256":"e31b81063bf5b599de277840c940d1ea6202bc5276480b6b4f1c81af1efc18e8"},{"filename":"templates/code-interpreter.ts","content":"/**\n * Code Interpreter Example\n *\n * Demonstrates server-side Python code execution for data analysis,\n * calculations, and visualizations.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicCalculation() {\n console.log('=== Basic Calculation ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Calculate the mean, median, and mode of: 10, 20, 30, 40, 50',\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Response:', response.output_text);\n\n // Inspect code execution\n response.output.forEach((item) => {\n if (item.type === 'code_interpreter_call') {\n console.log('\\nCode executed:');\n console.log(item.input);\n console.log('\\nResult:', item.output);\n }\n });\n}\n\nasync function dataAnalysis() {\n console.log('=== Data Analysis ===\\n');\n\n const salesData = [\n { month: 'Jan', revenue: 10000 },\n { month: 'Feb', revenue: 12000 },\n { month: 'Mar', revenue: 11500 },\n { month: 'Apr', revenue: 13000 },\n { month: 'May', revenue: 14500 },\n { month: 'Jun', revenue: 16000 },\n ];\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: `Analyze this sales data and provide insights:\n${JSON.stringify(salesData, null, 2)}\n\nCalculate:\n1. Total revenue\n2. Average monthly revenue\n3. Growth rate from Jan to Jun\n4. Best performing month`,\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Analysis:', response.output_text);\n}\n\nasync function chartGeneration() {\n console.log('=== Chart Generation ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: `Create a bar chart showing monthly revenue:\n- Jan: $10,000\n- Feb: $12,000\n- Mar: $11,500\n- Apr: $13,000\n- May: $14,500\n- Jun: $16,000`,\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Response:', response.output_text);\n\n // Find chart output\n response.output.forEach((item) => {\n if (item.type === 'code_interpreter_call') {\n console.log('\\nChart code:');\n console.log(item.input);\n\n // Check for file outputs (charts saved as files)\n if (item.outputs) {\n item.outputs.forEach((output) => {\n if (output.type === 'image') {\n console.log('Chart URL:', output.url);\n }\n });\n }\n }\n });\n}\n\nasync function fileProcessing() {\n console.log('=== File Processing ===\\n');\n\n // Upload file first\n const file = await openai.files.create({\n file: Buffer.from('name,age,city\\nAlice,30,NYC\\nBob,25,LA\\nCharlie,35,Chicago'),\n purpose: 'assistants',\n });\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Analyze the CSV file and tell me the average age',\n tools: [\n {\n type: 'code_interpreter',\n file_ids: [file.id], // ✅ Access uploaded file\n },\n ],\n });\n\n console.log('Analysis:', response.output_text);\n}\n\nasync function complexCalculation() {\n console.log('=== Complex Calculation ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: `Solve this math problem step by step:\n\nA company's revenue grows by 15% each year. If the revenue in year 1 is $100,000:\n1. What will the revenue be in year 5?\n2. What is the total revenue across all 5 years?\n3. What year will the revenue first exceed $200,000?`,\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Solution:', response.output_text);\n\n // Show step-by-step reasoning\n response.output.forEach((item) => {\n if (item.type === 'reasoning') {\n console.log('\\nReasoning:', item.summary[0].text);\n }\n if (item.type === 'code_interpreter_call') {\n console.log('\\nCode:', item.input);\n console.log('Result:', item.output);\n }\n });\n}\n\nasync function statisticalAnalysis() {\n console.log('=== Statistical Analysis ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: `Perform statistical analysis on this dataset:\n[12, 15, 18, 20, 22, 25, 28, 30, 35, 40]\n\nCalculate:\n1. Standard deviation\n2. Variance\n3. 25th, 50th, 75th percentiles\n4. Outliers (if any)`,\n tools: [{ type: 'code_interpreter' }],\n });\n\n console.log('Analysis:', response.output_text);\n}\n\nasync function codeInterpreterWithTimeout() {\n console.log('=== Code Interpreter with Background Mode ===\\n');\n\n // For long-running code, use background mode\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Process this large dataset and generate a comprehensive report',\n background: true, // ✅ Extended timeout for long-running code\n tools: [{ type: 'code_interpreter' }],\n });\n\n // Poll for completion\n let result = await openai.responses.retrieve(response.id);\n\n while (result.status === 'in_progress') {\n console.log('Still processing...');\n await new Promise((resolve) => setTimeout(resolve, 5000));\n result = await openai.responses.retrieve(response.id);\n }\n\n if (result.status === 'completed') {\n console.log('Result:', result.output_text);\n } else {\n console.error('Failed:', result.error);\n }\n}\n\nasync function handleCodeInterpreterErrors() {\n console.log('=== Error Handling ===\\n');\n\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Run this Python code: import invalid_module',\n tools: [{ type: 'code_interpreter' }],\n });\n\n // Check for execution errors in output\n response.output.forEach((item) => {\n if (item.type === 'code_interpreter_call' && item.error) {\n console.error('Code execution error:', item.error);\n }\n });\n } catch (error: any) {\n if (error.type === 'code_interpreter_timeout') {\n console.error('Code execution timed out. Use background mode for long tasks.');\n } else {\n console.error('Error:', error.message);\n }\n }\n}\n\n// Run examples\nbasicCalculation();\n// dataAnalysis();\n// chartGeneration();\n// fileProcessing();\n// complexCalculation();\n// statisticalAnalysis();\n// codeInterpreterWithTimeout();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":6088,"content_sha256":"264b95a309c57ab4c44a3105ade4a83eec3bf4f004adccabd527b4c82846fb4c"},{"filename":"templates/file-search.ts","content":"/**\n * File Search Example\n *\n * Demonstrates RAG (Retrieval-Augmented Generation) without building\n * your own vector store. OpenAI handles embeddings and search automatically.\n */\n\nimport OpenAI from 'openai';\nimport fs from 'fs';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicFileSearch() {\n console.log('=== Basic File Search ===\\n');\n\n // 1. Upload file (one-time setup)\n const file = await openai.files.create({\n file: fs.createReadStream('./knowledge-base.pdf'),\n purpose: 'assistants',\n });\n\n console.log('File uploaded:', file.id);\n\n // 2. Search file for information\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What does the document say about pricing?',\n tools: [\n {\n type: 'file_search',\n file_ids: [file.id],\n },\n ],\n });\n\n console.log('Answer:', response.output_text);\n\n // 3. Inspect search results\n response.output.forEach((item) => {\n if (item.type === 'file_search_call') {\n console.log('\\nSearch query:', item.query);\n console.log('Relevant chunks:', item.results.length);\n\n item.results.forEach((result, idx) => {\n console.log(`\\nChunk ${idx + 1}:`);\n console.log('Text:', result.text.substring(0, 200) + '...');\n console.log('Score:', result.score);\n console.log('File:', result.file_id);\n });\n }\n });\n}\n\nasync function multipleFileSearch() {\n console.log('=== Multiple File Search ===\\n');\n\n // Upload multiple files\n const file1 = await openai.files.create({\n file: fs.createReadStream('./product-guide.pdf'),\n purpose: 'assistants',\n });\n\n const file2 = await openai.files.create({\n file: fs.createReadStream('./pricing-doc.pdf'),\n purpose: 'assistants',\n });\n\n const file3 = await openai.files.create({\n file: fs.createReadStream('./faq.pdf'),\n purpose: 'assistants',\n });\n\n // Search across all files\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the key features and how much does the premium plan cost?',\n tools: [\n {\n type: 'file_search',\n file_ids: [file1.id, file2.id, file3.id], // ✅ Multiple files\n },\n ],\n });\n\n console.log('Answer (synthesized from all files):', response.output_text);\n}\n\nasync function conversationalFileSearch() {\n console.log('=== Conversational File Search ===\\n');\n\n // Upload knowledge base\n const file = await openai.files.create({\n file: fs.createReadStream('./company-handbook.pdf'),\n purpose: 'assistants',\n });\n\n // Create conversation\n const conv = await openai.conversations.create();\n\n // First question\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'What is the PTO policy?',\n tools: [{ type: 'file_search', file_ids: [file.id] }],\n });\n\n console.log('Q1:', response1.output_text);\n\n // Follow-up question (model remembers previous answer)\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'How do I request it?',\n tools: [{ type: 'file_search', file_ids: [file.id] }],\n });\n\n console.log('Q2:', response2.output_text);\n // Model knows \"it\" refers to PTO from previous turn\n}\n\nasync function fileSearchWithCitations() {\n console.log('=== File Search with Citations ===\\n');\n\n const file = await openai.files.create({\n file: fs.createReadStream('./research-paper.pdf'),\n purpose: 'assistants',\n });\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Summarize the key findings and provide citations',\n tools: [{ type: 'file_search', file_ids: [file.id] }],\n });\n\n console.log('Summary:', response.output_text);\n\n // Extract citations\n response.output.forEach((item) => {\n if (item.type === 'file_search_call') {\n console.log('\\nCitations:');\n item.results.forEach((result, idx) => {\n console.log(`[${idx + 1}] File: ${result.file_id}, Page: ${result.page || 'N/A'}`);\n });\n }\n });\n}\n\nasync function filterSearchResults() {\n console.log('=== Filter Search Results by Relevance ===\\n');\n\n const file = await openai.files.create({\n file: fs.createReadStream('./large-document.pdf'),\n purpose: 'assistants',\n });\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Find all mentions of \"quarterly revenue\" in the document',\n tools: [{ type: 'file_search', file_ids: [file.id] }],\n });\n\n // Filter high-confidence results\n response.output.forEach((item) => {\n if (item.type === 'file_search_call') {\n const highConfidence = item.results.filter((r) => r.score > 0.7);\n\n console.log(`Found ${highConfidence.length} high-confidence matches:`);\n highConfidence.forEach((result) => {\n console.log('Text:', result.text);\n console.log('Score:', result.score);\n console.log('---');\n });\n }\n });\n}\n\nasync function supportedFileTypes() {\n console.log('=== Supported File Types ===\\n');\n\n // Upload different file types\n const pdfFile = await openai.files.create({\n file: fs.createReadStream('./document.pdf'),\n purpose: 'assistants',\n });\n\n const textFile = await openai.files.create({\n file: fs.createReadStream('./notes.txt'),\n purpose: 'assistants',\n });\n\n const markdownFile = await openai.files.create({\n file: fs.createReadStream('./README.md'),\n purpose: 'assistants',\n });\n\n const codeFile = await openai.files.create({\n file: fs.createReadStream('./main.ts'),\n purpose: 'assistants',\n });\n\n // Search across different file types\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Find information about the authentication system',\n tools: [\n {\n type: 'file_search',\n file_ids: [pdfFile.id, textFile.id, markdownFile.id, codeFile.id],\n },\n ],\n });\n\n console.log('Answer:', response.output_text);\n}\n\nasync function handleFileSearchErrors() {\n console.log('=== Error Handling ===\\n');\n\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Search for information',\n tools: [\n {\n type: 'file_search',\n file_ids: ['file_invalid'], // ❌ Invalid file ID\n },\n ],\n });\n } catch (error: any) {\n if (error.type === 'invalid_request_error') {\n console.error('File not found. Upload file first.');\n } else {\n console.error('Error:', error.message);\n }\n }\n}\n\nasync function listUploadedFiles() {\n console.log('=== List Uploaded Files ===\\n');\n\n const files = await openai.files.list({\n purpose: 'assistants',\n });\n\n console.log(`Found ${files.data.length} files:`);\n files.data.forEach((file) => {\n console.log('ID:', file.id);\n console.log('Filename:', file.filename);\n console.log('Size:', file.bytes, 'bytes');\n console.log('Created:', new Date(file.created_at * 1000));\n console.log('---');\n });\n}\n\nasync function deleteFile(fileId: string) {\n // Delete file (cleanup)\n await openai.files.delete(fileId);\n console.log('File deleted:', fileId);\n}\n\n// Run examples\n// basicFileSearch();\n// multipleFileSearch();\n// conversationalFileSearch();\n// fileSearchWithCitations();\n// filterSearchResults();\n// listUploadedFiles();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":7324,"content_sha256":"faaa5ac5fc37a266577c09319cf8deb491ebf1d4b364e2b63a2a1140f38417e8"},{"filename":"templates/image-generation.ts","content":"/**\n * Image Generation Example\n *\n * Demonstrates integrated DALL-E image generation in the Responses API.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicImageGeneration() {\n console.log('=== Basic Image Generation ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create an image of a futuristic cityscape at sunset',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Response:', response.output_text);\n\n // Find image in output\n response.output.forEach((item) => {\n if (item.type === 'image_generation_call') {\n console.log('\\nPrompt used:', item.prompt);\n console.log('Image URL:', item.output.url);\n console.log('Image expires in 1 hour');\n }\n });\n}\n\nasync function conversationalImageGeneration() {\n console.log('=== Conversational Image Generation ===\\n');\n\n // Create conversation\n const conv = await openai.conversations.create();\n\n // First request\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Create an image of a cartoon cat wearing a wizard hat',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Turn 1:', response1.output_text);\n\n // Modification request (model remembers previous image)\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Make it more colorful and add a magic wand',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Turn 2:', response2.output_text);\n // Model generates new image with modifications\n}\n\nasync function multipleImages() {\n console.log('=== Multiple Images ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create 3 different logo designs for a tech startup',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Response:', response.output_text);\n\n // Collect all images\n const images: string[] = [];\n response.output.forEach((item) => {\n if (item.type === 'image_generation_call') {\n images.push(item.output.url);\n }\n });\n\n console.log(`\\nGenerated ${images.length} images:`);\n images.forEach((url, idx) => {\n console.log(`Image ${idx + 1}: ${url}`);\n });\n}\n\nasync function imageWithSpecifications() {\n console.log('=== Image with Specifications ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: `Create an image with these specifications:\n- Subject: Modern minimalist office space\n- Style: Photorealistic\n- Lighting: Natural daylight from large windows\n- Colors: Neutral tones (white, gray, wood)\n- Details: Include plants and modern furniture`,\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Response:', response.output_text);\n}\n\nasync function imageForPresentation() {\n console.log('=== Image for Presentation ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create a professional infographic showing the growth of AI adoption from 2020 to 2025',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Response:', response.output_text);\n}\n\nasync function saveImageToFile() {\n console.log('=== Save Image to File ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create an image of a mountain landscape',\n tools: [{ type: 'image_generation' }],\n });\n\n // Find and download image\n for (const item of response.output) {\n if (item.type === 'image_generation_call') {\n const imageUrl = item.output.url;\n console.log('Downloading image from:', imageUrl);\n\n // Download image\n const imageResponse = await fetch(imageUrl);\n const imageBuffer = await imageResponse.arrayBuffer();\n\n // Save to file\n const fs = await import('fs');\n fs.writeFileSync('./generated-image.png', Buffer.from(imageBuffer));\n\n console.log('Image saved to: ./generated-image.png');\n }\n }\n}\n\nasync function iterativeImageRefinement() {\n console.log('=== Iterative Image Refinement ===\\n');\n\n const conv = await openai.conversations.create();\n\n // Initial image\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Create a logo for a coffee shop',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Initial design:', response1.output_text);\n\n // Refinement 1\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Make the colors warmer and add a coffee bean illustration',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Refinement 1:', response2.output_text);\n\n // Refinement 2\n const response3 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Perfect! Can you make it circular instead of square?',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Final design:', response3.output_text);\n}\n\nasync function handleImageGenerationErrors() {\n console.log('=== Error Handling ===\\n');\n\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create an image [multiple requests]',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Success:', response.output_text);\n } catch (error: any) {\n if (error.type === 'rate_limit_error') {\n console.error('DALL-E rate limit exceeded');\n console.error('Retry after:', error.headers?.['retry-after']);\n\n // Implement exponential backoff\n const delay = parseInt(error.headers?.['retry-after'] || '5') * 1000;\n console.log(`Waiting ${delay}ms before retry...`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n\n // Retry request\n const retryResponse = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create an image',\n tools: [{ type: 'image_generation' }],\n });\n\n console.log('Retry success:', retryResponse.output_text);\n } else if (error.type === 'content_policy_violation') {\n console.error('Image prompt violates content policy');\n console.error('Please revise prompt to comply with guidelines');\n } else {\n console.error('Error:', error.message);\n }\n }\n}\n\nasync function combinedImageAndAnalysis() {\n console.log('=== Image Generation + Code Interpreter ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create a chart showing sales growth from 2020-2025, then generate an image visualization',\n tools: [\n { type: 'code_interpreter' },\n { type: 'image_generation' },\n ],\n });\n\n console.log('Response:', response.output_text);\n\n // Model uses code interpreter for data, then image generation for visualization\n}\n\n// Run examples\nbasicImageGeneration();\n// conversationalImageGeneration();\n// multipleImages();\n// imageWithSpecifications();\n// saveImageToFile();\n// iterativeImageRefinement();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":7025,"content_sha256":"3baed2545680351c89a67895ca615a4a9b19173ccc97947729056ddc39dd1a17"},{"filename":"templates/mcp-integration.ts","content":"/**\n * MCP Server Integration Example\n *\n * Demonstrates how to connect to external MCP (Model Context Protocol) servers\n * for tool integration. MCP is built into the Responses API.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicMCPIntegration() {\n console.log('=== Basic MCP Integration ===\\n');\n\n // Connect to a public MCP server (dice rolling example)\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Roll 2d6 dice for me',\n tools: [\n {\n type: 'mcp',\n server_label: 'dice',\n server_url: 'https://dmcp.example.com', // Replace with real MCP server\n },\n ],\n });\n\n console.log('Response:', response.output_text);\n\n // Inspect MCP tool calls\n response.output.forEach((item) => {\n if (item.type === 'mcp_list_tools') {\n console.log('\\nDiscovered tools:', item.tools);\n }\n if (item.type === 'mcp_call') {\n console.log('\\nTool called:', item.name);\n console.log('Arguments:', item.arguments);\n console.log('Output:', item.output);\n }\n });\n}\n\nasync function mcpWithAuthentication() {\n console.log('=== MCP with OAuth Authentication ===\\n');\n\n // Connect to Stripe MCP server (requires OAuth token)\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create a payment link for $20',\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: process.env.STRIPE_OAUTH_ACCESS_TOKEN, // ✅ OAuth token\n },\n ],\n });\n\n console.log('Response:', response.output_text);\n\n // Find payment link in output\n response.output.forEach((item) => {\n if (item.type === 'mcp_call' && item.name === 'create_payment_link') {\n console.log('\\nPayment link created:', item.output);\n }\n });\n}\n\nasync function multipleMCPServers() {\n console.log('=== Multiple MCP Servers ===\\n');\n\n // Connect to multiple MCP servers at once\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Check my Stripe balance and create a payment link for the remaining amount',\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: process.env.STRIPE_OAUTH_TOKEN,\n },\n {\n type: 'mcp',\n server_label: 'database',\n server_url: 'https://db-mcp.example.com',\n authorization: process.env.DB_API_KEY,\n },\n ],\n });\n\n console.log('Response:', response.output_text);\n}\n\nasync function mcpWithConversation() {\n console.log('=== MCP with Stateful Conversation ===\\n');\n\n // Create conversation\n const conv = await openai.conversations.create();\n\n // First turn: Use MCP tool\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Create a $50 payment link for premium subscription',\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: process.env.STRIPE_OAUTH_TOKEN,\n },\n ],\n });\n\n console.log('Turn 1:', response1.output_text);\n\n // Second turn: Model remembers previous action\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Can you show me the details of that payment link?',\n });\n\n console.log('Turn 2:', response2.output_text);\n // Model recalls payment link from turn 1\n}\n\nasync function handleMCPErrors() {\n console.log('=== MCP Error Handling ===\\n');\n\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Use the Stripe tool',\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: process.env.STRIPE_OAUTH_TOKEN,\n },\n ],\n });\n\n console.log('Success:', response.output_text);\n } catch (error: any) {\n // Handle specific MCP errors\n if (error.type === 'mcp_connection_error') {\n console.error('MCP server connection failed:', error.message);\n console.error('Check server URL and network connectivity');\n } else if (error.type === 'mcp_authentication_error') {\n console.error('MCP authentication failed:', error.message);\n console.error('Verify authorization token is valid and not expired');\n } else {\n console.error('Unexpected error:', error);\n }\n }\n}\n\n/**\n * Custom MCP Server Example\n *\n * If you want to build your own MCP server, it needs to implement:\n * 1. POST /mcp/list_tools - Return available tools\n * 2. POST /mcp/call_tool - Execute tool and return result\n *\n * Example MCP server response format:\n */\nconst exampleMCPListToolsResponse = {\n tools: [\n {\n name: 'get_weather',\n description: 'Get current weather for a city',\n input_schema: {\n type: 'object',\n properties: {\n city: { type: 'string' },\n units: { type: 'string', enum: ['celsius', 'fahrenheit'] },\n },\n required: ['city'],\n },\n },\n ],\n};\n\nconst exampleMCPCallToolResponse = {\n result: {\n temperature: 72,\n condition: 'sunny',\n humidity: 45,\n },\n};\n\n// Run examples\nbasicMCPIntegration();\n// mcpWithAuthentication();\n// multipleMCPServers();\n// mcpWithConversation();\n// handleMCPErrors();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":5428,"content_sha256":"1e9735f30491751e892113471752a5d5901837040351fad9ebe3dc4c25bda5ec"},{"filename":"templates/package.json","content":"{\n \"name\": \"openai-responses-examples\",\n \"version\": \"1.0.0\",\n \"description\": \"OpenAI Responses API Examples\",\n \"type\": \"module\",\n \"scripts\": {\n \"basic\": \"tsx templates/basic-response.ts\",\n \"conversation\": \"tsx templates/stateful-conversation.ts\",\n \"mcp\": \"tsx templates/mcp-integration.ts\",\n \"code\": \"tsx templates/code-interpreter.ts\",\n \"file\": \"tsx templates/file-search.ts\",\n \"web\": \"tsx templates/web-search.ts\",\n \"image\": \"tsx templates/image-generation.ts\",\n \"background\": \"tsx templates/background-mode.ts\",\n \"worker\": \"wrangler dev templates/cloudflare-worker.ts\"\n },\n \"dependencies\": {\n \"openai\": \"^5.19.1\"\n },\n \"devDependencies\": {\n \"@cloudflare/workers-types\": \"^5.0.0\",\n \"@types/node\": \"^20.0.0\",\n \"tsx\": \"^4.7.1\",\n \"typescript\": \"^5.3.3\",\n \"wrangler\": \"^3.95.0\"\n },\n \"engines\": {\n \"node\": \">=18.0.0\"\n }\n}\n","content_type":"application/json; charset=utf-8","language":"json","size":878,"content_sha256":"aed5981aee220c51aeace47250be0083f505fa997ad9277e96fb36b7797199c1"},{"filename":"templates/stateful-conversation.ts","content":"/**\n * Stateful Conversation Example\n *\n * Demonstrates automatic state management using conversation IDs.\n * The model remembers previous turns automatically.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function automaticStateManagement() {\n console.log('=== Automatic State Management ===\\n');\n\n // 1. Create conversation\n const conversation = await openai.conversations.create({\n metadata: {\n user_id: 'user_123',\n session_type: 'support',\n },\n });\n\n console.log('Conversation ID:', conversation.id);\n\n // 2. First turn\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conversation.id, // ✅ Reuse this ID\n input: 'What are the 5 Ds of dodgeball?',\n });\n\n console.log('Turn 1:', response1.output_text);\n console.log('');\n\n // 3. Second turn - model remembers context\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conversation.id, // ✅ Same ID\n input: 'Tell me more about the first one',\n });\n\n console.log('Turn 2:', response2.output_text);\n // Model knows \"first one\" refers to first D from previous turn\n console.log('');\n\n // 4. Third turn - still remembers everything\n const response3 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conversation.id, // ✅ Same ID\n input: 'What was my original question?',\n });\n\n console.log('Turn 3:', response3.output_text);\n // Model recalls original question from turn 1\n}\n\nasync function manualStateManagement() {\n console.log('=== Manual State Management ===\\n');\n\n // Alternative: Manually manage history array\n let history = [\n { role: 'user', content: 'Tell me a joke' },\n ];\n\n // First turn\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: history,\n store: true, // Optional: store for retrieval later\n });\n\n console.log('Turn 1:', response.output_text);\n\n // Add response to history\n history = [\n ...history,\n ...response.output.map((el) => ({\n role: el.role,\n content: el.content,\n })),\n ];\n\n // Second turn\n history.push({ role: 'user', content: 'Tell me another' });\n\n const secondResponse = await openai.responses.create({\n model: 'gpt-5',\n input: history, // ✅ Full history\n });\n\n console.log('Turn 2:', secondResponse.output_text);\n}\n\nasync function listConversations() {\n // List all conversations (for user dashboard)\n const conversations = await openai.conversations.list({\n limit: 10,\n });\n\n console.log('=== Recent Conversations ===');\n conversations.data.forEach((conv) => {\n console.log('ID:', conv.id);\n console.log('Created:', new Date(conv.created_at * 1000));\n console.log('Metadata:', conv.metadata);\n console.log('');\n });\n}\n\nasync function deleteConversation(conversationId: string) {\n // Delete conversation (cleanup)\n await openai.conversations.delete(conversationId);\n console.log('Conversation deleted:', conversationId);\n}\n\n// Run examples\nautomaticStateManagement();\n// manualStateManagement();\n// listConversations();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":3126,"content_sha256":"05a359dd63f5a927a7c20c5feb273555f24445fb6a61fe641c36bd300807bfa8"},{"filename":"templates/web-search.ts","content":"/**\n * Web Search Example\n *\n * Demonstrates real-time web search for current information.\n * No cutoff date limitations.\n */\n\nimport OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nasync function basicWebSearch() {\n console.log('=== Basic Web Search ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the latest updates on GPT-5?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Answer:', response.output_text);\n\n // Inspect search results\n response.output.forEach((item) => {\n if (item.type === 'web_search_call') {\n console.log('\\nSearch query:', item.query);\n console.log('Sources:', item.results.length);\n\n item.results.forEach((result, idx) => {\n console.log(`\\nSource ${idx + 1}:`);\n console.log('Title:', result.title);\n console.log('URL:', result.url);\n console.log('Snippet:', result.snippet);\n });\n }\n });\n}\n\nasync function currentEvents() {\n console.log('=== Current Events ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the top tech news stories today?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('News summary:', response.output_text);\n}\n\nasync function factChecking() {\n console.log('=== Fact Checking ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Is it true that GPT-5 was released in 2025? Find recent sources.',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Fact check:', response.output_text);\n\n // Get source citations\n response.output.forEach((item) => {\n if (item.type === 'web_search_call') {\n console.log('\\nSources:');\n item.results.forEach((result) => {\n console.log('-', result.url);\n });\n }\n });\n}\n\nasync function researchQuestion() {\n console.log('=== Research Question ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the pros and cons of using Cloudflare Workers for serverless applications?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Research findings:', response.output_text);\n}\n\nasync function conversationalWebSearch() {\n console.log('=== Conversational Web Search ===\\n');\n\n // Create conversation\n const conv = await openai.conversations.create();\n\n // First question\n const response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'What is the current price of Bitcoin?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Q1:', response1.output_text);\n\n // Follow-up question (model remembers previous answer)\n const response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'How has it changed in the last 24 hours?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Q2:', response2.output_text);\n}\n\nasync function comparisonResearch() {\n console.log('=== Comparison Research ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Compare the features and pricing of OpenAI GPT-5 vs Anthropic Claude 3.5 Sonnet',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Comparison:', response.output_text);\n}\n\nasync function localInformation() {\n console.log('=== Local Information ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the best restaurants in San Francisco for Italian food?',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Recommendations:', response.output_text);\n}\n\nasync function productReviews() {\n console.log('=== Product Reviews ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are people saying about the iPhone 16 Pro? Find recent reviews.',\n tools: [{ type: 'web_search' }],\n });\n\n console.log('Review summary:', response.output_text);\n}\n\nasync function combinedTools() {\n console.log('=== Combined Tools (Web Search + Code Interpreter) ===\\n');\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Find the current Bitcoin price and calculate what $1000 would be worth',\n tools: [\n { type: 'web_search' },\n { type: 'code_interpreter' },\n ],\n });\n\n console.log('Answer:', response.output_text);\n\n // Model uses web search to get price, then code interpreter to calculate\n}\n\nasync function webSearchWithFileSearch() {\n console.log('=== Web Search + File Search ===\\n');\n\n // Upload internal document\n const file = await openai.files.create({\n file: Buffer.from('Internal policy: Always check external sources for pricing info'),\n purpose: 'assistants',\n });\n\n const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What is our policy on competitor pricing research?',\n tools: [\n { type: 'file_search', file_ids: [file.id] },\n { type: 'web_search' },\n ],\n });\n\n console.log('Answer:', response.output_text);\n // Model checks internal policy, then searches web if needed\n}\n\n// Run examples\nbasicWebSearch();\n// currentEvents();\n// factChecking();\n// researchQuestion();\n// conversationalWebSearch();\n// comparisonResearch();\n","content_type":"text/typescript; charset=utf-8","language":"typescript","size":5271,"content_sha256":"933ab768867bf1302cf8e7da4b73de221a342baeca5fd946feec1c923cbc625c"}],"content_json":{"type":"doc","content":[{"type":"heading","attrs":{"level":1},"content":[{"text":"OpenAI Responses API","type":"text"}]},{"type":"paragraph","content":[{"text":"Status","type":"text","marks":[{"type":"strong"}]},{"text":": Production Ready ","type":"text"},{"text":"Last Updated","type":"text","marks":[{"type":"strong"}]},{"text":": 2025-10-25 ","type":"text"},{"text":"API Launch","type":"text","marks":[{"type":"strong"}]},{"text":": March 2025 ","type":"text"},{"text":"Dependencies","type":"text","marks":[{"type":"strong"}]},{"text":": [email protected]+ (Node.js) or fetch API (Cloudflare Workers)","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"What Is the Responses API?","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API (","type":"text"},{"text":"/v1/responses","type":"text","marks":[{"type":"code_inline"}]},{"text":") is OpenAI's unified interface for building agentic applications, launched in March 2025. It fundamentally changes how you interact with OpenAI models by providing ","type":"text"},{"text":"stateful conversations","type":"text","marks":[{"type":"strong"}]},{"text":" and a ","type":"text"},{"text":"structured loop for reasoning and acting","type":"text","marks":[{"type":"strong"}]},{"text":".","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Key Innovation: Preserved Reasoning State","type":"text"}]},{"type":"paragraph","content":[{"text":"Unlike Chat Completions where reasoning is discarded between turns, Responses ","type":"text"},{"text":"keeps the notebook open","type":"text","marks":[{"type":"strong"}]},{"text":". The model's step-by-step thought processes survive into the next turn, improving performance by approximately ","type":"text"},{"text":"5% on TAUBench","type":"text","marks":[{"type":"strong"}]},{"text":" and enabling better multi-turn interactions.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Why Use Responses Over Chat Completions?","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Feature","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Chat Completions","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Responses API","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Benefit","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"State Management","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Manual (you track history)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Automatic (conversation IDs)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Simpler code, less error-prone","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Reasoning","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Dropped between turns","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Preserved across turns","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Better multi-turn performance","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tools","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Client-side round trips","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Server-side hosted","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Lower latency, simpler code","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output Format","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Single message","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Polymorphic (messages, reasoning, tool calls)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Richer debugging, better UX","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Cache Utilization","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Baseline","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"40-80% better","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Lower costs, faster responses","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MCP Support","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Manual integration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Built-in","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Easy external tool connections","type":"text"}]}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Quick Start (5 Minutes)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"1. Get API Key","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"# Sign up at https://platform.openai.com/\n# Navigate to API Keys section\n# Create new key and save securely\nexport OPENAI_API_KEY=\"sk-proj-...\"","type":"text"}]},{"type":"paragraph","content":[{"text":"Why this matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API key required for all requests","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Keep secure (never commit to git)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use environment variables","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"2. Install SDK (Node.js)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"bash"},"content":[{"text":"npm install openai","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"import OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the 5 Ds of dodgeball?',\n});\n\nconsole.log(response.output_text);","type":"text"}]},{"type":"paragraph","content":[{"text":"CRITICAL:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Always use server-side (never expose API key in client code)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Model defaults to ","type":"text"},{"text":"gpt-5","type":"text","marks":[{"type":"code_inline"}]},{"text":" (can use ","type":"text"},{"text":"gpt-5-mini","type":"text","marks":[{"type":"code_inline"}]},{"text":", ","type":"text"},{"text":"gpt-4o","type":"text","marks":[{"type":"code_inline"}]},{"text":", etc.)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"input","type":"text","marks":[{"type":"code_inline"}]},{"text":" can be string or array of messages","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"3. Or Use Direct API (Cloudflare Workers)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// No SDK needed - use fetch()\nconst response = await fetch('https://api.openai.com/v1/responses', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: 'gpt-5',\n input: 'Hello, world!',\n }),\n});\n\nconst data = await response.json();\nconsole.log(data.output_text);","type":"text"}]},{"type":"paragraph","content":[{"text":"Why fetch?","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No dependencies in edge environments","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Full control over request/response","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Works in Cloudflare Workers, Deno, Bun","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Responses vs Chat Completions: Complete Comparison","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"When to Use Each","type":"text"}]},{"type":"paragraph","content":[{"text":"Use Responses API when:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Building agentic applications (reasoning + actions)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Need preserved reasoning state across turns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Want built-in tools (Code Interpreter, File Search, Web Search)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Using MCP servers for external integrations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Implementing conversational AI with automatic state management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Background processing for long-running tasks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Need polymorphic outputs (messages, reasoning, tool calls)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Use Chat Completions when:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Simple one-off text generation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Fully stateless interactions (no conversation continuity needed)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Legacy integrations (existing Chat Completions code)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Very simple use cases without tools","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Architecture Differences","type":"text"}]},{"type":"paragraph","content":[{"text":"Chat Completions Flow:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"User Input → Model → Single Message → Done\n(Reasoning discarded, state lost)","type":"text"}]},{"type":"paragraph","content":[{"text":"Responses API Flow:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"User Input → Model (preserved reasoning) → Polymorphic Outputs\n ↓ (server-side tools)\n Tool Call → Tool Result → Model → Final Response\n(Reasoning preserved, state maintained)","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Performance Benefits","type":"text"}]},{"type":"paragraph","content":[{"text":"Cache Utilization:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Chat Completions: Baseline performance","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API: ","type":"text"},{"text":"40-80% better cache utilization","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Result: Lower latency + reduced costs","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Reasoning Performance:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Chat Completions: Reasoning dropped between turns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API: Reasoning preserved across turns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Result: ","type":"text"},{"text":"5% better on TAUBench","type":"text","marks":[{"type":"strong"}]},{"text":" (GPT-5 with Responses vs Chat Completions)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Stateful Conversations","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Automatic State Management","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API can automatically manage conversation state using ","type":"text"},{"text":"conversation IDs","type":"text","marks":[{"type":"strong"}]},{"text":".","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Creating a Conversation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Create conversation with initial message\nconst conversation = await openai.conversations.create({\n metadata: { user_id: 'user_123' },\n items: [\n {\n type: 'message',\n role: 'user',\n content: 'Hello!',\n },\n ],\n});\n\nconsole.log(conversation.id); // \"conv_abc123...\"","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"Using Conversation ID","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// First turn\nconst response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: 'conv_abc123',\n input: 'What are the 5 Ds of dodgeball?',\n});\n\nconsole.log(response1.output_text);\n\n// Second turn - model remembers previous context\nconst response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: 'conv_abc123',\n input: 'Tell me more about the first one',\n});\n\nconsole.log(response2.output_text);\n// Model automatically knows \"first one\" refers to first D from previous turn","type":"text"}]},{"type":"paragraph","content":[{"text":"Why this matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No manual history tracking required","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Reasoning state preserved between turns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automatic context management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Lower risk of context errors","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Manual State Management (Alternative)","type":"text"}]},{"type":"paragraph","content":[{"text":"If you need full control, you can manually manage history:","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"let history = [\n { role: 'user', content: 'Tell me a joke' },\n];\n\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: history,\n store: true, // Optional: store for retrieval later\n});\n\n// Add response to history\nhistory = [\n ...history,\n ...response.output.map(el => ({\n role: el.role,\n content: el.content,\n })),\n];\n\n// Next turn\nhistory.push({ role: 'user', content: 'Tell me another' });\n\nconst secondResponse = await openai.responses.create({\n model: 'gpt-5',\n input: history,\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"When to use manual management:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Need custom history pruning logic","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Want to modify conversation history programmatically","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Implementing custom caching strategies","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Built-in Tools (Server-Side)","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API includes ","type":"text"},{"text":"server-side hosted tools","type":"text","marks":[{"type":"strong"}]},{"text":" that eliminate costly backend round trips.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Available Tools","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Purpose","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use Case","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Code Interpreter","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Execute Python code","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Data analysis, calculations, charts","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"File Search","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"RAG without vector stores","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Search uploaded files for answers","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Web Search","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Real-time web information","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Current events, fact-checking","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Image Generation","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"DALL-E integration","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Create images from descriptions","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"MCP","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Connect external tools","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Stripe, databases, custom APIs","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Code Interpreter","type":"text"}]},{"type":"paragraph","content":[{"text":"Execute Python code server-side for data analysis, calculations, and visualizations.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Calculate the mean, median, and mode of: 10, 20, 30, 40, 50',\n tools: [{ type: 'code_interpreter' }],\n});\n\nconsole.log(response.output_text);\n// Model writes and executes Python code, returns results","type":"text"}]},{"type":"paragraph","content":[{"text":"Advanced Example: Data Analysis","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Analyze this sales data and create a bar chart showing monthly revenue: [data here]',\n tools: [{ type: 'code_interpreter' }],\n});\n\n// Check output for code execution results\nresponse.output.forEach(item => {\n if (item.type === 'code_interpreter_call') {\n console.log('Code executed:', item.input);\n console.log('Result:', item.output);\n }\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"Why this matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No need to run Python locally","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Sandboxed execution environment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automatic chart generation","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Can process uploaded files","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"File Search (RAG Without Vector Stores)","type":"text"}]},{"type":"paragraph","content":[{"text":"Search through uploaded files without building your own RAG pipeline.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// 1. Upload files first (one-time setup)\nconst file = await openai.files.create({\n file: fs.createReadStream('knowledge-base.pdf'),\n purpose: 'assistants',\n});\n\n// 2. Use file search\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What does the document say about pricing?',\n tools: [\n {\n type: 'file_search',\n file_ids: [file.id],\n },\n ],\n});\n\nconsole.log(response.output_text);\n// Model searches file and provides answer with citations","type":"text"}]},{"type":"paragraph","content":[{"text":"Supported File Types:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"PDFs, Word docs, text files","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Markdown, HTML","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Code files (Python, JavaScript, etc.)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Max: 512MB per file","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Web Search","type":"text"}]},{"type":"paragraph","content":[{"text":"Get real-time information from the web.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'What are the latest updates on GPT-5?',\n tools: [{ type: 'web_search' }],\n});\n\nconsole.log(response.output_text);\n// Model searches web and provides current information with sources","type":"text"}]},{"type":"paragraph","content":[{"text":"Why this matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No cutoff date limitations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Automatic source citations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Real-time data access","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No need for external search APIs","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Image Generation (DALL-E)","type":"text"}]},{"type":"paragraph","content":[{"text":"Generate images directly in the Responses API.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create an image of a futuristic cityscape at sunset',\n tools: [{ type: 'image_generation' }],\n});\n\n// Find image in output\nresponse.output.forEach(item => {\n if (item.type === 'image_generation_call') {\n console.log('Image URL:', item.output.url);\n }\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"Models Available:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"DALL-E 3 (default)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Various sizes and quality options","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"MCP Server Integration","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API has built-in support for ","type":"text"},{"text":"Model Context Protocol (MCP)","type":"text","marks":[{"type":"strong"}]},{"text":" servers, allowing you to connect external tools.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"What Is MCP?","type":"text"}]},{"type":"paragraph","content":[{"text":"MCP is an open protocol that standardizes how applications provide context to LLMs. It allows you to:","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Connect to external APIs (Stripe, databases, CRMs)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use hosted MCP servers","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Build custom tool integrations","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Basic MCP Integration","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Roll 2d6 dice',\n tools: [\n {\n type: 'mcp',\n server_label: 'dice',\n server_url: 'https://example.com/mcp',\n },\n ],\n});\n\n// Model discovers available tools on MCP server and uses them\nconsole.log(response.output_text);","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"MCP with Authentication (OAuth)","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Create a $20 payment link',\n tools: [\n {\n type: 'mcp',\n server_label: 'stripe',\n server_url: 'https://mcp.stripe.com',\n authorization: process.env.STRIPE_OAUTH_TOKEN,\n },\n ],\n});\n\nconsole.log(response.output_text);\n// Model uses Stripe MCP server to create payment link","type":"text"}]},{"type":"paragraph","content":[{"text":"CRITICAL:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API does NOT store authorization tokens","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Must provide token with each request","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use environment variables for security","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Polymorphic Output: MCP Tool Calls","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Roll 2d4+1',\n tools: [\n {\n type: 'mcp',\n server_label: 'dice',\n server_url: 'https://dmcp.example.com',\n },\n ],\n});\n\n// Inspect tool calls\nresponse.output.forEach(item => {\n if (item.type === 'mcp_call') {\n console.log('Tool:', item.name);\n console.log('Arguments:', item.arguments);\n console.log('Output:', item.output);\n }\n if (item.type === 'mcp_list_tools') {\n console.log('Available tools:', item.tools);\n }\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"Output Types:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"mcp_list_tools","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Tools discovered on server","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"mcp_call","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Tool invocation and result","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"message","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Final response to user","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Reasoning Preservation","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"How It Works","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API preserves the model's ","type":"text"},{"text":"internal reasoning state","type":"text","marks":[{"type":"strong"}]},{"text":" across turns, unlike Chat Completions which discards it.","type":"text"}]},{"type":"paragraph","content":[{"text":"Visual Analogy:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Chat Completions","type":"text","marks":[{"type":"strong"}]},{"text":": Model has a scratchpad, writes reasoning, then ","type":"text"},{"text":"tears out the page","type":"text","marks":[{"type":"strong"}]},{"text":" before responding","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API","type":"text","marks":[{"type":"strong"}]},{"text":": Model keeps the scratchpad open, ","type":"text"},{"text":"previous reasoning visible","type":"text","marks":[{"type":"strong"}]},{"text":" for next turn","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Performance Impact","type":"text"}]},{"type":"paragraph","content":[{"text":"TAUBench Results (GPT-5):","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Chat Completions: Baseline score","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API: ","type":"text"},{"text":"+5% better","type":"text","marks":[{"type":"strong"}]},{"text":" (purely from preserved reasoning)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Why This Matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Better multi-turn problem solving","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"More coherent long conversations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Improved step-by-step reasoning","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Fewer context errors","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Reasoning Summaries (Free!)","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API provides ","type":"text"},{"text":"reasoning summaries","type":"text","marks":[{"type":"strong"}]},{"text":" at no additional cost.","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Solve this complex math problem: [problem]',\n});\n\n// Inspect reasoning\nresponse.output.forEach(item => {\n if (item.type === 'reasoning') {\n console.log('Model reasoning:', item.summary[0].text);\n }\n if (item.type === 'message') {\n console.log('Final answer:', item.content[0].text);\n }\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"Use Cases:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Debugging model decisions","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit trails for compliance","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Understanding model thought process","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Building transparent AI systems","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Background Mode (Long-Running Tasks)","type":"text"}]},{"type":"paragraph","content":[{"text":"For tasks that take longer than standard timeout limits, use ","type":"text"},{"text":"background mode","type":"text","marks":[{"type":"strong"}]},{"text":".","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Analyze this 500-page document and summarize key findings',\n background: true,\n tools: [{ type: 'file_search', file_ids: [fileId] }],\n});\n\n// Returns immediately with status\nconsole.log(response.status); // \"in_progress\"\nconsole.log(response.id); // Use to check status later\n\n// Poll for completion\nconst checkStatus = async (responseId) => {\n const result = await openai.responses.retrieve(responseId);\n if (result.status === 'completed') {\n console.log(result.output_text);\n } else if (result.status === 'failed') {\n console.error('Task failed:', result.error);\n } else {\n // Still running, check again later\n setTimeout(() => checkStatus(responseId), 5000);\n }\n};\n\ncheckStatus(response.id);","type":"text"}]},{"type":"paragraph","content":[{"text":"When to Use:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Large file processing","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Complex calculations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Multi-step research tasks","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Data analysis on large datasets","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Timeout Limits:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Standard mode: 60 seconds","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Background mode: Up to 10 minutes","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Polymorphic Outputs","type":"text"}]},{"type":"paragraph","content":[{"text":"The Responses API returns ","type":"text"},{"text":"multiple output types","type":"text","marks":[{"type":"strong"}]},{"text":" instead of a single message.","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Output Types","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Type","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Description","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Example","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"message","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Text response to user","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Final answer, explanation","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"reasoning","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Model's internal thought process","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Step-by-step reasoning summary","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"code_interpreter_call","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Code execution","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Python code + results","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"mcp_call","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool invocation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool name, args, output","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"mcp_list_tools","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Available tools","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tool definitions from MCP server","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"file_search_call","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"File search results","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Matched chunks, citations","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"web_search_call","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Web search results","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"URLs, snippets","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"image_generation_call","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Image generation","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Image URL","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Processing Polymorphic Outputs","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Search the web for the latest AI news and summarize',\n tools: [{ type: 'web_search' }],\n});\n\n// Process different output types\nresponse.output.forEach(item => {\n switch (item.type) {\n case 'reasoning':\n console.log('Reasoning:', item.summary[0].text);\n break;\n case 'web_search_call':\n console.log('Searched:', item.query);\n console.log('Sources:', item.results);\n break;\n case 'message':\n console.log('Response:', item.content[0].text);\n break;\n }\n});\n\n// Or use helper for text-only\nconsole.log(response.output_text);","type":"text"}]},{"type":"paragraph","content":[{"text":"Why This Matters:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Better debugging (see all steps)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Audit trails (track all tool calls)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Richer UX (show progress to users)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Compliance (log all actions)","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Migration from Chat Completions","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Breaking Changes","type":"text"}]},{"type":"table","attrs":{"layout":null},"content":[{"type":"tr","content":[{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Feature","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Chat Completions","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Responses API","type":"text"}]}]},{"type":"th","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Migration","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Endpoint","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/v1/chat/completions","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"/v1/responses","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Update URL","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Parameter","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"messages","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"input","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Rename parameter","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"State","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Manual (","type":"text"},{"text":"messages","type":"text","marks":[{"type":"code_inline"}]},{"text":" array)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Automatic (","type":"text"},{"text":"conversation","type":"text","marks":[{"type":"code_inline"}]},{"text":" ID)","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Use conversation IDs","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Tools","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"tools","type":"text","marks":[{"type":"code_inline"}]},{"text":" array with functions","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Built-in types + MCP","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Update tool definitions","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Output","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"choices[0].message.content","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"output_text","type":"text","marks":[{"type":"code_inline"}]},{"text":" or ","type":"text"},{"text":"output","type":"text","marks":[{"type":"code_inline"}]},{"text":" array","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Update response parsing","type":"text"}]}]}]},{"type":"tr","content":[{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Streaming","type":"text","marks":[{"type":"strong"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"data: {\"choices\":[...]}","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"SSE with multiple item types","type":"text"}]}]},{"type":"td","attrs":{"colspan":1,"rowspan":1,"colwidth":null,"alignment":""},"content":[{"type":"paragraph","content":[{"text":"Update stream parser","type":"text"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Migration Example","type":"text"}]},{"type":"paragraph","content":[{"text":"Before (Chat Completions):","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.chat.completions.create({\n model: 'gpt-5',\n messages: [\n { role: 'system', content: 'You are a helpful assistant.' },\n { role: 'user', content: 'Hello!' },\n ],\n});\n\nconsole.log(response.choices[0].message.content);","type":"text"}]},{"type":"paragraph","content":[{"text":"After (Responses):","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n model: 'gpt-5',\n input: [\n { role: 'developer', content: 'You are a helpful assistant.' },\n { role: 'user', content: 'Hello!' },\n ],\n});\n\nconsole.log(response.output_text);","type":"text"}]},{"type":"paragraph","content":[{"text":"Key Differences:","type":"text","marks":[{"type":"strong"}]}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"chat.completions.create","type":"text","marks":[{"type":"code_inline"}]},{"text":" → ","type":"text"},{"text":"responses.create","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"messages","type":"text","marks":[{"type":"code_inline"}]},{"text":" → ","type":"text"},{"text":"input","type":"text","marks":[{"type":"code_inline"}]}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"system","type":"text","marks":[{"type":"code_inline"}]},{"text":" role → ","type":"text"},{"text":"developer","type":"text","marks":[{"type":"code_inline"}]},{"text":" role","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"choices[0].message.content","type":"text","marks":[{"type":"code_inline"}]},{"text":" → ","type":"text"},{"text":"output_text","type":"text","marks":[{"type":"code_inline"}]}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"When to Migrate","type":"text"}]},{"type":"paragraph","content":[{"text":"Migrate now if:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Building new applications","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Need stateful conversations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Using agentic patterns (reasoning + tools)","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Want better performance (preserved reasoning)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Stay on Chat Completions if:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Simple one-off generations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Legacy integrations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ No need for state management","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Error Handling","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Common Errors and Solutions","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"1. Session State Not Persisting","type":"text"}]},{"type":"paragraph","content":[{"text":"Error:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":""},"content":[{"text":"Conversation state not maintained between turns","type":"text"}]},{"type":"paragraph","content":[{"text":"Cause:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Not using conversation IDs","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Using different conversation IDs per turn","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Create conversation once\nconst conv = await openai.conversations.create();\n\n// Reuse conversation ID for all turns\nconst response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id, // ✅ Same ID\n input: 'First message',\n});\n\nconst response2 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id, // ✅ Same ID\n input: 'Follow-up message',\n});","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"2. MCP Server Connection Failed","type":"text"}]},{"type":"paragraph","content":[{"text":"Error:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"json"},"content":[{"text":"{\n \"error\": {\n \"type\": \"mcp_connection_error\",\n \"message\": \"Failed to connect to MCP server\"\n }\n}","type":"text"}]},{"type":"paragraph","content":[{"text":"Causes:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Invalid server URL","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Missing or expired authorization token","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Server not responding","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solutions:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// 1. Verify URL is correct\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Test MCP',\n tools: [\n {\n type: 'mcp',\n server_label: 'test',\n server_url: 'https://api.example.com/mcp', // ✅ Full URL\n authorization: process.env.AUTH_TOKEN, // ✅ Valid token\n },\n ],\n});\n\n// 2. Test server URL manually\nconst testResponse = await fetch('https://api.example.com/mcp');\nconsole.log(testResponse.status); // Should be 200\n\n// 3. Check token expiration\nconsole.log('Token expires:', parseJWT(token).exp);","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"3. Code Interpreter Timeout","type":"text"}]},{"type":"paragraph","content":[{"text":"Error:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"json"},"content":[{"text":"{\n \"error\": {\n \"type\": \"code_interpreter_timeout\",\n \"message\": \"Code execution exceeded time limit\"\n }\n}","type":"text"}]},{"type":"paragraph","content":[{"text":"Cause:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Code runs longer than 30 seconds","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Use background mode for long-running code\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Process this large dataset',\n background: true, // ✅ Extended timeout\n tools: [{ type: 'code_interpreter' }],\n});\n\n// Poll for results\nconst result = await openai.responses.retrieve(response.id);","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"4. Image Generation Rate Limit","type":"text"}]},{"type":"paragraph","content":[{"text":"Error:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"json"},"content":[{"text":"{\n \"error\": {\n \"type\": \"rate_limit_error\",\n \"message\": \"DALL-E rate limit exceeded\"\n }\n}","type":"text"}]},{"type":"paragraph","content":[{"text":"Cause:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Too many image generation requests","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Implement retry with exponential backoff\nconst generateImage = async (prompt, retries = 3) => {\n try {\n return await openai.responses.create({\n model: 'gpt-5',\n input: prompt,\n tools: [{ type: 'image_generation' }],\n });\n } catch (error) {\n if (error.type === 'rate_limit_error' && retries > 0) {\n const delay = (4 - retries) * 1000; // 1s, 2s, 3s\n await new Promise(resolve => setTimeout(resolve, delay));\n return generateImage(prompt, retries - 1);\n }\n throw error;\n }\n};","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"5. File Search Relevance Issues","type":"text"}]},{"type":"paragraph","content":[{"text":"Problem:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"File search returns irrelevant results","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Use more specific queries\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Find sections about pricing in Q4 2024 specifically', // ✅ Specific\n // NOT: 'Find pricing' (too vague)\n tools: [{ type: 'file_search', file_ids: [fileId] }],\n});\n\n// Or filter results manually\nresponse.output.forEach(item => {\n if (item.type === 'file_search_call') {\n const relevantChunks = item.results.filter(\n chunk => chunk.score > 0.7 // ✅ Only high-confidence matches\n );\n }\n});","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"6. Cost Tracking Confusion","type":"text"}]},{"type":"paragraph","content":[{"text":"Problem:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Billing different than expected","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Explanation:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API bills for: input tokens + output tokens + tool usage + stored conversations","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Chat Completions bills only: input tokens + output tokens","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Monitor usage\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Hello',\n store: false, // ✅ Don't store if not needed\n});\n\nconsole.log('Usage:', response.usage);\n// {\n// prompt_tokens: 10,\n// completion_tokens: 20,\n// tool_tokens: 5,\n// total_tokens: 35\n// }","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"7. Conversation Not Found","type":"text"}]},{"type":"paragraph","content":[{"text":"Error:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"json"},"content":[{"text":"{\n \"error\": {\n \"type\": \"invalid_request_error\",\n \"message\": \"Conversation conv_xyz not found\"\n }\n}","type":"text"}]},{"type":"paragraph","content":[{"text":"Causes:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conversation ID typo","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conversation deleted","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Conversation expired (90 days)","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Verify conversation exists before using\nconst conversations = await openai.conversations.list();\nconst exists = conversations.data.some(c => c.id === 'conv_xyz');\n\nif (!exists) {\n // Create new conversation\n const newConv = await openai.conversations.create();\n // Use newConv.id\n}","type":"text"}]},{"type":"heading","attrs":{"level":4},"content":[{"text":"8. Tool Output Parsing Failed","type":"text"}]},{"type":"paragraph","content":[{"text":"Problem:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Can't access tool outputs correctly","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Solution:","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// Use helper methods\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Search for AI news',\n tools: [{ type: 'web_search' }],\n});\n\n// Helper: Get text-only output\nconsole.log(response.output_text);\n\n// Manual: Inspect all outputs\nresponse.output.forEach(item => {\n console.log('Type:', item.type);\n console.log('Content:', item);\n});","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Production Patterns","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Cost Optimization","type":"text"}]},{"type":"paragraph","content":[{"text":"1. Use Conversation IDs (Cache Benefits)","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ✅ GOOD: Reuse conversation ID\nconst conv = await openai.conversations.create();\nconst response1 = await openai.responses.create({\n model: 'gpt-5',\n conversation: conv.id,\n input: 'Question 1',\n});\n// 40-80% better cache utilization\n\n// ❌ BAD: New manual history each time\nconst response2 = await openai.responses.create({\n model: 'gpt-5',\n input: [...previousHistory, newMessage],\n});\n// No cache benefits","type":"text"}]},{"type":"paragraph","content":[{"text":"2. Disable Storage When Not Needed","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// For one-off requests\nconst response = await openai.responses.create({\n model: 'gpt-5',\n input: 'Quick question',\n store: false, // ✅ Don't store conversation\n});","type":"text"}]},{"type":"paragraph","content":[{"text":"3. Use Smaller Models When Possible","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// For simple tasks\nconst response = await openai.responses.create({\n model: 'gpt-5-mini', // ✅ 50% cheaper\n input: 'Summarize this paragraph',\n});","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Rate Limit Handling","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const createResponseWithRetry = async (params, maxRetries = 3) => {\n for (let i = 0; i \u003c maxRetries; i++) {\n try {\n return await openai.responses.create(params);\n } catch (error) {\n if (error.type === 'rate_limit_error' && i \u003c maxRetries - 1) {\n const delay = Math.pow(2, i) * 1000; // Exponential backoff\n console.log(`Rate limited, retrying in ${delay}ms`);\n await new Promise(resolve => setTimeout(resolve, delay));\n } else {\n throw error;\n }\n }\n }\n};","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Monitoring and Logging","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const monitoredResponse = async (input) => {\n const startTime = Date.now();\n\n try {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input,\n });\n\n // Log success metrics\n console.log({\n status: 'success',\n latency: Date.now() - startTime,\n tokens: response.usage.total_tokens,\n model: response.model,\n conversation: response.conversation_id,\n });\n\n return response;\n } catch (error) {\n // Log error metrics\n console.error({\n status: 'error',\n latency: Date.now() - startTime,\n error: error.message,\n type: error.type,\n });\n throw error;\n }\n};","type":"text"}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Node.js vs Cloudflare Workers","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Node.js Implementation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"import OpenAI from 'openai';\n\nconst openai = new OpenAI({\n apiKey: process.env.OPENAI_API_KEY,\n});\n\nexport async function handleRequest(input: string) {\n const response = await openai.responses.create({\n model: 'gpt-5',\n input,\n tools: [{ type: 'web_search' }],\n });\n\n return response.output_text;\n}","type":"text"}]},{"type":"paragraph","content":[{"text":"Pros:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Full SDK support","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Type safety","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Streaming helpers","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Cons:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Requires Node.js runtime","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Larger bundle size","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Cloudflare Workers Implementation","type":"text"}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"export default {\n async fetch(request: Request, env: Env): Promise\u003cResponse> {\n const { input } = await request.json();\n\n const response = await fetch('https://api.openai.com/v1/responses', {\n method: 'POST',\n headers: {\n 'Authorization': `Bearer ${env.OPENAI_API_KEY}`,\n 'Content-Type': 'application/json',\n },\n body: JSON.stringify({\n model: 'gpt-5',\n input,\n tools: [{ type: 'web_search' }],\n }),\n });\n\n const data = await response.json();\n\n return new Response(data.output_text, {\n headers: { 'Content-Type': 'text/plain' },\n });\n },\n};","type":"text"}]},{"type":"paragraph","content":[{"text":"Pros:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No dependencies","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Edge deployment","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Faster cold starts","type":"text"}]}]}]},{"type":"paragraph","content":[{"text":"Cons:","type":"text","marks":[{"type":"strong"}]}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Manual request building","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"No type safety without custom types","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Always Do / Never Do","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"✅ Always Do","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use conversation IDs for multi-turn interactions","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const conv = await openai.conversations.create();\n// Reuse conv.id for all related turns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Handle all output types in polymorphic responses","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"response.output.forEach(item => {\n if (item.type === 'reasoning') { /* log */ }\n if (item.type === 'message') { /* display */ }\n});","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Use background mode for long-running tasks","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"const response = await openai.responses.create({\n background: true, // ✅ For tasks >30s\n ...\n});","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Provide authorization tokens for MCP servers","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"tools: [{\n type: 'mcp',\n authorization: process.env.TOKEN, // ✅ Required\n}]","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Monitor token usage for cost control","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"console.log(response.usage.total_tokens);","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"❌ Never Do","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never expose API keys in client-side code","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ❌ DANGER: API key in browser\nconst response = await fetch('https://api.openai.com/v1/responses', {\n headers: { 'Authorization': 'Bearer sk-proj-...' }\n});","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never assume single message output","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ❌ BAD: Ignores reasoning, tool calls\nconsole.log(response.output[0].content);\n\n// ✅ GOOD: Use helper or check all types\nconsole.log(response.output_text);","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never reuse conversation IDs across users","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ❌ DANGER: User A sees User B's conversation\nconst sharedConv = 'conv_123';","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never ignore error types","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ❌ BAD: Generic error handling\ntry { ... } catch (e) { console.log('error'); }\n\n// ✅ GOOD: Type-specific handling\ncatch (e) {\n if (e.type === 'rate_limit_error') { /* retry */ }\n if (e.type === 'mcp_connection_error') { /* alert */ }\n}","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Never poll faster than 1 second for background tasks","type":"text","marks":[{"type":"strong"}]}]},{"type":"code_block","attrs":{"wrap":false,"language":"typescript"},"content":[{"text":"// ❌ BAD: Too frequent\nsetInterval(() => checkStatus(), 100);\n\n// ✅ GOOD: Reasonable interval\nsetInterval(() => checkStatus(), 5000);","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"References","type":"text"}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Official Documentation","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Responses API Guide","type":"text","marks":[{"type":"strong"}]},{"text":": https://platform.openai.com/docs/guides/responses","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"API Reference","type":"text","marks":[{"type":"strong"}]},{"text":": https://platform.openai.com/docs/api-reference/responses","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"MCP Integration","type":"text","marks":[{"type":"strong"}]},{"text":": https://platform.openai.com/docs/guides/tools-connectors-mcp","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Blog Post (Why Responses API)","type":"text","marks":[{"type":"strong"}]},{"text":": https://developers.openai.com/blog/responses-api/","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"Starter App","type":"text","marks":[{"type":"strong"}]},{"text":": https://github.com/openai/openai-responses-starter-app","type":"text"}]}]}]},{"type":"heading","attrs":{"level":3},"content":[{"text":"Skill Resources","type":"text"}]},{"type":"bullet_list","content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"templates/","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Working code examples","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/responses-vs-chat-completions.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Feature comparison","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/mcp-integration-guide.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - MCP server setup","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/built-in-tools-guide.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Tool usage patterns","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/stateful-conversations.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Conversation management","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/migration-guide.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Chat Completions → Responses","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"references/top-errors.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Common errors and solutions","type":"text"}]}]}]},{"type":"hr","attrs":{"markup":"---"}},{"type":"heading","attrs":{"level":2},"content":[{"text":"Next Steps","type":"text"}]},{"type":"ordered_list","attrs":{"order":1,"listStyle":"number"},"content":[{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Read ","type":"text"},{"text":"templates/basic-response.ts","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Simple example","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Try ","type":"text"},{"text":"templates/stateful-conversation.ts","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Multi-turn chat","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Explore ","type":"text"},{"text":"templates/mcp-integration.ts","type":"text","marks":[{"type":"code_inline"}]},{"text":" - External tools","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Review ","type":"text"},{"text":"references/top-errors.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - Avoid common pitfalls","type":"text"}]}]},{"type":"list_item","content":[{"type":"paragraph","content":[{"text":"✅ Check ","type":"text"},{"text":"references/migration-guide.md","type":"text","marks":[{"type":"code_inline"}]},{"text":" - If migrating from Chat Completions","type":"text"}]}]}]},{"type":"heading","attrs":{"level":2},"content":[{"text":"Happy building with the Responses API!","type":"text","marks":[{"type":"strong"}]},{"text":" 🚀","type":"text"}]}]},"metadata":{"date":"2026-06-05","name":"openai-responses","author":"@skillopedia","source":{"stars":44,"repo_name":"droid-tings","origin_url":"https://github.com/ovachiever/droid-tings/blob/HEAD/skills/openai-responses/SKILL.md","repo_owner":"ovachiever","body_sha256":"fc55f8b6dfde6343acf0cdf6cd5c6b9ceca7d96834b577f6351ee7631593ac5c","cluster_key":"b65102efbf9e75b1f39bba81b2605e78a82e9680740587576038e23e9387d6f3","clean_bundle":{"format":"clean-skill-bundle-v1","source":"ovachiever/droid-tings/skills/openai-responses/SKILL.md","attachments":[{"id":"8e225198-c8b9-59b2-9129-1edc3d7bd326","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/8e225198-c8b9-59b2-9129-1edc3d7bd326/attachment.json","path":".claude-plugin/plugin.json","size":753,"sha256":"33fe15b2c9ccb1a797aecffcffba1c633c4ca2b4e2757b2f87ecdc2a11bc45a4","contentType":"application/json; charset=utf-8"},{"id":"5898c8a9-6af5-5bee-91e3-a0c55e2c306b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/5898c8a9-6af5-5bee-91e3-a0c55e2c306b/attachment.md","path":"README.md","size":12006,"sha256":"e00c618abdc3e2c28c9db503cd85cc6b0ec7a57424e141d87eddb89dca0e6103","contentType":"text/markdown; charset=utf-8"},{"id":"d109f211-513d-52a5-b5e8-747d48e5953f","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/d109f211-513d-52a5-b5e8-747d48e5953f/attachment.md","path":"references/built-in-tools-guide.md","size":2699,"sha256":"a07254faa0f53ac67ab91287bdbfc6b36f3a520cd06b6b8a694e357611911886","contentType":"text/markdown; charset=utf-8"},{"id":"58779886-ec03-55f6-9cbd-2b725f25f38c","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/58779886-ec03-55f6-9cbd-2b725f25f38c/attachment.md","path":"references/mcp-integration-guide.md","size":2505,"sha256":"7274e02438b844693d333b2930c42d698965397aec93721b64d8096e3c686f87","contentType":"text/markdown; charset=utf-8"},{"id":"2bc1e39d-91c7-59df-b1cf-23cfe582994b","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/2bc1e39d-91c7-59df-b1cf-23cfe582994b/attachment.md","path":"references/migration-guide.md","size":4774,"sha256":"a11440e235ecee2612191575546d34efc70acac477fc4d2b9ef3d2c04c490deb","contentType":"text/markdown; charset=utf-8"},{"id":"125c6444-549f-592e-a679-323a0dd4c5f2","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/125c6444-549f-592e-a679-323a0dd4c5f2/attachment.md","path":"references/reasoning-preservation.md","size":1586,"sha256":"4ab83ec57388f0bff560d750da5764c9fddd45c34a79fb465936bff2ee0ba8a9","contentType":"text/markdown; charset=utf-8"},{"id":"7690652f-2518-535d-b64e-cafc31b4dac1","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/7690652f-2518-535d-b64e-cafc31b4dac1/attachment.md","path":"references/responses-vs-chat-completions.md","size":11754,"sha256":"6683958e7c68c112794e9dae815c5961a403f3890fe6c46d00d966caa83f72c2","contentType":"text/markdown; charset=utf-8"},{"id":"0f2fe925-4b68-5f4d-83d1-81d7d5fb7dc5","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/0f2fe925-4b68-5f4d-83d1-81d7d5fb7dc5/attachment.md","path":"references/stateful-conversations.md","size":1695,"sha256":"b961ac639b3229f5e5d79212cbcb95fc23bdc536a966fabbe7717baa5b881f41","contentType":"text/markdown; charset=utf-8"},{"id":"ab92f1ed-0ecf-50f1-8c22-53b993f6c876","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/ab92f1ed-0ecf-50f1-8c22-53b993f6c876/attachment.md","path":"references/top-errors.md","size":11342,"sha256":"f3666d2f2c2e1e25fb01b6885e606b46e1d62dd41dee517e47cec98e46171fbc","contentType":"text/markdown; charset=utf-8"},{"id":"0b28acfb-98b6-59f9-8870-6ecf89d1a5fc","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/0b28acfb-98b6-59f9-8870-6ecf89d1a5fc/attachment.sh","path":"scripts/check-versions.sh","size":2905,"sha256":"7368ff263e5d286d5f5ba19df227429b99fef4ec90292110cf64d84078088f5a","contentType":"application/x-sh; charset=utf-8"},{"id":"7fa3184e-826d-5152-85ca-dd1929390254","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/7fa3184e-826d-5152-85ca-dd1929390254/attachment.ts","path":"templates/background-mode.ts","size":7910,"sha256":"47628f8c9307577a04e1338fe3b165221189f42902b78a8beb3c86ac7aec53f8","contentType":"text/typescript; charset=utf-8"},{"id":"af4efe82-e948-5a7b-a954-f9b4e1952583","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/af4efe82-e948-5a7b-a954-f9b4e1952583/attachment.ts","path":"templates/basic-response.ts","size":1625,"sha256":"82a3fe9b5836fe7c7b417f1454d8fe6b9a895a3122acdc1e4a729ce04faa423c","contentType":"text/typescript; charset=utf-8"},{"id":"05101938-4a0f-569b-b077-f3d86f14bc5a","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/05101938-4a0f-569b-b077-f3d86f14bc5a/attachment.ts","path":"templates/cloudflare-worker.ts","size":8794,"sha256":"e31b81063bf5b599de277840c940d1ea6202bc5276480b6b4f1c81af1efc18e8","contentType":"text/typescript; charset=utf-8"},{"id":"b265df65-f868-52d9-960c-663870326d27","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/b265df65-f868-52d9-960c-663870326d27/attachment.ts","path":"templates/code-interpreter.ts","size":6088,"sha256":"264b95a309c57ab4c44a3105ade4a83eec3bf4f004adccabd527b4c82846fb4c","contentType":"text/typescript; charset=utf-8"},{"id":"1860649a-f12e-51c1-8f9f-1cb164c7885d","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/1860649a-f12e-51c1-8f9f-1cb164c7885d/attachment.ts","path":"templates/file-search.ts","size":7324,"sha256":"faaa5ac5fc37a266577c09319cf8deb491ebf1d4b364e2b63a2a1140f38417e8","contentType":"text/typescript; charset=utf-8"},{"id":"e873dfce-baf8-5c5a-be3d-d8a7bc9e16c8","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/e873dfce-baf8-5c5a-be3d-d8a7bc9e16c8/attachment.ts","path":"templates/image-generation.ts","size":7025,"sha256":"3baed2545680351c89a67895ca615a4a9b19173ccc97947729056ddc39dd1a17","contentType":"text/typescript; charset=utf-8"},{"id":"995d202e-c2c0-5f9a-9465-4c19f8d68012","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/995d202e-c2c0-5f9a-9465-4c19f8d68012/attachment.ts","path":"templates/mcp-integration.ts","size":5428,"sha256":"1e9735f30491751e892113471752a5d5901837040351fad9ebe3dc4c25bda5ec","contentType":"text/typescript; charset=utf-8"},{"id":"65d1d3c1-082a-5cf2-a14f-e142da4dcdcf","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/65d1d3c1-082a-5cf2-a14f-e142da4dcdcf/attachment.json","path":"templates/package.json","size":878,"sha256":"aed5981aee220c51aeace47250be0083f505fa997ad9277e96fb36b7797199c1","contentType":"application/json; charset=utf-8"},{"id":"53312013-d9d1-5326-b5c3-7335b6f610cb","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/53312013-d9d1-5326-b5c3-7335b6f610cb/attachment.ts","path":"templates/stateful-conversation.ts","size":3126,"sha256":"05a359dd63f5a927a7c20c5feb273555f24445fb6a61fe641c36bd300807bfa8","contentType":"text/typescript; charset=utf-8"},{"id":"4d4175a5-20ce-56f5-a55c-c1e8f0b54088","key":"uploads/10433ee7-ad12-4ae0-b34e-97553e46c6c8/4d4175a5-20ce-56f5-a55c-c1e8f0b54088/attachment.ts","path":"templates/web-search.ts","size":5271,"sha256":"933ab768867bf1302cf8e7da4b73de221a342baeca5fd946feec1c923cbc625c","contentType":"text/typescript; charset=utf-8"}],"bundle_sha256":"00613821d6bbc640bb64e9162356d1a837d002e64f96dba35443c4a9cc2b1586","attachment_count":20,"text_attachments":20,"attachment_storage":"skillopedia-attachments-v1","binary_attachments":0,"excluded_attachments":[]},"cluster_size":2,"skill_md_path":"skills/openai-responses/SKILL.md","import_metadata":{"date":"2026-06-05","author":"@skillopedia","version":"v1","category":"web-development","category_label":"Web"},"exact_dupes_collapsed_into_this":1},"license":"MIT","version":"v1","category":"web-development","import_tag":"clean-skills-v1","description":"Build agentic AI applications with OpenAI's Responses API - the stateful successor to Chat Completions. Preserves reasoning across turns for 5% better multi-turn performance and 40-80% improved cache utilization.\n\nUse when: building AI agents with persistent reasoning, integrating MCP servers for external tools, using built-in Code Interpreter/File Search/Web Search, managing stateful conversations, implementing background processing for long tasks, or migrating from Chat Completions to gain polymorphic outputs and server-side tools.\n"}},"renderedAt":1782980964096}

OpenAI Responses API Status : Production Ready Last Updated : 2025-10-25 API Launch : March 2025 Dependencies : [email protected]+ (Node.js) or fetch API (Cloudflare Workers) --- What Is the Responses API? The Responses API ( ) is OpenAI's unified interface for building agentic applications, launched in March 2025. It fundamentally changes how you interact with OpenAI models by providing stateful conversations and a structured loop for reasoning and acting . Key Innovation: Preserved Reasoning State Unlike Chat Completions where reasoning is discarded between turns, Responses keeps the notebook o…