DEV Community

Cover image for How to integrate GitHub CopilotKit with Prisma Integration into your nextJs project Using OpenAI
Gulshan Sharma
Gulshan Sharma

Posted on

How to integrate GitHub CopilotKit with Prisma Integration into your nextJs project Using OpenAI

What is GitHub CopilotKit:

Build deeply integrated AI assistants & agents designed to work alongside your users inside applications.End-to-end systems integrations with deep customizability and support for the leading LLM ecosystem solutions.

GitHub CopilotKit can seamlessly integrate with multiple AI providers, including OpenAI, Azure OpenAI, and Google Gemini, offering flexibility and scalability to meet diverse business needs. This multi-provider compatibility allows organizations to leverage advanced AI models from different platforms, ensuring access to cutting-edge technologies and features. By supporting multiple providers, Copilot enables users to select the most suitable AI service based on performance, cost, compliance, or specific use-case requirements. This adaptability also reduces dependency on a single provider, enhancing reliability and enabling hybrid AI strategies for improved efficiency and innovation. Document

Create a NextJs Project

Create an app using nextJs: documention

npx create-next-app@latest

Intgreate prisma
Install Prisma ORM: documention

npm install prisma --save-dev
npm install @prisma/client  
npx prisma init     
prisma generate   
Enter fullscreen mode Exit fullscreen mode

Schema structure in Prisma:

generator client {
  provider = "prisma-client-js"
}

datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}
model Blogs{
  id        Int    @id @default(autoincrement())
  title     String
  content   String
  createdAt DateTime @default(now())
}

Enter fullscreen mode Exit fullscreen mode

Schema deploy on database server in Prisma:

npm prisma migrate dev     
npm prisma migrate deploy    
Enter fullscreen mode Exit fullscreen mode

The resources to create a free tire PostgreSQL Database:
neon
supabase

Steps to integration of GitHub CopilotKit:

Add GitHub CopilotKit into the app/layout.js

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

 <CopilotKit runtimeUrl="/api/copilotkit"> 
         {children}
  </CopilotKit>
Enter fullscreen mode Exit fullscreen mode

.env configure environment variables

DATABASE_URL="postgresql://xxxxxxx"
OPENAI_API_KEY=xxxxxxx
Enter fullscreen mode Exit fullscreen mode

Customize the app/page.js for CopilotPopup

"use client";
import { useEffect, useState } from "react";
import { CopilotPopup } from "@copilotkit/react-ui";

export default function Home() {
  const [blogs, setBlogs] =useState([])

  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch('/api/blogs');
      const blogData = await response.json();
      setBlogs(blogData);
    };
    fetchData();
  }, []);
  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
    <main className="flex flex-col gap-8 row-start-2 items-center sm:items-start">
    <table className="table-auto border-collapse border border-gray-300 w-full">
          <thead>
            <tr className="bg-gray-200">
              <th className="border border-gray-300 px-4 py-2">ID</th>
              <th className="border border-gray-300 px-4 py-2">Title</th>
              <th className="border border-gray-300 px-4 py-2">Content</th>
            </tr>
          </thead>
          <tbody>

            {blogs ? blogs.map((blog, idex) => (
            <tr key={idex}>
              <td className="border border-gray-300 px-4 py-2">{blog.id}</td>
              <td className="border border-gray-300 px-4 py-2">{blog.title}</td>
              <td className="border border-gray-300 px-4 py-2">{blog.content}</td>
            </tr>
            )) : <tr><td colSpan={4}> No records found</td></tr>}
          </tbody>
        </table>
        <CopilotPopup
      instructions={"You are assisting the blogs as best as you can. Answer in the best way possible given the data you have."}
      labels={{
        title: "Blog Assistant",
        initial: "Need any help?",
      }}
    />
    </main>

  </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Create an API endpoint for api/copilotkit/route.js and blog data api/blogs/route.js

api/copilotkit/route.js

import {
    CopilotRuntime,
    OpenAIAdapter,
    copilotRuntimeNextJSAppRouterEndpoint
  } from '@copilotkit/runtime';
  import { PrismaClient } from '@prisma/client';
  const serviceAdapter = new OpenAIAdapter();
  const prisma = new PrismaClient();
  const runtime = new CopilotRuntime({
    actions: ({properties,url}) => {
        return [
            {
                name: "updateDb",
                description: "Update blog item to the list",
                parameters: [
                  {
                    name: "id",
                    type: "number",
                    description: "The ID of the post item to data fetch",
                    required: true,
                  },
                  {
                    name: "updateTitle",
                    type: "string",
                    description: "The update title of the blog post to be updated",
                    required: true,
                  },
                  {
                    name: "updateContent",
                    type: "string",
                    description: "The update content of the blog post to be updated",
                    required: true,
                  }
                ],
                handler: async ({ id, updateTitle, updateContent }) => {
                  await prisma.blogs.update({
                    where: {
                      id : Number(id),
                    },
                    data: {
                      title: updateTitle,
                      content: updateContent
                    }
                  })
                },
              },
              {
                name: "addDb",
                description: "Add blog item to the list",
                parameters: [
                  {
                    name: "createTitle",
                    type: "string",
                    description: "The add title of the blog post to be updated",
                    required: true,
                  },
                  {
                    name: "createContent",
                    type: "string",
                    description: "The add content of the blog post to be updated",
                    required: true,
                  }
                ],
                handler: async ({ createTitle, createContent }) => {
                  await prisma.blogs.create({
                    data: {
                      title: createTitle,
                      content: createContent
                    }
                  })
                },
              }
        ]
    }
  });

  export const POST = async (req) => {
    const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
      runtime,
      serviceAdapter,
      endpoint: '/api/copilotkit',
    });
    return handleRequest(req);
  };
Enter fullscreen mode Exit fullscreen mode

api/blogs/route.js

import { NextResponse } from 'next/server';
import { PrismaClient } from '@prisma/client';
const prisma = new PrismaClient();
export async function GET() {
  try {
    const tableData = await prisma.blogs.findMany();
    return NextResponse.json(tableData);
  } catch (error) {
    console.error('Error fetching data:', error);
    return NextResponse.json({ error: 'Error fetching data' }, { status: 500 });
  } finally {
    await prisma.$disconnect();
  }
}
Enter fullscreen mode Exit fullscreen mode

To run Copiltkit make a build and run the project

We can directly run it on locally because of the strict mode in nextJs. so first we have to make a build and then run the project

npm run build
npm run start
Enter fullscreen mode Exit fullscreen mode

Finally your website is ready to use the Copilotkit

Project Screenshot

Hey, My name is Gulshan, If you have enjoyed and learned something useful, like this post, add a comment.

Don't forget to give it a start 😅.

Happy Coding 🧑‍💻

Top comments (1)

Collapse
 
mohit_saini_e632c0b964b87 profile image
Mohit Saini

Thank you for sharing such a detailed guide on the technical steps to integrate and use CopilotKit. This comprehensive tutorial will be incredibly helpful for anyone looking to get started with an integrated AI assistant. I appreciate the clarity and depth you’ve provided—it's a great resource for both beginners and experienced developers!