Files
triggerdotdev--trigger.dev/docs/examples/open-ai-with-retrying.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

47 lines
1.3 KiB
Plaintext

---
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;
},
});
```