Crafting Multi-Chapter Narratives with Amazon Bedrock: A Journey into Automated Storytelling
Tags: aws, programming, python, ai
Published: 2023-10-21 22:54:55

**Prologue: The Endeavor to Create Automated Storytelling**
In the realm of creative writing, the stroke of a pen (or the clack of a keyboard) has always been a human endeavor. Yet, as artificial intelligence (AI) burgeons with sophistication, we find ourselves with curious companions in the journey of storytelling. In this project, we ventured to craft a multi-chapter narrative using the AI model by AI21 Labs on Amazon Bedrock, unleashing the imaginative prowess of machines. Here’s a glimpse into our expedition.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mdma6lt0kmndkbynovok.png)

**Chapter 1: Unveiling the Protagonist - Amazon Bedrock's AI21.j2-ultra**

```
import boto3
import json

bedrock = boto3.client(service_name='bedrock-runtime', region_name='us-west-2')
```
Replace the region with the region you want to use which has Amazon Bedrock available.

In the snippet above, we import the necessary libraries and create a client for the Bedrock Runtime service. This client will be our conduit to the AI model, enabling us to invoke the model and receive its generated text.


**Chapter 2: Creating the Genesis by Defining the Function**
Our journey begins with defining a function 'generate_chapter' that takes a narrative prompt and returns a generated chapter based on that prompt.

```
def generate_chapter(prompt):
    # Prepare the request body
    body = json.dumps({
        "prompt": prompt,
        "maxTokens": 4096,  # Adjust as needed
        "temperature": 0.7,
        "topP": 0.8
    })

    modelId = 'ai21.j2-ultra'

    response = bedrock.invoke_model(body=body, modelId=modelId, accept='application/json', contentType='application/json')

    response_body = json.loads(response.get('body').read())
    text = response_body.get("completions")[0].get("data").get("text")

    return text
```

In this function, we prepare a request to the AI model, specifying the narrative prompt alongside other parameters like 'maxTokens', 'temperature', and 'topP' to control the generation process. The model is then invoked, and the generated text is extracted from the response, ready to be woven into our evolving story.

**Chapter 3: The Narrative Unfolds - Generating Chapters**
With the mechanism to create individual chapters in place, we set forth to generate a multi-chapter narrative, each chapter building upon the last.

```
# Initial prompt for Chapter 1
initial_prompt = "Once upon a time in a land far, far away...\n\nChapter 1:"

# Generate 3 chapters
story = initial_prompt
for chapter_number in range(1, 4):
    print(f"Generating Chapter {chapter_number}...")
    chapter_title = f"\n\nChapter {chapter_number}:"
    chapter_prompt = story + chapter_title + "Based on this chapter, write the chapter number and continue the story"
    chapter_text = generate_chapter(chapter_prompt)
    # Extract the new chapter from the generated text
    new_chapter = chapter_text.split(chapter_title)[-1].strip()
    # Append the new chapter to the story
    story += f"\n{new_chapter}"
```

Here, we initiate the narrative with a whimsical prompt. A loop then iterates through the chapters, each time generating a new chapter based on the entire story thus far, ensuring a coherent progression of the narrative.

**The Tome is Bound: Saving the Story**
As the AI breathes life into the final words of the narrative, we ensure the tale is not lost to the digital ether, but saved for posterity.

```
with open('story.txt', 'w') as file:
    file.write(story)

print("Story written to story.txt")
```

With a simple file write operation, the story birthed from the alliance of human and machine is saved, ready to be shared, read, and reminisced.

**Epilogue: Dreams of Further Exploration**
The project was a voyage into the uncharted waters of automated storytelling. While the AI's narrative prowess showcased promise, it also reflected the nuances and intricacies inherent to storytelling, a realm where human imagination has always reigned supreme. Yet, as we skim through the pages of the generated tale, we can’t help but marvel at the potential symbiosis of human creativity and machine capability, each pushing the boundaries of what's possible in the realm of storytelling.

And as the closing line of our generated narrative states, "From that day on, the Kingdom of Dreams was safe, and the people were able to sleep peacefully once again," we too take a moment of respite, with dreams of further explorations in the confluence of AI and creativity.

But as the sun sets on the Kingdom of Dreams, shadows loom on the horizon. The silence of the night is a harbinger of the tales yet untold, the adventures yet embarked upon. With a quill in one hand and code in the other, we stand at the precipice of a new narrative frontier. As the dusk of today's accomplishments makes way for the dawn of tomorrow's endeavors, one can't help but wonder - what new stories will the morrow bring? What uncharted territories of imagination shall we venture into next, as the saga of human and machine continues to unfold? The page is yet to be turned, the story yet to be told...

**Author's note:**
Please note that given the nature of Generative AI, responses may vary and you may not always get a good format in the way responses are formatted. This is something I am still experimenting on as well and will build on in further posts.