AI-Powered Frontend UI Components Generator (Next.js, GPT4, Langchain, & CopilotKit)
Tags: webdev, javascript, tutorial, programming
Published: 2024-05-06 18:27:32

## **TL;DR**

In this article, you will learn how to build an AI-powered frontend UI components generator that enables you to generate Next.js Tailwind CSS UI components with an implementation tutorial.

We'll cover how to:

- Build the UI components generator web app using Next.js, TypeScript, and Tailwind CSS.
- Use CopilotKit to integrate AI functionalities into the UI components generator.
- Integrate an embedded code editor to make changes to the generated code.

## Prerequisites

To fully understand this tutorial, you need to have a basic understanding of React or Next.js.

Here are the tools required to build the AI-powered UI components generator:

- [Ace Code Editor](https://ace.c9.io/) - an embeddable code editor written in JavaScript that matches the features and performance of native editors.
- [Langchain](https://www.langchain.com/) - provides a framework that enables AI agents to search the web and research any topic.
- [OpenAI API](https://platform.openai.com/api-keys) - provides an API key that enables you to carry out various tasks using ChatGPT models.
- [Tavily AI](https://tavily.com/) - a search engine that enables AI agents to conduct research and access real-time knowledge within the application.
- [CopilotKit](https://github.com/CopilotKit) - an open-source copilot framework for building custom AI chatbots, in-app AI agents, and text areas.

## Project Set up and Package Installation

First, create a Next.js application by running the code snippet below in your terminal:

```tsx
npx create-next-app@latest aiuigenerator
```

Select your preferred configuration settings. For this tutorial, we'll be using TypeScript and Next.js App Router.


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

Next, install Ace code editor, and Langchain packages and their dependencies.

```tsx
npm install react-ace @langchain/langgraph
```

Finally, install the CopilotKit packages. These packages enable us to retrieve data from the React state and add AI copilot to the application.

```tsx
npm install @copilotkit/react-ui @copilotkit/react-textarea @copilotkit/react-core @copilotkit/backend
```

Congratulations! You're now ready to build an AI-powered blog.

## **Building The UI Components Generator Frontend**

In this section, I will walk you through the process of creating the UI components generator frontend with static content to define the generator’s user interface.

To get started, go to `/[root]/src/app` in your code editor and create a folder called `components`. Inside the components folder, create two files named `Header.tsx`, and `CodeTutorial.tsx` .

In the `Header.tsx` file, add the following code that defines a functional component named `Header` that will render the generator’s navbar.

```tsx
"use client";

import Link from "next/link";

export default function Header() {
  return (
    <>
      <header className="flex flex-wrap sm:justify-start sm:flex-nowrap z-50 w-full bg-gray-800 border-b border-gray-200 text-sm py-3 sm:py-0 ">
        <nav
          className="relative max-w-7xl w-full mx-auto px-4 sm:flex sm:items-center sm:justify-between sm:px-6 lg:px-8"
          aria-label="Global">
          <div className="flex items-center justify-between">
            <Link
              className="w-full flex-none text-xl text-white font-semibold p-6"
              href="/"
              aria-label="Brand">
              AI-UI-Components-Generator
            </Link>
          </div>
        </nav>
      </header>
    </>
  );
}
```

In the `CodeTutorial.tsx` file, add the following code that defines a functional component named `CodeTutorial` that renders the UI components generator homepage that will display the generated UI components, embedded code editor and generated implementation tutorial.

```tsx
"use client";

import Markdown from "react-markdown";
import { useState } from "react";
import AceEditor from "react-ace";
import React from "react";

export default function CodeTutorial() {
  const [code, setCode] = useState<string[]>([
    `<h1 class="text-red-500">Hello World</h1>`,
  ]);
  const [codeToDisplay, setCodeToDisplay] = useState<string>(code[0] || "");
  const [codeTutorial, setCodeTutorial] = useState(``);

  function onChange(newCode: any) {
    setCodeToDisplay(newCode);
  }

  return (
    <>
      <main className=" min-h-screen px-4">
        <div className="w-full h-full min-h-[70vh] flex justify-between gap-x-1 ">
          <div className="w-2/3 min-h-[60vh] rounded-lg bg-white shadow-lg p-2 border mt-8 overflow-auto">
            <div
              className="w-full min-h-[60vh] rounded-lg"
              dangerouslySetInnerHTML={{ __html: codeToDisplay }}
            />
          </div>
          <AceEditor
            placeholder="Placeholder Text"
            mode="html"
            theme="monokai"
            name="blah2"
            className="w-[50%] min-h-[60vh] p-2 mt-8 rounded-lg"
            onChange={onChange}
            fontSize={14}
            lineHeight={19}
            showPrintMargin={true}
            showGutter={true}
            highlightActiveLine={true}
            value={codeToDisplay}
            setOptions={{
              enableBasicAutocompletion: true,
              enableLiveAutocompletion: true,
              enableSnippets: false,
              showLineNumbers: true,
              tabSize: 2,
            }}
          />
        </div>
        <div className="w-10/12 mx-auto">
          <div className="mt-8">
            <h1 className="text-white text-center text-xl font-semibold p-6">
              Code Tutorial
            </h1>
            {codeTutorial ? (
              <Markdown className="text-white">{codeTutorial}</Markdown>
            ) : (
              <div className="text-white">
                The Code Tutorial Will Appear Here
              </div>
            )}
          </div>
        </div>
      </main>
    </>
  );
}
```

Next, go to `/[root]/src/page.tsx` file, and add the following code that imports `CodeTutorial` and `Header` components and defines a functional component named `Home`.

```tsx
import React from "react";
import Header from "./components/Header";
import CodeTutorial from "./components/CodeTutorial";

export default function Home() {
  return (
    <>
      <Header />
      <CodeTutorial />
    </>
  );
}

```

Next, remove the CSS code in the globals.css file and add the following CSS code.

```css
@tailwind base;
@tailwind components;
@tailwind utilities;

@tailwind base;
@tailwind components;
@tailwind utilities;

body {
  height: 100vh;
  background-color: rgb(16, 23, 42);
}

pre {
  margin: 1rem;
  padding: 1rem;
  border-radius: 10px;
  background-color: black;
  overflow: auto;
}

h2,
p {
  padding-bottom: 1rem;
  padding-top: 1rem;
}

code {
  margin-bottom: 2rem;
}

```

Finally, run the command `npm run dev` on the command line and then navigate to http://localhost:3000/. 

Now you should view the UI Components generator frontend on your browser, as shown below.


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

## **Integrating AI Functionalities To The Components Generator Using CopilotKit**

In this section, you will learn how to add an AI copilot to the UI components generator to generate UI components code and implementation tutorial using CopilotKit.

CopilotKit offers both frontend and [backend](https://docs.copilotkit.ai/getting-started/quickstart-backend) packages. They enable you to plug into the React states and process application data on the backend using AI agents.

First, let's add the CopilotKit React components to the blog frontend.

### **Adding CopilotKit to the Blog Frontend**

Here, I will walk you through the process of integrating the UI components generator with the CopilotKit frontend to facilitate UI components code and implementation tutorial generation. 

To get started, use the code snippet below to import `useMakeCopilotReadable`, and `useCopilotAction`, custom hooks at the top of the `/[root]/src/app/components/CodeTutorial.tsx` file.

```tsx
import {
  useCopilotAction,
  useMakeCopilotReadable,
} from "@copilotkit/react-core";
```

Inside the `CodeTutorial` function, below the state variables, add the following code that uses the `useMakeCopilotReadable` hook to add the code that will be generated as context for the in-app chatbot. The hook makes the code readable to the copilot.

```tsx
useMakeCopilotReadable(codeToDisplay);
```

Below the code above, add the following code that uses the `useCopilotAction` hook to set up an action called `generateCodeAndImplementationTutorial` which will enable generation of UI components code and implementation tutorial.

The action takes in two parameters called `code` and `tutorial` which enables generation of a UI component code and implementation tutorial.

The action contains a handler function that generates a UI component code and implementation tutorial based on a given prompt. 

Inside the handler function, `codeToDisplay` state is updated with the newly generated code while `codeTutorial` state is updated with the newly generated tutorial, as shown below.

```tsx
useCopilotAction(
    {
      name: "generateCodeAndImplementationTutorial",
      description:
        "Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.",
      parameters: [
        {
          name: "code",
          type: "string",
          description: "Code to be generated",
          required: true,
        },
        {
          name: "tutorial",
          type: "string",
          description:
            "Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.",
          required: true,
        },
      ],
      handler: async ({ code, tutorial }) => {
        setCode((prev) => [...prev, code]);
        setCodeToDisplay(code);
        setCodeTutorial(tutorial);
      },
    },
    [codeToDisplay, codeTutorial]
  );
```

After that, go to `/[root]/src/app/page.tsx` file and import CopilotKit frontend packages and styles at the top using the code below.

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

Then use `CopilotKit` to wrap the `CopilotSidebar` and  `CodeTutorial` components, as shown below. The `CopilotKit` component specifies the URL for CopilotKit's backend endpoint (`/api/copilotkit/`) while the `CopilotSidebar` renders the in-app chatbot that you can give prompts to generate UI components code and implementation tutorial.

```tsx
export default function Home() {
  return (
    <>
      <Header />
      <CopilotKit url="/api/copilotkit">
        <CopilotSidebar
          instructions="Help the user generate code. Ask the user if to generate its tutorial."
          defaultOpen={true}
          labels={{
            title: "Code & Tutorial Generator",
            initial: "Hi! 👋 I can help you generate code and its tutorial.",
          }}>
          <CodeTutorial />
        </CopilotSidebar>
      </CopilotKit>
    </>
  );
}
```

After that, run the development server and navigate to http://localhost:3000. You should see that the in-app chatbot was integrated into the UI components generator.


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

### **Adding CopilotKit Backend to the Blog**

Here, I will walk you through the process of integrating the UI components generator with the CopilotKit backend that handles requests from frontend, and provides function calling and various LLM backends such as GPT. 

Also, we will integrate an AI agent named Tavily that can research any topic on the web.

To get started, create a file called `.env.local` in the root directory. Then add the environment variables below in the file that hold your `ChatGPT` and `Tavily` Search API keys.

```
OPENAI_API_KEY="Your ChatGPT API key"
TAVILY_API_KEY="Your Tavily Search API key"
```

To get the ChatGPT API key, navigate to https://platform.openai.com/api-keys.


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

To get the Tavily Search API key, navigate to https://app.tavily.com/home


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

After that, go to `/[root]/src/app` and create a folder called `api`. In the `api` folder, create a folder called `copilotkit`. 

In the `copilotkit` folder, create a file called `research.ts`. Then Navigate to [this research.ts gist file](https://gist.github.com/TheGreatBonnie/58dc21ebbeeb8cbb08df665db762738c), copy the code, and add it to the **`research.ts`** file

Next, create a file called `route.ts` in the `/[root]/src/app/api/copilotkit` folder. The file will contain code that sets up a backend functionality to process POST requests. It conditionally includes a "research" action that performs research on a given topic.

Now import the following modules at the top of the file.

```tsx
import { CopilotBackend, OpenAIAdapter } from "@copilotkit/backend"; // For backend functionality with CopilotKit.
import { researchWithLangGraph } from "./research"; // Import a custom function for conducting research.
import { AnnotatedFunction } from "@copilotkit/shared"; // For annotating functions with metadata.

```

Below the code above, define a runtime environment variable and a function named `researchAction` that researches a certain topic using the code below.

```tsx
// Define a runtime environment variable, indicating the environment where the code is expected to run.
export const runtime = "edge";

// Define an annotated function for research. This object includes metadata and an implementation for the function.
const researchAction: AnnotatedFunction<any> = {
  name: "research", // Function name.
  description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description.
  argumentAnnotations: [ // Annotations for arguments that the function accepts.
    {
      name: "topic", // Argument name.
      type: "string", // Argument type.
      description: "The topic to research. 5 characters or longer.", // Argument description.
      required: true, // Indicates that the argument is required.
    },
  ],
  implementation: async (topic) => { // The actual function implementation.
    console.log("Researching topic: ", topic); // Log the research topic.
    return await researchWithLangGraph(topic); // Call the research function and return its result.
  },
};

```

Then add the code below under the code above to define an asynchronous function that handles POST requests.

```tsx
// Define an asynchronous function that handles POST requests.
export async function POST(req: Request): Promise<Response> {
  const actions: AnnotatedFunction<any>[] = []; // Initialize an array to hold actions.

  // Check if a specific environment variable is set, indicating access to certain functionality.
  if (process.env.TAVILY_API_KEY) {
    actions.push(researchAction); // Add the research action to the actions array if the condition is true.
  }

  // Instantiate CopilotBackend with the actions defined above.
  const copilotKit = new CopilotBackend({
    actions: actions,
  });

  // Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter.
  return copilotKit.response(req, new OpenAIAdapter());
}

```

## How To Generate UI Components

Now go to the in-app chatbot you integrated earlier and give it a prompt like, “generate a contact form.” 

Once it is done generating, you should see the contact form component generated together with its implementation tutorial, as shown below. You can also modify the generated code using the embedded code editor.


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


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

Congratulations! You’ve completed the project for this tutorial.

## Conclusion

[CopilotKit](https://copilotkit.ai/) is an incredible tool that allows you to add AI Copilots to your products within minutes. Whether you're interested in AI chatbots and assistants or automating complex tasks, CopilotKit makes it easy.

If you need to build an AI product or integrate an AI tool into your software applications, you should consider CopilotKit.

You can find the source code for this tutorial on GitHub: [https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator](https://github.com/TheGreatBonnie/AIPoweredUIComponentsGenerator)