Story Generation with Generative Models | Generative AI

Written by- AionlinecourseGenerative AI Tutorials

28_story_generation_with_generative_models


Introduction

Technology and storytelling have been combined by artificial intelligence, revolutionizing storytelling. Captivating tales may be produced using generative models that leverage advances in machine learning. With the help of technology, narrative will be able to transcend human constraints in the future, opening up new possibilities for creativity and expression. The possibilities for narrative creativity are expanded by this fascinating world of tale creation.


Importance of story generation

Story generation breaks through the conventional boundaries of time, expertise, and resource constraints to enable individuals and enterprises to easily produce captivating narratives. In marketing, education, and entertainment, it encourages greater resonance and deeper connection with a range of consumers. In addition to spurring creativity, story creation democratizes access to the transformational potential of the story.


Let’s dive into these story generation with generative models

  • GPT-4
  • Gemini-pro

Overview story generation with generative models GPT-4 and Gemini-pro

GPT-4: GPT-4's sophisticated language models, which produce imaginative, cogent tales, transform the story-generation process. Its fine-tuning powers open up new possibilities for AI-driven narrative discovery and inventive storytelling.


The Workflow:

28_story_generation_gpt_4


Implementation of story generation Using GPT-4

Let’s go through a simple code to understand things better:

Step 1: Installation of OpenAI Library

!pip install openai


Step 2: Importing Necessary Libraries

OpenAI's API, driven by models like GPT-3, GPT-4 allows developers to generate human-like text with ease. This advanced technology finds applications in chatbots, content creation, translation, and more, making it accessible for diverse software integrations.

import os
import openai


Step 3: Setting Up OpenAI API Key

# Replace with your OpenAI API key
openai.api_key = os.environ.get("OPENAI_API_KEY")


Step 4: Initializing OpenAI Client

from openai import OpenAI
client = OpenAI(api_key='Typing your-api-key')


Step 5: Defining Function to Generate API Validation Tests

This Python method takes an input API description and creates API validation tests using OpenAI's GPT-4 model. It obtains the created tests, gives the description to the model, and then delivers the tests back. This simplifies the process of creating API tests.

def generate_api_validation_tests(api_description, max_tokens=20, temperature=0.7):
  response = client.chat.completions.create(
      model="gpt-4",
      messages=[
          {"role": "system", "content": “You are a good story Generator"},
          {"role": "user", "content": api_description}
      ],
      max_tokens=max_tokens,
      temperature=temperature
  )
  return response.choices[0].message.content


Step 6: Generating API Validation Tests and Print the generated Story

This code will print the generated API validation tests based on the input description "love", with a maximum of 100 tokens and a temperature of 0.5, controlling the randomness of the generated text.

api_description = "love"
api_validation_tests = generate_api_validation_tests(api_description, max_tokens=100, temperature=0.5)
print(api_validation_tests)

Generated story Output

Generated Story:
Title: "The Unseen Threads of Love"
"Once upon a time, in the quaint town of Breezewood, lived a young woman named Emily. Emily was known for her radiant smile and her kindness that touched the hearts of everyone around. She owned a small bookstore, a haven filled with tales of love, adventure, and mystery. However, Emily's own life was void of the romance that she often read about in her books.
In the same town lived a young man named Ethan."


Gemini-pro: Gemini-Pro is a powerful language model designed for creative tasks like story generation. It can analyze vast amounts of text data to understand narrative structure and craft original stories.

The Workflow:

28_story_generation_gemini_pro

Step 1: Installation of Library

!pip install -q -U google-generativeai


Step 2: Importing Necessary Libraries

import pathlib
import textwrap
import google.generativeai as genai
# Used to securely store your API key
from google.colab import userdata
from IPython.display import display
from IPython.display import Markdown


Step 3: Markdown List Formatter

The `to_markdown` function converts plain text into Markdown, specifically formatting list items by replacing bullet points with Markdown list indicators and indenting the text with block quote symbols. This facilitates easy Markdown formatting for platforms supporting it.

def to_markdown(text):
text = text.replace('•', '  *')
return Markdown(textwrap.indent(text, '> ', predicate=lambda _: True))


Step 4: Configuring Google API Key & Model Selection

GOOGLE_API_KEY=userdata.get('api_key')
genai.configure(api_key=GOOGLE_API_KEY)
for m in genai.list_models():
if 'generateContent' in m.supported_generation_methods:
  print(m.name)
model = genai.GenerativeModel('gemini-pro')


Step 5: Generator

input_prompt="""You are an expert in story generation"""
%%time
response = model.generate_content("love")
to_markdown(response.text)

Output

"Love"
"A flame that burns bright and warm, A passion that sets hearts ablaze. A bond that transcends physical form, A connection that forever stays.
Love is a dance, a beautiful art, Where two souls intertwine as one. It mends broken hearts, heals the part, And makes life feel like heaven begun.
It's a gentle touch, a whispered word, A look that speaks volumes untold. It's a journey, a path to be heard, Where dreams and desires unfold.
Love is a tapestry, rich and grand, Woven with threads of joy and bliss. It's a painting, a masterpiece unplanned, A canvas that time and space can't dismiss.
It's a song, a melody that flows, A symphony that fills the air. It's a whisper, a secret that knows, The meaning of life beyond compare.
Love is a river, flowing deep, With currents of passion and desire. It nourishes souls, helps them to leap, And sets their spirits on fire.
It's a mountain, rising high, A symbol of hope and aspiration. It inspires us to reach for the sky, And embrace life with jubilation.
Love is a flower, blooming in bloom, Its petals soft, its fragrance sweet. It adds beauty to every room, And makes life's journey complete.
It's a star, shining in the night, A beacon of hope in the darkest hour. It guides us through storms with its light, And gives us the strength to soar.
Love is a flame, burning eternally, A fire that consumes all that is impure. It sets hearts free, makes them soar with glee, And makes life a grand adventure.
So cherish love, hold it dear, For it's a gift beyond compare. Let it fill your soul with joy and cheer, And make your life a love affair."


Conclusion

Generative models, such as GPT-4 and Gemini-pro, provide seamless storytelling in marketing, education, and entertainment, revolutionizing creative storytelling. These cutting-edge models provide limitless chances for creativity and expression, surpassing time and expertise restrictions while promoting deeper audience relationships and inventiveness.