copilotkit-setup

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CopilotKit Setup

CopilotKit 安装配置

Prerequisites

前置要求

Live Documentation (MCP)

实时文档(MCP)

This plugin includes an MCP server (
copilotkit-docs
) that provides
search-docs
and
search-code
tools for querying live CopilotKit documentation and source code.
  • Claude Code: Auto-configured by the plugin's
    .mcp.json
    -- no setup needed.
  • Codex: Requires manual configuration. See the copilotkit-debug skill for setup instructions.
本插件包含一个MCP服务(
copilotkit-docs
),提供
search-docs
search-code
工具,用于查询CopilotKit的实时文档和源代码。
  • Claude Code: 由插件的
    .mcp.json
    自动配置,无需额外设置。
  • Codex: 需要手动配置,参考copilotkit-debug技能的配置说明完成设置。

Environment

环境要求

Before starting setup, verify:
  1. Node.js >= 18 (required for
    fetch
    globals used by the runtime)
  2. An AI provider API key (one of:
    OPENAI_API_KEY
    ,
    ANTHROPIC_API_KEY
    ,
    GOOGLE_API_KEY
    )
  3. A React-based frontend (Next.js App Router, Next.js Pages Router, Vite + React, or Angular)
  4. A backend capable of running the runtime (same Next.js app via API routes, or a standalone Express/Hono server)
开始配置前,请确认满足以下条件:
  1. Node.js >= 18(运行时需要全局
    fetch
    API支持)
  2. AI服务提供商API密钥(支持以下任意一种:
    OPENAI_API_KEY
    ANTHROPIC_API_KEY
    GOOGLE_API_KEY
  3. 基于React的前端项目(支持Next.js App Router、Next.js Pages Router、Vite + React、Angular)
  4. 可运行CopilotKit运行时的后端环境(可以是同一Next.js应用的API路由,也可以是独立的Express/Hono服务)

Framework Detection

框架检测

Before generating any code, detect the project's framework by checking files in the project root. See
references/framework-detection.md
for the full decision tree.
Quick summary:
Signal FileFramework
next.config.{js,ts,mjs}
+
app/
directory
Next.js App Router
next.config.{js,ts,mjs}
+
pages/
directory
Next.js Pages Router
angular.json
Angular
vite.config.{js,ts}
+ React deps in package.json
Vite + React
生成代码前,请先检查项目根目录的文件来识别项目使用的框架,完整判断逻辑参考
references/framework-detection.md
快速判断规则:
检测文件对应框架
next.config.{js,ts,mjs}
+
app/
目录
Next.js App Router
next.config.{js,ts,mjs}
+
pages/
目录
Next.js Pages Router
angular.json
Angular
vite.config.{js,ts}
+ package.json中包含React依赖
Vite + React

Setup Workflow

配置流程

Step 1: Install packages

步骤1:安装依赖包

All packages use the
@copilotkit
namespace.
Frontend (React) packages:
bash
npm install @copilotkit/react @copilotkit/core
Runtime packages (backend):
bash
npm install @copilotkit/runtime @copilotkit/agent
If the runtime runs in the same Next.js app as the frontend, install all four packages together.
For standalone Express backends, also install Express adapter dependencies:
bash
npm install express cors
npm install -D @types/express @types/cors
所有依赖包都使用
@copilotkit
命名空间。
前端(React)依赖:
bash
npm install @copilotkit/react @copilotkit/core
运行时(后端)依赖:
bash
npm install @copilotkit/runtime @copilotkit/agent
如果运行时和前端部署在同一个Next.js应用中,可以一次性安装所有4个依赖包。
如果是独立的Express后端,还需要额外安装Express适配器依赖:
bash
npm install express cors
npm install -D @types/express @types/cors

Step 2: Configure the runtime

步骤2:配置运行时

The runtime is the server-side component that manages agent execution. See
references/runtime-architecture.md
for details.
There are two endpoint styles:
  1. Multi-route (Hono) -- uses
    createCopilotEndpoint
    . Requires a catch-all route (
    [[...slug]]
    in Next.js). Each operation (run, connect, stop, info, transcribe, threads) gets its own HTTP path.
  2. Single-route (Hono or Express) -- uses
    createCopilotEndpointSingleRoute
    or
    createCopilotEndpointSingleRouteExpress
    . All operations go through a single POST endpoint with method multiplexing.
运行时是负责管理Agent执行的服务端组件,详细说明参考
references/runtime-architecture.md
支持两种端点模式:
  1. 多路由模式(Hono) -- 使用
    createCopilotEndpoint
    ,需要配置通配路由(Next.js中为
    [[...slug]]
    ),每个操作(运行、连接、停止、信息查询、语音转写、会话管理)都对应独立的HTTP路径。
  2. 单路由模式(Hono或Express) -- 使用
    createCopilotEndpointSingleRoute
    createCopilotEndpointSingleRouteExpress
    ,所有操作都通过同一个POST端点处理,通过方法复用实现不同功能。

Next.js App Router (recommended: multi-route with Hono)

Next.js App Router(推荐:Hono多路由模式)

Create
src/app/api/copilotkit/[[...slug]]/route.ts
:
typescript
import {
  CopilotRuntime,
  createCopilotEndpoint,
  InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful AI assistant.",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
  runner: new InMemoryAgentRunner(),
});

const app = createCopilotEndpoint({
  runtime,
  basePath: "/api/copilotkit",
});

export const GET = handle(app);
export const POST = handle(app);
This requires
hono
as a dependency:
bash
npm install hono
创建
src/app/api/copilotkit/[[...slug]]/route.ts
typescript
import {
  CopilotRuntime,
  createCopilotEndpoint,
  InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful AI assistant.",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
  runner: new InMemoryAgentRunner(),
});

const app = createCopilotEndpoint({
  runtime,
  basePath: "/api/copilotkit",
});

export const GET = handle(app);
export const POST = handle(app);
该配置需要安装
hono
依赖:
bash
npm install hono

Next.js App Router (alternative: single-route)

Next.js App Router(替代方案:单路由模式)

Create
src/app/api/copilotkit/route.ts
:
typescript
import {
  CopilotRuntime,
  createCopilotEndpointSingleRoute,
  InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful AI assistant.",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
  runner: new InMemoryAgentRunner(),
});

const app = createCopilotEndpointSingleRoute({
  runtime,
  basePath: "/api/copilotkit",
});

export const POST = handle(app);
When using single-route, the frontend must set
useSingleEndpoint
on the provider (see Step 3).
创建
src/app/api/copilotkit/route.ts
typescript
import {
  CopilotRuntime,
  createCopilotEndpointSingleRoute,
  InMemoryAgentRunner,
} from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { handle } from "hono/vercel";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
  prompt: "You are a helpful AI assistant.",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
  runner: new InMemoryAgentRunner(),
});

const app = createCopilotEndpointSingleRoute({
  runtime,
  basePath: "/api/copilotkit",
});

export const POST = handle(app);
使用单路由模式时,前端需要在Provider中设置
useSingleEndpoint
(参考步骤3)。

Standalone Express Server

独立Express服务

Create
src/index.ts
:
typescript
import express from "express";
import { CopilotRuntime } from "@copilotkit/runtime";
import { createCopilotEndpointSingleRouteExpress } from "@copilotkit/runtime/express";
import { BuiltInAgent, defineTool } from "@copilotkit/agent";
import { z } from "zod";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
});

const app = express();

app.use(
  "/api/copilotkit",
  createCopilotEndpointSingleRouteExpress({
    runtime,
    basePath: "/",
  }),
);

const port = Number(process.env.PORT ?? 4000);
app.listen(port, () => {
  console.log(`CopilotKit runtime listening at http://localhost:${port}/api/copilotkit`);
});
For multi-route Express, use
createCopilotEndpointExpress
instead (imported from
@copilotkit/runtime/express
).
创建
src/index.ts
typescript
import express from "express";
import { CopilotRuntime } from "@copilotkit/runtime";
import { createCopilotEndpointSingleRouteExpress } from "@copilotkit/runtime/express";
import { BuiltInAgent, defineTool } from "@copilotkit/agent";
import { z } from "zod";

const agent = new BuiltInAgent({
  model: "openai/gpt-4o",
});

const runtime = new CopilotRuntime({
  agents: {
    default: agent,
  },
});

const app = express();

app.use(
  "/api/copilotkit",
  createCopilotEndpointSingleRouteExpress({
    runtime,
    basePath: "/",
  }),
);

const port = Number(process.env.PORT ?? 4000);
app.listen(port, () => {
  console.log(`CopilotKit runtime listening at http://localhost:${port}/api/copilotkit`);
});
如果需要为Express使用多路由模式,替换为
createCopilotEndpointExpress
即可(从
@copilotkit/runtime/express
导入)。

Standalone Hono Server (non-Vercel)

独立Hono服务(非Vercel环境)

typescript
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { serve } from "@hono/node-server";

const runtime = new CopilotRuntime({
  agents: {
    default: new BuiltInAgent({ model: "openai/gpt-4o" }),
  },
});

const app = createCopilotEndpoint({
  runtime,
  basePath: "/api/copilotkit",
});

serve({ fetch: app.fetch, port: 8787 });
Requires
@hono/node-server
:
bash
npm install hono @hono/node-server
typescript
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
import { BuiltInAgent } from "@copilotkit/agent";
import { serve } from "@hono/node-server";

const runtime = new CopilotRuntime({
  agents: {
    default: new BuiltInAgent({ model: "openai/gpt-4o" }),
  },
});

const app = createCopilotEndpoint({
  runtime,
  basePath: "/api/copilotkit",
});

serve({ fetch: app.fetch, port: 8787 });
需要安装
@hono/node-server
依赖:
bash
npm install hono @hono/node-server

Step 3: Set up the frontend provider

步骤3:配置前端Provider

Wrap your application with
CopilotKitProvider
from
@copilotkit/react
.
Important: Import the stylesheet in your root layout:
typescript
import "@copilotkit/react/styles.css";
使用
@copilotkit/react
导出的
CopilotKitProvider
包裹你的应用。
重要: 请在根布局中导入样式文件:
typescript
import "@copilotkit/react/styles.css";

Next.js App Router

Next.js App Router

In
src/app/page.tsx
(or a client component):
tsx
"use client";

import { CopilotKitProvider, CopilotChat } from "@copilotkit/react";

export default function Home() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <div style={{ height: "100vh" }}>
        <CopilotChat />
      </div>
    </CopilotKitProvider>
  );
}
src/app/page.tsx
(或任意客户端组件)中配置:
tsx
"use client";

import { CopilotKitProvider, CopilotChat } from "@copilotkit/react";

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

Connecting to an external runtime

连接外部运行时

When the runtime runs on a separate server (e.g., Express on port 4000):
tsx
<CopilotKitProvider
  runtimeUrl="http://localhost:4000/api/copilotkit"
  useSingleEndpoint
>
  {children}
</CopilotKitProvider>
Set
useSingleEndpoint
when the backend uses single-route endpoints (
createCopilotEndpointSingleRoute
or
createCopilotEndpointSingleRouteExpress
).
如果运行时部署在独立的服务上(比如运行在4000端口的Express服务),配置如下:
tsx
<CopilotKitProvider
  runtimeUrl="http://localhost:4000/api/copilotkit"
  useSingleEndpoint
>
  {children}
</CopilotKitProvider>
当后端使用单路由端点时(
createCopilotEndpointSingleRoute
createCopilotEndpointSingleRouteExpress
),需要设置
useSingleEndpoint
参数。

CopilotKitProvider key props

CopilotKitProvider核心参数

PropTypeDescription
runtimeUrl
string
URL of the CopilotKit runtime endpoint
useSingleEndpoint
boolean
Set to
true
when using single-route endpoints
headers
Record<string, string>
Custom headers sent with every request
credentials
RequestCredentials
Fetch credentials mode (e.g.,
"include"
for cookies)
publicApiKey
string
Copilot Cloud public API key (if using hosted runtime)
showDevConsole
boolean | "auto"
Show the dev inspector (
"auto"
= development only)
renderToolCalls
ReactToolCallRenderer[]
Custom renderers for tool call UI
frontendTools
ReactFrontendTool[]
Frontend-defined tools (declarative alternative to
useFrontendTool
)
onError
(event) => void
Global error handler
参数类型说明
runtimeUrl
string
CopilotKit运行时端点的URL
useSingleEndpoint
boolean
使用单路由端点时设置为
true
headers
Record<string, string>
每个请求携带的自定义请求头
credentials
RequestCredentials
Fetch凭证模式(比如设置为
"include"
携带Cookie)
publicApiKey
string
Copilot Cloud公钥(使用托管运行时时需要)
showDevConsole
boolean | "auto"
显示开发调试面板(
"auto"
表示仅开发环境显示)
renderToolCalls
ReactToolCallRenderer[]
工具调用UI的自定义渲染器
frontendTools
ReactFrontendTool[]
前端定义的工具(是
useFrontendTool
的声明式替代方案)
onError
(event) => void
全局错误处理函数

Step 4: Add a chat UI component

步骤4:添加聊天UI组件

CopilotKit provides three pre-built chat layouts:
ComponentUsage
CopilotChat
Inline chat, fills its container
CopilotSidebar
Collapsible sidebar panel
CopilotPopup
Floating popup widget
Example with sidebar:
tsx
<CopilotKitProvider runtimeUrl="/api/copilotkit" showDevConsole="auto">
  <YourApp />
  <CopilotSidebar
    defaultOpen
    width="420px"
    labels={{
      modalHeaderTitle: "AI Assistant",
      chatInputPlaceholder: "Ask me anything...",
    }}
  />
</CopilotKitProvider>
CopilotKit提供3种开箱即用的聊天布局:
组件用途
CopilotChat
内嵌聊天组件,自动填充父容器
CopilotSidebar
可折叠的侧边栏聊天面板
CopilotPopup
悬浮弹窗聊天组件
侧边栏组件示例:
tsx
<CopilotKitProvider runtimeUrl="/api/copilotkit" showDevConsole="auto">
  <YourApp />
  <CopilotSidebar
    defaultOpen
    width="420px"
    labels={{
      modalHeaderTitle: "AI助手",
      chatInputPlaceholder: "有什么我可以帮你的...",
    }}
  />
</CopilotKitProvider>

Step 5: Set environment variables

步骤5:配置环境变量

Create a
.env.local
(Next.js) or
.env
file:
OPENAI_API_KEY=sk-...
The
BuiltInAgent
automatically resolves API keys from environment variables based on the model prefix:
  • openai/*
    models read
    OPENAI_API_KEY
  • anthropic/*
    models read
    ANTHROPIC_API_KEY
  • google/*
    models read
    GOOGLE_API_KEY
You can also pass
apiKey
directly to
BuiltInAgent
if needed.
创建
.env.local
(Next.js项目)或
.env
文件:
OPENAI_API_KEY=sk-...
BuiltInAgent
会根据模型前缀自动从环境变量中读取对应的API密钥:
  • openai/*
    模型读取
    OPENAI_API_KEY
  • anthropic/*
    模型读取
    ANTHROPIC_API_KEY
  • google/*
    模型读取
    GOOGLE_API_KEY
如果需要,你也可以直接向
BuiltInAgent
传递
apiKey
参数。

Step 6: Connect to CopilotCloud (telemetry)

步骤6:连接CopilotCloud(埋点统计)

CopilotKit uses telemetry to understand adoption, improve the product, and provide better support. Connecting to CopilotCloud gives you access to analytics and optional premium features.
  1. Ask the user if they'd like to connect to CopilotCloud (default: yes).
  2. If yes, run the CopilotKit CLI authentication flow (verify the exact command with
    npx copilotkit --help
    as it may vary by version):
    bash
    npx copilotkit auth
  3. Guide the user through the browser-based authentication that opens.
  4. Once authentication completes, the CLI outputs a license key (format:
    ck_...
    ).
  5. Add the license key to the
    CopilotKitProvider
    :
    tsx
    <CopilotKitProvider
      runtimeUrl="/api/copilotkit"
      licenseKey="ck_..."
    >
    Alternatively, store it as an environment variable (
    COPILOTKIT_LICENSE_KEY
    in
    .env.local
    or
    .env
    ) and reference it:
    tsx
    <CopilotKitProvider
      runtimeUrl="/api/copilotkit"
      licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY}
    >
See
references/telemetry-setup.md
for full details on what the license key enables and how to opt out.
CopilotKit通过埋点统计来了解产品 adoption、优化产品体验、提供更好的技术支持。连接CopilotCloud后你可以使用数据分析功能和可选的高级特性。
  1. 询问用户是否愿意连接CopilotCloud(默认选择同意)。
  2. 如果同意,运行CopilotKit CLI鉴权流程(可以通过
    npx copilotkit --help
    确认最新命令,不同版本可能有差异):
    bash
    npx copilotkit auth
  3. 引导用户完成打开的浏览器端鉴权流程。
  4. 鉴权完成后,CLI会输出一个License密钥(格式:
    ck_...
    )。
  5. 将License密钥添加到
    CopilotKitProvider
    中:
    tsx
    <CopilotKitProvider
      runtimeUrl="/api/copilotkit"
      licenseKey="ck_..."
    >
    也可以将其存储为环境变量(
    .env.local
    .env
    中的
    COPILOTKIT_LICENSE_KEY
    )后引用:
    tsx
    <CopilotKitProvider
      runtimeUrl="/api/copilotkit"
      licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY}
    >
关于License密钥的功能和如何关闭埋点的完整说明参考
references/telemetry-setup.md

Step 7: Verify the setup

步骤7:验证配置

  1. Start the dev server
  2. Open the app in a browser
  3. The chat UI should render and connect to the runtime
  4. Send a test message -- you should receive an AI response
  5. Check the runtime's
    /info
    endpoint (GET) to confirm it reports available agents
  1. 启动开发服务
  2. 在浏览器中打开应用
  3. 聊天UI应该正常渲染并成功连接到运行时
  4. 发送一条测试消息,应该可以收到AI的回复
  5. 访问运行时的
    /info
    端点(GET请求),确认返回的可用Agent信息正常

Quick Reference

快速参考

Package map

依赖包说明

PackagePurpose
@copilotkit/react
React components, hooks, provider
@copilotkit/core
Core types, agent abstraction, state management
@copilotkit/runtime
Server-side runtime, endpoint factories, agent runners
@copilotkit/agent
BuiltInAgent
,
defineTool
, model resolution
@copilotkit/shared
Shared utilities, logger, types
包名用途
@copilotkit/react
React组件、Hooks、Provider
@copilotkit/core
核心类型、Agent抽象、状态管理
@copilotkit/runtime
服务端运行时、端点工厂、Agent执行器
@copilotkit/agent
BuiltInAgent
defineTool
、模型解析逻辑
@copilotkit/shared
通用工具、日志、类型定义

Endpoint factory functions

端点工厂函数

FunctionImportProtocolFramework
createCopilotEndpoint
@copilotkit/runtime
Multi-route (Hono)Next.js App Router, Hono standalone
createCopilotEndpointSingleRoute
@copilotkit/runtime
Single-route (Hono)Next.js App Router
createCopilotEndpointExpress
@copilotkit/runtime/express
Multi-route (Express)Express standalone
createCopilotEndpointSingleRouteExpress
@copilotkit/runtime/express
Single-route (Express)Express standalone
函数名导入来源协议支持框架
createCopilotEndpoint
@copilotkit/runtime
多路由(Hono)Next.js App Router、独立Hono服务
createCopilotEndpointSingleRoute
@copilotkit/runtime
单路由(Hono)Next.js App Router
createCopilotEndpointExpress
@copilotkit/runtime/express
多路由(Express)独立Express服务
createCopilotEndpointSingleRouteExpress
@copilotkit/runtime/express
单路由(Express)独立Express服务

Runtime classes

运行时类

ClassUse case
CopilotRuntime
Compatibility shim; auto-selects SSE or Intelligence mode
CopilotSseRuntime
Explicit SSE mode (default, in-memory threads)
CopilotIntelligenceRuntime
Intelligence mode (durable threads, realtime events)
类名适用场景
CopilotRuntime
兼容层,自动选择SSE或智能模式
CopilotSseRuntime
显式SSE模式(默认,内存级会话存储)
CopilotIntelligenceRuntime
智能模式(持久化会话、实时事件)

Agent runners

Agent执行器

RunnerDescription
InMemoryAgentRunner
Default. Stores thread state in process memory. Suitable for development and single-instance deployments.
IntelligenceAgentRunner
Used automatically with
CopilotIntelligenceRuntime
. Connects to CopilotKit Intelligence Platform via WebSocket.
执行器说明
InMemoryAgentRunner
默认执行器,将会话状态存储在进程内存中,适合开发环境和单实例部署
IntelligenceAgentRunner
CopilotIntelligenceRuntime
自动使用,通过WebSocket连接到CopilotKit智能平台

Supported models (BuiltInAgent)

支持的模型(BuiltInAgent)

Format:
"provider/model-name"
string or a Vercel AI SDK
LanguageModel
instance.
OpenAI:
openai/gpt-5
,
openai/gpt-5-mini
,
openai/gpt-4.1
,
openai/gpt-4.1-mini
,
openai/gpt-4.1-nano
,
openai/gpt-4o
,
openai/gpt-4o-mini
,
openai/o3
,
openai/o3-mini
,
openai/o4-mini
Anthropic:
anthropic/claude-sonnet-4.5
,
anthropic/claude-sonnet-4
,
anthropic/claude-3.7-sonnet
,
anthropic/claude-opus-4.1
,
anthropic/claude-opus-4
,
anthropic/claude-3.5-haiku
Google:
google/gemini-2.5-pro
,
google/gemini-2.5-flash
,
google/gemini-2.5-flash-lite
Any
string
is accepted (for custom/unlisted models); the provider is parsed from the prefix before
/
.
格式:
"服务商/模型名"
字符串,或者Vercel AI SDK的
LanguageModel
实例。
OpenAI:
openai/gpt-5
,
openai/gpt-5-mini
,
openai/gpt-4.1
,
openai/gpt-4.1-mini
,
openai/gpt-4.1-nano
,
openai/gpt-4o
,
openai/gpt-4o-mini
,
openai/o3
,
openai/o3-mini
,
openai/o4-mini
Anthropic:
anthropic/claude-sonnet-4.5
,
anthropic/claude-sonnet-4
,
anthropic/claude-3.7-sonnet
,
anthropic/claude-opus-4.1
,
anthropic/claude-opus-4
,
anthropic/claude-3.5-haiku
Google:
google/gemini-2.5-pro
,
google/gemini-2.5-flash
,
google/gemini-2.5-flash-lite
支持任意字符串格式(用于自定义/未列出的模型),服务商名称会从
/
前的前缀自动解析。