Logo
Docs
Tutorial: AI Powered Textarea

Step 2: Setup CopilotKit

Now that we have our todo list app running, we're ready to integrate CopilotKit. For this tutorial, we will install the following dependencies:

  • @copilotkit/react-core: The core library for CopilotKit, which contains the CopilotKit provider and useful hooks.
  • @copilotkit/react-textarea: The textarea component for CopilotKit, which enables you to get instant context-aware autocompletions in your app.

Install Dependencies

To install the CopilotKit dependencies, run the following:

npm install @copilotkit/react-core @copilotkit/react-textarea

Setup CopilotKit

Set up Copilot Runtime Endpoint

Add your OpenAI API key to your .env file in the root of your project:

.env
OPENAI_API_KEY=your_api_key_here

Please note that the code below uses GPT-4o, which requires a paid OpenAI API key. If you are using a free OpenAI API key, change the model to a different option such as gpt-3.5-turbo.

Endpoint Setup

Create a new route to handle the /api/copilotkit endpoint.

app/api/copilotkit/route.ts
import {
  CopilotRuntime,
  OpenAIAdapter,
  copilotRuntimeNextJSAppRouterEndpoint,
} from '@copilotkit/runtime';
import OpenAI from 'openai';
import { NextRequest } from 'next/server';
 
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const serviceAdapter = new OpenAIAdapter({ openai });
const runtime = new CopilotRuntime();
 
export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter,
    endpoint: '/api/copilotkit',
  });
 
  return handleRequest(req);
};

Your Copilot Runtime endpoint should be available at http://localhost:3000/api/copilotkit.

Configure the CopilotKit Provider

app/page.tsx
"use client";
 
import { EmailThread } from "@/components/EmailThread";
import { EmailsProvider } from "@/lib/hooks/use-emails";
import { CopilotKit } from "@copilotkit/react-core"; 
import "@copilotkit/react-textarea/styles.css"; 
 
export default function Home() {
  return (
    <CopilotKit runtimeUrl="/api/copilotkit">
      <EmailsProvider>
        <EmailThread />
      </EmailsProvider>
    </CopilotKit> 
  );
}

Let's break this down:

  • First, we imported the CopilotKit provider from @copilotkit/react-core.
  • Then, we wrapped the page with the <CopilotKit> provider.
  • We imported the built-in styles from @copilotkit/react-textarea. This is optional.

In the next step, we'll implement the AI-powered textarea as a replacement for our existing input component.

On this page

Edit on GitHub