|
| 1 | +--- |
| 2 | +title: "Generate an image using DALL·E 3" |
| 3 | +sidebarTitle: "Generate image using DALL·E" |
| 4 | +description: "This example will show you how to generate an image using DALL·E 3 and text using GPT-4o with Trigger.dev." |
| 5 | +--- |
| 6 | + |
| 7 | +## Overview |
| 8 | + |
| 9 | +This example demonstrates how to use Trigger.dev to make reliable calls to AI APIs, specifically OpenAI's GPT-4o and DALL-E 3. It showcases automatic retrying with a maximum of 3 attempts, built-in error handling to avoid timeouts, and the ability to trace and monitor API calls. |
| 10 | + |
| 11 | +## Task code |
| 12 | + |
| 13 | +```ts trigger/generateContent.ts |
| 14 | +import { task } from "@trigger.dev/sdk/v3"; |
| 15 | +import OpenAI from "openai"; |
| 16 | + |
| 17 | +const openai = new OpenAI({ |
| 18 | + apiKey: process.env.OPENAI_API_KEY, |
| 19 | +}); |
| 20 | + |
| 21 | +type Payload = { |
| 22 | + theme: string; |
| 23 | + description: string; |
| 24 | +}; |
| 25 | + |
| 26 | +export const generateContent = task({ |
| 27 | + id: "generate-content", |
| 28 | + retry: { |
| 29 | + maxAttempts: 3, // Retry up to 3 times |
| 30 | + }, |
| 31 | + run: async ({ theme, description }: Payload) => { |
| 32 | + |
| 33 | + // Generate text |
| 34 | + const textResult = await openai.chat.completions.create({ |
| 35 | + model: "gpt-4o", |
| 36 | + messages: generateTextPrompt(theme, description), |
| 37 | + }); |
| 38 | + |
| 39 | + if (!textResult.choices[0]) { |
| 40 | + throw new Error("No content, retrying…"); |
| 41 | + } |
| 42 | + |
| 43 | + // Generate image |
| 44 | + const imageResult = await openai.images.generate({ |
| 45 | + model: "dall-e-3", |
| 46 | + prompt: generateImagePrompt(theme, description), |
| 47 | + }); |
| 48 | + |
| 49 | + if (!imageResult.data[0]) { |
| 50 | + throw new Error("No image, retrying…"); |
| 51 | + } |
| 52 | + |
| 53 | + return { |
| 54 | + text: textResult.choices[0], |
| 55 | + image: imageResult.data[0].url, |
| 56 | + }; |
| 57 | + }, |
| 58 | +}); |
| 59 | + |
| 60 | +function generateTextPrompt(theme: string, description: string): any { |
| 61 | + return `Theme: ${theme}\n\nDescription: ${description}`; |
| 62 | +} |
| 63 | + |
| 64 | +function generateImagePrompt(theme: string, description: string): any { |
| 65 | + return `Theme: ${theme}\n\nDescription: ${description}`; |
| 66 | +} |
| 67 | +``` |
| 68 | + |
| 69 | +## GitHub repo |
| 70 | + |
| 71 | +View this example task [on GitHub](https://github.com/triggerdotdev/v3-test-projects/blob/main/website-examples/trigger/generateContent.ts). |
0 commit comments