Skip to content
Home » Blog » Building a Simple Prompt Generator in Python

Building a Simple Prompt Generator in Python

Building a Simple Prompt Generator in Python

Introduction

Creating a prompt generator is a fun and educational project that can be useful for writers, educators, and developers. In this blog post, we’ll walk you through the process of creating a prompt generator using Python. This generator will provide creative prompts for different categories such as stories, scenarios, poetry, and arguments. We’ll include a detailed code snippet to demonstrate how to achieve this.

Ready to design your own prompt generator? If you’re up for the challenge, you’re in the right spot. Let’s start our journey by building the prompt generator app from scratch. Let’s get started!”

Why Build a Prompt Generator?

A prompt generator can be a powerful tool for several reasons:

Writers

  • Overcoming Writer’s Block: One of the most common challenges writers face is writer’s block. A prompt generator can provide a variety of ideas and scenarios to kickstart the creative process and help writers to overcome these mental hurdles.
  • Inspiration for New Ideas: Even seasoned writers need fresh ideas from time to time. A prompt generator can offer unique and unexpected prompts that inspire new stories, characters, and plot twists.
  • Daily Writing Practice: For writers who are looking to improve their skills, daily prompts can serve as practice exercises, encouraging regular writing habits and experimentation with different category and styles.

Educators

  • Creative Writing Assignments: Teachers can use prompt generators to create engaging and diverse writing assignments for their students. By providing prompts that cover a range of topics and themes, students’ imagination and enhance their writing abilities.
  • Classroom Activities: Prompt generators can be used for in-class writing exercises, group activities, or even writing competitions. They can help make writing lessons more interactive and enjoyable.
  • Differentiated Learning: By offering a variety of prompts, educators can address different skill levels and interests, ensuring that all students are both challenged and engaged.

Must Read


Developers

Building a prompt generator is a valuable project for developers, offering multiple benefits:

  • Learning and Practicing Coding Skills: It helps developers learn and practice working with data structures, randomization, user input, and potentially integrating databases and APIs.
  • Portfolio Project: A prompt generator showcases problem-solving skills and the ability to create functional, user-friendly applications, making it a strong addition to a developer’s portfolio.
  • Exploring New Technologies: This project provides an opportunity to explore new programming languages, libraries, and frameworks, with possibilities for advanced features like user authentication, data storage, and machine learning integration.

Getting Started with Python

Before we enter into the code, ensure you have Python installed on your system. You can download it from the official Python website.

Let’s break down the components of our prompt generator.

Step 1: Import Required Libraries

In the initial step of our project, we’re going to import the libraries that are essential for our prompt generator.


import random
import json
    

random library

This library provides functions for generating random numbers. In our prompt generator project, we’ll utilize it to select prompts randomly. This randomness adds variety to the prompts presented to users, making the experience more engaging and unpredictable.

json library

JSON (JavaScript Object Notation) is a lightweight data interchange format that is easy for humans to read and write, and easy for machines to parse and generate. We’ll use the json library to handle exporting and importing prompts. This allows us to save prompts to a file and load them back into our program when needed, enabling persistence of prompts across different sessions.

By importing these libraries, we set up the foundation for our prompt generator project, enabling functionalities such as random prompt selection and data persistence through JSON serialization. These libraries provide the necessary tools to create a strong and functional prompt generator application.

Step 2: Define the PromptGenerator Class

This Python code defines a class named PromptGenerator which summarizes various functionalities of our prompt generator. Let’s break down what each part of the class does:


class PromptGenerator:
    def __init__(self):
        self.prompts = {
            "story": [
                "Write a short story about a time traveler stranded in the Middle Ages.",
                "Describe a futuristic cityscape bustling with life.",
                "Create a dialogue between two robots discussing the meaning of existence."
            ],
            "scenario": [
                "Imagine a world where humans have colonized Mars. What challenges do they face?",
                "Invent a new technology that revolutionizes transportation.",
                "Imagine a society where emotions are controlled by a central authority."
            ],
            "poetry": [
                "Write a poem about the beauty of nature.",
                "Compose a sonnet about love and loss.",
                "Craft a haiku about the changing seasons."
            ],
            "argument": [
                "Write a persuasive argument for why space exploration is important.",
                "Debate the ethics of artificial intelligence.",
                "Argue for or against the existence of extraterrestrial life."
            ]
        }
        self.categories = list(self.prompts.keys())
    

__init__ Method

This is a special method in Python classes that is called when a new instance of the class is created. In this method, the PromptGenerator class initializes its attributes.

self.prompts Dictionary:

This dictionary contains different categories of prompts as keys, with each category mapped to a list of prompts. For example, the "story" category contains prompts related to storytelling, while the "scenario" category contains prompts for imagining different scenarios, and so on.

self.categories List

This attribute stores a list of all the categories available in the prompts dictionary. It’s created by extracting the keys from the prompts dictionary using the keys() method and converting them into a list.

By defining the PromptGenerator class in this way, we create a structure that organizes prompts into categories and provides methods for managing these prompts, such as generating, adding, editing, removing, and searching for prompts within each category. This class serves as the core component of our prompt generator application.

Illustration of a computer screen showing Python code with colorful prompts, representing the process of building a simple prompt generator in Python.
Dive into Python coding with our tutorial on building a simple prompt generator. Unleash your creativity and conquer writer’s block!

Step 3: Generate Random Prompts

This generate_prompt method is responsible for generating a random prompt based on the specified category and difficulty level. Let’s go through the code and understand how it works:


    def generate_prompt(self, category=None, difficulty=None):
        if category:
            if category in self.prompts:
                if difficulty:
                    filtered_prompts = [prompt for prompt in self.prompts[category] if difficulty.lower() in prompt.lower()]
                    if filtered_prompts:
                        return random.choice(filtered_prompts)
                    else:
                        return f"No prompts found for the '{difficulty}' difficulty in the '{category}' category."
                else:
                    return random.choice(self.prompts[category])
            else:
                return f"Sorry, I don't have prompts for the '{category}' category."
        else:
            all_prompts = [prompt for prompt_list in self.prompts.values() for prompt in prompt_list]
            return random.choice(all_prompts)
    

Here’s a breakdown of what each part of the method does:

Input Parameters

The method takes two optional parameters:

  • category: Specifies the category of prompts from which to choose. If not specified, prompts from all categories will be considered.
  • difficulty: Specifies the difficulty level of prompts. If specified, only prompts containing the specified difficulty level (case-insensitive) will be considered.

Category Check

The “Category Check” process involves several steps:

  1. If a category is provided, the method verifies its existence in the self.prompts dictionary.
  2. If the category exists:
    • When a difficulty level is also provided, prompts in the specified category are filtered based on the given difficulty level using list comprehension.
    • If filtered prompts are available, one is randomly selected and returned.
    • When no prompts match the specified difficulty level, a message indicating the absence of prompts for the specified category and difficulty level is returned.
    • If no difficulty level is specified, a prompt is randomly selected from the specified category and returned.
  3. If the specified category does not exist, a message indicating the unavailability of prompts for the specified category is returned.

Random Prompt Selection

If no category is specified, it creates a list (all_prompts) containing all prompts from all categories. It then randomly selects one prompt from this list and returns it.

Overall, this method efficiently handles the generation of random prompts based on the specified category and difficulty level, providing flexibility and customization options for users of the prompt generator.

Step 4: List Categories

This list_categories method serves to provide users with a list of all available categories within the prompt generator. Let’s expand on its functionality:


def list_categories(self):
    return self.categories
    

This method is quite straightforward:

  1. self.categories: This attribute stores a list of all available categories in the prompt generator. It was initialized in the __init__ method of the PromptGenerator class.
  2. Return Statement: The method simply returns the list of categories stored in the self.categories attribute.

By calling this method, users can easily obtain a list of all available categories, allowing them to explore the various options for prompts within the generator.

Step 5: Add, Remove, and Edit Prompts

These methods offer functionality for users to manage their prompt collection, including adding, removing, and editing prompts. Let’s elaborate on each method:


    def add_prompt(self, category, prompt):
        if category in self.prompts:
            self.prompts[category].append(prompt)
        else:
            self.prompts[category] = [prompt]
            self.categories.append(category)

    def remove_prompt(self, category, prompt):
        if category in self.prompts and prompt in self.prompts[category]:
            self.prompts[category].remove(prompt)
            return f"Prompt '{prompt}' removed from the '{category}' category."
        else:
            return f"Prompt '{prompt}' not found in the '{category}' category."

    def edit_prompt(self, category, old_prompt, new_prompt):
        if category in self.prompts and old_prompt in self.prompts[category]:
            index = self.prompts[category].index(old_prompt)
            self.prompts[category][index] = new_prompt
            return f"Prompt '{old_prompt}' edited to '{new_prompt}' in the '{category}' category."
        else:
            return f"Prompt '{old_prompt}' not found in the '{category}' category."
    

add_prompt(self, category, prompt)

This method allows users to add a new prompt to the specified category.It first checks if the specified category exists in the self.prompts dictionary.

If the category exists, it appends the new prompt to the list of prompts in that category. If the category doesn’t exist, it creates a new category with the provided prompt and updates the self.categories list accordingly.

remove_prompt(self, category, prompt)

This method enables users to remove a prompt from the specified category.It checks if both the specified category and prompt exist in the self.prompts dictionary.If they exist, it removes the specified prompt from the list of prompts in that category.

If either the category or prompt doesn’t exist, it returns a message indicating that the prompt was not found in the specified category.

edit_prompt(self, category, old_prompt, new_prompt)

This method allows users to edit an existing prompt in the specified category. It verifies if the specified category and the old prompt exist in the self.prompts dictionary. If they exist, it finds the index of the old prompt in the list of prompts for that category and replaces it with the new prompt. If either the category or the old prompt is not found, it returns a message indicating that the old prompt was not found in the specified category.

These methods provide users with the necessary tools to customize and manage their prompt collection according to their preferences and needs.

Step 6: Search Prompts

This search_prompt method facilitates users in finding prompts containing specific keywords.


    def search_prompt(self, keyword):
        matching_prompts = []
        for category, prompts in self.prompts.items():
            for prompt in prompts:
                if keyword.lower() in prompt.lower():
                    matching_prompts.append(prompt)
        return matching_prompts

    

Here’s how it works:

Repeating through Categories and Prompts

The method repeats over each category and its associated prompts in the self.prompts dictionary.

Keyword Matching

Within each category, it checks each prompt to see if the specified keyword (case-insensitive) is present in the prompt text. If a match is found, the prompt is added to the matching_prompts list.

Returning Matching Prompts

After repeating all categories and prompts, the method returns a list containing all prompts that contain the specified keyword.

By utilizing this method, users can efficiently search for prompts relevant to their interests or themes by specifying keywords, thereby enhancing the usability and flexibility of the prompt generator.

Step 7: Export and Import Prompts

These methods allow users to export their prompts to a file or import prompts from a file, enhancing the flexibility and portability of the prompt generator. Let’s expand on each method:


def export_prompts(self, filename):
    with open(filename, 'w') as f:
        json.dump(self.prompts, f, indent=4)
    return f"Prompts exported to '{filename}'."

def import_prompts(self, filename):
    with open(filename, 'r') as f:
        self.prompts = json.load(f)
        self.categories = list(self.prompts.keys())
    return f"Prompts imported from '{filename}'."

    

export_prompts(self, filename)

This method allows users to export their prompts to a file specified by the filename parameter.

  • It opens the file in write mode ('w') using a context manager (with open(...)).
  • And it uses the json.dump() function to serialize the self.prompts dictionary into JSON format and write it to the file.
  • It returns a message indicating the successful export of prompts to the specified file.

import_prompts(self, filename)

  1. This method enables users to import prompts from a file specified by the filename parameter.
    • It opens the file in read mode ('r') using a context manager.
    • Uses the json.load() function to deserialize the JSON data from the file and load it into the self.prompts dictionary.
    • It updates the self.categories attribute to reflect any changes in the categories based on the imported prompts.
    • It returns a message confirming the successful import of prompts from the specified file.

These methods empower users to manage their prompt collections more efficiently by allowing them to save their prompts to a file for later use or import prompts from an external source.

Step 8: Get Total Prompts

This get_total_prompts method serves to provide users with information regarding the total number of prompts available in the prompt generator, either overall or within a specific category. Let’s explain its functionality:


def get_total_prompts(self, category=None):
    if category:
        if category in self.prompts:
            return len(self.prompts[category])
        else:
            return f"Sorry, '{category}' category not found."
    else:
        total_prompts = sum([len(prompts) for prompts in self.prompts.values()])
        return total_prompts

    

Here’s how it works:

Category-Specific Count

A category is specified, the method checks if the provided category exists in the self.prompts dictionary.

  • If the category exists, it returns the total number of prompts within that category using the len() function on the list of prompts in that category.
  • If the specified category is not found, it returns a message indicating that the category was not found.

Overall Count

  1. If no category is specified, the method calculates the total number of prompts across all categories.
    • It iterates through each category in the self.prompts dictionary and sums up the lengths of all lists of prompts within each category using a list comprehension.
    • It returns the total count of prompts across all categories.

This method provides users with insight into the number of prompts available, allowing them to gauge the breadth of available prompts and make informed decisions when utilizing the prompt generator.

Example Usage


# Example usage
generator = PromptGenerator()

print(generator.get_total_prompts())  # Get total number of prompts in all categories
print(generator.get_total_prompts("story"))  # Get total number of prompts in the "story" category

    
Illustration depicting a Python code snippet with colorful prompts emerging from it, symbolizing the process of building a simple prompt generator. Text overlay reads 'Building a Simple Prompt Generator in Python.' Get ready to unlock your creativity!
Empower Your Imagination: Explore the magic of Python with our step-by-step guide to building a prompt generator. Let your creativity soar!

Conclusion

Building a prompt generator in Python is an excellent project to enhance your programming skills while creating a useful tool. By following the steps outlined above, you can create a flexible and STRONG prompt generator customize to your needs.

You can expand this project by adding more features or integrating it into a larger application.

Source code

app.py


from flask import Flask, render_template, request, jsonify
from prompt_generator import PromptGenerator

app = Flask(__name__)
generator = PromptGenerator()

@app.route('/')
def index():
    return render_template('index.html', categories=generator.list_categories())

@app.route('/generate', methods=['POST'])
def generate():
    category = request.form.get('category')
    topic = request.form.get('topic')
    prompt = generator.generate_prompt(category=category, topic=topic)
    return jsonify(prompt=prompt)

if __name__ == '__main__':
    app.run(debug=True)

    

prompt_generator.py


import random
import json


class PromptGenerator:
    def __init__(self):
        self.prompts = {
            "story": [
                "Write a short story about a {}.",
                "Describe a day in the life of a {}.",
                "Create a dialogue between two {} discussing the meaning of existence."
            ],
            "scenario": [
                "Imagine a world where {} is a common phenomenon. What challenges do people face?",
                "Invent a new technology that revolves around {}.",
                "Imagine a society where {} is controlled by a central authority."
            ],
            "poetry": [
                "Write a poem about {}.",
                "Compose a sonnet about {} and its significance.",
                "Craft a haiku about {}."
            ],
            "argument": [
                "Write a persuasive argument for why {} is important.",
                "Debate the ethics of {}.",
                "Argue for or against the existence of {} in our world."
            ]
        }
        self.categories = list(self.prompts.keys())

    def generate_prompt(self, category=None, topic=None):
        if not topic:
            return "Please provide a topic."

        templates = []

        if category:
            if category in self.prompts:
                templates = self.prompts[category]
            else:
                return f"Sorry, I don't have prompts for the '{category}' category."
        else:
            templates = [prompt for prompt_list in self.prompts.values() for prompt in prompt_list]

        selected_template = random.choice(templates)
        prompt = selected_template.format(topic)

        return prompt

    def list_categories(self):
        return self.categories

    def add_prompt(self, category, prompt):
        if category in self.prompts:
            self.prompts[category].append(prompt)
        else:
            self.prompts[category] = [prompt]
            self.categories.append(category)

    def remove_prompt(self, category, prompt):
        if category in self.prompts and prompt in self.prompts[category]:
            self.prompts[category].remove(prompt)
            return f"Prompt '{prompt}' removed from the '{category}' category."
        else:
            return f"Prompt '{prompt}' not found in the '{category}' category."

    def edit_prompt(self, category, old_prompt, new_prompt):
        if category in self.prompts and old_prompt in self.prompts[category]:
            index = self.prompts[category].index(old_prompt)
            self.prompts[category][index] = new_prompt
            return f"Prompt '{old_prompt}' edited to '{new_prompt}' in the '{category}' category."
        else:
            return f"Prompt '{old_prompt}' not found in the '{category}' category."

    def search_prompt(self, keyword):
        matching_prompts = []
        for category, prompts in self.prompts.items():
            for prompt in prompts:
                if keyword.lower() in prompt.lower():
                    matching_prompts.append(prompt)
        return matching_prompts

    def export_prompts(self, filename):
        with open(filename, 'w') as f:
            json.dump(self.prompts, f, indent=4)
        return f"Prompts exported to '{filename}'."

    def import_prompts(self, filename):
        with open(filename, 'r') as f:
            self.prompts = json.load(f)
            self.categories = list(self.prompts.keys())
        return f"Prompts imported from '{filename}'."

    def get_total_prompts(self, category=None):
        if category:
            if category in self.prompts:
                return len(self.prompts[category])
            else:
                return f"Sorry, '{category}' category not found."
        else:
            total_prompts = sum([len(prompts) for prompts in self.prompts.values()])
            return total_prompts

    
Image depicting a Python code editor with snippets of code showcasing the creation process of a prompt generator. The code snippets are accompanied by annotations highlighting key steps in building the generator. This visual emphasizes the simplicity and versatility of creating a prompt generator using Python.
Explore the diverse output generated by our Python Prompt Generator, offering creative prompts for writers, educators, and developers.

Additional features

Although the current version of the prompt generator is quite comprehensive, there are several additional features that could enhance its usability and applicability in real-world scenarios. Here are a few suggestions:

User Authentication

Implement a user authentication system to allow multiple users to access and manage prompts securely.

Database Integration

It helps to store prompts and categories in a database for better scalability and data management.

Role-based Access Control

Assign different roles (e.g., admin, moderator, user) to users and restrict access to certain features based on their roles.

Prompt Voting/Rating

Allow users to vote or rate prompts, and display the most popular or highest-rated prompts.

Scheduled Prompt Generation

Implement a scheduler to automatically generate prompts at specified intervals (e.g., daily, weekly) and notify users.

Prompt Sharing

Enable users to share prompts with others via email, social media, or direct links.

Integration with AI Models

Integrate the prompt generator with AI models (e.g., GPT-3) to generate responses or content based on the prompts.

Prompt Generation API

Create an API for the prompt generator, allowing external applications to access and utilize prompt generation functionality.

Prompt Analytics

Track and analyze usage metrics (e.g., number of prompts generated, popular categories) to gain insights into user behavior.

Customizable Difficulty Levels

Allow users to specify custom difficulty levels or criteria for generating prompts.

Adding these features would make the prompt generator more versatile and suitable for use in real-world applications, such as educational platforms, content creation tools, and writing communities.

FAQ’s

FAQ Section
1. What is a prompt generator and why should I build one?
A prompt generator is a tool that provides random writing prompts to inspire creativity. Building one in Python is a great way to practice coding skills, learn about data structures, and create a useful application that can aid writers and educators.
2. What are the prerequisites for building a prompt generator in Python?
To build a prompt generator, you need basic knowledge of Python, including functions, classes, and handling data structures like lists and dictionaries. Additionally, having Python installed on your system is essential.
3. How do I install the required libraries for this project?
For this project, you primarily need Python’s built-in random and json libraries. These come pre-installed with Python, so there’s no need for additional installations.
4. Can I add my own prompts to the generator?
Yes, the prompt generator includes methods for adding, editing, and removing prompts. You can customize the prompts by modifying the prompt collection in the PromptGenerator class or using the provided methods to dynamically add new prompts.
5. How can I extend the functionality of the prompt generator?
You can extend the functionality by adding features such as user authentication, database integration for storing prompts, or even incorporating machine learning to generate more sophisticated prompts. The possibilities are vast and can be tailored to your needs.
6. How do I use the web application version of the prompt generator?
The web application version uses Flask to create a simple web interface. After setting up the Flask environment, you can run the app.py file, and access the application through your web browser. From there, you can generate prompts based on specified categories and topics.

About The Author

2 thoughts on “Building a Simple Prompt Generator in Python”

  1. Pingback: How to Build Your own Advanced AI Writer - EmiTechLogic

  2. Pingback: How to Create a Chatgpt for PDF with Python - EmiTechLogic

Leave a Reply

Your email address will not be published. Required fields are marked *