How I Coded a Story Generator using OpenAI’s GPT-3.

Cee Lopez
Bootcamp
Published in
7 min readApr 14, 2023

Are you a writer who has writer’s block? Are you looking for inspiration for your next story? Look no further than OpenAI’s GPT-3 API. In this article, we will explore how to build a short story generator using OpenAI’s GPT-3 API.

What is OpenAI’s GPT-3 API?

OpenAI’s GPT-3 API is a language generation tool that uses deep learning to generate text. The model is trained on a large corpus of text and can generate text in a variety of styles and genres. It has been used to create everything from poetry to chatbots to computer code.

Image of the Final Product

Building a Short Story Generator

For this tutorial, we will be building a short story generator that takes user input and generates a short story based on that input. We will be using JavaScript and the Fetch API to make requests to the OpenAI GPT-3 API.

How to Get an OpenAI API Key

To use the OpenAI GPT-3 API, you’ll need to sign up for an OpenAI API key. Here’s how:

  1. Go to the OpenAI API page and click the “Sign Up for the API” button.
  2. Enter your email address and click “Continue.”
  3. Create a password and click “Sign Up.”
  4. Fill in the required fields with your personal information, company name (if applicable), and intended use for the API. Be sure to read and agree to the terms of service and privacy policy.
  5. Click “Submit.”
  6. You’ll be directed to a page with information about your API key. Be sure to keep this information safe and secure, as it gives you access to the powerful OpenAI GPT-3 API.
Here is where you create the APIKEY.
Make sure you keep this key somewhere safe, once you hit Done you won’t be able to access the key again.

Setting Up Your Environment

Before we can begin building our short story generator, we need to set up our environment. First, we need to sign up for the OpenAI GPT-3 API and obtain an API key. Once we have our API key, we can start building our generator.

We will be using JavaScript to make requests to the OpenAI GPT-3 API, so we will need to create an HTML file and a JavaScript file. We will also need to include the Fetch API in our HTML file by adding the following script tag to the head of our HTML file:

<script src="https://unpkg.com/whatwg-fetch@latest"></script>

Creating the Form

Now that we have our environment set up, we can start building our short story generator. The first thing we need to do is create a form that will allow the user to input their story parameters. We will be using HTML and Bootstrap to create our form. Here is the code for our form:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/tailwindcss@2.2.17/dist/tailwind.min.css" rel="stylesheet">
<title>Story Generator</title>
</head>
<body class="bg-gray-900 text-white">
<div class="container mx-auto">
<!-- Input forms for user preferences -->
<div id="input-form" class="p-4">
<form id="story-form">
<div>
<label for="genre" class="block">Genre:</label>
<select id="genre" class="block w-full bg-gray-800 text-white mt-1 p-2">
<option value="sci-fi">Science Fiction</option>
<option value="fantasy">Fantasy</option>
<option value="mystery">Mystery</option>
<option value="romance">Romance</option>
<option value="horror">Horror</option>
</select>
</div>
<div class="mt-4">
<label for="num-characters" class="block">Number of Characters:</label>
<input id="num-characters" type="number" min="1" max="5" value="1" class="block w-full bg-gray-800 text-white mt-1 p-2">
</div>
<div id="characters-container" class="mt-4">
<div class="character-input">
<label for="character1-name" class="block">Character 1 Name:</label>
<input id="character1-name" type="text" class="block w-full bg-gray-800 text-white mt-1 p-2">
<label for="character1-sex" class="block mt-2">Character 1 Sex:</label>
<select id="character1-sex" class="block w-full bg-gray-800 text-white mt-1 p-2">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
</div>
</div>
<div class="mt-4">
<label for="reader-age" class="block">Reader Age:</label>
<input id="reader-age" type="number" min="1" value="18" class="block w-full bg-gray-800 text-white mt-1 p-2">
</div>
<button type="submit" class="mt-4 bg-purple-500 hover:bg-purple-600 px-4 py-2 text-white">Generate Story</button>
</form>
</div>
<!-- Display area for the generated story -->
<div id="story-display" class="mt-4 p-4">
<h2 class="text-2xl font-bold mb-4">Generated Story:</h2>
<div id="generated-story" class="bg-gray-800 p-4 rounded text-white whitespace-pre-wrap">
<!-- The generated story will be displayed here -->
</div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>

Our form has five fields: genre, reader age, number of characters, and character name/sex. We also have a Generate Story button that will trigger our short story generator I am utilizing tailwindcss, do keep in mind this base code was actually generated by ChatGPT itself.

Story Generation

Now that we have our form set up, we can start building our short story generator. We will be using JavaScript and the Fetch API to make requests to the OpenAI GPT-3 API. Here is the code for our short story generator:

document.addEventListener('DOMContentLoaded', () => {
const numCharactersInput = document.getElementById('num-characters');
const charactersContainer = document.getElementById('characters-container');
const storyForm = document.getElementById('story-form');

// Function to create character input fields
function createCharacterInputs(numCharacters) {
charactersContainer.innerHTML = ''; // Clear the container first

// Loop through and create character input fields
for (let i = 1; i <= numCharacters; i++) {
const characterDiv = document.createElement('div');
characterDiv.className = 'character-input mt-4';

const nameLabel = document.createElement('label');
nameLabel.htmlFor = `character${i}-name`;
nameLabel.textContent = `Character ${i} Name:`;
nameLabel.className = 'block';

const nameInput = document.createElement('input');
nameInput.id = `character${i}-name`;
nameInput.type = 'text';
nameInput.className = 'block w-full bg-gray-800 text-white mt-1 p-2';

const sexLabel = document.createElement('label');
sexLabel.htmlFor = `character${i}-sex`;
sexLabel.textContent = `Character ${i} Sex:`;
sexLabel.className = 'block mt-2';

const sexSelect = document.createElement('select');
sexSelect.id = `character${i}-sex`;
sexSelect.className = 'block w-full bg-gray-800 text-white mt-1 p-2';

const maleOption = document.createElement('option');
maleOption.value = 'male';
maleOption.textContent = 'Male';

const femaleOption = document.createElement('option');
femaleOption.value = 'female';
femaleOption.textContent = 'Female';

const otherOption = document.createElement('option');
otherOption.value = 'other';
otherOption.textContent = 'Other';

sexSelect.append(maleOption, femaleOption, otherOption);

characterDiv.append(nameLabel, nameInput, sexLabel, sexSelect);
charactersContainer.appendChild(characterDiv);
}
}

// Create the initial character input fields
createCharacterInputs(numCharactersInput.value);

// Add an event listener for the numCharactersInput to recreate the character input fields
numCharactersInput.addEventListener('input', () => {
createCharacterInputs(numCharactersInput.value);
});

// Add an event listener for the story form submission
storyForm.addEventListener('submit', async (e) => {
e.preventDefault();

// Get the user's input from the form
const genre = document.getElementById('genre').value;
const numCharacters = parseInt(document.getElementById('num-characters').value, 10);
const readerAge = parseInt(document.getElementById('reader-age').value, 10);

// Build the characters array with names and sexes
const characters = [];
for (let i = 1; i <= numCharacters; i++) {
const name = document.getElementById(`character${i}-name`).value;
const sex = document.getElementById(`character${i}-sex`).value;
characters.push({ name, sex });
}

// Build the prompt based on the user's input
let prompt = `Create a short story in the ${genre} genre for a reader aged ${readerAge}. `;
prompt += `The story should have ${numCharacters} main character(s): `;
characters.forEach((char, index) => {
prompt += `${char.name} (${
char.sex})${index === characters.length - 1 ? '.' : ', '}`;
});
prompt += '\n\nStory: ';

// Call the generateStory function and update the generated-story div
const storyText = await generateStory(prompt);
document.getElementById('generated-story').innerText = storyText;
});

});



// Function to call the OpenAI API
async function generateStory(prompt) {
const response = await fetch('https://api.openai.com/v1/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YOURAPIKEYGOESHERE'
},
body: JSON.stringify({
model: 'text-davinci-003',
prompt: prompt,
max_tokens: 1200,
n: 1,
stop: null,
temperature: 1.0,
}),
});

const data = await response.json();
if (data.choices && data.choices.length > 0) {
return data.choices[0].text;
} else {
// Return a default message or an error message to the user
return 'An error occurred while generating the story. Please try again.';
}
}

Conclusion

I was able to build a short story generator using the OpenAI GPT-3 API and JavaScript. I created a simple HTML form where users can input parameters, and then used the Fetch API to send a request to the GPT-3 API and receive a short story in response. The next thing that I would like to try is to switch to the turbo3.5 language model, it is more affordable to use and equally as powerful as davinci.

This project demonstrates the power of machine learning and natural language processing, and how it can be used to create interesting and engaging applications. With the OpenAI API, developers have access to some of the most advanced language models in the world, and can use them to build a wide range of applications.

If you’re interested in exploring the OpenAI API further, be sure to check out the documentation and start experimenting with different models and parameters. The possibilities are endless!

I write about tips, tricks and tools of AI especially ChatGPT and Midjourney! If you find this article helpful and would like to support me, make sure to:

  • 👏🏻 Clap for the story to help this article be featured
  • Follow me on this journey

--

--

Bootcamp
Bootcamp

Published in Bootcamp

From idea to product, one lesson at a time. Bootcamp is a collection of resources and opinion pieces about UX, UI, and Product. To submit your story: https://tinyurl.com/bootspub1