* Call OpenAI Responses API with image_generation tool. * Returns the response ID and base64 image data.
( apiKey: string, prompt: string, size: string, quality: string, )
| 31 | * Returns the response ID and base64 image data. |
| 32 | */ |
| 33 | async function callImageGeneration( |
| 34 | apiKey: string, |
| 35 | prompt: string, |
| 36 | size: string, |
| 37 | quality: string, |
| 38 | ): Promise<{ responseId: string; imageData: string }> { |
| 39 | const controller = new AbortController(); |
| 40 | const timeout = setTimeout(() => controller.abort(), 240_000); |
| 41 | |
| 42 | try { |
| 43 | const response = await fetch("https://api.openai.com/v1/responses", { |
| 44 | method: "POST", |
| 45 | headers: { |
| 46 | "Authorization": `Bearer ${apiKey}`, |
| 47 | "Content-Type": "application/json", |
| 48 | }, |
| 49 | body: JSON.stringify({ |
| 50 | model: "gpt-4o", |
| 51 | input: prompt, |
| 52 | tools: [{ |
| 53 | type: "image_generation", |
| 54 | model: "gpt-image-2", |
| 55 | size, |
| 56 | quality, |
| 57 | }], |
| 58 | }), |
| 59 | signal: controller.signal, |
| 60 | }); |
| 61 | |
| 62 | if (!response.ok) { |
| 63 | const error = await response.text(); |
| 64 | if (response.status === 403 && error.includes("organization must be verified")) { |
| 65 | throw new Error( |
| 66 | "OpenAI organization verification required.\n" |
| 67 | + "Go to https://platform.openai.com/settings/organization to verify.\n" |
| 68 | + "After verification, wait up to 15 minutes for access to propagate.", |
| 69 | ); |
| 70 | } |
| 71 | throw new Error(`API error (${response.status}): ${error.slice(0, 200)}`); |
| 72 | } |
| 73 | |
| 74 | const data = await response.json() as any; |
| 75 | |
| 76 | const imageItem = data.output?.find((item: any) => |
| 77 | item.type === "image_generation_call" |
| 78 | ); |
| 79 | |
| 80 | if (!imageItem?.result) { |
| 81 | throw new Error( |
| 82 | `No image data in response. Output types: ${data.output?.map((o: any) => o.type).join(", ") || "none"}` |
| 83 | ); |
| 84 | } |
| 85 | |
| 86 | return { |
| 87 | responseId: data.id, |
| 88 | imageData: imageItem.result, |
| 89 | }; |
| 90 | } finally { |