Files
triggerdotdev--trigger.dev/docs/examples/generate-image-with-dall-e3.mdx
T
James Ritchie c1690bd1ae New React to PDF example task (#1300)
* Better code snippet to clarify your framework

* New page for react-pdf

* Added 3 more examples

* New react to PDF example

* Alphabeticalise the side menu

* Removed github link and tweaked title
2024-09-13 16:46:52 +01:00

67 lines
1.8 KiB
Plaintext

---
title: "Generate an image using DALL·E 3"
sidebarTitle: "DALL·E image generation"
description: "This example will show you how to generate an image using DALL·E 3 and text using GPT-4o with Trigger.dev."
---
## Overview
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.
## Task code
```ts trigger/generateContent.ts
import { task } from "@trigger.dev/sdk/v3";
import OpenAI from "openai";
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
type Payload = {
theme: string;
description: string;
};
export const generateContent = task({
id: "generate-content",
retry: {
maxAttempts: 3, // Retry up to 3 times
},
run: async ({ theme, description }: Payload) => {
// Generate text
const textResult = await openai.chat.completions.create({
model: "gpt-4o",
messages: generateTextPrompt(theme, description),
});
if (!textResult.choices[0]) {
throw new Error("No content, retrying…");
}
// Generate image
const imageResult = await openai.images.generate({
model: "dall-e-3",
prompt: generateImagePrompt(theme, description),
});
if (!imageResult.data[0]) {
throw new Error("No image, retrying…");
}
return {
text: textResult.choices[0],
image: imageResult.data[0].url,
};
},
});
function generateTextPrompt(theme: string, description: string): any {
return `Theme: ${theme}\n\nDescription: ${description}`;
}
function generateImagePrompt(theme: string, description: string): any {
return `Theme: ${theme}\n\nDescription: ${description}`;
}
```