Building and Managing the Story Manager

Introduction and Context Setting

Welcome to the second unit of our course, where we will focus on building the Story Manager for our short story generation service. In the previous lesson, we laid the foundation by creating a structured base prompt using a prompt management system. Now, we will take the next step by developing a system to manage and store the stories generated by our service. The Story Manager will allow us to save, retrieve, and organize stories, making it a crucial component of our application.

Before we dive into building the Story Manager, let's briefly recall some fundamental concepts that will be useful. A class can be thought of as a blueprint for creating objects, allowing us to group related data and functionality together. A collection is a way to store multiple items together, such as a list of stories. We will use these concepts to create and manage our stories efficiently.

Creating the StoryManager Class

Let's start by defining the structure for our Story Manager. This component will be responsible for managing our stories.

Python
class StoryManager:
    def __init__(self):
        self.stories = []

Here, we define a class named StoryManager. Inside this class, we set up a collection called stories that will hold our generated stories. This collection is initialized as empty, ready to store stories as they are created.

Note that this implementation keeps stories in memory only during the program’s execution. Once the program stops, the stored stories are lost. For long-term persistence, we’ll later need to store them in a database or file.

Adding Stories to the Manager

Next, we need a way to add stories to our manager. Let's create a method that allows us to do this.

Python
def add_story(self, prompt, story):
    self.stories.append({"id": len(self.stories), "prompt": prompt, "story": story})
    return self.stories[-1]

The add_story method takes two pieces of information: the prompt and the story itself. It creates a new entry containing a unique identifier (based on the current number of stories), the prompt, and the story. This entry is added to the collection of stories. The method then returns the newly added story, allowing us to confirm that it was successfully stored.

Retrieving Stories

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal