lang: zh slug: copilotkit title: ‘CopilotKit:31K+ 星星’ description: ‘CopilotKit 是用于应用内 AI 副驾驶和生成 UI 的开源前端堆栈。 使用预构建组件、useCopilotAction 挂钩和生产就绪部署构建 React Angular AI 助手。 涵盖安装、LangChain 集成、自托管以及与 Vercel AI SDK 的基准测试。’ tags: [“guide”, “open-source”, “reference”, “tutorial”] date: 2026-05-19 00:00:00+08:00 lastmod: 2026-05-19 00:00:00+08:00 tech_stack: [] application_domain: Llm Frameworks source_version: ’' licensing_model: Open Source license_type: MIT file_size: ’' file_md5: ’' download_url: ’' backup_url: ’' github_repo: ‘https://github.com/CopilotKit/CopilotKit' last_maintained: ‘2026-05-19’ draft: false categories: [’llm-frameworks’] aliases:
- /posts/copilotkit/
faqs:
- q: ‘Does CopilotKit require Next.js, or can it work with any React app?’ a: ‘CopilotKit works with any React 18+ application, not just Next.js. The runtime endpoint can be hosted separately on Express, Fastify, or any Node server, and the @copilotkit/react-core package has no Next.js dependency.’
- q: ‘Which LLM providers does CopilotKit support?’ a: ‘CopilotKit officially supports OpenAI (GPT-4o, GPT-4o-mini), Anthropic (Claude 3.5), Groq (Llama 3, Mixtral), Google Gemini, and Azure OpenAI. Community adapters exist for Cohere, Mistral, and local models via Ollama.’
- q: ‘What is the difference between useCopilotReadable and useCopilotAction?’ a: ‘useCopilotReadable makes React state visible to the LLM so the copilot sees what the user sees, while useCopilotAction registers typed functions the LLM can call to mutate frontend state, such as adding todos, navigating pages, or submitting forms.’
- q: ‘Is CopilotKit free to use in production?’ a: ‘Yes, the core framework is MIT-licensed and free forever. The free Developer tier includes 200 threads, 1GB multimodal storage, and 3-day thread retention, while paid plans add headless UI, analytics, security features, and higher limits.’
- q: ‘What is the AG-UI protocol used by CopilotKit?’ a: ‘AG-UI is an open wire protocol for agent-to-frontend communication created by CopilotKit, standardizing streaming chat, tool calls, and state sharing. As of 2026 it is supported by Google, Microsoft, Amazon, LangChain, and Mastra.’
featureImage: /images/articles/copilotkit-31k-stars-react-또는-angular-앱에.png #
{{< resource-info >}}
CopilotKit is the open-source frontend stack that turns any React or Angular application into an AI-native product. With 31,536 GitHub stars, 3,300+ forks, and a fresh $27M Series A (May 2026), it has become the default choice for teams shipping in-app AI assistants that read application state, trigger frontend actions, and render generative UI components inside chat interfaces.
This CopilotKit tutorial walks through a production-grade setup: installing packages, wiring the runtime, exposing React state to the LLM, defining frontend actions, deploying to a VPS, and hardening for production traffic. Whether you are building a CopilotKit React integration or adding a React AI assistant to an existing codebase, every command and config is copy-paste ready.
什么是 CopilotKit?CopilotKit 是一个用于构建应用内 AI 副驾驶和生成式 UI 体验的前端框架。 它为 React 提供预构建的 AI copilot 组件(CopilotSidebar、CopilotChat、CopilotPopup)、类型化挂钩(useCopilotReadable、useCopilotAction)以及连接到 OpenAI、LangChain、LangGraph、Groq 或任何自定义代理后端的可插入运行时。该项目由 CopilotKit Inc. 维护,并获得 MIT 许可,迄今为止已筹集 2700 万美元资金。 该团队由约 25 名工程师组成,每周发布版本并维护 AG-UI 开放协议,这是一种代理到前端通信的有线标准,现已得到 Google、微软、亚马逊、LangChain 和 Mastra 的支持。—## CopilotKit 的工作原理CopilotKit 位于前端应用程序和 LLM 或代理后端之间。 它通过干净的三层架构处理流式聊天、工具调用、状态同步和生成式 UI 渲染:| Layer | Responsibility | Key Files | #
|—|—|—|
| UI Components | Render chat sidebar, popup, or inline chat | CopilotSidebar, CopilotChat, CopilotPopup |
| React Hooks | Expose state + actions to the LLM | useCopilotReadable, useCopilotAction |
| Copilot Runtime | Route requests to LLM/agent backends | app/api/copilotkit/route.ts |
- useCopilotAction — 注册 LLM 可以调用的类型函数来改变前端状态(添加待办事项、导航页面、提交表单)。
- Copilot Runtime — 一个 API 端点,用于将前端请求代理到 LLM、处理身份验证并管理线程状态。
- 生成式 UI — 在聊天中呈现的 React 组件作为对工具调用(天气卡、任务项、数据表)的响应。
- AG-UI 协议 — 用于代理到前端通信的开放线路格式。 CopilotKit 是参考实现。—## 安装和设置### 先决条件- Node.js 20+(Node 18 将失败 - CopilotKit 使用本机获取功能)
- Next.js 15 与 App Router(推荐)或 React 18+
- OpenAI、Anthropic 或 Groq API 密钥### 第 1 步:安装软件包```` bas h
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime
用于LangChain集成(可选) #
npm install @copilotkit/runtime-langchain
对于 Groq 适配器(可选) #
npm install @copilotkit/运行时 groq-sdk
### 步骤2:添加环境变量
bas
h
.env.local #
OPENAI_API_KEY=sk-your-openai-key
GROQ_API_KEY=gsk-your-groq-key
COPILOTKIT_API_KEY=ck-your-copilot-cloud-key # 可选,用于云功能
### 步骤 3:创建运行时端点在 Next.js 项目中创建 `app/api/copilotkit/route.ts`:重击
.env.local #
OPENAI_API_KEY=sk-your-openai-key GROQ_API_KEY=gsk-your-groq-key COPILOTKIT_API_KEY=ck-your-copilot-cloud-key # 可选,用于云功能 ``呃”; 从“openai”导入OpenAI;const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });const 运行时 = new CopilotRuntime({ 行动:[], });const serviceAdapter = new OpenAIAdapter({ openai, 型号: “gpt-4o” });导出 const POST = 异步(要求:N```打字稿 导入{ 副驾驶运行时, OpenAI适配器, copilotRuntimeNextJSAppRouterEndpoint, 来自“@copilotkit/runtime”; 从“next/server”导入{NextRequest}; 从“openai”导入OpenAI;
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const 运行时 = new CopilotRuntime({ 行动:[], });
const serviceAdapter = new OpenAIAdapter({ openai, 型号: “gpt-4o” });
导出 const POST = async (req: NextRequest) => { const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ 运行时, 服务适配器, 端点:“/api/copilotkit”, });
返回handleRequest(req); }; ``它"> <副驾驶侧边栏 默认打开={假} 标签={{ 标题:“人工智能助手”, 初始:“嗨!今天有什么可以帮您的吗?”, 占位符:“输入消息…”, }}
{孩子}
</副驾驶侧边栏>
</副驾驶套件>
);
}
### 步骤 5:运行开发服务器
bas
h
npm 运行开发
打开http://localhost:3000 #
单击副驾驶按钮 — 您的 AI 助手已上线 #
````—## 与 LangChain、LangGraph 和 OpenAI 集成### OpenAI 适配器(最简单)OpenAI 适配器是最快的生产路径。 它直接连接到 GPT-4o,无需额外的后端基础设施:``打字稿 // app/api/copilotkit/route.ts — OpenAI v``` ts x // app/layout.tsx 或 app/page.tsx “使用客户端”;
从“@copilotkit/react-core”导入 { CopilotKit } ; 从“@copilotkit/react-ui”导入{CopilotSidebar}; 导入“@copilotkit/react-ui/styles.css”;
导出默认函数 RootLayout({ Children }: { Children: React.ReactNode }) {
返回(
{孩子} </副驾驶侧边栏> </副驾驶套件> ); } 用于插入自定义链、检索器和代理的适配器:``打字稿 // app/api/copilotkit/route.ts — LangChain 变体 从“@copilotkit/runtime”导入 { CopilotRuntime, LangChainAdapter }; 从“@langchain/openai”导入 { ChatOpenAI }; 从“next/server”导入{NextRequest};const 运行时 = new CopilotRuntime({ actions: [] });导出 const POST = async (req: NextRequest) => { const 模型 = new ChatOpenAI({ 型号名称:“gpt-4o”, openAIApiKey:process.env.OPENAI_API_KEY, }); const serviceAdapter = new LangChainAdapter({ 模型 });const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ 运行时, serviceAda``` bas h npm 运行开发
打开http://localhost:3000 #
单击副驾驶按钮 — 您的 AI 助手已上线 #
````)对于有状态多步代理,请连接到 LangGraph 后端:``打字稿 // app/api/copilotkit/route.ts — LangGraph 变体 导入{ 副驾驶运行时, LangGraphHttpAgent, 来自“@copilotkit/runtime”; 从“next/server”导入{NextRequest};const 运行时 = new CopilotRuntime({ 代理商:{ myAgent```打字稿 // app/api/copilotkit/route.ts — OpenAI 变体 从“@copilotkit/runtime”导入 { CopilotRuntime, OpenAIAdapter }; 从“@copilotkit/runtime”导入{copilotRuntimeNextJSAppRouterEndpoint}; 从“openai”导入OpenAI;
const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }); const 运行时 = new CopilotRuntime({ actions: [] }); const serviceAdapter = new OpenAIAdapter({ openai, 型号: “gpt-4o” });
导出 const POST = (req: NextRequest) => copilotRuntimeNextJSAppRouterEndpoint({ 运行时, 服务适配器, 端点:“/api/copilotkit”, }).handleRequest(req);
om
“groq-sdk”;
从“next/server”导入{NextRequest};const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const copilotKit = new CopilotRuntime();
const serviceAdapter = new GroqAdapter({
格罗克,
型号:“llama3-groq-8b-8192-工具使用预览”,
});导出 const POST = async (req: NextRequest) => {
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
运行时:copilotKit,
服务适配器,
端点:“/api/copilotkit”,
});
返回handleRequest(req);
};
````---## 真实 TSX 示例:Task Manager Copilot这是一个完整的、可用于生产的任务管理器,具有 CopilotKit 集成。 人工智能可以读取任务、添加新任务、将其标记为完成以及在聊天中呈现任务卡。````
ts
x
// 一个```打字稿
// app/api/copilotkit/route.ts — LangChain 变体
从“@copilotkit/runtime”导入 { CopilotRuntime, LangChainAdapter };
从“@langchain/openai”导入 { ChatOpenAI };
从“next/server”导入{NextRequest};
const 运行时 = new CopilotRuntime({ actions: [] });
导出 const POST = async (req: NextRequest) => {
const 模型 = new ChatOpenAI({
型号名称:“gpt-4o”,
openAIApiKey:process.env.OPENAI_API_KEY,
});
const serviceAdapter = new LangChainAdapter({ 模型 });
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
运行时,
服务适配器,
端点:“/api/copilotkit”,
});
返回handleRequest(req);
};
``` 值:任务,
});// 操作:添加新任务
useCopilotAction({
名称:“添加任务”,
description: "在任务列表中添加一个新任务",
参数:[
{
名称:“标题”,
类型:“字符串”,
描述:“要添加的任务的标题”,
要求:真实,
},
{
名称:“优先级”,
类型:“字符串”,
描述:“优先级:低、中或高”,
必需:假,
},
],
处理程序: ({ 标题, 优先级 = "中" }) => {
常量 newTask: 任务 = {
id: Date.now().toString(),
标题,
已完成:假,
优先级:优先级为任务[“优先级”],
};
setTasks((上一个) => [...上一个, newTask]);
返回`已添加任务:“${title}”和 ${p```
typescrip
t
// app/api/copilotkit/route.ts — LangGraph 变体
导入{
副驾驶运行时,
LangGraphHttpAgent,
来自“@copilotkit/runtime”;
从“next/server”导入{NextRequest};
const 运行时 = new CopilotRuntime({
代理商:{
myAgent: 新 LangGraphHttpAgent({
url: "http://localhost:8000/agent",
}),
},
});
const serviceAdapter = new OpenAIAdapter({
openai: 新的 OpenAI({ apiKey: process.env.OPENAI_API_KEY }),
});
导出 const POST = (req: NextRequest) =>
copilotRuntimeNextJSAppRouterEndpoint({
运行时,
服务适配器,
端点:“/api/copilotkit”,
}).handleRequest(req);
``电子任务',
描述:“从列表中删除任务”,
参数:[
{
名称:“任务ID”,
类型:“字符串”,
描述:“要删除的任务的ID”,
要求:真实,
},
],
处理程序:({taskId})=>{
setTasks((prev) => prev.filter((t) => t.id !== taskId));
return `已删除的任务 ${taskId}`;
},
});返回(
<div className="任务管理器">
<h2>我的任务({tasks.filter((t) => !t.completed).length} 待处理)</h2>
<ul>
{tasks.map((任务) => (
<li key={task.id} className={task.completed ? “完成”:“”}>
<span>[{task.priority}] {task.title}</span>
{task.completed && <span className=```打字稿
导入{
副驾驶运行时,
格罗克适配器,
copilotRuntimeNextJSAppRouterEndpoint,
来自“@copilotkit/runtime”;
从“groq-sdk”导入 Groq;
从“next/server”导入{NextRequest};
const groq = new Groq({ apiKey: process.env.GROQ_API_KEY });
const copilotKit = new CopilotRuntime();
const serviceAdapter = new GroqAdapter({
格罗克,
型号:“llama3-groq-8b-8192-工具使用预览”,
});
导出 const POST = async (req: NextRequest) => {
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
运行时:copilotKit,
服务适配器,
端点:“/api/copilotkit”,
});
返回handleRequest(req);
};
ority -${task.priority}`}>{task.priority}
状态:{任务.完成? “已完成”:“正在进行”}
从“反应”导入{useState}; 从“@copilotkit/react-core”导入{useCopilotReadable,useCopilotAction};
接口任务{ id:字符串; 标题:字符串; 完成:布尔值; 优先级:“低”| “中”| “高”; }
导出函数TaskManager() { const [任务,setTasks] = useState<任务[]>([ { id: “1”, title: “审查拉取请求 #42”, 已完成: false, 优先级: “高” }, { id: “2”, title: “更新 API 文档”,completed: true,priority: “medium” }, ]);
// 向 LLM 公开任务状态 useCopilotReadable({ 描述:“用户当前的任务列表,包含完成状态和优先级”, 值:任务, });
// 操作:添加新任务
useCopilotAction({
名称:“添加任务”,
description: “在任务列表中添加一个新任务”,
参数:[
{
名称:“标题”,
类型:“字符串”,
描述:“要添加的任务的标题”,
要求:真实,
},
{
名称:“优先级”,
类型:“字符串”,
描述:“优先级:低、中或高”,
必需:假,
},
],
处理程序: ({ 标题, 优先级 = “中” }) => {
常量 newTask: 任务 = {
id: Date.now().toString(),
标题,
已完成:假,
优先级:优先级为任务[“优先级”],
};
setTasks((上一个) => […上一个, newTask]);
return 已添加任务:“${title}”,优先级为 ${priority};
},
});
// 操作:将任务标记为完成 useCopilotAction({ 名称:“完成任务”, 描述:“通过标题或 ID 将任务标记为已完成”, 参数:[ { 名称:“任务ID”, 类型:“字符串”, 描述:“要标记完成的任务的 ID”, 要求:真实, }, ], 处理程序:({taskId})=>{ 设置任务((上一个)=> prev.map((t) => (t.id === taskId ? { …t, 已完成: true } : t)) ); 返回“将任务 ${taskId} 标记为已完成”; }, });
// 操作:删除任务
useCopilotAction({
name: “删除任务”,
描述:“从列表中删除任务”,
参数:[
{
名称:“任务ID”,
类型:“字符串”,
描述:“要删除的任务的ID”,
要求:真实,
},
],
处理程序:({taskId})=>{
setTasks((prev) => prev.filter((t) => t.id !== taskId));
return 已删除的任务 ${taskId};
},
});
返回(
我的任务({tasks.filter((t) => !t.completed).length} 待处理)
-
{tasks.map((任务) => (
- [{task.priority}] {task.title} {task.completed && 完成} ))}
{任务.标题}
{task.priority}状态:{任务.完成? “已完成”:“正在进行”}
常量速率限制 = 新速率限制({ redis: Redis.fromEnv(), limiter: Ratelimit.slidingWindow(20, “1 m”), // 每分钟 20 个请求 });
导出异步函数中间件(req:NextRequest){ if (req.nextUrl.pathname === “/api/copilotkit”) { const ip = 请求.ip ?? “127.0.0.1”; const { success } =等待ratelimit.limit(ip); 如果(!成功){ return NextResponse.json({ error: “速率受限” }, { status: 429 }); } } 返回 NextResponse.next(); }
// 将 LangSmith 跟踪添加到运行时
从“langsmith”导入{客户端};
const langsmith = 新客户端({
apiKey: process.env.LANGSMITH_API_KEY,
项目名称:“副驾驶套件生产”,
});
const 运行时 = new CopilotRuntime({
行动:[],
中间件:[
异步(ctx,下一个)=> {
const trace = wait langsmith.createRun({ name: "copilot-request" });
尝试{
常量结果=等待下一个();
等待 langsmith.updateRun(trace.id, { 错误: null });
返回结果;
} 捕获(错误){
等待 langsmith.updateRun(trace.id, { 错误: String(err) });
抛出错误;
}
},
],
});
````
💬 留言讨论