PythonIntermediate PythonNumPySQLGen AI
HTMLCSSJavaScriptIntermediate JavaScriptReactp5.jsNode.js
Command LineGit & GitHub
C++JavaData Structures & Algorithms
  • ...

  • bookmark

    ...

  • ...

  • ...

  • bookmark

    ...


  • Generate a Poem with Google Gemini

    Katherin Solis

    Prerequisites: HTML, CSS, JavaScript fundamentals
    Versions: Node.js 18, Vite 5, React 18
    Read Time: 45 minutes

    Introduction

    Words, lyrics, music, poetry. Whether it's John Lennon or William Blake, songwriters and poets manage to express feelings that appeal to generations with their writing style. Now imagine if you could combine their styles or even create a new style. In this project tutorial, we will create a poem-generating website using the power of Google Gemini. The poem below changes after a certain number of seconds to always keep you inspired. The best part is that you can customize this completely based on your preferences by the end of this tutorial.

    generator demo

    Before we dive into the wonders of literary voices and how their styles can be mimicked, let's go over the basics of what you will need to complete this project.

    Get an API Key 🔑

    To use the Gemini API, we need an API key. Visit the Google AI Studio, and sign in to a Google account to quickly create a key. Remember: Store your Google Gemini key in a separate file for best practice.

    For more information, you can check out the Google Gemini Documentation.

    Setting Up 🔨

    • Initialize your React application using Vite. Check out our tutorial on setting up with Vite if you need to!
    • Install the necessary packages for using the Gemini API in your project directory.
    npm install @google/generative-ai
    

    Initialize Your Server

    Now that we have our base React application ready to go, let's initiate our development server!

    npm install
    npm run dev
    

    Creating the Poem Generator

    Let's get started with becoming our very own AI poet! In the src folder of your project, create a PoemBox.jsx file. Here, we're going to connect to Gemini and generate our poems!

    Let's get started by importing the model:

    import { GoogleGenerativeAI } from "@google/generative-ai";
    

    Define a <PoemBox> function component. Then, we're going to create a function called fetchPoem(). We'll place our data fetching code here in a try-catch block so we're able to detect and understand errors when we're developing!

    Here, let's also create a variable called genAI, and initialize our instance of the model. Remember your API key that's been stored away? Go ahead and copy that into your instance!

    import { GoogleGenerativeAI } from "@google/generative-ai";
    export default function PoemBox() {
      function fetchPoem() {
        try {
          const genAI = new GoogleGenerativeAI("YOUR_API_KEY"); // replace with your key
        }
      } catch (err) {
        // error handle here
      }
    }
    

    Now, let's focus on setting up the state so we can update our poem! You're going to create three state variables inside your <PoemBox> component.

    const [response, setResponse] = useState("");
    const [error, setError] = useState(null);
    const [currentTime, setCurrentTime] = useState(new Date());
    

    Going back to our fetchPoem() function, let's get started with prompting Gemini!

    Using Gemini

    At this point, our API key should be ready to go! Let's use the current Google generative AI model, gemini-1.5-flash. We're then going to:

    • Create a prompt that will generate our poem.
    • Await a result from the model.
    • Generate a response that we'll use to update the state.
    • Catch if an error occurs.

    Your function should now look like so

    const fetchPoem = async () => {
      try {
        const genAI = new GoogleGenerativeAI("YOUR_API_KEY");
        const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
        const prompt = "AI PROMPT HERE";
        const result = await model.generateContent(prompt);
        const text = result.response.text();
        setResponse(text);
      } catch (err) {
        setError(err.message);
      }
    };
    

    More on Prompting

    Like ChapGPT, Google Gemini is made of LLMs that use NLP to interpret and respond to user inputs. LLMs (short for "Large Language Models") are machine learning models that can understand and generate text based on human language patterns. NLP (short for "Natural Language Processing") is the technology that lets models interpret and manipulate human language. Much like any conversation, you have to have good prompts to experience the best results.
    Prompting on Gemini is like prompting for any other LLM. Here are some things you should remember as you write your prompt.

    💬 Natural Language: talk to the language model as if you are giving instructions to a stranger.

    • If you want: a poem that rhymes about sunsets
    • Prompt for: "write me a sonnet about sunsets in New York"

    🎯 Precise Instructions: avoid using vague or filler words. (e.g., "like, some, a few")

    • If you want: a short poem about tea
    • Prompt for: "write me a haiku about earl grey"

    😊 Context: the more context you provide the more useful Gemini can be.

    • If you want: a fish poem in Dr.Seuss style
    • Prompt for: "write a poem about fish using an anapestic tetrameter in the style of Dr.Seuss"

    🔑 Keywords: Gemini works better when specific keywords are used in the prompt.

    • If you want: a poem similar to work by Rupi Kaur
    • Prompt for: "write me a 10-word poem in the tone of milk and honey by rupi kaur."

    Note: Be respectful of literary intellectual property, technology is a tool that should be used ethically. Learn more about AI Responsibility here.

    The Timer

    We're just a tad bit closer to unlocking your inner AI poet! We want our component to generate a new poem about every 30 seconds!

    Note: For testing purposes, decrease the interval between each poem to observe the results more quickly. However, we don’t recommend promoting the model too quickly since it can overwhelm the version of our model.

    Let's use a handy useEffect() hook to create an interval!

    useEffect(() => {
      // Fetch a poem on initial render
      fetchPoem();
    
      // Fetch a new poem every 30 seconds
      const poemIntervalId = setInterval(fetchPoem, 30000);
      return () => {
        clearInterval(poemIntervalId); // Cleanup poem interval on component unmount
      };
    }, []);
    

    Completion

    Let's display our poems! ✍️

    Remember the error handling we set up in our fetchPoem() function? We'll conditionally render our poem based on whether there are any errors. Our return statement should look like this:

    return <div>{error ? <p>{error}</p> : <p>{response}</p>}</div>;
    

    That's it you just created a <PoemBox> component! Don't forget to import it and use the <PoemBox> component in the App.js file to make it all come together.

    Congrats

    You just created your very own poem generator! 🚀

    Here is how you can take your poem generator to the next level:

    • Prompt a user to input their own poem style.
    • Add a feature to save poems.
    • Design and add CSS.
    • Add a Clock component to display the time.
    • Generate poems in different languages.
    • Create a feature to share poems on social media.
    • Generate poems based on a user's mood.

    Here are some examples we made to inspire your creativity:

    generator css demos

    More Resources

    Hope you had fun generating poems, here are some helpful links!

    Share your poems! We would love to see what you built, so make sure to tag us @codedex_io on Twitter ✍️

    Need Help?

    codedex coin
    author image

    Katherin

    Joined 11-28-2023

    Hi I’m Kat I love everything coffee and learning about tech.

    • New York, NY
    • Codédex

    MORE FROM@KATHERIN

    project

    Generate AI Art with Krea.AI

    BeginnerAI

    project

    Predict Prices with Linear Regression

    DSIntermed.

    RECOMMENDED COURSE

    Origins III: JavaScript