Generating and Managing Stories with the StoryGeneratorService
Introduction and Context Setting
Welcome to the third unit of our course on building a short story generation service. In this lesson, we will focus on generating short stories using AI. We will explore the StoryGeneratorService class, which is a key component of our application. This class will help us take user input, interact with the Claude model, and manage the generated content effectively. By the end of this lesson, you will understand how to integrate these components to create a functional story generation service.
Before we dive into the new material, let's briefly revisit some key concepts from our previous lessons. We have already covered the PromptManager class, which is responsible for formatting user input into a structured prompt. Additionally, we have discussed the StoryManager class, which helps us manage and store generated stories. These components are essential for the functionality of our story generation service, and we will build upon them in this lesson.
Exploring the StoryGeneratorService Class
Let's start by understanding the structure and purpose of the StoryGeneratorService class. This class is responsible for generating stories based on user input and managing the interaction with the Claude model.
First, we initialize the StoryGeneratorService class:
- Here, we import the necessary modules and classes. The
Anthropicclass is used to interact with the Claude model. - The
StoryGeneratorServiceclass initializes with two main components:StoryManagerfor managing stories andAnthropicfor interacting with the AI model. - The
api_keyis retrieved from environment variables, ensuring secure access to the Claude model.
Generating a Story with User Input
Now, let's walk through the process of generating a story using the generate_story method. This method takes user input, formats it, and sends it to the Claude model.
- The
generate_storymethod starts by formatting the user input usingPromptManager.format_prompt(user_input, tone). - It then sends a request to the Claude model using
self.claude_client.messages.create(), specifying the model and the formatted prompt. - The response from the model contains the generated story, which is then stored using
self.story_manager.add_story(prompt, story). - If an error occurs during this process, it is caught, and a
RuntimeErroris raised with a descriptive message.
Note that response.content assumes the model returns the full story as a plain string. If the Claude API structure changes or wraps the response in a nested format (e.g., response.content[0]['text']), you'll need to adjust this line accordingly. Always inspect the returned object format when integrating third-party APIs.
