diff --git a/docs/examples/generate-image-with-dall-e3.mdx b/docs/examples/generate-image-with-dall-e3.mdx index 6547a90beb..abcab2cf78 100644 --- a/docs/examples/generate-image-with-dall-e3.mdx +++ b/docs/examples/generate-image-with-dall-e3.mdx @@ -1,6 +1,6 @@ --- title: "Generate an image using DALL·E 3" -sidebarTitle: "Generate image using DALL·E" +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." --- @@ -64,8 +64,4 @@ function generateTextPrompt(theme: string, description: string): any { function generateImagePrompt(theme: string, description: string): any { return `Theme: ${theme}\n\nDescription: ${description}`; } -``` - -## GitHub repo - -View this example task [on GitHub](https://github.com/triggerdotdev/v3-test-projects/blob/main/website-examples/trigger/generateContent.ts). \ No newline at end of file +``` \ No newline at end of file diff --git a/docs/examples/open-ai-with-retrying.mdx b/docs/examples/open-ai-with-retrying.mdx new file mode 100644 index 0000000000..c89ca4bdc8 --- /dev/null +++ b/docs/examples/open-ai-with-retrying.mdx @@ -0,0 +1,47 @@ +--- +title: "Call OpenAI with retrying" +sidebarTitle: "OpenAI with retrying" +description: "This example will show you how to call OpenAI with retrying using Trigger.dev." +--- + +## Overview + +Sometimes OpenAI calls can take a long time to complete, or they can fail. This task will retry if the API call fails completely or if the response is empty. + +## Task code + +```ts trigger/openai.ts +import { task } from "@trigger.dev/sdk/v3"; +import OpenAI from "openai"; + +const openai = new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, +}); + +export const openaiTask = task({ + id: "openai-task", + //specifying retry options overrides the defaults defined in your trigger.config file + retry: { + maxAttempts: 10, + factor: 1.8, + minTimeoutInMs: 500, + maxTimeoutInMs: 30_000, + randomize: false, + }, + run: async (payload: { prompt: string }) => { + //if this fails, it will throw an error and retry + const chatCompletion = await openai.chat.completions.create({ + messages: [{ role: "user", content: payload.prompt }], + model: "gpt-3.5-turbo", + }); + + if (chatCompletion.choices[0]?.message.content === undefined) { + //sometimes OpenAI returns an empty response, let's retry by throwing an error + throw new Error("OpenAI call failed"); + } + + return chatCompletion.choices[0].message.content; + }, +}); + +``` \ No newline at end of file diff --git a/docs/examples/react-pdf.mdx b/docs/examples/react-pdf.mdx new file mode 100644 index 0000000000..165e938476 --- /dev/null +++ b/docs/examples/react-pdf.mdx @@ -0,0 +1,69 @@ +--- +title: "Generate a PDF using react-pdf and save it to R2" +sidebarTitle: "React to PDF" +description: "This example will show you how to generate a PDF using Trigger.dev." +--- + +## Overview + +This example demonstrates how to use Trigger.dev to generate a PDF using `react-pdf` and save it to Cloudflare R2. + +## Task code + +```ts trigger/generateResumePDF.ts +import { logger, task } from "@trigger.dev/sdk/v3"; +import { Document, Page, Text, View } from "@react-pdf/renderer"; +import { renderToBuffer } from "@react-pdf/renderer"; +import { PutObjectCommand, S3Client } from "@aws-sdk/client-s3"; + +// Initialize S3 client +const s3Client = new S3Client({ + region: "auto", + endpoint: process.env.S3_ENDPOINT, + credentials: { + accessKeyId: process.env.R2_ACCESS_KEY_ID ?? "", + secretAccessKey: process.env.R2_SECRET_ACCESS_KEY ?? "", + }, +}); + +export const generateResumePDF = task({ + id: "generate-resume-pdf", + run: async (payload: { text: string }) => { + logger.log("Generating PDF resume", payload); + + // Render the ResumeDocument component to a PDF buffer + const pdfBuffer = await renderToBuffer( + + + + {payload.text} + + + + ); + + // Generate a unique filename + const filename = `${payload.text + .replace(/\s+/g, "-") + .toLowerCase()}-${Date.now()}.pdf`; + + // Upload to R2 + const s3Key = `resumes/${filename}`; + const uploadParams = { + Bucket: process.env.S3_BUCKET, + Key: s3Key, + Body: pdfBuffer, + ContentType: "application/pdf", + }; + + logger.log("Uploading to R2 with params", uploadParams); + + // Upload the PDF to R2 and return the URL. + await s3Client.send(new PutObjectCommand(uploadParams)); + const s3Url = `https://${process.env.S3_BUCKET}.s3.amazonaws.com/${s3Key}`; + logger.log("PDF uploaded to R2", { url: s3Url }); + return { pdfUrl: s3Url }; + }, +}); + +``` \ No newline at end of file diff --git a/docs/examples/resend-email-sequence.mdx b/docs/examples/resend-email-sequence.mdx new file mode 100644 index 0000000000..522aaa2be7 --- /dev/null +++ b/docs/examples/resend-email-sequence.mdx @@ -0,0 +1,72 @@ +--- +title: "Send a sequence of emails using Resend" +sidebarTitle: "Resend email sequence" +description: "This example will show you how to send a sequence of emails over several days using Resend with Trigger.dev." +--- + +## Overview + +Each email is wrapped in retry.onThrow. This will retry the block of code if an error is thrown. This is useful when you don’t want to retry the whole task, but just a part of it. The entire task will use the default retrying, so can also retry. + +Additionally this task uses wait.for to wait for a certain amount of time before sending the next email. During the waiting time, the task will be paused and will not consume any resources. + +## Task code + +```ts trigger/email-sequence.ts +import { Resend } from "resend"; + +const resend = new Resend(process.env.RESEND_ASP_KEY); + +export const emailSequence = task({ + id: "email-sequence", + run: async (payload: { userId: string; email: string; name: string }) => { + console.log(`Start email sequence for user ${payload.userId}`, payload); + + //send the first email immediately + const firstEmailResult = await retry.onThrow( + async ({ attempt }) => { + const { data, error } = await resend.emails.send({ + from: "hello@trigger.dev", + to: payload.email, + subject: "Welcome to Trigger.dev", + html: `

Hello ${payload.name},

Welcome to Trigger.dev

`, + }); + + if (error) { + //throwing an error will trigger a retry of this block + throw error; + } + + return data; + }, + { maxAttempts: 3 } + ); + + //then wait 3 days + await wait.for({ days: 3 }); + + //send the second email + const secondEmailResult = await retry.onThrow( + async ({ attempt }) => { + const { data, error } = await resend.emails.send({ + from: "hello@trigger.dev", + to: payload.email, + subject: "Some tips for you", + html: `

Hello ${payload.name},

Here are some tips for you…

`, + }); + + if (error) { + //throwing an error will trigger a retry of this block + throw error; + } + + return data; + }, + { maxAttempts: 3 } + ); + + //etc... + }, +}); + +``` \ No newline at end of file diff --git a/docs/mint.json b/docs/mint.json index 64080ea8a2..24083ce9f3 100644 --- a/docs/mint.json +++ b/docs/mint.json @@ -252,7 +252,12 @@ }, { "group": "Examples", - "pages": ["examples/generate-image-with-dall-e3"] + "pages": [ + "examples/generate-image-with-dall-e3", + "examples/open-ai-with-retrying", + "examples/react-pdf", + "examples/resend-email-sequence" + ] } ], "footerSocials": { diff --git a/docs/snippets/cli-commands-develop.mdx b/docs/snippets/cli-commands-develop.mdx index d333f0d174..a29fddf54b 100644 --- a/docs/snippets/cli-commands-develop.mdx +++ b/docs/snippets/cli-commands-develop.mdx @@ -90,13 +90,15 @@ Install the concurrently package as a dev dependency: concurrently --raw --kill-others npm:dev:remix npm:dev:trigger ``` -Then add something like this in your package.json scripts. This assumes you're running Next.js so swap that bit out if you're not: +Then add something like this in your package.json scripts: ```json "scripts": { "dev": "concurrently --raw --kill-others npm:dev:*", - "dev:next": "next dev", "dev:trigger": "npx trigger.dev@beta dev", + // Add your framework-specific dev script here, for example: + // "dev:next": "next dev", + // "dev:remix": "remix dev", //... } ``` \ No newline at end of file