...

/

Implement API to Generate Tweets with Images Using OpenAI

Implement API to Generate Tweets with Images Using OpenAI

Implement the API that uses OpenAI and Dall-e model to generate twitter tweets with images based on a given topic.

Before creating the API endpoint, let's make a script ready that will accept a topic on which the user wants to generate the tweet. As discussed earlier, we will use the GPT model using OpenAI and a suitable prompt to generate the tweet. Once we have the AI generated tweet ready, we will use the Dall•E model to work with image generation. Basically, Dall•E is an AI artist! It's an image generation system developed by OpenAI that creates images from text prompts.

Generate image based on the tweet

Since we already have a function ready that generates a tweet using GPT model, we will use the same function in our script. Additionally, we will use the images module from the openai package to generate images using Dall•E. We will use dall-e-3 model for this project since it is the latest model. Let's jump into the code now.

Press + to interact
// Import the require module
const { OpenAI } = require("openai");
// Function to generate tweet based on the topic given
const generateTweetForTopic = async (topic) => {
// Instance of OpenAI
const openai = new OpenAI({ apiKey: openai_api_key });
// Use OpenAI chat completions and the prompt to generate the tweet
const response = await openai.chat.completions.create({
model: 'gpt-3.5-turbo',
messages: [
{
role: 'user',
content: `You are an expert Twitter tweet generator. Write a tweet
on the topic: ${topic} that can go viral on Twitter.
It should be intersting, unique and catchy to read. Your tone
should be funny and your response should not contain
anything other than the tweet. Your tweet should be less
than 255 characters.`
}
],
temperature: 1.5
});
return response.choices[0].message.content.trim();
}
const generateImageForTweet = async (topic, tweet) => {
// Instance of OpenAI
const openai = new OpenAI({ apiKey: openai_api_key });
// Use OpenAI images module and the prompt to generate the image
const response = await openai.images.generate({
model: "dall-e-3",
prompt: `You are an expert graphic designer who design amazing illustrations
for twitter tweets. You need to generate an image related to the topic:
${topic} and the tweet: ${tweet}. Your image should be of high quality
and not controversial.`,
n: 1,
size: "1024x1024"
});
return response.data[0].url;
}
// Used the immediately invoked function expression
(async () => {
try{
const topic = "machine learning";
const tweet = await generateTweetForTopic(topic);
const imageURL = await generateImageForTweet(topic, tweet);
console.log("Tweet:<br>", tweet);
console.log('<br><br>');
console.log(`Image:<br><img src='${imageURL}' height='300px' width='300px'/>`);
} catch (e) {
console.log("Error: ", e);
}
})();

The above code may take a little while to execute since we ...