78 lines
2.0 KiB
Plaintext
78 lines
2.0 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";
|
|
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}`;
|
|
}
|
|
```
|
|
|
|
## Testing your task
|
|
|
|
To test this task in the dashboard, you can use the following payload:
|
|
|
|
```json
|
|
{
|
|
"theme": "A beautiful sunset",
|
|
"description": "A sunset over the ocean with a tiny yacht in the distance."
|
|
}
|
|
```
|