Create Haiku Poetry with AI Using Next.js

Create Haiku Poetry with AI Using Next.js

Table of Contents:

  1. Introduction
  2. Setting up the Next.js app
  3. Installing necessary dependencies
  4. Creating an API endpoint for generating haikus
  5. Using the OpenAI Package for streaming responses
  6. Adding user customization for haiku inspiration
  7. Building the front-end interface
  8. Styling the form and output
  9. Deploying the app to Vercel
  10. Conclusion

Introduction

Welcome to this Tutorial on generating haikus using AI! In this article, we will walk through the process of setting up a Next.js app and integrating the OpenAI package to create a simple haiku generator. Whether you're a seasoned programmer or just getting started, this tutorial will provide you with the knowledge you need to build your own AI-powered Poetry app. Let's dive in!

Setting up the Next.js app

To begin, we need to set up a new Next.js project. Open your terminal and run the following command:

npx create-next-app HaikuGPT

This command will create a new Next.js app with the default options. Once the project is created, navigate into the project directory using the following command:

cd HaikuGPT

Now, let's open the project in your preferred code editor.

Installing necessary dependencies

In order to style our form elements and handle streaming responses from the OpenAI API, we need to install a couple of Node.js modules. Run the following command in your terminal to install these dependencies:

npm install tailwindcss-forms @openai/api

The tailwindcss-forms module is a plugin that helps style form elements like text areas when using Tailwind CSS for your styling. The @openai/api module is the star of the show, as it simplifies the integration with streaming AI APIs.

Creating an API endpoint for generating haikus

Next, we'll create an API endpoint that will generate the haikus. In Next.js, the routes are constructed based on the directory structure. Create a new file named haiku.js inside the pages/api directory. This file will contain the logic for generating the haikus.

export default async function haiku(request, response) {
  // Logic for generating haikus
}

For now, let's just return a simple "Hello, world!" response so that we can test if the API endpoint is working correctly.

export default async function haiku(request, response) {
  response.status(200).json({ message: "Hello, world!" });
}

To test the API endpoint, start the Next.js development server by running the following command in your terminal:

npm run dev

Then, open your browser and navigate to http://localhost:3000/api/haiku. You should see the "Hello, world!" response.

Using the OpenAI package for streaming responses

Now that we have the API endpoint set up, let's integrate the OpenAI package to handle streaming responses from the AI model.

First, we need to install the openai package and import the necessary objects for streaming responses. Run the following command in your terminal:

npm install @openai/api stream

Next, let's import the required objects and set up the initial messages that will be given to the model.

import { openai, openaiStream, openaiStreamingTextCompletion } from "@openai/api";

const systemPrompt = "You are a creative writer who only responds in haiku.";
const userPrompt = "I like coffee.";

const messages = [
  { role: "system", content: systemPrompt },
  { role: "user", content: userPrompt },
];

With the necessary setup in place, we can replace the "Hello, world!" response with an actual haiku generated using the OpenAI model.

const gptResponse = await openai.complete({
  engine: "davinci",
  prompt: messages,
  temperature: 1.3,
  max_tokens: 50,
});

const haiku = gptResponse.choices[0].text.trim();

response.status(200).json({ haiku });

Now, when you navigate to http://localhost:3000/api/haiku, you should see a randomly generated haiku.

Adding user customization for haiku inspiration

Currently, the haiku generator is limited to responding to the Prompt "I like coffee." Let's change that and allow users to provide their own custom inspiration for the haikus.

First, we need to modify the API endpoint to accept a POST request instead of a GET request.

export default async function haiku(request, response) {
  if (request.method === "POST") {
    // Logic for generating haikus
  } else {
    response.status(405).json({ message: "Method not allowed" });
  }
}

To obtain the prompt value from the request body, we can use the await request.json() function. Remember to use the await keyword, as this is an asynchronous function.

export default async function haiku(request, response) {
  if (request.method === "POST") {
    const { prompt } = await request.json();
    // Logic for generating haikus using the prompt
  } else {
    response.status(405).json({ message: "Method not allowed" });
  }
}

Now that the backend is ready, let's switch over to the frontend and allow users to provide their own haiku inspiration.

Building the front-end interface

In order to capture user input and display the generated haikus, we need to build a simple form and output area on the front-end.

Open the pages/index.js file and remove the default content. We'll start from scratch and build the form and output area from the ground up.

Add the following code to create a form element, a text input, a button, and a div to display the output:

import { useState } from "react";

export default function Home() {
  const [input, setInput] = useState("");
  const [haiku, setHaiku] = useState("");

  const handleSubmit = async (e) => {
    e.preventDefault();

    const response = await fetch("/api/haiku", {
      method: "POST",
      body: JSON.stringify({ prompt: input }),
      headers: {
        "Content-Type": "application/json",
      },
    });

    const data = await response.json();
    setHaiku(data.haiku);
  };

  const handleInputChange = (e) => {
    setInput(e.target.value);
  };

  return (
    <div className="flex flex-col items-center justify-center min-h-screen py-2">
      <form className="mb-4" onSubmit={handleSubmit}>
        <input
          type="text"
          className="border border-gray-300 px-3 py-2 rounded-md w-64"
          placeholder="Enter your inspiration"
          value={input}
          onChange={handleInputChange}
        />
        <button
          type="submit"
          className="bg-blue-500 text-white px-4 py-2 rounded-md ml-2"
        >
          Generate Haiku
        </button>
      </form>
      <div className="px-4 py-2 border border-gray-300 rounded-md">
        {haiku}
      </div>
    </div>
  );
}

Now, when you run the development server and navigate to http://localhost:3000, you should see a form where you can enter your own haiku inspiration. Upon submitting the form, the generated haiku will be displayed below.

Styling the form and output

At the moment, our form and output area look pretty plain. Let's style them using Tailwind CSS and make them more visually appealing.

In the pages/index.js file, delete the existing styles for the input and output elements. We'll use some pre-built styles from Tailwind UI to style our form.

<input
  type="text"
  className="w-full px-4 py-2 border border-gray-300 rounded-md shadow-sm focus:outline-none focus:ring-indigo-500 focus:border-indigo-500"
  placeholder="Enter your inspiration"
  value={input}
  onChange={handleInputChange}
/>
<div className="bg-white px-4 py-2 border border-gray-300 rounded-md shadow-sm">
  {haiku}
</div>

After making these changes, you should see that the form and output area now have a more polished appearance.

Deploying the app to Vercel

Now that we have our haiku generator up and running locally, let's deploy it to Vercel so that it can be accessed online.

Before deploying, make sure you have a Vercel account and the Vercel CLI installed on your machine. Then, run the following command in your terminal:

vercel

Follow the prompts to log in to your Vercel account and deploy the app. Once the deployment process is complete, you will be provided with a URL where you can access your haiku generator.

Conclusion

Congratulations! You have successfully built a haiku generator using AI and Next.js. By following this tutorial, you have learned how to set up a Next.js app, integrate the OpenAI package, and enable user customization for haiku inspiration. You have also learned how to build a simple front-end interface and deploy the app to Vercel. Now it's time to unleash your creativity and generate beautiful haikus. Happy coding!


Highlights:

  • Set up a Next.js app to generate haikus using AI
  • Integrated the OpenAI package for streaming responses
  • Allowed user customization for haiku inspiration
  • Built a front-end interface with form and output display
  • Styled the form and output using Tailwind CSS
  • Deployed the app to Vercel for online access

FAQ

Q: Can I use the haiku generator for other types of poems? A: Currently, the haiku generator is specifically designed for generating haikus. However, with some modifications to the code and prompt structure, you can adapt it to generate other types of poems as well.

Q: Is the generated haiku always unique? A: The haikus generated by the AI model are unique to a certain extent. However, due to the nature of AI-generated content, there is a possibility of encountering similar or identical haikus.

Q: Can I run the haiku generator on my own server? A: Yes, you can run the haiku generator on your own server by following the installation instructions and code provided in the tutorial. The code is available on GitHub for reference.


Resources:

Most people like

Find AI tools in Toolify

Join TOOLIFY to find the ai tools

Get started

Sign Up
App rating
4.9
AI Tools
20k+
Trusted Users
5000+
No complicated
No difficulty
Free forever
Browse More Content