Logo

dev-resources.site

for different kinds of informations.

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

Published at
12/24/2024
Categories
ai
nextjs
prisma
githubcopilot
Author
gulshan_sharma_7d2daa9d67
Categories
4 categories in total
ai
open
nextjs
open
prisma
open
githubcopilot
open
Author
25 person written this
gulshan_sharma_7d2daa9d67
open
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 🧑‍💻

prisma Article's
30 articles in total
Favicon
How to Fix the “Record to Delete Does Not Exist” Error in Prisma
Favicon
Building Type-Safe APIs: Integrating NestJS with Prisma and TypeScript
Favicon
Deploying an Existing Express API + Prisma + Supabase Project to Vercel
Favicon
Exploring the Power of Full-Stack Development with Next.js and Prisma
Favicon
How to integrate GitHub CopilotKit with Prisma Integration into your nextJs project Using OpenAI
Favicon
วิธีทำ Auth API ด้วย Express, JWT, MySQL และ Prisma
Favicon
Prisma
Favicon
How we built "Space-Ease" using Next.js
Favicon
Query Objects Instead of Repositories: A Modern Approach to Data Access
Favicon
Common Data Loss Scenarios & Solutions in Prisma Schema Changes
Favicon
How I Solved Common Prisma ORM Errors: Debugging Tips and Best Practices
Favicon
Prisma 101 baby.
Favicon
Prisma
Favicon
QueryBuilder in Action Part 1
Favicon
Prisma ORM: Revolutionizing Database Interactions
Favicon
Prisma & MongoDB: server to be run as a replica set
Favicon
Using GenAI to Tackle Complex Prisma Model Migrations
Favicon
When Embedded AuthN Meets Embedded AuthZ - Building Multi-Tenant Apps With Better-Auth and ZenStack
Favicon
Building Multi-Tenant Apps Using StackAuth's "Teams" and Next.js
Favicon
The Most Awaited Prisma Course Is Here! 😍
Favicon
**Building a Full-Stack Next.js Starter Kit: Authentication, GraphQL, and Testing**
Favicon
Integrate DAYTONA and let the magic begin....
Favicon
Cloudflare D1 and Prisma: Not a Good Combination (For Now)
Favicon
Resolving the `DO $$` Issue in Drizzle ORM with Nile Postgres
Favicon
Nuxt Authorization: How to Implement Team Role-Based Access Control in Nuxt 3
Favicon
Getting Started with Prisma, SQLite, and Express
Favicon
Senior Developer Advocate
Favicon
Building Multi-Tenant Apps Using Clerk's "Organization" and Next.js
Favicon
How to use ORMs (Prisma / Drizzle / Knex.js) in a TypeScript backend built with Encore.ts
Favicon
Pagination and Sorting with Prisma in TypeScript

Featured ones: