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/Intelligence传输、中间件、转录。
  2. Core
    @copilotkit/core
    )——共享状态管理、工具注册、建议引擎。无需被应用直接导入。
  3. React
    @copilotkit/react
    )——提供者、聊天组件、钩子。重新导出
    @ag-ui/client
    的所有内容,因此应用只需一次导入。

Workflow

工作流程

1. Set Up the Runtime (Server)

1. 设置Runtime(服务器)

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

快速参考:钩子

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
钩子名称用途
useFrontendTool
注册Agent可在浏览器中调用的工具
useComponent
将React组件注册为聊天渲染工具(
useFrontendTool
的便捷封装)
useAgentContext
与Agent共享可JSON序列化的应用状态
useAgent
根据Agent ID获取
AbstractAgent
实例;订阅消息/状态/运行状态变更
useInterrupt
通过渲染+可选处理器/过滤器处理来自Agent的
on_interrupt
事件
useHumanInTheLoop
注册一个工具,在用户通过渲染UI响应前暂停执行
useRenderTool
为工具调用注册渲染器(按名称或通配符
"*"
useDefaultRenderTool
使用内置可展开卡片UI注册通配符
"*"
渲染器
useRenderToolCall
内部钩子,返回一个函数以解析给定工具调用的正确渲染器
useRenderActivityMessage
用于按类型渲染活动消息的内部钩子
useRenderCustomMessages
用于渲染自定义消息装饰器的内部钩子
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
根提供者——配置runtime URL、请求头、Agent、错误处理器
CopilotChat
连接到Agent的完整聊天界面(内联布局)
CopilotPopup
带切换按钮的浮动弹窗聊天
CopilotSidebar
带切换按钮的可折叠侧边栏聊天
CopilotChatView
无头聊天视图,包含消息视图、输入框、滚动、建议的插槽
CopilotChatInput
带发送/停止/转录控件的聊天输入文本框
CopilotChatMessageView
渲染消息列表
CopilotChatSuggestionView
渲染建议胶囊

Quick Reference: Runtime

快速参考: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
自动检测型runtime(委托给SSE或Intelligence)
CopilotSseRuntime
显式SSE模式runtime
CopilotIntelligenceRuntime
带持久化线程的Intelligence模式runtime
createCopilotEndpoint
创建包含所有CopilotKit路由的Hono应用
createCopilotEndpointExpress
创建包含所有CopilotKit路由的Express路由器
CopilotKitIntelligence
Intelligence平台客户端配置