copilotkit

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CopilotKit

CopilotKit

Full-stack open-source framework (MIT, v1.51.3, Python SDK v0.1.78) for building agentic applications with AI copilots embedded directly in React and Angular UIs. Angular support via
@copilotkitnext/angular
(Angular 18+19). 28k+ GitHub stars.
一款全栈开源框架(MIT协议,版本v1.51.3,Python SDK版本v0.1.78),用于在React和Angular UI中直接嵌入AI Copilot,构建智能代理应用。Angular支持通过
@copilotkitnext/angular
实现(适配Angular 18+19版本)。GitHub星标数超28k。

When to Use This Skill

适用场景

  • User wants to add an AI copilot, assistant, or chatbot to a React/Next.js app
  • User is working with CopilotKit hooks, components, or runtime
  • User asks about AI-powered text areas or form completion
  • User needs to connect a Python agent (LangGraph/CrewAI) to a React frontend
  • User is implementing human-in-the-loop or generative UI patterns
  • User asks about AG-UI protocol or MCP Apps
  • User wants to sync state between a UI and an AI agent
  • 用户希望为React/Next.js应用添加AI Copilot、助手或聊天机器人
  • 用户正在使用CopilotKit的Hooks、组件或Runtime
  • 用户咨询AI驱动的文本框或表单填充功能
  • 用户需要将Python代理(LangGraph/CrewAI)与React前端连接
  • 用户正在实现人机协作(Human-in-the-loop)或生成式UI模式
  • 用户咨询AG-UI协议或MCP Apps
  • 用户希望同步UI与AI代理之间的状态

Architecture

架构

+---------------------------------------------------------+
|  Frontend Layer                                          |
|  @copilotkit/react-core  - Provider, hooks               |
|  @copilotkit/react-ui    - Chat components, styles        |
+-------------------+-------------------------------------+
                    | AG-UI Protocol (HTTP event streaming)
+-------------------v-------------------------------------+
|  Backend Layer                                           |
|  @copilotkit/runtime     - CopilotRuntime                |
|  LLM Adapters: OpenAI, Anthropic, Google, Groq, etc      |
+-------------------+-------------------------------------+
                    | HTTP (AG-UI events)
+-------------------v-------------------------------------+
|  Agent Layer (optional)                                  |
|  copilotkit (Python SDK) - LangGraph, CrewAI, etc        |
|  Or: Google ADK, AWS Strands, Microsoft Agent FW, etc    |
+---------------------------------------------------------+
+---------------------------------------------------------+
|  Frontend Layer                                          |
|  @copilotkit/react-core  - Provider, hooks               |
|  @copilotkit/react-ui    - Chat components, styles        |
+-------------------+-------------------------------------+
                    | AG-UI Protocol (HTTP event streaming)
+-------------------v-------------------------------------+
|  Backend Layer                                           |
|  @copilotkit/runtime     - CopilotRuntime                |
|  LLM Adapters: OpenAI, Anthropic, Google, Groq, etc      |
+-------------------+-------------------------------------+
                    | HTTP (AG-UI events)
+-------------------v-------------------------------------+
|  Agent Layer (optional)                                  |
|  copilotkit (Python SDK) - LangGraph, CrewAI, etc        |
|  Or: Google ADK, AWS Strands, Microsoft Agent FW, etc    |
+---------------------------------------------------------+

Quick Start

快速开始

New project

新项目初始化

bash
npx copilotkit@latest create -f next
bash
npx copilotkit@latest create -f next

Existing project

现有项目集成

bash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime
bash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtime

Environment

环境配置

bash
undefined
bash
undefined

.env.local

.env.local

OPENAI_API_KEY="sk-..."
OPENAI_API_KEY="sk-..."

or ANTHROPIC_API_KEY, GOOGLE_API_KEY, GROQ_API_KEY

或使用ANTHROPIC_API_KEY、GOOGLE_API_KEY、GROQ_API_KEY

undefined
undefined

Backend API route (
app/api/copilotkit/route.ts
)

后端API路由(
app/api/copilotkit/route.ts

typescript
import {
  CopilotRuntime,
  OpenAIAdapter, // or AnthropicAdapter, GoogleGenerativeAIAdapter, GroqAdapter, LangChainAdapter
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { NextRequest } from "next/server";

const serviceAdapter = new OpenAIAdapter({ model: "gpt-4o" });
const runtime = new CopilotRuntime();

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter,
    endpoint: "/api/copilotkit",
  });
  return handleRequest(req);
};
typescript
import {
  CopilotRuntime,
  OpenAIAdapter, // 或AnthropicAdapter、GoogleGenerativeAIAdapter、GroqAdapter、LangChainAdapter
  copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { NextRequest } from "next/server";

const serviceAdapter = new OpenAIAdapter({ model: "gpt-4o" });
const runtime = new CopilotRuntime();

export const POST = async (req: NextRequest) => {
  const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
    runtime,
    serviceAdapter,
    endpoint: "/api/copilotkit",
  });
  return handleRequest(req);
};

Frontend provider (
layout.tsx
)

前端Provider配置(
layout.tsx

typescript
import { CopilotKit } from "@copilotkit/react-core";
import "@copilotkit/react-ui/styles.css";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <CopilotKit runtimeUrl="/api/copilotkit">
          {children}
        </CopilotKit>
      </body>
    </html>
  );
}
typescript
import { CopilotKit } from "@copilotkit/react-core";
import "@copilotkit/react-ui/styles.css";

export default function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="en">
      <body>
        <CopilotKit runtimeUrl="/api/copilotkit">
          {children}
        </CopilotKit>
      </body>
    </html>
  );
}

Chat UI (
page.tsx
)

聊天UI(
page.tsx

typescript
import { CopilotPopup } from "@copilotkit/react-ui"; // or CopilotSidebar, CopilotChat

export default function Home() {
  return (
    <>
      <YourApp />
      <CopilotPopup
        instructions="You are an AI assistant for this app."
        labels={{ title: "Assistant", initial: "How can I help?" }}
      />
    </>
  );
}
typescript
import { CopilotPopup } from "@copilotkit/react-ui"; // 或CopilotSidebar、CopilotChat

export default function Home() {
  return (
    <>
      <YourApp />
      <CopilotPopup
        instructions="You are an AI assistant for this app."
        labels={{ title: "Assistant", initial: "How can I help?" }}
      />
    </>
  );
}

Core Hooks

核心Hooks

useCopilotReadable
-- Expose app state to LLM

useCopilotReadable
-- 向LLM暴露应用状态

typescript
useCopilotReadable({
  description: "Current user profile and preferences",
  value: { name: user.name, role: user.role, preferences },
});
typescript
useCopilotReadable({
  description: "Current user profile and preferences",
  value: { name: user.name, role: user.role, preferences },
});

useCopilotAction
-- Define executable actions

useCopilotAction
-- 定义可执行操作

typescript
useCopilotAction({
  name: "addItem",
  description: "Add a new item to the list",
  parameters: [
    { name: "title", type: "string", required: true },
    { name: "priority", type: "string", description: "low, medium, or high" },
  ],
  handler: async ({ title, priority = "medium" }) => {
    setItems(prev => [...prev, { id: Date.now().toString(), title, priority }]);
    return `Added "${title}" with ${priority} priority`;
  },
});
typescript
useCopilotAction({
  name: "addItem",
  description: "Add a new item to the list",
  parameters: [
    { name: "title", type: "string", required: true },
    { name: "priority", type: "string", description: "low, medium, or high" },
  ],
  handler: async ({ title, priority = "medium" }) => {
    setItems(prev => [...prev, { id: Date.now().toString(), title, priority }]);
    return `Added "${title}" with ${priority} priority`;
  },
});

useCopilotChat
-- Programmatic chat control

useCopilotChat
-- 程序化控制聊天

typescript
const { appendMessage, stopGeneration, reset, reloadMessages } = useCopilotChat();
typescript
const { appendMessage, stopGeneration, reset, reloadMessages } = useCopilotChat();

useCopilotAdditionalInstructions
-- Dynamic context-aware prompts

useCopilotAdditionalInstructions
-- 动态上下文提示

typescript
useCopilotAdditionalInstructions({
  instructions: "User is on the settings page. Help them configure preferences.",
});
typescript
useCopilotAdditionalInstructions({
  instructions: "User is on the settings page. Help them configure preferences.",
});

useCopilotChatSuggestions
-- Auto-generate suggestions from app state

useCopilotChatSuggestions
-- 根据应用状态自动生成建议

typescript
useCopilotChatSuggestions({
  instructions: "Suggest actions based on the current app state.",
});
typescript
useCopilotChatSuggestions({
  instructions: "Suggest actions based on the current app state.",
});

useAgent
-- v2 agent state sync (superset of useCoAgent)

useAgent
-- v2版本代理状态同步(useCoAgent的超集)

typescript
const { state, setState, run, stop } = useAgent({ name: "my_agent" });
useAgent
is the v2 replacement for
useCoAgent
. It includes all
useCoAgent
functionality plus time-travel debugging and improved state management. Prefer
useAgent
for new projects.
typescript
const { state, setState, run, stop } = useAgent({ name: "my_agent" });
useAgent
useCoAgent
的v2替代版本,包含
useCoAgent
的所有功能,同时支持时间回溯调试和优化的状态管理。新项目建议优先使用
useAgent

CopilotTask
-- Run one-off programmatic tasks

CopilotTask
-- 运行一次性程序化任务

typescript
import { CopilotTask } from "@copilotkit/react-core";

const task = new CopilotTask({ instructions: "Summarize the data" });
await task.run(context);
typescript
import { CopilotTask } from "@copilotkit/react-core";

const task = new CopilotTask({ instructions: "Summarize the data" });
await task.run(context);

Advanced Patterns

进阶模式

Detailed guides organized by topic -- load only what's needed:
  • Generative UI (static AG-UI, declarative A2UI, open-ended MCP Apps): See references/generative-ui.md
  • Shared State & CoAgents (useCoAgent, useAgent, bidirectional sync, LangGraph): See references/coagents-shared-state.md
  • Human-in-the-Loop (buildtime/runtime HITL, approval flows, agent steering): See references/human-in-the-loop.md
  • Runtime & Adapters (all LLM adapters, framework endpoints, backend actions): See references/runtime-adapters.md
  • Python SDK (LangGraphAgent, FastAPI, actions, state, events): See references/python-sdk.md
  • Styling & Customization (CSS, custom components, headless mode): See references/styling-customization.md
  • Troubleshooting (common issues, CORS, env vars, Docker): See references/troubleshooting.md
  • AG-UI Protocol (events, architecture, CLI scaffolding): See references/ag-ui-protocol.md
按主题分类的详细指南,按需查看:
  • 生成式UI(静态AG-UI、声明式A2UI、开放式MCP Apps):参考references/generative-ui.md
  • 共享状态与CoAgent(useCoAgent、useAgent、双向同步、LangGraph):参考references/coagents-shared-state.md
  • 人机协作(Human-in-the-Loop)(构建时/运行时HITL、审批流程、代理引导):参考references/human-in-the-loop.md
  • Runtime与适配器(所有LLM适配器、框架端点、后端操作):参考references/runtime-adapters.md
  • Python SDK(LangGraphAgent、FastAPI、操作、状态、事件):参考references/python-sdk.md
  • 样式与自定义(CSS、自定义组件、无头模式):参考references/styling-customization.md
  • 故障排查(常见问题、CORS、环境变量、Docker):参考references/troubleshooting.md
  • AG-UI协议(事件、架构、CLI脚手架):参考references/ag-ui-protocol.md

UI Components

UI组件

ComponentImportUse case
CopilotChat
@copilotkit/react-ui
Embedded inline chat panel
CopilotSidebar
@copilotkit/react-ui
Collapsible sidebar chat
CopilotPopup
@copilotkit/react-ui
Floating popup chat
CopilotTextarea
@copilotkit/react-ui
AI-powered textarea drop-in
All accept
instructions
,
labels
,
suggestions
, custom message/input components, and
observabilityHooks
.
组件导入路径适用场景
CopilotChat
@copilotkit/react-ui
嵌入式内联聊天面板
CopilotSidebar
@copilotkit/react-ui
可折叠侧边栏聊天
CopilotPopup
@copilotkit/react-ui
悬浮弹窗聊天
CopilotTextarea
@copilotkit/react-ui
AI驱动的文本框替代组件
所有组件均支持
instructions
labels
suggestions
、自定义消息/输入组件以及
observabilityHooks
参数。

CopilotKit Provider Props

CopilotKit Provider属性

PropTypePurpose
runtimeUrl
string
Self-hosted runtime endpoint
publicApiKey
string
Copilot Cloud API key
headers
object
Custom auth headers
credentials
string
Cookie handling (
"include"
for cross-origin)
agent
string
Default agent name
properties
object
Thread metadata, authorization
onError
function
Error handler callback
showDevConsole
boolean
Dev error banners
enableInspector
boolean
Debugging inspector tool
renderActivityMessages
array
Custom renderers (A2UI, etc.)
属性类型用途
runtimeUrl
string
自托管Runtime端点
publicApiKey
string
Copilot Cloud API密钥
headers
object
自定义认证头
credentials
string
Cookie处理方式(跨域场景使用
"include"
agent
string
默认代理名称
properties
object
会话元数据、授权信息
onError
function
错误处理回调
showDevConsole
boolean
开发环境错误提示横幅
enableInspector
boolean
调试检查工具
renderActivityMessages
array
自定义渲染器(如A2UI)

Agent Protocols

代理协议

ProtocolPurposePackage
AG-UIAgent <-> User interaction, event streaming
@ag-ui/core
,
@ag-ui/client
MCPAgent <-> External toolsMCP server integration
A2AAgent <-> Agent communicationA2A protocol support
协议用途
AG-UI代理与用户交互、事件流
@ag-ui/core
@ag-ui/client
MCP代理与外部工具交互MCP服务器集成
A2A代理间通信支持A2A协议

Supported Agent Frameworks

支持的代理框架

LangGraph, CrewAI, Google ADK, AWS Strands, Microsoft Agent Framework, Mastra, PydanticAI, AG2, LlamaIndex, Agno, VoltAgent, Blaxel.
LangGraph、CrewAI、Google ADK、AWS Strands、Microsoft Agent Framework、Mastra、PydanticAI、AG2、LlamaIndex、Agno、VoltAgent、Blaxel。

LLM Adapters

LLM适配器

OpenAIAdapter
,
AnthropicAdapter
,
GoogleGenerativeAIAdapter
,
GroqAdapter
,
LangChainAdapter
,
OpenAIAssistantAdapter
.
OpenAIAdapter
AnthropicAdapter
GoogleGenerativeAIAdapter
GroqAdapter
LangChainAdapter
OpenAIAssistantAdapter

Key Packages

核心包

PackagePurpose
@copilotkit/react-core
Provider + all hooks
@copilotkit/react-ui
Chat UI components + styles
@copilotkit/runtime
Backend runtime + LLM adapters + framework endpoints
copilotkit
(Python)
Python SDK for LangGraph/CrewAI agents
@copilotkitnext/angular
Angular SDK (Angular 18+19)
@ag-ui/core
AG-UI protocol types/events
@ag-ui/client
AG-UI client implementation
用途
@copilotkit/react-core
Provider及所有Hooks
@copilotkit/react-ui
聊天UI组件及样式
@copilotkit/runtime
后端Runtime、LLM适配器及框架端点
copilotkit
(Python)
用于LangGraph/CrewAI代理的Python SDK
@copilotkitnext/angular
Angular SDK(适配Angular 18+19)
@ag-ui/core
AG-UI协议类型与事件
@ag-ui/client
AG-UI客户端实现

Error Handling

错误处理

Frontend
onError
callback

前端
onError
回调

typescript
<CopilotKit
  runtimeUrl="/api/copilotkit"
  onError={(error) => {
    console.error("CopilotKit error:", error);
    toast.error("AI assistant encountered an error");
  }}
>
typescript
<CopilotKit
  runtimeUrl="/api/copilotkit"
  onError={(error) => {
    console.error("CopilotKit error:", error);
    toast.error("AI assistant encountered an error");
  }}
>

Tool render
"failed"
status

工具渲染
"failed"
状态

All render functions receive
status === "failed"
when a tool errors. Always handle this:
typescript
render: ({ status, args, result }) => {
  if (status === "failed") return <ErrorCard message="Tool execution failed" />;
  // ...
}
所有渲染函数在工具执行出错时会收到
status === "failed"
状态,务必处理该情况:
typescript
render: ({ status, args, result }) => {
  if (status === "failed") return <ErrorCard message="Tool execution failed" />;
  // ...
}

Python SDK exception types

Python SDK异常类型

ExceptionMeaning
ActionNotFoundException
Requested action not registered
AgentNotFoundException
Requested agent not found in endpoint
异常含义
ActionNotFoundException
请求的操作未注册
AgentNotFoundException
端点中未找到请求的代理

Versioning

版本信息

Current version: v1.51.3 (Python SDK v0.1.78). The v2 runtime interface is available at the
/v2
path. Next-generation packages use the
@copilotkitnext/*
namespace (e.g.,
@copilotkitnext/angular
).
当前版本:v1.51.3(Python SDK版本v0.1.78)。v2版本Runtime接口可通过
/v2
路径访问。下一代包使用
@copilotkitnext/*
命名空间(例如
@copilotkitnext/angular
)。

Common Anti-Patterns

常见反模式

Don'tDo Instead
Put API keys in client-side codeUse server-side env vars + runtime endpoint
Create a new CopilotRuntime per requestInstantiate once, reuse across requests
Skip
status
checks in render functions
Always handle "inProgress", "complete", "failed"
Use
useCoAgent
for new projects
Prefer
useAgent
(v2 superset with time travel)
Hardcode instructions in every componentUse
useCopilotAdditionalInstructions
for page-specific context
Forget to import stylesAdd
import "@copilotkit/react-ui/styles.css"
in layout
Mix
runtimeUrl
and
publicApiKey
without reason
Pick one deployment mode unless you need hybrid
Put heavy computation in action handlersReturn data from handlers, compute in render
错误做法正确做法
在客户端代码中存储API密钥使用服务端环境变量 + Runtime端点
每次请求创建新的CopilotRuntime实例初始化一次,复用所有请求
渲染函数中跳过
status
检查
始终处理"inProgress"、"complete"、"failed"状态
新项目使用
useCoAgent
优先使用
useAgent
(v2超集,支持时间回溯)
在每个组件中硬编码提示词使用
useCopilotAdditionalInstructions
添加页面级上下文提示
忘记导入样式文件在Layout中添加
import "@copilotkit/react-ui/styles.css"
无特殊需求同时使用
runtimeUrl
publicApiKey
选择一种部署模式,除非需要混合部署
在操作处理器中执行大量计算从处理器返回数据,在渲染阶段进行计算

Common Patterns Cheat Sheet

常用模式速查

Want to...Use
Show a chat bubble
<CopilotPopup>
Give LLM app context
useCopilotReadable()
Let LLM call functions
useCopilotAction()
Render UI from tool calls
useFrontendTool()
or
useRenderToolCall()
Default fallback tool renderer
useDefaultTool()
Sync state bidirectionally
useCoAgent()
Use v2 agent state sync
useAgent()
(superset of useCoAgent)
Show agent progress
useCoAgentStateRender()
Ask user for approval
useHumanInTheLoop()
Handle LangGraph interrupts
useLangGraphInterrupt()
Control chat programmatically
useCopilotChat()
Run one-off tasks
CopilotTask
Connect Python agent
CopilotKitRemoteEndpoint
+
LangGraphAgent
Scaffold AG-UI app
npx create-ag-ui-app
Persist conversationsThread model + StorageRunners
需求对应工具/API
展示聊天气泡
<CopilotPopup>
向LLM提供应用上下文
useCopilotReadable()
允许LLM调用函数
useCopilotAction()
根据工具调用渲染UI
useFrontendTool()
useRenderToolCall()
默认回退工具渲染器
useDefaultTool()
双向同步状态
useCoAgent()
使用v2代理状态同步
useAgent()
(useCoAgent的超集)
展示代理进度
useCoAgentStateRender()
请求用户审批
useHumanInTheLoop()
处理LangGraph中断
useLangGraphInterrupt()
程序化控制聊天
useCopilotChat()
运行一次性任务
CopilotTask
连接Python代理
CopilotKitRemoteEndpoint
+
LangGraphAgent
搭建AG-UI应用
npx create-ag-ui-app
持久化会话线程模型 + StorageRunners