Skip to main content
CopilotKit provides a complete React SDK with hooks, components, and providers to build AI-powered applications. The React integration is built on top of the AG-UI protocol and provides a declarative API for managing agents, tools, and chat interfaces.

Installation

1

Install the package

Install the React package and its styles:
npm install @copilotkitnext/react
# or
pnpm add @copilotkitnext/react
# or
yarn add @copilotkitnext/react
2

Import styles

Import the CopilotKit styles in your root layout or main component:
import "@copilotkitnext/react/styles.css";
3

Set up the provider

Wrap your application with CopilotKitProvider:
import { CopilotKitProvider } from "@copilotkitnext/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      {/* Your app content */}
    </CopilotKitProvider>
  );
}

Core Concepts

CopilotKitProvider

The CopilotKitProvider is the root component that manages the connection to your CopilotKit runtime and provides context to all child components.
import { CopilotKitProvider } from "@copilotkitnext/react";

<CopilotKitProvider
  runtimeUrl="/api/copilotkit"
  headers={{
    Authorization: "Bearer your-token"
  }}
  credentials="include"
  publicApiKey="ck_pub_..."
  showDevConsole="auto"
  onError={({ error, code, context }) => {
    console.error("CopilotKit error:", error);
  }}
>
  {children}
</CopilotKitProvider>

Key Props

  • runtimeUrl - URL of your CopilotKit runtime endpoint
  • headers - Custom headers to include in requests
  • credentials - Fetch credentials mode (e.g., “include” for cookies)
  • publicApiKey - CopilotCloud public API key
  • showDevConsole - Show developer console (“auto” shows on localhost)
  • onError - Error handler for runtime and agent errors
  • renderToolCalls - Array of tool call renderers
  • frontendTools - Array of frontend tools
  • humanInTheLoop - Array of human-in-the-loop tools

Using Agents

The useAgent hook connects to an agent and subscribes to its state changes.
import { useAgent } from "@copilotkitnext/react";

function MyComponent() {
  const { agent } = useAgent({
    agentId: "my-agent", // Optional, defaults to DEFAULT_AGENT_ID
    updates: [
      UseAgentUpdate.OnMessagesChanged,
      UseAgentUpdate.OnStateChanged,
      UseAgentUpdate.OnRunStatusChanged,
    ],
  });

  // Access agent properties
  const messages = agent.messages;
  const state = agent.state;
  const isRunning = agent.isRunning;

  // Interact with agent
  const handleSendMessage = async () => {
    await agent.run({
      messages: [{ role: "user", content: "Hello!" }],
    });
  };

  return (
    <div>
      <button onClick={handleSendMessage}>Send Message</button>
    </div>
  );
}

Frontend Tools

Frontend tools allow the agent to execute functions in the browser. Use useFrontendTool to register tools dynamically:
import { useFrontendTool } from "@copilotkitnext/react";
import { z } from "zod";

function MyComponent() {
  useFrontendTool({
    name: "sayHello",
    description: "Display a greeting message to the user",
    parameters: z.object({
      name: z.string().describe("The name to greet"),
    }),
    handler: async ({ name }) => {
      alert(`Hello ${name}!`);
      return `Greeted ${name}`;
    },
    render: ({ args, status }) => (
      <div>
        Greeting {args.name}... (Status: {status})
      </div>
    ),
  });

  return <div>Tool registered!</div>;
}

Tool Call Rendering

Render custom UI for tool executions using defineToolCallRenderer:
import { defineToolCallRenderer } from "@copilotkitnext/react";
import { z } from "zod";

const searchRenderer = defineToolCallRenderer({
  name: "search",
  args: z.object({
    query: z.string(),
    limit: z.number().optional(),
  }),
  render: ({ name, args, status }) => (
    <div className="search-tool-call">
      <h3>Searching for: {args.query}</h3>
      {args.limit && <p>Limit: {args.limit} results</p>}
      <p>Status: {status}</p>
    </div>
  ),
});

// Pass to provider
<CopilotKitProvider
  runtimeUrl="/api/copilotkit"
  renderToolCalls={[searchRenderer]}
>
  {children}
</CopilotKitProvider>
You can also use a wildcard renderer to handle any undefined tools:
const wildcardRenderer = defineToolCallRenderer({
  name: "*",
  render: ({ name, args, status }) => (
    <div className="unknown-tool">
      <strong>Tool: {name}</strong>
      <pre>{JSON.stringify(args, null, 2)}</pre>
      <p>Status: {status}</p>
    </div>
  ),
});

Agent Context

Provide dynamic context to your agent using useAgentContext:
import { useAgentContext } from "@copilotkitnext/react";

function CurrentUser() {
  const user = useCurrentUser();
  
  useAgentContext({
    description: "Current user information",
    value: {
      id: user.id,
      name: user.name,
      email: user.email,
    },
  });

  return <div>Logged in as {user.name}</div>;
}

Suggestions

Configure AI-generated suggestions using useConfigureSuggestions:
import { useConfigureSuggestions } from "@copilotkitnext/react";

function MyComponent() {
  // Dynamic suggestions
  useConfigureSuggestions({
    instructions: "Suggest follow-up actions based on the current page",
    available: "always",
  });

  // Or static suggestions
  useConfigureSuggestions({
    suggestions: [
      {
        title: "Get Started",
        message: "Help me get started with CopilotKit",
      },
      {
        title: "Documentation",
        message: "Show me the documentation",
      },
    ],
  });
}

Chat Components

CopilotKit provides pre-built chat UI components:

CopilotChat

The main chat interface component:
import { CopilotChat } from "@copilotkitnext/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <div style={{ height: "100vh" }}>
        <CopilotChat
          threadId="thread-123"
          input={{
            placeholder: "Ask me anything...",
            toolsMenu: [
              {
                label: "Help",
                action: () => console.log("Help clicked"),
              },
            ],
          }}
        />
      </div>
    </CopilotKitProvider>
  );
}

CopilotSidebar

A sidebar variant of the chat interface:
import { CopilotSidebar } from "@copilotkitnext/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <div style={{ display: "flex", height: "100vh" }}>
        <main style={{ flex: 1 }}>
          {/* Your main content */}
        </main>
        <CopilotSidebar />
      </div>
    </CopilotKitProvider>
  );
}

CopilotPopup

A popup/modal variant:
import { CopilotPopup } from "@copilotkitnext/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      {/* Your app content */}
      <CopilotPopup />
    </CopilotKitProvider>
  );
}

Complete Example

Here’s a full example integrating CopilotKit in a Next.js application:
"use client";

import {
  CopilotChat,
  CopilotKitProvider,
  useFrontendTool,
  useAgentContext,
  useConfigureSuggestions,
} from "@copilotkitnext/react";
import "@copilotkitnext/react/styles.css";
import { useState } from "react";
import { z } from "zod";

export default function Home() {
  return (
    <CopilotKitProvider
      runtimeUrl="/api/copilotkit"
      showDevConsole="auto"
    >
      <div style={{ height: "100vh" }}>
        <ChatInterface />
      </div>
    </CopilotKitProvider>
  );
}

function ChatInterface() {
  const [count, setCount] = useState(0);

  // Provide context about current state
  useAgentContext({
    description: "Current counter value",
    value: count,
  });

  // Configure suggestions
  useConfigureSuggestions({
    instructions: "Suggest actions related to the counter",
    available: "always",
  });

  // Register a frontend tool
  useFrontendTool({
    name: "incrementCounter",
    description: "Increment the counter by a specified amount",
    parameters: z.object({
      amount: z.number().describe("Amount to increment"),
    }),
    handler: async ({ amount }) => {
      setCount((prev) => prev + amount);
      return `Counter incremented by ${amount}`;
    },
  });

  return (
    <div>
      <div style={{ padding: "20px" }}>
        <h1>Counter: {count}</h1>
        <button onClick={() => setCount(count + 1)}>Increment</button>
      </div>
      <CopilotChat threadId="counter-thread" />
    </div>
  );
}

TypeScript Support

CopilotKit is fully typed with TypeScript. Import types for custom implementations:
import type {
  ReactFrontendTool,
  ReactToolCallRenderer,
  CopilotKitProviderProps,
  UseAgentProps,
} from "@copilotkitnext/react";

Next Steps

Human-in-the-Loop

Learn how to add approval flows to your tools

Tool Development

Build custom tools for your agents

Agent Configuration

Configure and customize your agents