Building 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 the PromptManager class. 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. In Python, a class is a blueprint for creating objects, and it allows us to bundle data and functionality together. Lists, on the other hand, are a versatile data structure that can store a collection of items. We will use these concepts to create and manage our stories efficiently. If you need a refresher, remember that a class is defined using the class keyword, and lists are created using square brackets [].
Creating the StoryManager Class
Let's start by defining the StoryManager class. This class will be responsible for managing our stories.
Here, we define a class named StoryManager. Inside the class, we have an __init__ method, which is a special method in Python used to initialize objects. The self.stories is a list that will hold our generated stories. This list 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’d later need to store them in a database or file.
Adding Stories to the Manager
Next, we need a method to add stories to our manager. Let's create the add_story method.
The add_story method takes two parameters: prompt and story. It appends a dictionary to the self.stories list, where each dictionary contains an id, prompt, and story. The id is generated using the current length of the list, ensuring each story has a unique identifier. The method returns the newly added story, allowing us to confirm the addition.
