copilotkit-setup
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCopilotKit Setup
CopilotKit 安装配置
Prerequisites
前置要求
Live Documentation (MCP)
实时文档(MCP)
This plugin includes an MCP server () that provides and tools for querying live CopilotKit documentation and source code.
copilotkit-docssearch-docssearch-code- Claude Code: Auto-configured by the plugin's -- no setup needed.
.mcp.json - Codex: Requires manual configuration. See the copilotkit-debug skill for setup instructions.
本插件包含一个MCP服务(),提供和工具,用于查询CopilotKit的实时文档和源代码。
copilotkit-docssearch-docssearch-code- Claude Code: 由插件的自动配置,无需额外设置。
.mcp.json - Codex: 需要手动配置,参考copilotkit-debug技能的配置说明完成设置。
Environment
环境要求
Before starting setup, verify:
- Node.js >= 18 (required for globals used by the runtime)
fetch - An AI provider API key (one of: ,
OPENAI_API_KEY,ANTHROPIC_API_KEY)GOOGLE_API_KEY - A React-based frontend (Next.js App Router, Next.js Pages Router, Vite + React, or Angular)
- A backend capable of running the runtime (same Next.js app via API routes, or a standalone Express/Hono server)
开始配置前,请确认满足以下条件:
- Node.js >= 18(运行时需要全局API支持)
fetch - AI服务提供商API密钥(支持以下任意一种:、
OPENAI_API_KEY、ANTHROPIC_API_KEY)GOOGLE_API_KEY - 基于React的前端项目(支持Next.js App Router、Next.js Pages Router、Vite + React、Angular)
- 可运行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 for the full decision tree.
references/framework-detection.mdQuick summary:
| Signal File | Framework |
|---|---|
| Next.js App Router |
| Next.js Pages Router |
| Angular |
| Vite + React |
生成代码前,请先检查项目根目录的文件来识别项目使用的框架,完整判断逻辑参考。
references/framework-detection.md快速判断规则:
| 检测文件 | 对应框架 |
|---|---|
| Next.js App Router |
| Next.js Pages Router |
| Angular |
| Vite + React |
Setup Workflow
配置流程
Step 1: Install packages
步骤1:安装依赖包
All packages use the namespace.
@copilotkitFrontend (React) packages:
bash
npm install @copilotkit/react @copilotkit/coreRuntime packages (backend):
bash
npm install @copilotkit/runtime @copilotkit/agentIf 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/corsStep 2: Configure the runtime
步骤2:配置运行时
The runtime is the server-side component that manages agent execution. See for details.
references/runtime-architecture.mdThere are two endpoint styles:
- Multi-route (Hono) -- uses . Requires a catch-all route (
createCopilotEndpointin Next.js). Each operation (run, connect, stop, info, transcribe, threads) gets its own HTTP path.[[...slug]] - Single-route (Hono or Express) -- uses or
createCopilotEndpointSingleRoute. All operations go through a single POST endpoint with method multiplexing.createCopilotEndpointSingleRouteExpress
运行时是负责管理Agent执行的服务端组件,详细说明参考。
references/runtime-architecture.md支持两种端点模式:
- 多路由模式(Hono) -- 使用,需要配置通配路由(Next.js中为
createCopilotEndpoint),每个操作(运行、连接、停止、信息查询、语音转写、会话管理)都对应独立的HTTP路径。[[...slug]] - 单路由模式(Hono或Express) -- 使用或
createCopilotEndpointSingleRoute,所有操作都通过同一个POST端点处理,通过方法复用实现不同功能。createCopilotEndpointSingleRouteExpress
Next.js App Router (recommended: multi-route with Hono)
Next.js App Router(推荐:Hono多路由模式)
Create :
src/app/api/copilotkit/[[...slug]]/route.tstypescript
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 as a dependency:
honobash
npm install hono创建:
src/app/api/copilotkit/[[...slug]]/route.tstypescript
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);该配置需要安装依赖:
honobash
npm install honoNext.js App Router (alternative: single-route)
Next.js App Router(替代方案:单路由模式)
Create :
src/app/api/copilotkit/route.tstypescript
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 on the provider (see Step 3).
useSingleEndpoint创建:
src/app/api/copilotkit/route.tstypescript
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中设置(参考步骤3)。
useSingleEndpointStandalone Express Server
独立Express服务
Create :
src/index.tstypescript
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 instead (imported from ).
createCopilotEndpointExpress@copilotkit/runtime/express创建:
src/index.tstypescript
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/expressStandalone 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-serverbash
npm install hono @hono/node-servertypescript
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-serverbash
npm install hono @hono/node-serverStep 3: Set up the frontend provider
步骤3:配置前端Provider
Wrap your application with from .
CopilotKitProvider@copilotkit/reactImportant: Import the stylesheet in your root layout:
typescript
import "@copilotkit/react/styles.css";使用导出的包裹你的应用。
@copilotkit/reactCopilotKitProvider重要: 请在根布局中导入样式文件:
typescript
import "@copilotkit/react/styles.css";Next.js App Router
Next.js App Router
In (or a client component):
src/app/page.tsxtsx
"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.tsxtsx
"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 when the backend uses single-route endpoints ( or ).
useSingleEndpointcreateCopilotEndpointSingleRoutecreateCopilotEndpointSingleRouteExpress如果运行时部署在独立的服务上(比如运行在4000端口的Express服务),配置如下:
tsx
<CopilotKitProvider
runtimeUrl="http://localhost:4000/api/copilotkit"
useSingleEndpoint
>
{children}
</CopilotKitProvider>当后端使用单路由端点时(或),需要设置参数。
createCopilotEndpointSingleRoutecreateCopilotEndpointSingleRouteExpressuseSingleEndpointCopilotKitProvider key props
CopilotKitProvider核心参数
| Prop | Type | Description |
|---|---|---|
| | URL of the CopilotKit runtime endpoint |
| | Set to |
| | Custom headers sent with every request |
| | Fetch credentials mode (e.g., |
| | Copilot Cloud public API key (if using hosted runtime) |
| | Show the dev inspector ( |
| | Custom renderers for tool call UI |
| | Frontend-defined tools (declarative alternative to |
| | Global error handler |
| 参数 | 类型 | 说明 |
|---|---|---|
| | CopilotKit运行时端点的URL |
| | 使用单路由端点时设置为 |
| | 每个请求携带的自定义请求头 |
| | Fetch凭证模式(比如设置为 |
| | Copilot Cloud公钥(使用托管运行时时需要) |
| | 显示开发调试面板( |
| | 工具调用UI的自定义渲染器 |
| | 前端定义的工具(是 |
| | 全局错误处理函数 |
Step 4: Add a chat UI component
步骤4:添加聊天UI组件
CopilotKit provides three pre-built chat layouts:
| Component | Usage |
|---|---|
| Inline chat, fills its container |
| Collapsible sidebar panel |
| 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种开箱即用的聊天布局:
| 组件 | 用途 |
|---|---|
| 内嵌聊天组件,自动填充父容器 |
| 可折叠的侧边栏聊天面板 |
| 悬浮弹窗聊天组件 |
侧边栏组件示例:
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 (Next.js) or file:
.env.local.envOPENAI_API_KEY=sk-...The automatically resolves API keys from environment variables based on the model prefix:
BuiltInAgent- models read
openai/*OPENAI_API_KEY - models read
anthropic/*ANTHROPIC_API_KEY - models read
google/*GOOGLE_API_KEY
You can also pass directly to if needed.
apiKeyBuiltInAgent创建(Next.js项目)或文件:
.env.local.envOPENAI_API_KEY=sk-...BuiltInAgent- 模型读取
openai/*OPENAI_API_KEY - 模型读取
anthropic/*ANTHROPIC_API_KEY - 模型读取
google/*GOOGLE_API_KEY
如果需要,你也可以直接向传递参数。
BuiltInAgentapiKeyStep 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.
- Ask the user if they'd like to connect to CopilotCloud (default: yes).
- If yes, run the CopilotKit CLI authentication flow (verify the exact command with as it may vary by version):
npx copilotkit --helpbashnpx copilotkit auth - Guide the user through the browser-based authentication that opens.
- Once authentication completes, the CLI outputs a license key (format: ).
ck_... - Add the license key to the :
CopilotKitProviderAlternatively, store it as an environment variable (tsx<CopilotKitProvider runtimeUrl="/api/copilotkit" licenseKey="ck_..." >inCOPILOTKIT_LICENSE_KEYor.env.local) and reference it:.envtsx<CopilotKitProvider runtimeUrl="/api/copilotkit" licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY} >
See for full details on what the license key enables and how to opt out.
references/telemetry-setup.mdCopilotKit通过埋点统计来了解产品 adoption、优化产品体验、提供更好的技术支持。连接CopilotCloud后你可以使用数据分析功能和可选的高级特性。
- 询问用户是否愿意连接CopilotCloud(默认选择同意)。
- 如果同意,运行CopilotKit CLI鉴权流程(可以通过确认最新命令,不同版本可能有差异):
npx copilotkit --helpbashnpx copilotkit auth - 引导用户完成打开的浏览器端鉴权流程。
- 鉴权完成后,CLI会输出一个License密钥(格式:)。
ck_... - 将License密钥添加到中:
CopilotKitProvider也可以将其存储为环境变量(tsx<CopilotKitProvider runtimeUrl="/api/copilotkit" licenseKey="ck_..." >或.env.local中的.env)后引用:COPILOTKIT_LICENSE_KEYtsx<CopilotKitProvider runtimeUrl="/api/copilotkit" licenseKey={process.env.NEXT_PUBLIC_COPILOTKIT_LICENSE_KEY} >
关于License密钥的功能和如何关闭埋点的完整说明参考。
references/telemetry-setup.mdStep 7: Verify the setup
步骤7:验证配置
- Start the dev server
- Open the app in a browser
- The chat UI should render and connect to the runtime
- Send a test message -- you should receive an AI response
- Check the runtime's endpoint (GET) to confirm it reports available agents
/info
- 启动开发服务
- 在浏览器中打开应用
- 聊天UI应该正常渲染并成功连接到运行时
- 发送一条测试消息,应该可以收到AI的回复
- 访问运行时的端点(GET请求),确认返回的可用Agent信息正常
/info
Quick Reference
快速参考
Package map
依赖包说明
| Package | Purpose |
|---|---|
| React components, hooks, provider |
| Core types, agent abstraction, state management |
| Server-side runtime, endpoint factories, agent runners |
| |
| Shared utilities, logger, types |
| 包名 | 用途 |
|---|---|
| React组件、Hooks、Provider |
| 核心类型、Agent抽象、状态管理 |
| 服务端运行时、端点工厂、Agent执行器 |
| |
| 通用工具、日志、类型定义 |
Endpoint factory functions
端点工厂函数
| Function | Import | Protocol | Framework |
|---|---|---|---|
| | Multi-route (Hono) | Next.js App Router, Hono standalone |
| | Single-route (Hono) | Next.js App Router |
| | Multi-route (Express) | Express standalone |
| | Single-route (Express) | Express standalone |
| 函数名 | 导入来源 | 协议 | 支持框架 |
|---|---|---|---|
| | 多路由(Hono) | Next.js App Router、独立Hono服务 |
| | 单路由(Hono) | Next.js App Router |
| | 多路由(Express) | 独立Express服务 |
| | 单路由(Express) | 独立Express服务 |
Runtime classes
运行时类
| Class | Use case |
|---|---|
| Compatibility shim; auto-selects SSE or Intelligence mode |
| Explicit SSE mode (default, in-memory threads) |
| Intelligence mode (durable threads, realtime events) |
| 类名 | 适用场景 |
|---|---|
| 兼容层,自动选择SSE或智能模式 |
| 显式SSE模式(默认,内存级会话存储) |
| 智能模式(持久化会话、实时事件) |
Agent runners
Agent执行器
| Runner | Description |
|---|---|
| Default. Stores thread state in process memory. Suitable for development and single-instance deployments. |
| Used automatically with |
| 执行器 | 说明 |
|---|---|
| 默认执行器,将会话状态存储在进程内存中,适合开发环境和单实例部署 |
| |
Supported models (BuiltInAgent)
支持的模型(BuiltInAgent)
Format: string or a Vercel AI SDK instance.
"provider/model-name"LanguageModelOpenAI: , , , , , , , , ,
openai/gpt-5openai/gpt-5-miniopenai/gpt-4.1openai/gpt-4.1-miniopenai/gpt-4.1-nanoopenai/gpt-4oopenai/gpt-4o-miniopenai/o3openai/o3-miniopenai/o4-miniAnthropic: , , , , ,
anthropic/claude-sonnet-4.5anthropic/claude-sonnet-4anthropic/claude-3.7-sonnetanthropic/claude-opus-4.1anthropic/claude-opus-4anthropic/claude-3.5-haikuGoogle: , ,
google/gemini-2.5-progoogle/gemini-2.5-flashgoogle/gemini-2.5-flash-liteAny is accepted (for custom/unlisted models); the provider is parsed from the prefix before .
string/格式:字符串,或者Vercel AI SDK的实例。
"服务商/模型名"LanguageModelOpenAI: , , , , , , , , ,
openai/gpt-5openai/gpt-5-miniopenai/gpt-4.1openai/gpt-4.1-miniopenai/gpt-4.1-nanoopenai/gpt-4oopenai/gpt-4o-miniopenai/o3openai/o3-miniopenai/o4-miniAnthropic: , , , , ,
anthropic/claude-sonnet-4.5anthropic/claude-sonnet-4anthropic/claude-3.7-sonnetanthropic/claude-opus-4.1anthropic/claude-opus-4anthropic/claude-3.5-haikuGoogle: , ,
google/gemini-2.5-progoogle/gemini-2.5-flashgoogle/gemini-2.5-flash-lite支持任意字符串格式(用于自定义/未列出的模型),服务商名称会从前的前缀自动解析。
/