Using ChatGPT's API to Auto-Create Social Media Videos by Code

20 March 2023 | 21 min read
Casper Kloppenburg

Learn how to use GPT-3 and GPT-4 to auto-generate Instagram Reels & Stories, YouTube Shorts, and TikTok videos using the OpenAI API and Node.js, PHP, or Python.

Imagine if you could auto-generate videos for your Instagram, YouTube, and TikTok accounts. Well, with the help of ChatGPT and a bit of code, you can make that happen! All you need to do is suggest a topic the AI should write about, and a script will take care of the rest. And in case you can't think of a topic, ChatGPT can come up with one, making the process entirely automated.

Just a few days ago, OpenAI made its popular gpt-3.5-turbo and gpt-4 AI models available through its API, enabling developers to create their own applications based on ChatGPT. In this tutorial, you'll learn how to use this API to automatically create marketing videos using AI-generated content. Although we'll focus on social media, the methods can be applied to any other form of auto-generated video.

To illustrate, I've used the example input "5 Fascinating Facts about the Golden Eagle" to generate the following video. All of its captions were generated by ChatGPT. The AI even chose the emojis and highlighted words:

The text captions in this video were automatically generated by ChatGPT.
Even the highlighted words and emojis are automatically chosen by the AI. πŸ¦ΎπŸ€–

Looking for a no-code approach? Here's an article that does the same thing, but with Zapier.

How to generate social media videos using ChatGPT's API?

In order to use ChatGPT for generating videos, we need to provide ChatGPT with clear instructions about the subject and format of the video. As ChatGPT was trained on data from all over the internet, it's able to produce both informative and entertaining video content on virtually any topic. A script can then parse ChatGPT's output to create a unique short-form video that is ready to be posted on social media, or used for any other purpose.

While we'll use JavaScript and Node.js, it can be done with any other programming language, such as PHP, Python, or Ruby as well. As you will see, the implementation of the code is simple and minimal. Let's get started!

You can find the full source code for this project in this GitHub repository.

Steps to follow

1. Create a new Node.js project

To start, let's create a new Node.js project and install the required NPM dependencies. Let's create a directory:

$ mkdir chatgpt-video

Navigate to the directory:

$ cd chatgpt-video

Run npm init to initialize a new application. This will create a package.json file for our project:

1$ npm init -y

As OpenAI is a REST API, we simply need to send HTTP requests to use ChatGPT. We'll use the Fetch API to do this. However, since the official Fetch API only works on Node.js 18 and above, we'll be using [email protected] to accommodate older versions. Nevertheless, with a very recent version of Node.js you can use the official Fetch API and skip installing [email protected]. Additionally, we'll be using the Creatomate API to render the final video. For that we'll be using its official NPM package creatomate:

$ npm i [email protected] creatomate

2. Obtaining an OpenAI API key

To access the OpenAI API, we first need to get ourselves an API key. This is pretty straightforward; just head on over to OpenAI's sign up page and create a free account.

OpenAI works with a credit system where you pay for the amount of tokens generated by ChatGPT. The exact price per token depends on the AI model. For this example, we'll use gpt-3.5-turbo, which costs $0.002 / 1K tokens (each token is about 0.75 output words). It is the same model that is used in the official ChatGPT application. A free account comes with $18.00 of usage credit, so there's plenty of room to test and experiment.

After logging in to your OpenAI dashboard, click View API keys and then Create new secret key. This will be the only time you'll see your API key, so make sure to store it somewhere safe:

3. Using ChatGPT in Node.js

Before diving in the Node.js code, let's talk briefly about ChatGPT and how it relates to other AI models. ChatGPT is a conversational AI model. It doesn't just consider the last question asked, but also the context of the whole conversation. This is why it's called ChatGPT; it's ideal for chatbots that need to keep track of the conversation to respond to follow-up questions.

The conversation history won't matter for our applications, as we'll be asking it just a single question. However, we have to make sure this question is precise so the AI knows how to answer it in a way our Node.js app can use.

You may wonder why we're using ChatGPT if we're not using its chat functionality. The answer can be found in its capabilities and pricing. The AI model used in ChatGPT is gpt-3.5-turbo, which yields very good results, is fast, and costs 1/10th compared to other GPT models. It's also trained on more recent data. For that reason, it's used in many non-chat application as well. Nevertheless, it might be worth exploring other available AI models, e.g., the more expensive GPT-4, in case you need to generate even more advanced video captions. Check out the OpenAI documentation for a complete list of available models.

With that in mind, let's move forward with our Node.js project. Create the file index.js, and copy-paste the following code:

index.js
1const fetch = require('node-fetch');
2
3// TODO: Make sure to insert your OpenAI key here:
4const openAiApiKey = 'Your OpenAI key';
5
6async function run() {
7
8  // Call OpenAI's API
9  const response = await fetch('https://api.openai.com/v1/chat/completions', {
10    method: 'POST',
11    headers: {
12      'Content-Type': 'application/json',
13      'Authorization': `Bearer ${openAiApiKey}`,
14    },
15    body: JSON.stringify({
16      // The model currently used by ChatGPT
17      'model': 'gpt-3.5-turbo',
18      // The conversation history of this chat. Let's start by saying hi.
19      'messages': [{
20        'role': 'user',
21        'content': 'Hi!'
22      }],
23    }),
24  });
25
26  // Catch any unsuccessful HTTP responses
27  if (!response.ok) {
28    console.error(`Error: OpenAI returned status code ${response.status}. `
29      + `Make sure that you've provided a valid OpenAI API key`);
30    process.exit(1);
31  }
32
33  // Parse ChatGPT's JSON response as a JavaScript object
34  const data = await response.json();
35
36  // Print the results to the console
37  console.log(JSON.stringify(data));
38}
39
40run()
41  .catch(error => console.error(error));
42

To use ChatGPT in our Node.js application, all we need is a simple POST request. We're calling the endpoint https://api.openai.com/v1/chat/completions and providing the API key obtained in the previous step. As part of the body, we must provide the AI model (gpt-3.5-turbo) as well as the conversation history of the chat.

Alternatively, if you received an invite to GPT-4, you can replace gpt-3.5-turbo with gpt-4.

We will start a new chat with the message "Hi!". To continue the ChatGPT conversation, we'd put the previous messages in the message field and call the endpoint again and again, so ChatGPT knows the context of the conversation. But as we're not using the API for a chatbot, a single API call is enough.

Now run the code using the following command in your terminal:

$ node index.js

Here's what we'll get back. OpenAI returned a list of choices containing the response from ChatGPT and the tokens we spent on this request. In this case, ChatGPT answered with: "Hello there! How can I assist you today?"

1{
2   "id": "chatcmpl-6tyHYiuGoY6W4aAf5lCdyEBKDpSAf",
3   "object": "chat.completion",
4   "created": 1678797784,
5   "model": "gpt-3.5-turbo-0301",
6   "usage": {
7      "prompt_tokens": 9,
8      "completion_tokens": 12,
9      "total_tokens": 21
10   },
11   "choices": [
12      {
13         "message": {
14            "role": "assistant",
15            "content": "\n\nHello there! How can I assist you today?"
16         },
17         "finish_reason": "stop",
18         "index": 0
19      }
20   ]
21}

That's all we need to get ChatGPT working in Node.js! Let's keep going and make it work for our specific requirements.

4. Generating text captions for the video

Let's take a moment to consider what we are trying to accomplish. Take a look at the video in the introduction. Basically, we're going to make a video with five different facts about a particular subject. So we need to tell ChatGPT to create a list of facts about that topic. And to ensure that the captions are not too long for use in the final video, it is necessary to instruct ChatGPT to return a list of short sentences.

Now, let's rerun the code from the previous step, but with the input prompt below. As you can see, these instructions do not have to be formatted as questions for ChatGPT to understand; a brief description will do:

Prompt: "5 Fascinating Facts about Polar Bears. Make a numbered list of 5 short sentences."

Here's what ChatGPT replied to me, but you may receive a different response as ChatGPT does not guarantee the same results even when you provide the exact input data:

1`1. Polar bears are considered the largest land predators on Earth.
22. They are excellent swimmers and have been known to swim for hundreds of miles.
33. The polar bear's fur is not white, but actually transparent and hollow.
44. They have a keen sense of smell and can detect prey from over a mile away.
55. Climate change and melting ice poses a serious threat to polar bear populations.`

Not bad! As you can see, ChatGPT gives us a neat list of facts about the topic we provided.

5. Optional: Auto-generating the video topic as well

For the purpose of this tutorial, let's assume we'll be making videos for marketing purposes. So we probably want to have some control over what ChatGPT writes about. But in case you're feeling uninspired, we can take it one step further and ask ChatGPT to come up with a topic as well. In this way, we'd be able to create unique videos without human involvement at all.

Here are some examples of input prompts and ChatGPT's responses:

Prompt: What would be a good topic for people who like canoeing, in the format: "The most [blank] facts about [blank]"
ChatGPT: The most fascinating facts about canoeing in North America

Prompt: What would be a good random topic, in the format: "The most [blank] facts about [blank]"
ChatGPT: The most surprising facts about cats

Those replies can then be used as topics for the auto-generated video. However, you'll probably want to provide some additional instructions to ensure that the videos are aligned with your brand and writing style.

6. Highlighting important words and inserting emojis

For the text captions of the video to be more compelling, we would like to highlight several key words. We'd also like to use emojis. Let's give ChatGPT instructions about how to do that in the format that works for us. As we'll be using Creatomate API for the final video, we can color the captions with inline style tags. Let me give you an example:

Prompt: 5 Fascinating Facts about Polar Bears. Make a numbered list of 5 short sentences with multiple emojis. Surround the most important words with [color #f1c40f] and [/color].

1`1. [color #f1c40f]🐾 Polar Bears [/color] are the largest land predator🦁 and can weigh up to 1,500 pounds!🐻
22. These majestic creatures have a thick layer of insulating fat and [color #f1c40f]πŸ‘οΈβ€πŸ—¨οΈ black skin [/color] to absorb sunlight and keep them warm in the freezing Arctic temperatures.πŸ₯Ά
33. Polar Bears have a remarkable sense of smell and can detect prey from up to a mile away!πŸ‘ƒ
44. Despite their size, they are expert swimmersπŸŠβ€β™€οΈ, with webbed feet and long claws to help them paddle through the icy water.🌊
55. Unfortunately, these beautiful animals are suffering from climate change and [color #f1c40f]❄️ melting ice caps, [/color] putting their survival at risk.🌍🐻`

Just like we asked, ChatGPT added color tags and emojis to the auto-generated text. Having completed the AI part, we can move on to our Node.js project to automatically create videos.

7. Creating a video template

In order to create MP4 videos, we'll be using Creatomate's API. Creatomate is a video editing API that lets you create and edit videos using a simple REST API. Because the video is rendered in the cloud, there's no need to host your own render servers, making this a very cost-effective way to make on-demand videos at scale. You can sign up for a free account here.

The first thing we need to do is create a video template. The template is the design of the video that will be used as the basis for rendering the video in our Node.js script. Once you have logged into your Creatomate dashboard, go to Templates and click New. This is where you can find all the pre-made video templates. Alternatively, you can create your own templates with the feature-rich video editor. This lets you generate any type of video for just about any use case.

As an alternative to using a template, you can also create a video entirely by coding using Creatomate's JSON-to-video format.

In this example, we will use the 5 Facts Story template that can be found under the Social Media category. To open the template in the video editor, click Create Template:

Double-click to watch full screen.

Take a look at the left-hand panel of the video editor. This is where you'll find the elements of the template, such as Intro-Text, Fact-1, Fact-2, etc. From our Node.js application, we'll replace these values with the text generated by ChatGPT.

For that, we'll need the API key and template ID. Click the Use Template button and choose API Integration:

Here you can find instructions on how to use the template through the API. In this case, we're looking for the API key (the value after Authorization: Bearer) and the template ID. Make sure you copy them both so we can use them in the next step:

8. Generating a short-form video

First, let's make a video and make sure we can use the Creatomate API in Node.js. In the next step we'll put it all together. Replace the content of index.js with the following:

index.js
1const Creatomate = require('creatomate');
2
3// TODO: Insert your Creatomate API key here
4const creatomateApiKey = 'Insert your Creatomate API key here';
5
6// TODO: Insert your template ID here
7const templateId = 'Insert your template ID here';
8
9async function run() {
10
11  console.log('Please wait while your video is being rendered...');
12
13  const client = new Creatomate.Client(creatomateApiKey);
14
15  // Render a video based on a template in your Creatomate project
16  const renders = await client.render({
17    templateId,
18    // These are the modifications that are inserted into the template
19    modifications: {
20      'Intro-Text': 'This text value replaces the default value of the Intro-Text element!'
21    },
22  });
23
24  console.log('Completed:', renders);
25}
26
27run()
28  .catch(error => console.error(error));
29

By running the above code, we'll get a video based on the template we just created in Creatomate. As you can see, we are passing modifications to the API in order to replace the Intro-Text element with another text value. Here, only the intro text is being replaced, but in the final code, we will replace all text captions with the auto-generated text from ChatGPT.

As soon as the asynchronous client.render() method returns, we receive a list of completed MP4 files, along with their URL where the video can be downloaded. We are rendering based on a template ID, so this will always result in a single video, but by providing template tags, it is possible to create multiple videos in one go.

We now have all parts of the script working separately. It's time to put it all together.

9. Putting it all together

As a reminder, you can find the full source code for this project in this GitHub repository.

Here's the final code. Take a look at it first, then we'll talk about how it works. But as you'll see, it's mostly the same code we discussed before:

index.js
1const Creatomate = require('creatomate');
2const fetch = require('node-fetch');
3
4// API keys passed to this script
5const creatomateApiKey = process.argv[2];
6const openAiApiKey = process.argv[3];
7
8// A topic on which you would like to generate a video. This will be passed on to ChatGPT.
9// It will also be used as the intro text for the final video.
10const topic = '5 fascinating facts about the Golden Eagle';
11
12// TODO: The ID of the template in your Creatomate account
13const templateId = 'Insert your template ID here';
14
15if (!creatomateApiKey || !openAiApiKey) {
16  console.error('\n\n⚠️  To run this example, please specify your API keys '
17    + 'as follows: node index.js CREATOMATE_API_KEY OPENAI_API_KEY');
18  process.exit(1);
19}
20
21async function run() {
22
23  console.log('Requesting a list of results from ChatGPT...');
24
25  // Call OpenAI's API
26  const response = await fetch('https://api.openai.com/v1/chat/completions', {
27    method: 'POST',
28    headers: {
29      'Content-Type': 'application/json',
30      'Authorization': `Bearer ${openAiApiKey}`,
31    },
32    body: JSON.stringify({
33      // The model currently used by ChatGPT
34      'model': 'gpt-3.5-turbo',
35      //  Ask ChatGPT to tell us something about the provided topic,
36      //  using additional instructions to get a useful response
37      'messages': [{
38        'role': 'user',
39        'content': `${topic}. Make a numbered list of 5 short sentences. `
40          + `Surround the most important words with [color #f1c40f] and [/color]. `
41          + `Emojis should be included in each sentence.`,
42      }],
43    }),
44  });
45
46  // Catch any unsuccessful HTTP responses
47  if (!response.ok) {
48    console.error(`Error: OpenAI returned status code ${response.status}. `
49      + `Make sure that you've provided a valid OpenAI API key`);
50    process.exit(1);
51  }
52
53  // Parse ChatGPT's JSON response as a JavaScript object
54  const data = await response.json();
55
56  // Check if ChatGPT's response is as expected before continuing
57  const reply = Array.isArray(data.choices) && data.choices[0].message?.content;
58  if (typeof reply !== 'string') {
59    console.error('Error: Received an unexpected response from OpenAI');
60    process.exit(1);
61  }
62
63  // We'll parse the response and insert it into this variable
64  const facts = {};
65
66  // Iterate through ChatGPT's response line by line
67  for (const textLine of reply.split(/\r?\n/)) {
68
69    // Match list item by a regular expression (each list item starts with a digit)
70    const matchResult = textLine.match(/^\d+?/);
71    if (matchResult) {
72      facts[`Fact-${matchResult[0]}`] = textLine;
73    }
74  }
75
76  // Check if the response contains values for each text placeholder
77  if (!facts['Fact-1'] || !facts['Fact-2'] || !facts['Fact-3'] || !facts['Fact-4']
78      || !facts['Fact-5']) {
79    console.error('Error: Expected OpenAI to return a list of 5 sentences');
80    process.exit(1);
81  }
82
83  console.log('Please wait while your video is being rendered...');
84
85  const client = new Creatomate.Client(creatomateApiKey);
86
87  // Render a video based on a template in your Creatomate project
88  const renders = await client.render({
89    // The ID of the template that we want to render
90    templateId,
91    // These are the modifications that are inserted into the template
92    modifications: {
93      'Intro-Text': topic,
94      ...facts,
95    },
96  });
97
98  console.log('Completed:', renders);
99}
100
101run()
102  .catch(error => console.error(error));
103

Apart from error handling, we only do a few things to glue ChatGPT and Creatomate together. Make sure you put a video topic and your template ID at the top of the file:

index.js (partial)
1// A topic on which you would like to generate a video. This will be passed on to ChatGPT.
2// It will also be used as the intro text for the final video.
3const topic = '5 fascinating facts about the Golden Eagle';
4
5// The ID of the template in your Creatomate account
6const templateId = 'Insert your template ID here';
7

The only thing that is new in this code is how we parse ChatGPT's response. As we can be sure that ChatGPT returns a numeric list of 5 sentences, we can break its reply into new lines via the regular expression /\r?\n/. Our next step is to find lines that start with a digit by using /^\d+?/. Once found, we insert the line into a JavaScript object named facts, using the names of the elements in our template (Fact-1, Fact-2, Fact-3, etc.) to insert the text values into the video.

index.js (partial)
1// We'll parse the response and insert it into this variable
2const facts = {};
3
4// Iterate through ChatGPT's response line by line
5for (const textLine of reply.split(/\r?\n/)) {
6
7  // Match list item by a regular expression (each list item starts with a digit)
8  const matchResult = textLine.match(/^\d+?/);
9  if (matchResult) {
10    facts[`Fact-${matchResult[0]}`] = textLine;
11  }
12}
13

As a final step, we add this object facts to the modifications we pass to Creatomate in order to create the MP4:

index.js (partial)
1// Render a video based on a template in your Creatomate project
2const renders = await client.render({
3  // The ID of the template that we want to render
4  templateId,
5  // These are the modifications that are inserted into the template
6  modifications: {
7    'Intro-Text': topic,
8    ...facts,
9  },
10});
11

10. Run the code

Now that the code is done, let's run it and see what we get! Make sure all source files are saved, then run the following command in your terminal, providing your Creatomate and OpenAI API keys:

$ node index.js CREATOMATE_API_KEY OPENAI_API_KEY

You'll have to wait a few moments for the video to render. An array of renders will be printed to the console when it's done. As we're only rendering one video at a time, the output looks like this:

1[
2  {
3     "id": "c7748b9c-893f-4f14-bf6d-8b3f5b5e5ab4",
4     "status": "succeeded",
5     "url": "https://cdn.creatomate.com/renders/c7748b9c-893f-4f14-bf6d-8b3f5b5e5ab4.mp4",
6     "snapshotUrl": "https://cdn.creatomate.com/snapshots/c7748b9c-893f-4f14-bf6d-8b3f5b5e5ab4.jpg",
7     "templateId": "ad1de625-c2d4-499b-a4b3-dc16429350bf",
8     "templateName": "5 Facts Story",
9     "templateTags": [],
10     "outputFormat": "mp4",
11     "width": 720,
12     "height": 1280,
13     "frameRate": 30.069268479864505,
14     "duration": 38.01223168316832,
15     "fileSize": 5675728,
16     "modifications": {
17      "Fact-1": "1. The [color #f1c40f]Golden Eagle[/color] is one of the largest birds of prey in the world, with a wingspan of up to [color #f1c40f]7 feet[/color]. πŸ¦…",
18      "Fact-2": "2. These majestic birds are found throughout the [color #f1c40f]Northern Hemisphere[/color], from [color #f1c40f]North America[/color] to [color #f1c40f]Europe[/color] and [color #f1c40f]Asia[/color]. 🌍",
19      "Fact-3": "3. [color #f1c40f]Golden Eagles[/color] have excellent eyesight and can spot prey from over a mile away. πŸ‘€",
20      "Fact-4": "4. Despite their name, [color #f1c40f]Golden Eagles[/color] are not actually fully golden - they are mostly brown with some golden feathers on their heads and necks. πŸ¦…πŸŒˆ",
21      "Fact-5": "5. These birds are known for their fierce and powerful hunting skills, and have been known to take down prey as large as [color #f1c40f]deer[/color] and [color #f1c40f]goats[/color]. πŸ—",
22      "Intro-Text": "5 fascinating facts about the Golden Eagle"
23    }
24  }
25]

Let's check out the URL we got back in the render result. Using ChatGPT, Creatomate, and Node.js, we just automatically generated a social media video that's ready to be shared!

Wrapping up

As we've explored in this article, automating video creation using AI and code is pretty straightforward once you know the trick. This opens up a whole new world of content creation and video automation, as well as exciting opportunities for developers to create new video-based solutions on top of AI. So far, we've only talked about social media, but think about what AI can do for other kinds of video, like marketing, personalization, storytelling, and text-to-speech video.

With GPT-4 now available, you can see the AI's true power when it comes to video generation. Imagine creating highly-dynamic videos using GPT-4, by merely describing the topic, desired images, preferred style, and format of the video. This will become a reality very soon with our JSON-to-video format and GPT-4's capability to write code. If you haven't already, I'd recommend watching back the developer Livestream of OpenAI to see what's in store for the next few years. There are exciting times ahead!

Start automating today

Start with a full-featured trial with 50 credits, no credit card required.
Get started for free