copilotkit-develop

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

CopilotKit v2 Development Skill

CopilotKit v2 开发技能

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 技能 查看配置说明。

Architecture Overview

架构概览

CopilotKit v2 is built on the AG-UI protocol (
@ag-ui/client
/
@ag-ui/core
). The stack has three layers:
  1. Runtime (
    @copilotkit/runtime
    ) -- Server-side. Hosts agents, handles SSE/Intelligence transport, middleware, transcription.
  2. Core (
    @copilotkit/core
    ) -- Shared state management, tool registry, suggestion engine. Not imported directly by apps.
  3. React (
    @copilotkit/react
    ) -- Provider, chat components, hooks. Re-exports everything from
    @ag-ui/client
    so apps need only one import.
CopilotKit v2 基于 AG-UI 协议(
@ag-ui/client
/
@ag-ui/core
)构建,技术栈分为三层:
  1. 运行时(Runtime)
    @copilotkit/runtime
    )—— 服务端,托管 Agent、处理 SSE/智能传输、中间件、转写功能。
  2. 核心(Core)
    @copilotkit/core
    )—— 共享状态管理、工具注册、推荐引擎,应用无需直接导入。
  3. React
    @copilotkit/react
    )—— Provider、聊天组件、Hooks,重新导出
    @ag-ui/client
    的所有内容,因此应用只需导入这一个包。

Workflow

工作流

1. Set Up the Runtime (Server)

1. 配置运行时(服务端)

Create a
CopilotRuntime
(or the explicit
CopilotSseRuntime
/
CopilotIntelligenceRuntime
) and expose it via
createCopilotEndpoint
(Hono) or
createCopilotEndpointExpress
(Express).
ts
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
import { LangGraphAgent } from "@ag-ui/langgraph";

const runtime = new CopilotRuntime({
  agents: {
    myAgent: new LangGraphAgent({ /* ... */ }),
  },
});

const app = createCopilotEndpoint({
  runtime,
  basePath: "/api/copilotkit",
});
创建
CopilotRuntime
(或显式使用
CopilotSseRuntime
/
CopilotIntelligenceRuntime
),并通过
createCopilotEndpoint
(Hono)或
createCopilotEndpointExpress
(Express)暴露接口。
ts
import { CopilotRuntime, createCopilotEndpoint } from "@copilotkit/runtime";
import { LangGraphAgent } from "@ag-ui/langgraph";

const runtime = new CopilotRuntime({
  agents: {
    myAgent: new LangGraphAgent({ /* ... */ }),
  },
});

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

2. Wrap Your App with the Provider (Client)

2. 使用 Provider 包裹你的应用(客户端)

tsx
import { CopilotKitProvider } from "@copilotkit/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <YourApp />
    </CopilotKitProvider>
  );
}
tsx
import { CopilotKitProvider } from "@copilotkit/react";

function App() {
  return (
    <CopilotKitProvider runtimeUrl="/api/copilotkit">
      <YourApp />
    </CopilotKitProvider>
  );
}

3. Add a Chat UI

3. 添加聊天 UI

Use
<CopilotChat>
,
<CopilotPopup>
, or
<CopilotSidebar>
:
tsx
import { CopilotChat } from "@copilotkit/react";

function ChatPage() {
  return <CopilotChat agentId="myAgent" />;
}
使用
<CopilotChat>
<CopilotPopup>
<CopilotSidebar>
tsx
import { CopilotChat } from "@copilotkit/react";

function ChatPage() {
  return <CopilotChat agentId="myAgent" />;
}

4. Register Frontend Tools

4. 注册前端工具

Let the agent call functions in the browser:
tsx
import { useFrontendTool } from "@copilotkit/react";
import { z } from "zod";

useFrontendTool({
  name: "highlightCell",
  description: "Highlight a spreadsheet cell",
  parameters: z.object({ row: z.number(), col: z.number() }),
  handler: async ({ row, col }) => {
    highlightCell(row, col);
    return "done";
  },
});
让 Agent 可以调用浏览器内的函数:
tsx
import { useFrontendTool } from "@copilotkit/react";
import { z } from "zod";

useFrontendTool({
  name: "highlightCell",
  description: "Highlight a spreadsheet cell",
  parameters: z.object({ row: z.number(), col: z.number() }),
  handler: async ({ row, col }) => {
    highlightCell(row, col);
    return "done";
  },
});

5. Share Application Context

5. 共享应用上下文

Provide runtime data to the agent:
tsx
import { useAgentContext } from "@copilotkit/react";

useAgentContext({
  description: "The user's current shopping cart",
  value: cart, // any JSON-serializable value
});
向 Agent 提供运行时数据:
tsx
import { useAgentContext } from "@copilotkit/react";

useAgentContext({
  description: "The user's current shopping cart",
  value: cart, // any JSON-serializable value
});

6. Handle Agent Interrupts

6. 处理 Agent 中断

When an agent pauses for human input:
tsx
import { useInterrupt } from "@copilotkit/react";

useInterrupt({
  render: ({ event, resolve }) => (
    <div>
      <p>{event.value.question}</p>
      <button onClick={() => resolve({ approved: true })}>Approve</button>
    </div>
  ),
});
当 Agent 暂停运行等待人工输入时:
tsx
import { useInterrupt } from "@copilotkit/react";

useInterrupt({
  render: ({ event, resolve }) => (
    <div>
      <p>{event.value.question}</p>
      <button onClick={() => resolve({ approved: true })}>Approve</button>
    </div>
  ),
});

7. Render Tool Calls in Chat

7. 在聊天中渲染工具调用

Show custom UI when tools execute:
tsx
import { useRenderTool } from "@copilotkit/react";
import { z } from "zod";

useRenderTool({
  name: "searchDocs",
  parameters: z.object({ query: z.string() }),
  render: ({ status, parameters, result }) => {
    if (status === "executing") return <Spinner>Searching {parameters.query}...</Spinner>;
    if (status === "complete") return <Results data={result} />;
    return <div>Preparing...</div>;
  },
}, []);
工具执行时展示自定义 UI:
tsx
import { useRenderTool } from "@copilotkit/react";
import { z } from "zod";

useRenderTool({
  name: "searchDocs",
  parameters: z.object({ query: z.string() }),
  render: ({ status, parameters, result }) => {
    if (status === "executing") return <Spinner>Searching {parameters.query}...</Spinner>;
    if (status === "complete") return <Results data={result} />;
    return <div>Preparing...</div>;
  },
}, []);

Quick Reference: Hooks

快速参考:Hooks

HookPurpose
useFrontendTool
Register a tool the agent can call in the browser
useComponent
Register a React component as a chat-rendered tool (convenience wrapper around
useFrontendTool
)
useAgentContext
Share JSON-serializable application state with the agent
useAgent
Get the
AbstractAgent
instance for an agent ID; subscribe to message/state/run-status changes
useInterrupt
Handle
on_interrupt
events from agents with render + optional handler/filter
useHumanInTheLoop
Register a tool that pauses execution until the user responds via a rendered UI
useRenderTool
Register a renderer for tool calls (by name or wildcard
"*"
)
useDefaultRenderTool
Register a wildcard
"*"
renderer using the built-in expandable card UI
useRenderToolCall
Internal hook returning a function to resolve the correct renderer for a given tool call
useRenderActivityMessage
Internal hook for rendering activity messages by type
useRenderCustomMessages
Internal hook for rendering custom message decorators
useSuggestions
Read the current suggestion list and control reload/clear
useConfigureSuggestions
Register static or dynamic (LLM-generated) suggestion configs
useThreads
List, rename, archive, and delete Intelligence platform threads
Hook用途
useFrontendTool
注册 Agent 可在浏览器中调用的工具
useComponent
注册 React 组件作为聊天渲染的工具(
useFrontendTool
的便捷封装)
useAgentContext
向 Agent 共享可序列化为 JSON 的应用状态
useAgent
获取指定 Agent ID 对应的
AbstractAgent
实例;订阅消息/状态/运行状态的变更
useInterrupt
处理 Agent 触发的
on_interrupt
事件,支持自定义渲染和可选的处理/过滤逻辑
useHumanInTheLoop
注册工具,暂停执行直到用户通过渲染的 UI 给出响应
useRenderTool
注册工具调用的渲染器(可按名称匹配或使用通配符
"*"
useDefaultRenderTool
使用内置的可展开卡片 UI 注册通配符
"*"
渲染器
useRenderToolCall
内部 Hook,返回为指定工具调用匹配正确渲染器的函数
useRenderActivityMessage
内部 Hook,用于按类型渲染活动消息
useRenderCustomMessages
内部 Hook,用于渲染自定义消息装饰器
useSuggestions
读取当前推荐列表,控制重载/清空操作
useConfigureSuggestions
注册静态或动态(LLM 生成)的推荐配置
useThreads
列出、重命名、归档和删除 Intelligence 平台的对话线程

Quick Reference: Components

快速参考:组件

ComponentPurpose
CopilotKitProvider
Root provider -- configures runtime URL, headers, agents, error handler
CopilotChat
Full chat interface connected to an agent (inline layout)
CopilotPopup
Chat in a floating popup with toggle button
CopilotSidebar
Chat in a collapsible sidebar with toggle button
CopilotChatView
Headless chat view with slots for message view, input, scroll, suggestions
CopilotChatInput
Chat input textarea with send/stop/transcribe controls
CopilotChatMessageView
Renders the message list
CopilotChatSuggestionView
Renders suggestion pills
组件用途
CopilotKitProvider
根 Provider,用于配置运行时地址、请求头、Agent、错误处理函数
CopilotChat
对接指定 Agent 的完整聊天界面(行内布局)
CopilotPopup
悬浮弹窗形式的聊天界面,自带切换按钮
CopilotSidebar
可折叠侧边栏形式的聊天界面,自带切换按钮
CopilotChatView
无样式聊天视图,提供消息列表、输入框、滚动、推荐项的插槽
CopilotChatInput
聊天输入文本框,自带发送/停止/转写控制按钮
CopilotChatMessageView
渲染消息列表
CopilotChatSuggestionView
渲染推荐胶囊按钮

Quick Reference: Runtime

快速参考:运行时

ExportPurpose
CopilotRuntime
Auto-detecting runtime (delegates to SSE or Intelligence)
CopilotSseRuntime
Explicit SSE-mode runtime
CopilotIntelligenceRuntime
Intelligence-mode runtime with durable threads
createCopilotEndpoint
Create a Hono app with all CopilotKit routes
createCopilotEndpointExpress
Create an Express router with all CopilotKit routes
CopilotKitIntelligence
Intelligence platform client configuration
导出项用途
CopilotRuntime
自动适配的运行时(自动委托给 SSE 或 Intelligence 模式)
CopilotSseRuntime
显式指定 SSE 模式的运行时
CopilotIntelligenceRuntime
支持持久化线程的 Intelligence 模式运行时
createCopilotEndpoint
创建包含所有 CopilotKit 路由的 Hono 应用
createCopilotEndpointExpress
创建包含所有 CopilotKit 路由的 Express 路由器
CopilotKitIntelligence
Intelligence 平台客户端配置