DEV Community

Cover image for How I Built a Music Lyric Finder App with CopilotKit and Next.js: A Step-by-Step Guide
Anietie Brownson
Anietie Brownson

Posted on

How I Built a Music Lyric Finder App with CopilotKit and Next.js: A Step-by-Step Guide

Hello there, my fellow open-source warriors! As the season of Hacktoberfest draws to a close, I hope you are making good progress with your contributions. Today I want to share with you how we can use the AI capabilities of Copilotkit to develop a web app that lets users search for song lyrics. Below are the key technologies we'll be using to build this project:

  • Next.js: A React framework that enables server-side rendering and static site generation for building fast, scalable web applications.
  • Tailwind CSS: A utility-first CSS framework for rapidly building custom user interfaces.
  • Shadcn UI: An open-source UI component library designed for modern web applications.
  • CopilotKit: An open-source tool that makes it easy to integrate production-ready Copilots into any application. With CopilotKit, you can seamlessly implement custom AI chatbots and AI agents to enhance the functionality of your application.

Project Setup

First, we'll create a new Next.js app. (At the time of writing this article, I'm using Next.js 14)

npx create-next-app@latest
Enter fullscreen mode Exit fullscreen mode

Choose your preferred options and then cd into your project and install the following dependencies:

npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime 
Enter fullscreen mode Exit fullscreen mode

Head on over to Groq Console, register for a new account if you don't have one and then in your dashboard, generate an API key

Groq console

Now in the root of your project, create an .env.local file and paste in your API key and the following parameters like so:

GROQ_API_KEY="groq api key"
GROQ_MODEL="llama3-8b-8192"
Enter fullscreen mode Exit fullscreen mode

Cool!, before we start working on the project, quickly install the ShadcnUI library:

npm install npx shadcn@latest init
Enter fullscreen mode Exit fullscreen mode

Choose your preferred configuration and then use the command below to get the Card component

npx shadcn@latest add card
Enter fullscreen mode Exit fullscreen mode

Optionally, you can also install the react-icons library

npm install react-icons --save
Enter fullscreen mode Exit fullscreen mode

Now that we have that out of the way, let's dive into building the project

GIF of man jumping into pool


Building the Project

We'll first of all start with the backend part of our app. Inside the app folder create a api folder. Inside the api folder, create two folders namely: actions and copilotkit. Your folder structure should look like this:

├── app
│ ├── api
│ │ ├── actions
│ │ └── copilotkit

Create a file called lyric.ts inside the actions folder. Copy the code below:

"use server";

export async function fetchLyrics({ song, artist }: { song: string; artist: string }) {

    const URL = `https://api.lyrics.ovh/v1/${artist}/${song}`; // url to access the lyrics api

    try {
        const response = await fetch(URL);

        if (!response.ok) {
            throw new Error("Lyrics not found");
        }

        const data = await response.json();

        return data.lyrics || "Lyrics not found.";
    } catch (error) {
        console.error("Error fetching lyrics:", error);
        return "An error occurred while fetching lyrics.";
    }
}

Enter fullscreen mode Exit fullscreen mode

Open the copilotkit folder and create a route.ts file. Copy the code below:

import {
  CopilotRuntime,
  GroqAdapter,
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { Groq } from "groq-sdk";
import { NextRequest } from "next/server";

const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const groqAdapter = new GroqAdapter({
  groq,
  model: process.env.GROQ_MODEL,
});

const runtime = new CopilotRuntime();

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter: groqAdapter,
    endpoint: "/api/copilotkit",
  });

  return handleRequest(req);
};
Enter fullscreen mode Exit fullscreen mode

Now we're done with the backend of our app. For the frontend, open the components folder created for us and create a file called LyricFinder.tsx. Your folder structure should look like this:

├── components
│ ├── ui
│ ├── LyricFinder.tsx

Now copy the code below:

"use client";

import { useState } from "react";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { CiMusicNote1 } from "react-icons/ci";
import { fetchLyrics } from "@/app/api/actions/lyrics";
import { useCopilotAction } from "@copilotkit/react-core";

export default function LyricFinder() {
  const [lyrics, setLyrics] = useState<string | null>(null); // State to hold the lyrics
  const [artist, setArtist] = useState<string>(""); // State to hold the artist name
  const [song, setSong] = useState<string>(""); // State to hold the song title

  // The useCopilotAction hook enables the copilot to perform actions within the app
  // Here, we're using the searchLyrics action to search for lyrics of a song
  useCopilotAction(
    {
      name: "searchLyrics",
      description: "Search for lyrics of a song.",
      parameters: [
        {
          name: "SongLyrics",
          type: "object",
          description: "The song and artist to search for.",
          attributes: [
            {
              name: "artist",
              type: "string",
              description: "The name of the artist.",
              required: true,
            },
            {
              name: "song",
              type: "string",
              description: "The title of the song.",
              required: true,
            },
          ],
          required: true,
        },
      ],
      // Handler function that searches for lyrics using the SongLyrics parameter
      handler: async ({
        SongLyrics,
      }: {
        SongLyrics: { artist: string; song: string };
      }) => {
        const { artist, song } = SongLyrics;
        setArtist(artist); // Updates artist state
        setSong(song); // Updates song state
        const fetchedLyrics = await fetchLyrics({ song, artist }); // Calls the fetchLyrics function
        setLyrics(fetchedLyrics); // Updates state with fetched lyrics
        return fetchedLyrics; // Returns the fetched lyrics
      },
      render: "Searching for lyrics...",
    },
    []
  ); // Dependency array (empty in this case)

  return (
    <>
      <header className="p-4 fixed bg-white w-full">
        <span className="flex gap-x-8 items-center">
          <CiMusicNote1 size={30} />
          <h1 className="text-3xl font-bold">Music Lyric Finder</h1>
        </span>
      </header>

      <section className="overflow-x-auto pt-20 px-4">
        <Card className="p-4">
          <CardHeader>
            <CardTitle>
              <div className="flex flex-col gap-y-5">
                <p>Artist: {artist}</p>
                <p>Song: {song}</p>
              </div>
            </CardTitle>
          </CardHeader>
          <CardContent>
            {lyrics ? (
              <pre className="whitespace-pre-wrap">{lyrics}</pre>
            ) : (
              <p>Lyrics will be displayed here</p>
            )}
          </CardContent>
        </Card>
      </section>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Open the page file in the root of your app folder and paste the code below:

import { CopilotKit } from "@copilotkit/react-core";
import { CopilotSidebar } from "@copilotkit/react-ui";
import "@copilotkit/react-ui/styles.css";
import LyricFinder from "../components/LyricFinder";

export default function Home() {
  return (
    <>
      <CopilotKit runtimeUrl="/api/copilotkit">
        <CopilotSidebar
          instructions={
            "Help the user search for lyrics for their favorite songs."
          }
          labels={{
            title: "Xi 👩", // Title displayed in the sidebar
            initial:
              "👋 Hi! I'm Xi, here to help you find lyrics for your favorite songs. Just type the song title and artist, and I'll get the lyrics for you.", // Initial greeting message
          }}
          defaultOpen={true} // Sidebar will be open by default
          clickOutsideToClose={false} // Prevents the sidebar from closingwhen clicking outside
        >
          <LyricFinder />
        </CopilotSidebar>
      </CopilotKit>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

Sweet! We're done with building the app. Open your terminal and start the development server

npm run dev
Enter fullscreen mode Exit fullscreen mode

Open http://localhost:3000 in your browser to view the app.

App Initial Screenshot

Conclusion

That’s a wrap! In this tutorial, we successfully used CopilotKit to build a Music Lyric Finder app, showcasing how easy it is to integrate AI into our application.

You can view the complete source code in this Github repo

Here's a live demo of the project here

Got any questions? Ask in the comments

Happy Hacking!

Top comments (0)