|
| 1 | +import { openai } from '@ai-sdk/openai'; |
| 2 | +import { streamText } from 'ai'; |
| 3 | +import { convertBase64ToUint8Array } from '../lib/convert-base64'; |
| 4 | +import { presentImages } from '../lib/present-image'; |
| 5 | +import { run } from '../lib/run'; |
| 6 | + |
| 7 | +run(async () => { |
| 8 | + console.log('Generating base image of an echidna...'); |
| 9 | + const baseResult = streamText({ |
| 10 | + model: 'openai/gpt-5-nano', |
| 11 | + prompt: |
| 12 | + 'Generate an image of an echidna swimming across the Mozambique channel.', |
| 13 | + tools: { |
| 14 | + image_generation: openai.tools.imageGeneration({ |
| 15 | + outputFormat: 'webp', |
| 16 | + quality: 'low', |
| 17 | + }), |
| 18 | + }, |
| 19 | + }); |
| 20 | + |
| 21 | + let baseImageData: Uint8Array | null = null; |
| 22 | + |
| 23 | + for await (const part of baseResult.fullStream) { |
| 24 | + if (part.type == 'tool-result' && !part.dynamic) { |
| 25 | + baseImageData = convertBase64ToUint8Array(part.output.result); |
| 26 | + await presentImages([ |
| 27 | + { |
| 28 | + mediaType: 'image/webp', |
| 29 | + base64: part.output.result, |
| 30 | + uint8Array: baseImageData, |
| 31 | + }, |
| 32 | + ]); |
| 33 | + } |
| 34 | + } |
| 35 | + |
| 36 | + if (!baseImageData) { |
| 37 | + throw new Error('No base image generated'); |
| 38 | + } |
| 39 | + |
| 40 | + console.log('Editing image to add vibrant colors...'); |
| 41 | + const editResult = streamText({ |
| 42 | + model: 'openai/gpt-5-nano', |
| 43 | + prompt: [ |
| 44 | + { |
| 45 | + role: 'user', |
| 46 | + content: [ |
| 47 | + { |
| 48 | + type: 'text', |
| 49 | + text: 'Make the echidna and water more vibrant with bright blues and purples. Keep the composition the same.', |
| 50 | + }, |
| 51 | + { |
| 52 | + type: 'file', |
| 53 | + data: baseImageData, |
| 54 | + mediaType: 'image/webp', |
| 55 | + }, |
| 56 | + ], |
| 57 | + }, |
| 58 | + ], |
| 59 | + tools: { |
| 60 | + image_generation: openai.tools.imageGeneration({ |
| 61 | + outputFormat: 'webp', |
| 62 | + quality: 'low', |
| 63 | + }), |
| 64 | + }, |
| 65 | + }); |
| 66 | + |
| 67 | + for await (const part of editResult.fullStream) { |
| 68 | + if (part.type == 'tool-result' && !part.dynamic) { |
| 69 | + await presentImages([ |
| 70 | + { |
| 71 | + mediaType: 'image/webp', |
| 72 | + base64: part.output.result, |
| 73 | + uint8Array: convertBase64ToUint8Array(part.output.result), |
| 74 | + }, |
| 75 | + ]); |
| 76 | + } |
| 77 | + } |
| 78 | +}); |
0 commit comments