copilotkit
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseCopilotKit
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 (Angular 18+19). 28k+ GitHub stars.
@copilotkitnext/angular一款全栈开源框架(MIT协议,版本v1.51.3,Python SDK版本v0.1.78),用于在React和Angular UI中直接嵌入AI Copilot,构建智能代理应用。Angular支持通过实现(适配Angular 18+19版本)。GitHub星标数超28k。
@copilotkitnext/angularWhen 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 nextbash
npx copilotkit@latest create -f nextExisting project
现有项目集成
bash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtimebash
npm install @copilotkit/react-core @copilotkit/react-ui @copilotkit/runtimeEnvironment
环境配置
bash
undefinedbash
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
undefinedundefinedBackend API route (app/api/copilotkit/route.ts
)
app/api/copilotkit/route.ts后端API路由(app/api/copilotkit/route.ts
)
app/api/copilotkit/route.tstypescript
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
)
layout.tsx前端Provider配置(layout.tsx
)
layout.tsxtypescript
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
)
page.tsx聊天UI(page.tsx
)
page.tsxtypescript
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
useCopilotReadableuseCopilotReadable
-- 向LLM暴露应用状态
useCopilotReadabletypescript
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
useCopilotActionuseCopilotAction
-- 定义可执行操作
useCopilotActiontypescript
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
useCopilotChatuseCopilotChat
-- 程序化控制聊天
useCopilotChattypescript
const { appendMessage, stopGeneration, reset, reloadMessages } = useCopilotChat();typescript
const { appendMessage, stopGeneration, reset, reloadMessages } = useCopilotChat();useCopilotAdditionalInstructions
-- Dynamic context-aware prompts
useCopilotAdditionalInstructionsuseCopilotAdditionalInstructions
-- 动态上下文提示
useCopilotAdditionalInstructionstypescript
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
useCopilotChatSuggestionsuseCopilotChatSuggestions
-- 根据应用状态自动生成建议
useCopilotChatSuggestionstypescript
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)
useAgentuseAgent
-- v2版本代理状态同步(useCoAgent的超集)
useAgenttypescript
const { state, setState, run, stop } = useAgent({ name: "my_agent" });useAgentuseCoAgentuseCoAgentuseAgenttypescript
const { state, setState, run, stop } = useAgent({ name: "my_agent" });useAgentuseCoAgentuseCoAgentuseAgentCopilotTask
-- Run one-off programmatic tasks
CopilotTaskCopilotTask
-- 运行一次性程序化任务
CopilotTasktypescript
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组件
| Component | Import | Use case |
|---|---|---|
| | Embedded inline chat panel |
| | Collapsible sidebar chat |
| | Floating popup chat |
| | AI-powered textarea drop-in |
All accept , , , custom message/input components, and .
instructionslabelssuggestionsobservabilityHooks| 组件 | 导入路径 | 适用场景 |
|---|---|---|
| | 嵌入式内联聊天面板 |
| | 可折叠侧边栏聊天 |
| | 悬浮弹窗聊天 |
| | AI驱动的文本框替代组件 |
所有组件均支持、、、自定义消息/输入组件以及参数。
instructionslabelssuggestionsobservabilityHooksCopilotKit Provider Props
CopilotKit Provider属性
| Prop | Type | Purpose |
|---|---|---|
| | Self-hosted runtime endpoint |
| | Copilot Cloud API key |
| | Custom auth headers |
| | Cookie handling ( |
| | Default agent name |
| | Thread metadata, authorization |
| | Error handler callback |
| | Dev error banners |
| | Debugging inspector tool |
| | Custom renderers (A2UI, etc.) |
| 属性 | 类型 | 用途 |
|---|---|---|
| | 自托管Runtime端点 |
| | Copilot Cloud API密钥 |
| | 自定义认证头 |
| | Cookie处理方式(跨域场景使用 |
| | 默认代理名称 |
| | 会话元数据、授权信息 |
| | 错误处理回调 |
| | 开发环境错误提示横幅 |
| | 调试检查工具 |
| | 自定义渲染器(如A2UI) |
Agent Protocols
代理协议
| Protocol | Purpose | Package |
|---|---|---|
| AG-UI | Agent <-> User interaction, event streaming | |
| MCP | Agent <-> External tools | MCP server integration |
| A2A | Agent <-> Agent communication | A2A protocol support |
| 协议 | 用途 | 包 |
|---|---|---|
| AG-UI | 代理与用户交互、事件流 | |
| 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适配器
OpenAIAdapterAnthropicAdapterGoogleGenerativeAIAdapterGroqAdapterLangChainAdapterOpenAIAssistantAdapterOpenAIAdapterAnthropicAdapterGoogleGenerativeAIAdapterGroqAdapterLangChainAdapterOpenAIAssistantAdapterKey Packages
核心包
| Package | Purpose |
|---|---|
| Provider + all hooks |
| Chat UI components + styles |
| Backend runtime + LLM adapters + framework endpoints |
| Python SDK for LangGraph/CrewAI agents |
| Angular SDK (Angular 18+19) |
| AG-UI protocol types/events |
| AG-UI client implementation |
| 包 | 用途 |
|---|---|
| Provider及所有Hooks |
| 聊天UI组件及样式 |
| 后端Runtime、LLM适配器及框架端点 |
| 用于LangGraph/CrewAI代理的Python SDK |
| Angular SDK(适配Angular 18+19) |
| AG-UI协议类型与事件 |
| AG-UI客户端实现 |
Error Handling
错误处理
Frontend onError
callback
onError前端onError
回调
onErrortypescript
<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"工具渲染"failed"
状态
"failed"All render functions receive when a tool errors. Always handle this:
status === "failed"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异常类型
| Exception | Meaning |
|---|---|
| Requested action not registered |
| Requested agent not found in endpoint |
| 异常 | 含义 |
|---|---|
| 请求的操作未注册 |
| 端点中未找到请求的代理 |
Versioning
版本信息
Current version: v1.51.3 (Python SDK v0.1.78). The v2 runtime interface is available at the path. Next-generation packages use the namespace (e.g., ).
/v2@copilotkitnext/*@copilotkitnext/angular当前版本:v1.51.3(Python SDK版本v0.1.78)。v2版本Runtime接口可通过路径访问。下一代包使用命名空间(例如)。
/v2@copilotkitnext/*@copilotkitnext/angularCommon Anti-Patterns
常见反模式
| Don't | Do Instead |
|---|---|
| Put API keys in client-side code | Use server-side env vars + runtime endpoint |
| Create a new CopilotRuntime per request | Instantiate once, reuse across requests |
Skip | Always handle "inProgress", "complete", "failed" |
Use | Prefer |
| Hardcode instructions in every component | Use |
| Forget to import styles | Add |
Mix | Pick one deployment mode unless you need hybrid |
| Put heavy computation in action handlers | Return data from handlers, compute in render |
| 错误做法 | 正确做法 |
|---|---|
| 在客户端代码中存储API密钥 | 使用服务端环境变量 + Runtime端点 |
| 每次请求创建新的CopilotRuntime实例 | 初始化一次,复用所有请求 |
渲染函数中跳过 | 始终处理"inProgress"、"complete"、"failed"状态 |
新项目使用 | 优先使用 |
| 在每个组件中硬编码提示词 | 使用 |
| 忘记导入样式文件 | 在Layout中添加 |
无特殊需求同时使用 | 选择一种部署模式,除非需要混合部署 |
| 在操作处理器中执行大量计算 | 从处理器返回数据,在渲染阶段进行计算 |
Common Patterns Cheat Sheet
常用模式速查
| Want to... | Use |
|---|---|
| Show a chat bubble | |
| Give LLM app context | |
| Let LLM call functions | |
| Render UI from tool calls | |
| Default fallback tool renderer | |
| Sync state bidirectionally | |
| Use v2 agent state sync | |
| Show agent progress | |
| Ask user for approval | |
| Handle LangGraph interrupts | |
| Control chat programmatically | |
| Run one-off tasks | |
| Connect Python agent | |
| Scaffold AG-UI app | |
| Persist conversations | Thread model + StorageRunners |
| 需求 | 对应工具/API |
|---|---|
| 展示聊天气泡 | |
| 向LLM提供应用上下文 | |
| 允许LLM调用函数 | |
| 根据工具调用渲染UI | |
| 默认回退工具渲染器 | |
| 双向同步状态 | |
| 使用v2代理状态同步 | |
| 展示代理进度 | |
| 请求用户审批 | |
| 处理LangGraph中断 | |
| 程序化控制聊天 | |
| 运行一次性任务 | |
| 连接Python代理 | |
| 搭建AG-UI应用 | |
| 持久化会话 | 线程模型 + StorageRunners |