# https://github.com/CopilotKit/CopilotKit 项目说明书

生成时间：2026-05-17 23:57:37 UTC

## 目录

- [快速入门指南](#getting-started)
- [项目结构](#project-structure)
- [系统架构](#system-architecture)
- [通信协议](#protocols)
- [Chat UI 组件](#chat-ui-components)
- [React Hooks API](#react-hooks)
- [CopilotRuntime 后端运行时](#copilot-runtime)
- [后端工具系统](#backend-tools)
- [生成式 UI](#generative-ui)
- [人在回路 (Human-in-the-Loop)](#human-in-the-loop)

<a id='getting-started'></a>

## 快速入门指南

### 相关页面

相关主题：[系统架构](#system-architecture), [Chat UI 组件](#chat-ui-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [README.md](https://github.com/CopilotKit/CopilotKit/blob/main/README.md)
- [examples/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/README.md)
- [packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)
- [packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)
- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [examples/v1/state-machine/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/state-machine/README.md)
- [examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
</details>

# 快速入门指南

本文档为开发者提供 CopilotKit 的完整快速入门路径，涵盖环境准备、安装配置、核心概念及示例运行等关键环节。

---

## 什么是 CopilotKit

CopilotKit 是一个用于构建 AI 原生应用的框架，支持 React、Vue、Angular 等主流前端框架的无缝集成。通过 CopilotKit，开发者可以快速将 AI 能力嵌入现有应用，实现自然语言交互、工具调用代理等功能。

资料来源：[README.md:1]()

---

## 前置要求

在开始使用 CopilotKit 之前，请确保开发环境满足以下要求：

| 类别 | 版本要求 |
|------|----------|
| Node.js | 18+ |
| 包管理器 | npm / yarn / pnpm |

资料来源：[examples/v1/form-filling/README.md:1]()

---

## 安装方式

### 使用 Copilot Cloud（推荐）

Copilot Cloud 提供托管式运行时，无需自行搭建后端服务。开发者只需获取公开 API Key 即可快速集成：

```bash
NEXT_PUBLIC_CPK_PUBLIC_API_KEY=your_copilotkit_api_key
```

> **注意**：公开 API Key 以 `ck_pub_` 开头，可从 [Copilot Cloud](https://cloud.copilotkit.ai) 获取。

资料来源：[examples/v1/travel/README.md:1]()

### 自托管运行时

如需完全控制运行时，可选择自托管方式。使用 `runtimeUrl` 配置自定义后端：

```typescript
<CopilotKit runtimeUrl="/api/copilotkit" />
```

资料来源：[packages/vue/README.md:1]()

---

## React 快速开始

### 基础配置

React 是 CopilotKit 最成熟的集成方案。首先在应用入口处配置 Provider：

```tsx
// app/layout.tsx
import { CopilotKit } from "@copilotkit/react-core";

export default function RootLayout({ children }) {
  return (
    <html lang="zh-CN">
      <body>
        <CopilotKit publicApiKey="ck_pub_...">
          {children}
        </CopilotKit>
      </body>
    </html>
  );
}
```

资料来源：[examples/v1/form-filling/README.md:1]()

### CopilotKit 配置参数

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `publicApiKey` | string | 是（使用 Copilot Cloud 时） | Copilot Cloud 公开 API Key |
| `runtimeUrl` | string | 是（自托管时） | 后端运行时地址 |
| `headers` | Record<string, string> | 否 | 默认请求头 |
| `licenseKey` | string | 否 | Copilot Cloud 许可证密钥 |

资料来源：[packages/angular/README.md:1]()

### 运行时配置

CopilotKit 运行时支持多种高级配置选项：

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

export default function App() {
  return (
    <CopilotKit
      runtimeUrl="/api/copilotkit"
      publicApiKey="ck_pub_..."
      properties={{
        userId: "user_123",
      }}
    >
      {children}
    </CopilotKit>
  );
}
```

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:1]()

---

## Vue 快速开始

### 安装依赖

```bash
npm install @copilotkit/vue
```

### Provider 配置

```vue
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue";
</script>

<template>
  <CopilotKitProvider runtime-url="/api/copilotkit">
    <slot />
  </CopilotKitProvider>
</template>
```

### 错误处理

Vue 集成支持统一的错误处理回调：

```vue
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue";
import type { KitCoreErrorCode } from "@copilotkit/sdk-core";

function onProviderError(event: {
  error: Error;
  code: KitCoreErrorCode;
  context: Record<string, any>;
}) {
  console.error(
    "CopilotKit provider error",
    event.code,
    event.context,
    event.error,
  );
}
</script>

<template>
  <CopilotKitProvider
    runtime-url="/api/copilotkit"
    :on-error="onProviderError"
  >
    <slot />
  </CopilotKitProvider>
</template>
```

资料来源：[packages/vue/README.md:1]()

### Debug 日志配置

```typescript
import { CopilotKitProvider, type DebugConfig } from "@copilotkit/vue";

const debug: DebugConfig = { 
  events: true, 
  lifecycle: true 
};
```

支持的值：

| 值 | 说明 |
|----|------|
| `true` / `false` | 启用或禁用事件 + 生命周期日志 |
| `{ events?: boolean; lifecycle?: boolean; verbose?: boolean }` | 细粒度控制 |

资料来源：[packages/vue/README.md:1]()

---

## Angular 快速开始

### 安装依赖

```bash
npm install @copilotkit/angular
```

### Provider 配置

```typescript
import { provideCopilotKit } from "@copilotkit/angular";

@Component({
  // ...
})
export class AppComponent {}
```

### CopilotKitConfig 配置接口

```typescript
export interface CopilotKitConfig {
  runtimeUrl?: string;
  headers?: Record<string, string>;
  licenseKey?: string;
  properties?: Record<string, unknown>;
  agents?: Record<string, AbstractAgent>;
  tools?: ClientTool[];
  renderToolCalls?: RenderToolCallConfig[];
  frontendTools?: FrontendToolConfig[];
  humanInTheLoop?: HumanInTheLoopConfig[];
}
```

| 参数 | 说明 |
|------|------|
| `runtimeUrl` | CopilotKit 运行时 URL |
| `headers` | 默认请求头 |
| `licenseKey` | Copilot Cloud 公开 API Key (`ck_pub_...`) |
| `properties` | 转发到 agent runs 的任意属性 |
| `agents` | 浏览器内本地 agents，按 `agentId` 索引 |
| `tools` | 运行时工具定义（无处理器） |
| `frontendTools` | 带处理器的客户端工具 |
| `humanInTheLoop` | 暂停等待用户输入的工具 |

资料来源：[packages/angular/README.md:1]()

---

## 运行示例项目

### 示例仓库结构

CopilotKit 仓库包含 47 个综合演示项目，展示各种集成方式和应用场景。

```mermaid
graph TD
    A[CopilotKit 示例] --> B[集成示例<br/>17个]
    A --> C[Canvas 应用<br/>示例]
    A --> D[Showcase<br/>展示项目]
    A --> E[v1/v2 旧版<br/>示例]
    
    B --> B1[LangGraph Python]
    B --> B2[LangGraph JS]
    B --> B3[Mastra]
    B --> B4[LlamaIndex]
    B --> B5[CrewAI Flows]
    
    C --> C1[LLamaIndex + Composio]
    
    D --> D1[Shell Docs]
    D --> D2[Spreadsheet]
    D --> D3[Deep Agents]
```

资料来源：[examples/README.md:1]()

### 通用运行步骤

大多数示例遵循统一的启动流程：

```bash
# 1. 克隆仓库
git clone https://github.com/CopilotKit/CopilotKit.git
cd CopilotKit

# 2. 进入示例目录
cd examples/showcases/spreadsheet

# 3. 安装依赖
pnpm install

# 4. 配置环境变量
cp .env.local.example .env.local
# 编辑 .env.local 填入必要的 API Key

# 5. 启动开发服务器
pnpm dev

# 6. 访问应用
# 打开 http://localhost:3000
```

资料来源：[examples/showcases/spreadsheet/README.md:1]()

### 使用状态机模式

`examples/v1/state-machine` 展示了基于 CopilotKit 的状态机架构：

```mermaid
graph LR
    S1[getContactInfo] --> S2[buildCar]
    S2 --> S3[sellFinancing]
    S3 --> S4[getFinancingInfo]
    S4 --> S5[getPaymentInfo]
    S5 --> S6[confirmOrder]
```

每个阶段都有独立的 Hook 文件：

| 阶段 | Hook 文件 |
|------|-----------|
| 收集客户信息 | `use-stage-get-contact-info.tsx` |
| 配置汽车选项 | `use-stage-build-car.tsx` |
| 展示融资选项 | `use-stage-sell-financing.tsx` |
| 收集融资详情 | `use-stage-get-financing-info.tsx` |
| 处理支付信息 | `use-stage-get-payment-info.tsx` |
| 确认订单 | `use-stage-confirm-order.tsx` |

资料来源：[examples/v1/state-machine/README.md:1]()

### 集成 LangGraph

对于需要复杂代理逻辑的应用，CopilotKit 支持与 LangGraph 深度集成：

```python
from copilotkit import CopilotKitMiddleware

agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-4"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md:1]()

---

## 数据流架构

CopilotKit 采用前后端分离架构，核心数据流如下：

```mermaid
sequenceDiagram
    participant User
    participant UI as 前端 UI
    participant CK as CopilotKit
    participant Agent as AI Agent
    participant Tools
    participant External as 外部服务

    User->>UI: 自然语言输入
    UI->>CK: 发送消息
    CK->>Agent: 转发请求
    Agent->>Tools: 执行工具
    Tools->>External: 调用外部 API
    External-->>Tools: 返回结果
    Tools-->>Agent: 工具执行结果
    Agent->>CK: 返回响应
    CK->>UI: 更新状态
    UI->>User: 显示结果
```

---

## 环境变量配置

### 必填变量

| 变量名 | 说明 | 获取方式 |
|--------|------|----------|
| `OPENAI_API_KEY` | OpenAI API 密钥 | [OpenAI Platform](https://platform.openai.com) |
| `NEXT_PUBLIC_COPILOT_PUBLIC_API_KEY` | Copilot Cloud 公开 API Key | [Copilot Cloud](https://cloud.copilotkit.ai) |

### 可选变量

| 变量名 | 说明 |
|--------|------|
| `COPILOT_CLOUD_PUBLIC_API_KEY` | CopilotKit Cloud 功能 |
| `GOOGLE_MAPS_API_KEY` | 地图服务集成（部分示例需要） |
| `COMPOSIO_API_KEY` | Composio 工具集成 |

资料来源：[examples/canvas/llamaindex-composio/README.md:1]()

---

## 核心概念

### 可读取状态（useCopilotReadable）

将前端应用状态暴露给 AI 引擎：

```tsx
import { useCopilotReadable } from "@copilotkit/react-core";

function Spreadsheet() {
  const data = useRef([["Header", "Value"]]);

  useCopilotReadable({
    name: "spreadsheet data",
    description: "Current spreadsheet content",
    value: data.current,
  });

  // ...
}
```

### 可操作动作（useCopilotAction）

定义 AI 可以执行的操作：

```tsx
import { useCopilotAction } from "@copilotkit/react-core";

useCopilotAction({
  name: "updateCell",
  description: "更新电子表格单元格",
  parameters: [
    {
      name: "cell",
      type: "string",
      required: true,
    },
    {
      name: "value",
      type: "string",
      required: true,
    },
  ],
  handler: async ({ cell, value }) => {
    // 执行更新逻辑
    return { success: true };
  },
});
```

### 工具渲染

自定义工具调用的 UI 渲染：

```tsx
export interface RenderToolCallConfig<Args> {
  name: string;              // 工具名，"*" 表示通配符
  args: z.ZodType<Args>;      // 参数 Zod schema
  component: Type<ToolRenderer<Args>>;
  agentId?: string;           // 可选的 agent 作用域
}
```

资料来源：[packages/angular/README.md:1]()

---

## 常见问题

### 依赖冲突

如果遇到 Python 导入错误：

```bash
cd agent
uv sync
```

如问题持续，删除虚拟环境后重新创建：

```bash
cd agent
rm -rf .venv
uv venv
uv sync
```

### 不同包管理器

所有示例都支持多种包管理器：

| 命令 | npm | yarn | pnpm |
|------|-----|------|------|
| 安装依赖 | `npm install` | `yarn install` | `pnpm install` |
| 启动开发 | `npm run dev` | `yarn dev` | `pnpm dev` |

资料来源：[examples/v1/form-filling/README.md:1]()

---

## 下一步

- 查看 [官方文档](https://docs.copilotkit.ai/getting-started/quickstart-chatbot) 获取完整功能说明
- 探索 [示例项目](https://github.com/CopilotKit/CopilotKit/tree/main/examples) 寻找灵感
- 加入 [Discord 社区](https://discord.gg/6dffbvGU3D) 获取帮助
- 关注 [X (Twitter)](https://x.com/copilotkit) 和 [LinkedIn](https://www.linkedin.com/company/copilotkit/) 了解最新动态

---

<a id='project-structure'></a>

## 项目结构

### 相关页面

相关主题：[系统架构](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/README.md)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [examples/showcases/presentation/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/presentation/README.md)
- [examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)
- [examples/showcases/adk-dashboard/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/adk-dashboard/README.md)
- [examples/integrations/langgraph-fastapi/package.json](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/package.json)
- [examples/integrations/ms-agent-framework-python/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/ms-agent-framework-python/README.md)
- [showcase/integrations/langgraph-typescript/src/app/demos/gen-ui-tool-based/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/langgraph-typescript/src/app/demos/gen-ui-tool-based/README.md)
</details>

# 项目结构

CopilotKit 是一个开源的 AI 助手和代理集成框架，旨在帮助开发者快速将深度集成的 AI 功能嵌入到应用程序中。项目采用 Monorepo 架构，组织清晰，包含核心运行时包、示例项目和展示应用。

## 目录架构概览

```
CopilotKit/
├── packages/              # 核心运行时包
├── examples/              # 示例项目集合
├── showcase/              # 集成展示应用
├── README.md              # 项目主文档
├── CONTRIBUTING.md        # 贡献指南
└── LICENSE                # MIT 许可证
```

## 核心包（packages）

核心包提供了 CopilotKit 的基础功能，包括运行时客户端、React 组件和 API 接口。

| 包名称 | 说明 |
|--------|------|
| `runtime-client-gql` | GraphQL 运行时客户端，负责与后端代理通信 |
| `react-textarea` | React 文本域组件，提供 AI 辅助输入功能 |
| 其他核心包 | 提供状态管理、上下文共享、UI 组件等 |

核心包的特点包括：

- **分钟级集成**：通过 CLI 快速启动项目
- **框架无关**：支持 React、Next.js、AGUI 等多种框架
- **生产级 UI**：提供可定制的组件或无头 UI
- **内置安全**：包含提示注入保护机制

资料来源：[packages/runtime-client-gql/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime-client-gql/README.md)

## 示例项目（examples）

`examples` 目录包含 47 个独立演示项目，展示 CopilotKit 与各种代理框架和应用的集成方式。每个示例都是自包含的项目，需要单独克隆和配置。

```bash
GIT_LFS_SKIP_SMUDGE=1 git clone <repo-url>
cd examples/<category>/<name>
# 按照示例的 README 进行设置
```

> **注意**：`v1/` 和 `v2/` 目录是早期版本的遗留工作区示例，不属于当前的统一演示集。

资料来源：[examples/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/README.md)

### 集成示例（integrations）

集成示例展示了 CopilotKit 与主流代理框架的集成方式，目前共有 17 个框架集成入门模板。

| 示例项目 | 说明 |
|----------|------|
| `langgraph-python` | 使用 LangGraph (Python) 和 CopilotKit 构建 AI 代理 |
| `langgraph-js` | 使用 LangGraph (JS) 的 Turborepo 单仓库模板 |
| `langgraph-fastapi` | 使用 LangGraph + FastAPI + Poetry 的模板 |
| `mastra` | 使用 Mastra 和 CopilotKit 构建代理 |
| `crewai-flows` | 使用 CrewAI Flows (uv-based) 的模板 |
| `llamaindex` | LlamaIndex 投资分析师代理模板 |
| `ms-agent-framework-python` | Microsoft Agent Framework (Python) 集成 |

集成项目通常包含以下目录结构：

```
<integration-name>/
├── frontend/              # Next.js 前端应用
├── agent/                # 代理服务器代码
├── package.json          # 项目依赖配置
└── README.md             # 设置说明
```

资料来源：[examples/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/README.md)

### 展示应用（showcases）

展示应用提供了功能完整的 CopilotKit 集成示例，涵盖从聊天界面到复杂业务应用的多种场景。

#### Deep Agents

深度代理展示应用演示了如何构建支持研究工具的 AI 代理系统。

**前端架构**：

```typescript
// 定义工具卡片组件
const researchToolCard = frame(({ props }) => {
  return <ToolCard {...props} />;
});
```

**后端代理配置**：

```python
agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-5.2"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

#### Presentation

演示文稿展示应用演示了如何将研究代理集成到幻灯片应用中。

#### Spreadsheet

电子表格展示应用允许用户通过自然语言请求构建预算表格。

**关键代码位置**：

- `/api/copilotkit/route.ts` - 研究代理 API 路由
- `/api/copilotkit/tavily.ts` - Tavily 研究 API 集成
- `useCopilotReadable` - 前端上下文共享钩子
- `updateSpreadsheet`、`appendToSpreadsheet`、`createSpreadsheet` - 表格操作钩子

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

#### ADK Dashboard

Google Agent Development Kit (ADK) 仪表板展示应用。

**目录结构**：

```
adk-dashboard/
├── src/app/              # Next.js 应用代码
├── agent/                # ADK 代理代码
├── package.json
└── .env.local
```

**环境变量配置**：

| 变量名 | 说明 |
|--------|------|
| `GOOGLE_API_KEY` | Google API 凭证 |
| `OPENAI_API_KEY` | OpenAI API 凭证 |

资料来源：[examples/showcases/adk-dashboard/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/adk-dashboard/README.md)

## 展示目录（showcase）

`showcase` 目录包含与最新代理框架集成的演示应用，采用统一的项目结构。

### 通用项目结构

```
showcase/integrations/<framework>/
├── src/
│   └── app/
│       ├── demos/
│       │   └── gen-ui-tool-based/
│       │       └── README.md    # 演示说明
│       ├── page.tsx            # 主页面
│       └── layout.tsx          # 布局组件
├── package.json
├── next.config.js
└── tailwind.config.ts
```

### 关键钩子

| 钩子名称 | 功能 |
|----------|------|
| `useAgent` | 原始代理句柄，提供 `messages`、`isRunning`、`addMessage` 等 |
| `useCopilotKit` | 暴露 `connectAgent`、`runAgent`、`stopAgent` 方法 |

资料来源：[showcase/integrations/langgraph-typescript/src/app/demos/gen-ui-tool-based/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/langgraph-typescript/src/app/demos/gen-ui-tool-based/README.md)

### 无头聊天（Headless Chat）

无头聊天演示展示了如何使用低级钩子从零构建完整的聊天 UI，而不依赖预构建组件。

**核心文件**：

| 文件 | 说明 |
|------|------|
| `page.tsx` | 提供者、代理连接、发送/停止处理器、工具调用渲染器注册 |
| `message-list.tsx` | 可滚动消息区域、用户/助手气泡、输入指示器 |
| `use-rendered-messages.tsx` | 按角色分发消息渲染 |

资料来源：[showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md)

## 可用脚本

### 集成项目脚本

| 脚本 | 说明 |
|------|------|
| `dev` | 启动 UI + 代理服务器（默认） |
| `dev:debug` | 启用调试日志启动 |
| `dev:ui` | 仅启动 Next.js UI 服务器 |
| `dev:agent` | 仅启动代理服务器 |
| `build` | 生产环境构建 |
| `start` | 启动生产服务器 |
| `lint` | 运行 ESLint 代码检查 |
| `install:agent` | 安装代理 Python 依赖 |

资料来源：[examples/integrations/ms-agent-framework-python/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/ms-agent-framework-python/README.md)

## 架构流程图

### 应用架构

```mermaid
graph TD
    A[用户界面] --> B[CopilotKit 前端组件]
    B --> C[useCopilotKit 钩子]
    C --> D[运行时客户端]
    D --> E[代理中间件]
    E --> F[AI 代理框架]
    F --> G[外部 API / 工具]
    G --> F
    F --> E
    E --> D
    D --> C
    C --> B
    B --> A
```

### 代理通信流程

```mermaid
sequenceDiagram
    participant U as 用户
    participant F as 前端组件
    participant R as 运行时客户端
    participant M as 代理中间件
    participant A as AI 代理
    
    U->>F: 发送消息
    F->>R: addMessage
    R->>M: 转发请求
    M->>A: 调用代理
    A->>A: 处理任务
    A->>G: 使用工具
    G-->>A: 返回结果
    A-->>M: 返回响应
    M-->>R: 格式化结果
    R-->>F: 更新状态
    F-->>U: 显示结果
```

## 技术栈概览

| 层级 | 技术选型 |
|------|----------|
| 前端框架 | React、Next.js |
| 样式方案 | Tailwind CSS |
| 代理框架 | LangGraph、Mastra、CrewAI、LlamaIndex、ADK 等 |
| 后端服务 | FastAPI、Python 运行时 |
| 部署方式 | Vercel、容器化 |

## 环境配置

### 常见环境变量

| 变量 | 说明 | 必需 |
|------|------|------|
| `OPENAI_API_KEY` | OpenAI API 密钥 | 是 |
| `GOOGLE_API_KEY` | Google API 密钥 | ADK 示例必需 |
| `TAVILY_API_KEY` | Tavily 研究 API | 研究代理示例必需 |

### 端口配置

| 服务 | 默认端口 |
|------|----------|
| Next.js UI | 3000 |
| Python 代理 | 8000 |
| FastAPI 服务 | 8000 |

## 贡献指南

CopilotKit 欢迎各种形式的贡献，包括代码、文档、演示应用创建或社区推广。

- **代码贡献**：参阅 [CONTRIBUTING.md](./CONTRIBUTING.md)
- **文档贡献**：参阅 [文档贡献指南](https://docs.copilotkit.ai/contributing/docs-contributions)
- **社区支持**：[Discord 服务器](https://discord.gg/6dffbvGU3D)

## 许可证

本项目源码采用 MIT 许可证开源。

资料来源：[README.md - License](https://github.com/CopilotKit/CopilotKit/blob/main/LICENSE)

---

<a id='system-architecture'></a>

## 系统架构

### 相关页面

相关主题：[CopilotRuntime 后端运行时](#copilot-runtime), [通信协议](#protocols)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)
- [packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)
- [examples/showcases/presentation/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/presentation/README.md)
</details>

# 系统架构

## 概述

CopilotKit 是一个用于构建 AI 原生应用的框架，提供了前端组件、运行时引擎和工具集成能力。其核心架构采用分层设计，涵盖前端 UI 组件层、运行时客户端层、后端运行时层以及多种框架集成适配层。

## 核心架构分层

### 技术栈概览

| 层级 | 技术范围 | 主要职责 |
|------|----------|----------|
| 前端组件层 | React、Vue、Angular | 提供可嵌入的 Copilot 聊天界面和交互组件 |
| 运行时客户端层 | @copilotkit/react、@copilotkit/vue、@copilotkit/angular | 管理状态、消息传递和工具调用 |
| 运行时引擎层 | @copilotkit/runtime | 处理 LLM 请求、工具执行和上下文管理 |
| 框架集成层 | LangGraph、Mastra、CrewAI、LlamaIndex | 与主流 AI 代理框架集成 |

## 运行时架构

### CopilotRuntime 核心配置

`CopilotRuntime` 是后端运行时的核心类，负责处理来自前端的请求并与 LLM 进行交互。

```typescript
// 资料来源：packages/runtime/src/lib/runtime/copilot-runtime.ts
const copilotRuntime = new CopilotRuntime({
  runtimeUrl: "/api/copilotkit",
  publicApiKey: process.env.COPILOT_CLOUD_PUBLIC_API_KEY,
});
```

### 运行时配置参数

| 参数 | 类型 | 说明 |
|------|------|------|
| `runtimeUrl` | `string` | CopilotKit 运行时端点地址 |
| `publicApiKey` | `string` | Copilot Cloud 公共 API 密钥 (`ck_pub_...`) |
| `headers` | `Record<string, string>` | 默认请求头 |
| `licenseKey` | `string` | 许可证密钥 |
| `properties` | `Record<string, unknown>` | 转发到 agent 运行的自定义属性 |
| `agents` | `Record<string, AbstractAgent>` | 本地浏览器内代理 |
| `tools` | `ClientTool[]` | 工具定义 |
| `renderToolCalls` | `RenderToolCallConfig[]` | 工具调用 UI 渲染配置 |
| `frontendTools` | `FrontendToolConfig[]` | 客户端工具配置 |
| `humanInTheLoop` | `HumanInTheLoopConfig[]` | 需要用户输入的工具 |
| `mcpServers` | `MCPEndpointConfig[]` | MCP 服务器配置 |
| `logging` | `CopilotObservabilityConfig` | 日志和可观测性配置 |

### 可观测性配置

```typescript
// 资料来源：packages/runtime/src/lib/runtime/copilot-runtime.ts
logging: {
  enabled: true,           // 启用日志
  progressive: true,       // 流式日志输出
  logger: {
    logRequest: (data) => langfuse.trace({ name: "LLM Request", input: data }),
    logResponse: (data) => langfuse.trace({ name: "LLM Response", output: data }),
    logError: (errorData) => langfuse.trace({ name: "LLM Error", metadata: errorData }),
  },
}
```

## 前端框架集成

### React 集成

React SDK 提供核心组件和 Hook：

| 组件/Hook | 功能 |
|-----------|------|
| `CopilotKit` | 根组件，配置运行时连接 |
| `CopilotChat` | 聊天界面组件 |
| `useCopilotReadable` | 将应用状态同步到 Copilot 引擎 |
| `useCopilotAction` | 定义可被代理调用的动作 |
| `useCoAgent` | 与代理状态双向同步 |

### Vue 集成

Vue SDK 通过 `CopilotKitProvider` 和 `CopilotChatMessageView` 提供聊天消息渲染能力：

```vue
// 资料来源：packages/vue/README.md
<CopilotKitProvider
  runtime-url="/api/copilotkit"
  :self-managed-agents="{}"
  :on-error="onProviderError"
  :a2ui="{ theme: { mode: 'light' } }"
>
  <slot />
</CopilotKitProvider>
```

### Angular 集成

Angular 通过 `provideCopilotKit` 注入配置：

```typescript
// 资料来源：packages/angular/README.md
export interface CopilotKitConfig {
  runtimeUrl?: string;
  headers?: Record<string, string>;
  licenseKey?: string;
  properties?: Record<string, unknown>;
  agents?: Record<string, AbstractAgent>;
  tools?: ClientTool[];
  renderToolCalls?: RenderToolCallConfig[];
  frontendTools?: FrontendToolConfig[];
  humanInTheLoop?: HumanInTheLoopConfig[];
}
```

## 数据流架构

### 完整数据流

```mermaid
graph TD
    User[用户交互] --> UI[前端 UI 组件]
    UI --> CK[CopilotKit 客户端]
    CK --> Runtime[CopilotRuntime]
    Runtime --> LLM[LLM Provider]
    LLM --> Runtime
    Runtime --> Agent[AI Agent 框架]
    Agent --> Tools[工具执行]
    Tools --> External[外部服务]
    External --> Tools
    Tools --> Agent
    Agent --> Runtime
    Runtime --> CK
    CK --> UI
    UI --> User
    
    subgraph 前端层
        UI
        CK
    end
    
    subgraph 后端层
        Runtime
        LLM
        Agent
        Tools
    end
```

### LlamaIndex + Composio 示例数据流

```mermaid
sequenceDiagram
    participant User as 用户
    participant UI as Canvas UI
    participant CK as CopilotKit
    participant Agent as LlamaIndex Agent
    participant Tools as 工具
    participant Composio as Composio
    participant GSheets as Google Sheets

    User->>UI: 与画布交互
    UI->>CK: 通过 useCoAgent 更新状态
    CK->>Agent: 发送状态 + 消息
    Agent->>Agent: 使用 GPT-4o 处理
    Agent->>Tools: 执行工具
    
    alt Google Sheets 同步
        Agent->>Composio: 执行 sheets_sync_all
        Composio->>GSheets: 更新电子表格
        GSheets-->>Composio: 确认更新
        Composio-->>Agent: 返回状态
    end

    Tools-->>Agent: 返回结果
    Agent->>CK: 返回更新后的状态
    CK->>UI: 同步状态变更
    UI->>User: 显示更新

    Note over Agent: 维护真相来源
    Note over UI,CK: 实时双向同步
    Note over Composio,GSheets: 外部工具集成
```

## 工具系统架构

### 工具类型体系

| 工具类型 | 说明 | 配置方式 |
|----------|------|----------|
| 客户端工具 | 前端执行的工具 | `FrontendToolConfig` |
| 服务端工具 | 后端执行的工具 | `ClientTool` |
| 远程工具 | 由代理运行时处理 | `available: "remote"` |
| 人机交互工具 | 需要用户确认 | `HumanInTheLoopConfig` |

### 工具定义接口

```typescript
// 资料来源：packages/angular/README.md
export interface FrontendToolConfig<Args> {
  name: string;
  description: string;
  parameters: z.ZodType<Args>;
  component?: Type<ToolRenderer<Args>>;
  handler: (args: Args, context: FrontendToolHandlerContext) => Promise<unknown>;
  agentId?: string;
}

export interface RenderToolCallConfig<Args> {
  name: string;              // 工具名称，"*" 表示通配符
  args: z.ZodType<Args>;     // 参数 Zod schema
  component: Type<ToolRenderer<Args>>;
  agentId?: string;          // 可选的代理作用域
}
```

### 工具渲染器

工具调用通过渲染器组件显示：

```typescript
// 资料来源：packages/angular/README.md
export interface ToolRenderer<Args> {
  toolCall: Signal<AngularToolCall<Args>>;
}

export interface HumanInTheLoopToolRenderer<Args> {
  toolCall: Signal<HumanInTheLoopToolCall<Args>>; // 包含 respond(result)
}
```

## 代理架构

### 代理配置

代理通过配置与 CopilotKit 集成：

```python
# 资料来源：examples/showcases/deep-agents/README.md
agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-5.2"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

### 支持的代理框架

| 框架 | 语言 | 集成方式 |
|------|------|----------|
| LangGraph | Python | `CopilotKitMiddleware` |
| LangGraph | JS/TS | Turborepo monorepo |
| Mastra | TypeScript | 原生集成 |
| CrewAI Flows | Python | uv-based 工作流 |
| LlamaIndex | Python | `get_ag_ui_workflow_router` |

## 消息渲染系统

### Vue 消息插槽

```vue
// 资料来源：packages/vue/README.md
<CopilotChatMessageView>
  <template #message-before>
    <!-- 自定义内容 -->
  </template>
  
  <template #assistant-message>
    <CustomAssistantMessage />
  </template>
  
  <template #tool-call-search_docs="{ args, status, result }">
    <SearchDocsToolCall :args="args" :status="status" :result="result" />
  </template>
</CopilotChatMessageView>
```

### 支持的插槽类型

| 消息级插槽 | 工具级插槽 |
|------------|------------|
| `message-before` | `tool-call-<toolName>` |
| `assistant-message` | `tool-call` (后备) |
| `user-message` | |
| `reasoning-message` | |
| `activity-<activityType>` | |
| `activity-message` | |
| `message-after` | |
| `cursor` | |

## MCP 协议集成

### MCP 服务器配置

```typescript
// 资料来源：packages/runtime/src/lib/runtime/copilot-runtime.ts
mcpServers?: MCPEndpointConfig[];
```

MCP（Model Context Protocol）允许连接外部 MCP 兼容服务器，获取其定义的工具：

> **配置说明：** 使用 `experimental_createMCPClient` 函数创建 MCP 客户端实例，支持 `@copilotkit/runtime` 和 `ai` 库。

## 状态管理

### 全局状态同步

```typescript
// 资料来源：examples/v1/state-machine/README.md
// 通过 useCopilotReadable 同步应用状态
useCopilotReadable({
  instructions: "提供当前表单状态",
  getValue: () => ({
    stage: currentStage,
    data: formData,
    progress: calculateProgress(),
  }),
});
```

### 阶段化状态机模式

| 阶段 | 文件位置 | 功能 |
|------|----------|------|
| getContactInfo | `use-stage-get-contact-info.tsx` | 收集客户信息 |
| buildCar | `use-stage-build-car.tsx` | 配置汽车选项 |
| sellFinancing | `use-stage-sell-financing.tsx` | 展示融资方案 |
| getFinancingInfo | `use-stage-get-financing-info.tsx` | 收集融资详情 |
| getPaymentInfo | `use-stage-get-payment-info.tsx` | 处理支付信息 |
| confirmOrder | `use-stage-confirm-order.tsx` | 确认订单 |

## 部署架构

### 典型部署拓扑

```mermaid
graph LR
    subgraph 前端
        NextJS[Next.js 应用]
        ReactApp[React 应用]
    end
    
    subgraph CopilotKit 层
        CKProvider[CopilotKit Provider]
        CKRuntime[运行时服务]
    end
    
    subgraph 代理框架
        LangGraph[LangGraph]
        Mastra[Mastra]
        LlamaIndex[LlamaIndex]
    end
    
    subgraph 外部服务
        OpenAI[OpenAI API]
        Tavily[Tavily 搜索]
        Composio[Composio]
    end
    
    NextJS --> CKProvider
    ReactApp --> CKProvider
    CKProvider --> CKRuntime
    CKRuntime --> LangGraph
    CKRuntime --> Mastra
    CKRuntime --> LlamaIndex
    LangGraph --> OpenAI
    LangGraph --> Tavily
    LlamaIndex --> Composio
    Composio --> ExternalApps[外部应用]
```

### 环境变量配置

| 变量 | 示例 | 用途 |
|------|------|------|
| `COPILOT_CLOUD_PUBLIC_API_KEY` | `ck_pub_...` | CopilotKit Cloud 功能 |
| `OPENAI_API_KEY` | `sk-...` | LLM API 密钥 |
| `COMPOSIO_API_KEY` | `...` | Composio 集成 |
| `TAVILY_API_KEY` | `...` | 在线研究功能 |

## 调试与日志

### Provider 调试配置

```typescript
// 资料来源：packages/vue/README.md
const debug: DebugConfig = { 
  events: true, 
  lifecycle: true,
  verbose: true  // 启用完整事件载荷
};
```

### 调试粒度控制

| 配置项 | 说明 |
|--------|------|
| `events` | 启用事件日志 |
| `lifecycle` | 启用生命周期日志 |
| `verbose` | 输出完整事件载荷 |

### 错误处理

```typescript
// 资料来源：packages/vue/README.md
function onProviderError(event: {
  code: string;
  error: Error;
  context: Record<string, any>;
}) {
  console.error(
    "CopilotKit provider error",
    event.code,
    event.context,
    event.error,
  );
}
```

## 相关文档

- [快速开始指南](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)
- [前端工具开发](https://docs.copilotkit.ai/core-concepts/tools)
- [代理开发](https://docs.copilotkit.ai/core-concepts/agents)
- [深度代理文档](https://docs.copilotkit.ai/integrations/langgraph/deep-agents)

---

<a id='protocols'></a>

## 通信协议

### 相关页面

相关主题：[系统架构](#system-architecture), [生成式 UI](#generative-ui)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/integrations/a2a-middleware/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
</details>

# 通信协议

CopilotKit 是一个多代理协作框架，支持多种通信协议以实现不同组件、代理和外部服务之间的高效交互。本文档详细介绍 CopilotKit 中的核心通信协议架构，包括 A2A 协议、AG-UI 协议、MCP 协议以及内部消息转换机制。

## 协议概述

CopilotKit 采用分层协议架构，支持从前端 UI 到后端代理、从单个应用到外部服务的全链路通信。

### 协议层次架构

```mermaid
graph TD
    A[前端 UI 层] --> B[AG-UI 协议]
    B --> C[CopilotKit Runtime]
    C --> D[A2A 协议]
    D --> E[多代理协调层]
    C --> F[MCP 协议]
    F --> G[外部 MCP 服务器]
    E --> H[LangGraph Agents]
    E --> I[其他 Agent 框架]
```

CopilotKit 的协议支持包括：

| 协议名称 | 全称 | 用途 | 数据格式 |
|---------|------|------|----------|
| AG-UI | Agent-User Interface | AI 代理与应用 UI 的双向通信 | JSON/GraphQL |
| A2A | Agent-to-Agent | 多代理之间的任务协作 | JSON over HTTP |
| MCP | Model Context Protocol | 与外部工具和服务的集成 | JSON-RPC |
| GraphQL | Graph Query Language | 运行时内部消息传递 | GraphQL |

资料来源：[examples/integrations/a2a-middleware/README.md]()

## AG-UI 协议

AG-UI（Agent-User Interface）协议是 CopilotKit 的核心协议，定义了 AI 代理与应用界面之间的标准通信方式。该协议支持生成式 UI 渲染、实时状态同步和工具调用等功能。

### 数据流架构

```mermaid
sequenceDiagram
    participant User
    participant UI as Canvas UI
    participant CK as CopilotKit
    participant Agent as LlamaIndex Agent
    participant Tools
    participant Composio
    participant GSheets as Google Sheets

    User->>UI: Interact with canvas
    UI->>CK: Update state via useCoAgent
    CK->>Agent: Send state + message
    Agent->>Agent: Process with GPT-4o
    Agent->>Tools: Execute tools

    alt Google Sheets Sync
        Agent->>Composio: Execute sheets_sync_all
        Composio->>GSheets: Update spreadsheet
        GSheets-->>Composio: Confirm update
        Composio-->>Agent: Return status
    end

    Tools-->>Agent: Return results
    Agent->>CK: Return updated state
    CK->>UI: Sync state changes
    UI->>User: Display updates
```

### 消息转换机制

CopilotKit Runtime 内部使用 `aguiToGQL` 函数将 AG-UI 协议消息转换为 GraphQL 格式，以支持统一的内部消息处理：

```typescript
import { aguiToGQL } from "../../graphql/message-conversion/agui-to-gql";
```

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:19]()

## A2A 协议

A2A（Agent-to-Agent）协议是 CopilotKit 用于多代理协作的通信标准。通过 A2A 中间件，CopilotKit 可以与基于不同框架构建的专门代理进行通信。

### 架构设计

```mermaid
graph LR
    A[Next.js UI<br/>CopilotKit] -->|AG-UI 协议| B[A2A Middleware]
    B -->|A2A 协议| C[Research Agent<br/>LangGraph]
    B -->|A2A 协议| D[Analysis Agent<br/>Mastra]
    B -->|A2A 协议| E[Custom Agent<br/>任意框架]
```

### A2A 中间件配置

A2A 中间件通过 `A2AMiddlewareAgent` 类实现，支持配置多个代理端点：

```typescript
import { A2AMiddlewareAgent } from "@copilotkit/runtime";

const a2aMiddlewareAgent = new A2AMiddlewareAgent({
  agentUrls: [
    researchAgentUrl,
    analysisAgentUrl,
    newAgentUrl,
  ],
});
```

资料来源：[examples/integrations/a2a-middleware/README.md]()

### 代理注册流程

添加新代理到 A2A 中间件的完整流程：

| 步骤 | 操作 | 位置 |
|------|------|------|
| 1 | 在指定端口运行代理服务 | `agents/new_agent.py` |
| 2 | 注册代理 URL 到中间件 | `app/api/copilotkit/route.ts` |
| 3 | 添加开发脚本到 package.json | `package.json` |
| 4 | 更新并发运行命令 | `concurrently` 配置 |

### 代理通信示例

代理通过标准化的消息格式进行通信：

```json
{
  "agentId": "research-agent",
  "capabilities": ["web-search", "content-analysis"],
  "skills": ["research", "fact-checking"],
  "message": {
    "type": "task",
    "content": "Research AI trends in 2024"
  }
}
```

## MCP 协议

MCP（Model Context Protocol）协议用于连接 CopilotKit 与外部 MCP 兼容服务器，使代理能够调用远程定义的工具。

### MCP 配置选项

CopilotKit Runtime 支持通过 `mcpServers` 配置项连接外部 MCP 服务器：

```typescript
const copilotKit = new CopilotRuntime({
  mcpServers: [
    {
      url: "https://mcp-server.example.com",
      name: "external-tools",
    },
  ],
  experimental_createMCPClient: async (endpoint) => {
    // 创建 MCP 客户端实例
  },
});
```

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:89-110]()

### MCP 端点配置

| 参数名 | 类型 | 说明 |
|--------|------|------|
| `url` | string | MCP 服务器地址 |
| `name` | string | 服务器标识名称 |
| `headers` | Record<string, string> | 认证和自定义请求头 |

## 生成式 UI 协议

生成式 UI（Generative UI）是 CopilotKit 的独特能力，允许代理动态生成用户界面组件。

### 工具调用渲染

通过 `useCopilotAction` 钩子注册工具调用的 UI 渲染：

```tsx
import { useCopilotAction } from "@copilotkit/core";

useCopilotAction({
  name: "hello_world",
  description: "Say hello to the user",
  available: "remote",
  parameters: [
    {
      name: "name",
      type: "string",
      required: true,
      description: "The name to greet",
    },
  ],
  handler: ({ name }) => {
    return `Hello, ${name}!`;
  },
});
```

### 前端工具与后端工具

| 工具类型 | 定义位置 | 调用方式 | 示例 |
|----------|----------|----------|------|
| 后端工具 | Python/LlamaIndex | 通过 A2A 执行 | `research()`, `analyze()` |
| 前端工具 | TypeScript/React | 浏览器端处理 | `highlightText()`, `showCard()` |

资料来源：[examples/canvas/llamaindex-composio/README.md]()

## LangGraph 集成协议

CopilotKit 通过中间件模式与 LangGraph 深度集成，支持复杂的多代理工作流。

### 中间件集成方式

```python
from copilotkit import CopilotKitMiddleware

agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-5.2"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md]()

### 状态同步协议

LangGraph 代理通过 CopilotKit 运行时保持与应用状态的实时双向同步：

```mermaid
graph LR
    A[应用状态] <-->|useCoAgent| B[CopilotKit Runtime]
    B <-->|AG-UI| C[LangGraph Agent]
    C <-->|MCP| D[外部工具]
```

## 传输层配置

### 运行时传输方式

CopilotKit 支持多种传输层配置：

| 传输方式 | 描述 | 适用场景 |
|----------|------|----------|
| REST | 标准 HTTP 请求响应 | 简单同步调用 |
| Streamable | 流式传输 | 实时生成内容 |
| Single | 单次往返 | 轻量级集成 |

### 头信息配置

运行时支持自定义 HTTP 头，用于认证和元数据传递：

```typescript
const copilotKit = new CopilotRuntime({
  runtimeUrl: "/api/copilotkit",
  headers: {
    "Authorization": "Bearer token",
    "X-Custom-Header": "value",
  },
});
```

## 协议安全考虑

### 公共 API 密钥

使用 Copilot Cloud 服务时需要配置公钥：

```tsx
<CopilotKit publicApiKey="ck_pub_..." />
```

### 头部注入防护

CopilotKit 内置提示注入防护机制，所有外部输入通过协议层时都会经过安全验证。

## 相关资源

- [AG-UI 协议文档](https://docs.ag-ui.com)
- [A2A 协议规范](https://a2a-protocol.org)
- [LangGraph 文档](https://langchain-ai.github.io/langgraph/)
- [CopilotKit 文档](https://docs.copilotkit.ai)

---

<a id='chat-ui-components'></a>

## Chat UI 组件

### 相关页面

相关主题：[React Hooks API](#react-hooks), [人在回路 (Human-in-the-Loop)](#human-in-the-loop)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/react-ui/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-ui/README.md)
- [showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md)
- [showcase/integrations/ms-agent-python/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-python/src/app/demos/headless-complete/README.md)
- [packages/angular/src/lib/components/chat/copilot-chat-input.types.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/src/lib/components/chat/copilot-chat-input.types.ts)
- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
</details>

# Chat UI 组件

## 概述

CopilotKit 的 Chat UI 组件是一套用于构建 AI 对话界面的 React/Vue/Angular 组件库。这些组件提供了开箱即用的对话体验，包括消息展示、输入处理、工具调用渲染等功能，同时支持高度定制以满足不同应用场景的需求。

Chat UI 组件的主要特点包括：

- **开箱即用的 UI 组件**：提供完整的聊天界面实现，无需从零开始构建
- **生成式 UI 支持**：支持 AI 动态生成的用户界面组件
- **工具调用渲染**：自动渲染代理调用的工具及其结果
- **多框架支持**：提供 React、Vue 和 Angular 的实现
- **可组合性**：所有组件都可以独立使用或组合使用

资料来源：[packages/react-ui/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-ui/README.md)

## 组件架构

CopilotKit 的 Chat UI 采用分层架构，从底层到顶层依次为：

```mermaid
graph TD
    A[应用层] --> B[Chat UI 组件层]
    B --> C[React Core Hooks]
    C --> D[Runtime Client]
    D --> E[后端 Agent]
    
    B1[CopilotChat] --> B2[CopilotChatMessageView]
    B2 --> B3[CopilotChatInput]
    B3 --> B4[useAgent Hook]
    
    F[Headless 模式] --> B4
```

### 核心组件层级

| 层级 | 组件 | 说明 |
|------|------|------|
| UI 层 | CopilotChat / CopilotPopup / CopilotSidebar | 完整聊天界面组件 |
| 消息层 | CopilotChatMessageView | 消息展示与渲染 |
| 输入层 | CopilotChatInput | 文本输入与控制 |
| 钩子层 | useAgent / useCopilotKit | 核心状态管理 |

资料来源：[showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md)

## 主要组件类型

### CopilotChat

完整的聊天界面组件，包含消息列表和输入框。这是构建标准聊天体验的主要组件。

**功能特性：**

- 内置消息列表，支持滚动和自动滚动到最新消息
- 集成的文本输入区域
- 打字指示器显示
- 工具调用渲染区域

### CopilotPopup

弹出式对话窗口组件，适用于需要临时呼出 AI 助手的场景。

**典型使用场景：**

- 浮动助手按钮触发
- 模态框式对话
- 侧边栏集成

### CopilotSidebar

侧边栏形式的对话组件，适合长时间对话或需要边浏览边对话的场景。

资料来源：[packages/react-ui/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-ui/README.md)

## Headless 模式

Headless 模式允许开发者完全从底层钩子构建自定义的聊天界面，而不依赖预建的 UI 组件。这是展示组件高度可组合性的最佳实践。

### 核心钩子

```mermaid
graph LR
    A[useAgent] --> B[返回 messages]
    A --> C[返回 isRunning]
    A --> D[返回 addMessage]
    
    E[useCopilotKit] --> F[connectAgent]
    E --> G[runAgent]
    E --> H[stopAgent]
    
    I[useRenderToolCall] --> J[渲染工具调用结果]
```

#### useAgent

提供原生的代理句柄，访问对话状态和操作：

```tsx
const agent = useAgent({ agentId, threadId });

// 可访问的属性
agent.messages      // 消息列表
agent.isRunning     // 运行状态
agent.addMessage()  // 添加消息方法
```

#### useCopilotKit

暴露运行时连接方法，用于驱动代理执行：

```tsx
const { connectAgent, runAgent, stopAgent } = useCopilotKit();

// 连接代理
connectAgent({ agentId });

// 运行代理
runAgent({ agentId, message });

// 停止执行
stopAgent();
```

#### useRenderToolCall

将工具调用转换为渲染的 React 节点：

```tsx
const renderToolCall = useRenderToolCall();

const renderedNode = renderToolCall(toolCallEntry);
```

资料来源：[showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md)

### Headless 实现示例

一个完整的 Headless 聊天实现通常包含以下文件结构：

```
page.tsx          # 提供者、代理连接、事件处理
message-list.tsx  # 消息容器、用户/助手消息气泡
use-rendered-messages.tsx  # 消息角色分发、渲染逻辑
```

**文件职责：**

| 文件 | 职责 |
|------|------|
| page.tsx | Provider 配置、agent 连接、send/stop 处理器、工具注册、输入栏 |
| message-list.tsx | 滚动消息区域、用户/助手气泡、输入指示器 |
| use-rendered-messages.tsx | 消息角色分发、工具调用渲染、reasoning 渲染 |

资料来源：[showcase/integrations/ms-agent-python/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-python/src/app/demos/headless-complete/README.md)

## 消息渲染系统

### 消息类型

CopilotKit 支持多种消息类型的渲染：

| 消息类型 | 说明 | 渲染方式 |
|----------|------|----------|
| user | 用户消息 | 用户消息气泡 |
| assistant | 助手文本消息 | 助手消息气泡 |
| toolCall | 工具调用 | 工具卡片/组件 |
| reasoning | 推理过程 | 推理折叠区域 |
| activity | 活动消息 | 活动指示器 |

### 工具调用渲染

工具调用渲染是 CopilotKit 的核心功能之一，支持后端工具和前端工具两种模式：

```mermaid
sequenceDiagram
    participant User
    participant UI as Chat UI
    participant Agent as Agent Runtime
    participant Backend as Backend Tools
    participant Frontend as Frontend Tools

    User->>UI: 发送消息
    UI->>Agent: 转发请求
    Agent->>Backend: 调用后端工具
    Backend-->>Agent: 返回结果
    Agent->>Frontend: 前端工具调用
    Frontend-->>Agent: 返回结果
    Agent-->>UI: 返回消息 + 工具调用
    UI->>UI: 渲染工具结果
```

#### 前端工具注册

使用 `useCopilotAction` 注册前端工具：

```tsx
useCopilotAction({
  name: "show_card",
  description: "显示卡片信息",
  parameters: [
    {
      name: "title",
      type: "string",
      required: true,
    },
    {
      name: "body",
      type: "string",
      required: true,
    },
  ],
  handler: ({ title, body }) => {
    // 处理工具调用
    return "Card displayed";
  },
});
```

#### 后端工具渲染

后端工具通过 `useRenderToolCall` 进行渲染：

```tsx
useRenderToolCall({
  toolCall: toolCallEntry,
  render: (props) => <ToolCard {...props} />,
});
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

## 聊天输入配置

### Angular 组件类型定义

在 Angular 实现中，聊天输入组件提供了丰富的配置选项：

```typescript
interface CopilotChatInputConfig {
  mode?: CopilotChatInputMode;
  toolsMenu?: (ToolsMenuItem | "-")[];
  autoFocus?: boolean;
  additionalToolbarItems?: TemplateRef<any>;
  value?: string;
  class?: string;
}
```

### 输入插槽配置

```typescript
interface CopilotChatInputSlots {
  textArea?: Type<any> | TemplateRef<any>;
  sendButton?: Type<any> | TemplateRef<any>;
  startTranscribeButton?: Type<any> | TemplateRef<any>;
  cancelTranscribeButton?: Type<any> | TemplateRef<any>;
  finishTranscribeButton?: Type<any> | TemplateRef<any>;
  addFileButton?: Type<any> | TemplateRef<any>;
  toolsButton?: Type<any> | TemplateRef<any>;
  toolbar?: Type<any> | TemplateRef<any>;
  audioRecorder?: Type<any> | TemplateRef<any>;
}
```

### 输出事件

```typescript
interface CopilotChatInputOutputs {
  submitMessage: (value: string) => void;
  startTranscribe: () => void;
  cancelTranscribe: () => void;
  finishTranscribe: () => void;
  addFile: () => void;
  changeValue: (value: string) => void;
}
```

资料来源：[packages/angular/src/lib/components/chat/copilot-chat-input.types.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/src/lib/components/chat/copilot-chat-input.types.ts)

## 组件集成流程

### 标准集成模式

```mermaid
graph TD
    A[应用入口] --> B[CopilotKitProvider]
    B --> C[CopilotChat 组件]
    
    D[配置运行时] --> B
    D1[runtimeUrl] --> D
    D2[agents] --> D
    
    C --> E[消息列表]
    C --> F[输入区域]
    
    E --> G[useRenderedMessages]
    F --> H[submitMessage]
```

### Vue 集成示例

```vue
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue";

function onProviderError(event: {
  error: Error;
  code: KitCoreErrorCode;
  context: Record<string, any>;
}) {
  console.error(
    "CopilotKit provider error",
    event.code,
    event.context,
    event.error,
  );
}
</script>

<template>
  <CopilotKitProvider
    runtime-url="/api/copilotkit"
    :self-managed-agents="{}"
    :on-error="onProviderError"
    :a2ui="{ theme: { mode: 'light' } }"
  >
    <slot />
  </CopilotKitProvider>
</template>
```

**配置说明：**

| 配置项 | 说明 |
|--------|------|
| runtimeUrl | CopilotKit 运行时端点 |
| selfManagedAgents | 自管理代理配置 |
| onError | 错误处理回调 |
| a2ui.theme | 生成式 UI 主题配置 |
| debug | 调试日志配置 |

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

## 生成式 UI (a2ui)

生成式 UI 是 CopilotKit 的核心特性，允许 AI 动态生成用户界面组件。

### a2ui 配置

```typescript
a2ui: {
  theme: {
    mode: 'light' | 'dark' | 'system'
  },
  surfaces: ['inline', 'sheet', 'modal']
}
```

### 渲染流程

```mermaid
graph LR
    A[Agent 响应] --> B{包含 a2ui?}
    B -->|是| C[前端渲染 a2ui 组件]
    B -->|否| D[标准消息渲染]
    
    C --> E[主题应用]
    E --> F[显示在指定 surface]
```

### 自定义渲染器

可以注册自定义的组件渲染器来处理特定工具调用：

```tsx
useRenderTool({
  toolName: "weather",
  render: (props) => <WeatherCard {...props} />,
});
```

当没有为工具注册自定义渲染器时，系统会使用 `useDefaultRenderTool` 作为后备渲染器。

资料来源：[showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/showcase/integrations/ms-agent-dotnet/src/app/demos/headless-complete/README.md)

## 调试与日志

### Provider 调试配置

```typescript
const debug: DebugConfig = {
  events: true,     // 事件日志
  lifecycle: true,  // 生命周期日志
  verbose: false    // 详细载荷（可选）
};
```

### 日志级别

| 级别 | 说明 |
|------|------|
| true/false | 启用/禁用基本事件和生命周期日志 |
| events | 事件日志 |
| lifecycle | 生命周期日志 |
| verbose | 包含完整载荷的详细日志 |

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

## 最佳实践

### 1. 组件选择

- **标准场景**：使用 `CopilotChat` 获得完整功能
- **临时助手**：使用 `CopilotPopup` 减少界面占用
- **边浏览边对话**：使用 `CopilotSidebar`

### 2. 自定义 UI

- 需要完全控制 UI 时，选择 Headless 模式
- 利用 `useAgent` 和 `useRenderToolCall` 构建自定义界面
- 复用 CopilotKit 的工具渲染机制

### 3. 性能优化

- 使用消息虚拟化处理长对话
- 懒加载工具渲染器
- 合理使用 `isRunning` 状态控制 UI 更新

### 4. 错误处理

- 配置 Provider 级别的 `onError` 处理器
- 在组件级别添加 `CopilotChat.onError` 处理
- 实现工具调用的错误边界

## 相关资源

- [CopilotKit 文档](https://docs.copilotkit.ai/getting-started/quickstart-chatbot)
- [CopilotKit GitHub 仓库](https://github.com/CopilotKit/CopilotKit)
- [Discord 社区](https://discord.gg/6dffbvGU3D)

---

<a id='react-hooks'></a>

## React Hooks API

### 相关页面

相关主题：[Chat UI 组件](#chat-ui-components)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/react-native/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-native/README.md)
- [packages/react-core/package.json](https://github.com/CopilotKit/CopilotKit/blob/main/packages/react-core/package.json)
- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [examples/v1/form-filling/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/form-filling/README.md)
- [examples/v1/chat-with-your-data/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/chat-with-your-data/README.md)
- [examples/showcases/presentation/package.json](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/presentation/package.json)
- [examples/integrations/langgraph-python-threads/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-python-threads/README.md)
</details>

# React Hooks API

## 概述

React Hooks API 是 CopilotKit 为 React 应用提供的核心编程接口，通过一系列 Hook 函数实现前端与 AI Copilot 的交互能力。这些 Hooks 封装了 CopilotKit 的状态管理、事件通信和 UI 控制逻辑，使开发者能够在 React 组件中便捷地接入 AI 功能。

CopilotKit 的 Hooks API 主要分布在两个包中：

| 包名 | 说明 | 导出内容 |
|------|------|---------|
| `@copilotkit/react-core` | 核心 Hooks，包含状态管理和交互逻辑 | `useAgent`、`useCopilotKit`、`useHumanInTheLoop`、`useThreads` 等 |
| `@copilotkit/react-native` | React Native 专用绑定，重导出 react-core 的 Hooks | 与 react-core 相同的 Hooks 集合 |

资料来源：[packages/react-native/README.md:1-10]()

## 核心 Hooks

### useCopilotKit

`useCopilotKit` 是获取 CopilotKit 上下文的根级 Hook，返回与 CopilotKit 实例交互所需的属性和方法。

**基本用法：**

```tsx
import { useCopilotKit } from "@copilotkit/react-core";

function ChatScreen() {
  const { 
    copilotKit, 
    threadId, 
    messages, 
    inputContent, 
    setInputContent,
    isGenerating 
  } = useCopilotKit();
  
  // 执行业务逻辑
}
```

**典型应用场景：**

在表单填写示例中，开发者使用 `useCopilotKit` 获取 CopilotKit 实例以实现表单状态同步：

```tsx
import { useCopilotKit } from "@copilotkit/react-core";

export default function App() {
  return (
    <CopilotKitProvider runtimeUrl="https://your-server/api/copilotkit">
      <ChatScreen />
    </CopilotKitProvider>
  );
}
```

资料来源：[packages/react-native/README.md:20-35]()

### useAgent

`useAgent` Hook 用于与 Copilot Agent 进行交互，支持获取代理状态、执行操作和处理事件。

**导入来源：**

```tsx
// 从 @copilotkit/react-core 导入
import { useAgent } from "@copilotkit/react-core";

// 或从 @copilotkit/react-native 导入（重导出）
import { useAgent } from "@copilotkit/react-native";
```

**API 导出配置：**

`@copilotkit/react-core` 包的 exports 配置支持两种导入方式：

```json
{
  "exports": {
    ".": {
      "import": "./dist/index.mjs",
      "require": "./dist/index.cjs"
    },
    "./v2": {
      "import": "./dist/v2/index.mjs",
      "require": "./dist/v2/index.cjs"
    }
  }
}
```

资料来源：[packages/react-core/package.json:20-32]()

### useHumanInTheLoop

`useHumanInTheLoop` Hook 实现人机协作模式，允许 AI 在执行关键操作前等待用户确认。

**功能特性：**

- 中断 AI 执行流程
- 向用户展示操作预览
- 等待用户确认或取消
- 恢复或放弃操作执行

**使用示例：**

```tsx
import { useHumanInTheLoop } from "@copilotkit/react-core";

function DisambiguationPrompt() {
  const { 
    interrupt, 
    resume, 
    discard 
  } = useHumanInTheLoop();
  
  // 处理用户交互逻辑
}
```

资料来源：[packages/react-native/README.md:8]()

### useThreads

`useThreads` Hook 提供会话线程管理能力，支持创建、切换和持久化对话上下文。

**线程管理功能：**

- 创建新线程
- 加载历史线程
- 切换活跃线程
- 线程元数据管理

**导出配置：**

```json
{
  "exports": {
    "./v2/context": {
      "import": "./dist/v2/context.mjs",
      "require": "./dist/v2/context.cjs"
    }
  }
}
```

资料来源：[packages/react-core/package.json:32-36]()

## 状态管理 Hooks

### useCopilotReadable

`useCopilotReadable` 用于将组件状态共享给 AI，使 Copilot 能够感知当前应用状态。

**典型用法：**

```tsx
import { useCopilotReadable } from "@copilotkit/react-core";

function Dashboard() {
  const formState = useFormState();
  
  useCopilotReadable({
    description: "仪表盘数据，包括销售趋势和产品表现",
    value: {
      salesData,
      productData,
      metrics: {
        totalRevenue,
        totalProfit,
        conversionRate
      }
    }
  });
}
```

**应用场景：**

| 场景 | 描述 |
|------|------|
| 表单状态同步 | 将表单字段和当前值传递给 AI |
| 数据仪表盘 | 共享业务指标和趋势数据 |
| 用户信息 | 提供当前用户上下文给 Copilot |

资料来源：[examples/v1/form-filling/README.md:30-45]()

### useCopilotAction

`useCopilotAction` 允许 AI 执行前端操作，实现生成式 UI 交互模式。

**定义可执行动作：**

```tsx
useCopilotAction({
  name: "fillIncidentReportForm",
  description: "填写安全事件报告表单",
  parameters: [
    { name: "incidentType", type: "string" },
    { name: "description", type: "string" }
  ],
  renderAndWaitForResponse: ({ args, status }) => {
    return <ConfirmationPrompt args={args} />;
  }
});
```

资料来源：[examples/v1/form-filling/README.md:50-60]()

## 完整使用架构

### 组件层级结构

```mermaid
graph TD
    A[应用根组件] --> B[CopilotKitProvider]
    B --> C[业务组件]
    C --> D[useCopilotKit]
    C --> E[useAgent]
    C --> F[useCopilotReadable]
    C --> G[useCopilotAction]
    D --> H[CopilotKit 上下文]
    E --> H
    F --> H
    G --> H
```

### 状态流转

```mermaid
sequenceDiagram
    participant U as 用户
    participant R as React组件
    participant H as Hooks API
    participant C as CopilotKit上下文
    participant A as AI后端
    
    U->>R: 触发交互
    R->>H: 调用 useCopilotKit/useAgent
    H->>C: 读取/更新状态
    C->>A: 发送请求
    A->>C: 返回响应
    C->>H: 推送更新
    H->>R: 触发重新渲染
    R->>U: 更新UI
```

## React Native 支持

### 与 Web SDK 的差异

| 特性 | Web SDK | React Native |
|------|---------|--------------|
| API 版本 | `/v2` 子路径导出 | 根路径即 v2 API |
| DOM 依赖 | 完整支持 | 无 DOM/CSS 依赖 |
| UI 组件 | 提供 UI 组件库 | 仅提供纯 Hooks |

**安装配置：**

```bash
npm install @copilotkit/react-native
```

**入口文件配置：**

```javascript
// index.js
import "@copilotkit/react-native/polyfills";

import { AppRegistry } from "react-native";
import App from "./App";
import { name as appName } from "./app.json";

AppRegistry.registerComponent(appName, () => App);
```

### 分片导入

React Native 包支持按需导入 polyfills：

```javascript
// 仅导入所需的 polyfill
import "@copilotkit/react-native/polyfills/streams";
import "@copilotkit/react-native/polyfills/encoding";
import "@copilotkit/react-native/polyfills/crypto";
import "@copilotkit/react-native/polyfills/dom";
import "@copilotkit/react-native/polyfills/location";
```

资料来源：[packages/react-native/README.md:50-60]()

## 依赖包版本

当前稳定版本为 **1.57.2**，相关包的版本信息：

| 包名 | 版本 | 用途 |
|------|------|------|
| `@copilotkit/react-core` | 1.57.2 | 核心 Hooks |
| `@copilotkit/react-native` | 1.57.2 | React Native 支持 |
| `@copilotkit/react-ui` | 1.57.2 | UI 组件库 |
| `@copilotkit/runtime` | 1.57.2 | 运行时核心 |

资料来源：[packages/react-core/package.json:3]()
资料来源：[packages/react-native/package.json:3]()

## 与后端集成

### 运行时配置

`CopilotKitProvider` 需要配置 `runtimeUrl` 指向 CopilotKit 后端服务：

```tsx
<CopilotKitProvider runtimeUrl="https://your-server/api/copilotkit">
  <App />
</CopilotKitProvider>
```

### 线程持久化

使用 `useThreads` 管理对话历史，支持跨会话恢复：

```tsx
function ChatInterface() {
  const { threads, activeThread, createThread, switchThread } = useThreads();
  
  // 线程管理逻辑
}
```

资料来源：[examples/integrations/langgraph-python-threads/README.md:60-80]()

## 最佳实践

### 1. 状态同步时机

- 在组件挂载时调用 `useCopilotReadable` 初始化状态
- 使用 `useCallback` 包装状态更新逻辑，避免不必要的重新渲染

### 2. 错误处理

```tsx
try {
  const { copilotKit } = useCopilotKit();
  await copilotKit.doSomething();
} catch (error) {
  console.error("CopilotKit 错误:", error);
}
```

### 3. 类型安全

利用 TypeScript 类型定义确保 API 调用的正确性：

```typescript
import type { CopilotKitConfig, Thread, Message } from "@copilotkit/react-core";
```

## 总结

React Hooks API 是 CopilotKit 前端开发的核心接口，通过 `@copilotkit/react-core` 和 `@copilotkit/react-native` 两个包提供完整的状态管理、动作执行和上下文共享能力。开发者应优先使用 `useCopilotKit` 获取基础上下文，根据具体场景选择 `useCopilotReadable` 共享状态或 `useCopilotAction` 定义可执行动作。对于需要人机协作的场景，可结合 `useHumanInTheLoop` 实现中断和确认流程。

---

<a id='copilot-runtime'></a>

## CopilotRuntime 后端运行时

### 相关页面

相关主题：[后端工具系统](#backend-tools), [系统架构](#system-architecture)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [packages/runtime/src/lib/runtime/copilot-runtime.ts](https://github.com/CopilotKit/CopilotKit/blob/main/packages/runtime/src/lib/runtime/copilot-runtime.ts)
- [packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)
- [packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)
- [examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)
- [examples/integrations/a2a-middleware/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [examples/v1/state-machine/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/v1/state-machine/README.md)
</details>

# CopilotRuntime 后端运行时

## 概述

CopilotRuntime 是 CopilotKit 框架的核心后端运行时组件，负责管理与 AI Agent 的通信、工具调用路由、消息转换以及前端与后端之间的状态同步。它作为 Next.js API 路由或独立后端服务运行，为 CopilotKit 前端组件提供运行时支持。

**核心职责：**

- 接收前端发送的 AI 请求并路由到相应的 Agent
- 管理工具定义和工具调用执行
- 处理消息格式转换（AG-UI 协议与 GraphQL 格式互转）
- 支持可观测性配置（日志记录、追踪）
- 连接外部 MCP（Model Context Protocol）服务器

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:1-100]()

## 核心配置选项

CopilotRuntime 通过配置对象初始化，支持多种定制化选项：

```typescript
import { CopilotRuntime } from "@copilotkit/runtime";

const copilotKit = new CopilotRuntime({
  runtimeUrl: "/api/copilotkit",
  headers: { "Authorization": `Bearer ${token}` },
  licenseKey: "ck_pub_...",
  properties: { customKey: "value" },
  agents: agentConfig,
  tools: [],
  renderToolCalls: [],
  frontendTools: [],
  humanInTheLoop: [],
  observability_c: { logging: { enabled: true } },
  mcpServers: [],
  experimental_createMCPClient: async (config) => { /* ... */ }
});
```

### 配置参数详解

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `runtimeUrl` | `string` | 否 | CopilotKit 运行时 URL，默认使用当前服务 |
| `headers` | `Record<string, string>` | 否 | 默认请求头，会被每个请求继承 |
| `licenseKey` | `string` | 否 | Copilot Cloud 公用 API 密钥（`ck_pub_...`） |
| `properties` | `Record<string, unknown>` | 否 | 转发到 Agent 运行时的自定义属性 |
| `agents` | `Record<string, AbstractAgent>` | 否 | 本地浏览器内 Agent 配置 |
| `tools` | `ClientTool[]` | 否 | 向运行时广告的工具定义（无处理器） |
| `renderToolCalls` | `RenderToolCallConfig[]` | 否 | 渲染工具调用的 UI 组件配置 |
| `frontendTools` | `FrontendToolConfig[]` | 否 | 带处理器的客户端工具 |
| `humanInTheLoop` | `HumanInTheLoopConfig[]` | 否 | 暂停等待用户输入的工具 |
| `observability_c` | `CopilotObservabilityConfig` | 否 | 可观测性配置（日志、追踪） |
| `mcpServers` | `MCPEndpointConfig[]` | 否 | 外部 MCP 服务器连接配置 |

资料来源：[packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)

## 架构设计

### 运行时架构图

```mermaid
graph TD
    subgraph 前端层 ["前端层 (Frontend)"]
        UI[CopilotKit UI 组件]
        React[React / Vue / Angular]
    end

    subgraph 运行时层 ["CopilotRuntime 层"]
        CR[CopilotRuntime 实例]
        MW[中间件处理]
        MSG[消息转换器]
        TOOL[工具路由]
    end

    subgraph Agent 层 ["Agent 层"]
        LG[LangGraph Agent]
        MI[LlamaIndex Agent]
        MA[Mastra Agent]
        CA[CrewAI Agent]
        A2A[A2A Middleware Agent]
    end

    subgraph 外部服务 ["外部服务"]
        MCP[MCP Server]
        OBS[可观测性服务]
    end

    UI --> CR
    CR --> MW
    MW --> MSG
    MSG --> TOOL
    TOOL --> LG
    TOOL --> MI
    TOOL --> MA
    TOOL --> CA
    TOOL --> A2A
    CR --> MCP
    CR --> OBS
```

### 请求处理流程

```mermaid
sequenceDiagram
    participant User as 用户
    participant UI as CopilotKit UI
    participant RT as CopilotRuntime
    participant Agent as AI Agent
    participant Tools as 工具系统

    User->>UI: 发送自然语言请求
    UI->>RT: 转发请求 (Action)
    RT->>RT: 消息格式转换
    RT->>Agent: 调用 Agent 执行
    Agent->>Agent: LLM 推理
    Agent->>Tools: 请求工具调用
    Tools-->>Agent: 返回工具结果
    Agent-->>RT: 返回响应结果
    RT->>RT: 状态更新
    RT-->>UI: 流式事件推送
    UI-->>User: 显示 AI 响应
```

## 使用方式

### Next.js API 路由集成

CopilotRuntime 最常见的用法是在 Next.js 应用中作为 API 路由处理程序：

```typescript
// app/api/copilotkit/route.ts
import { CopilotRuntime, CopilotKitServiceAdapter } from "@copilotkit/runtime";
import { LangGraphApolloClient } from "@langchain/langgraph-sdk";

const langgraphAdapter = new LangGraphApolloClient({
  deployment: process.env.LANGGRAPH_DEPLOYMENT!,
  apiKey: process.env.LANGGRAPH_API_KEY,
});

export async function POST(req: Request): Promise<Response> {
  const copilotKit = new CopilotRuntime({
    tools: [
      {
        id: "research",
        name: "Research",
        description: "Search for information",
        argument: {
          type: "object",
          properties: {
            query: { type: "string" }
          }
        }
      }
    ]
  });

  return copilotKit.streamRequest(
    req,
    langgraphAdapter
  );
}
```

资料来源：[examples/canvas/langgraph-python/src/app/api/copilotkit/route.ts](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/langgraph-python/src/app/api/copilotkit/route.ts)

### 可观测性配置

CopilotRuntime 支持详细的可观测性配置，可集成 Langfuse 等追踪服务：

```typescript
const copilotKit = new CopilotRuntime({
  observability_c: {
    logging: {
      enabled: true,
      progressive: true, // 设为 false 启用缓冲日志
      logger: {
        logRequest: (data) => langfuse.trace({ 
          name: "LLM Request", 
          input: data 
        }),
        logResponse: (data) => langfuse.trace({ 
          name: "LLM Response", 
          output: data 
        }),
        logError: (errorData) => langfuse.trace({ 
          name: "LLM Error", 
          metadata: errorData 
        }),
      },
    },
  },
});
```

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:50-70]()

## 工具系统

### 工具类型

CopilotRuntime 支持多种工具定义方式：

| 工具类型 | 说明 | 配置位置 |
|----------|------|----------|
| **Backend Tools** | 后端定义的工具，Agent 调用后由运行时执行 | `tools` 参数 |
| **Frontend Tools** | 前端定义的工具，Agent 调用后回传前端执行 | `frontendTools` 参数 |
| **Human-in-the-Loop** | 需人工确认的工具调用 | `humanInTheLoop` 参数 |
| **MCP Tools** | 外部 MCP 服务器提供的工具 | `mcpServers` 参数 |

### 后端工具定义示例

```typescript
const copilotKit = new CopilotRuntime({
  tools: [
    {
      id: "update_spreadsheet",
      name: "Update Spreadsheet",
      description: "更新电子表格中的单元格值",
      argument: {
        type: "object",
        properties: {
          cell: { type: "string", description: "单元格引用，如 A1" },
          value: { type: "string", description: "要写入的值" }
        },
        required: ["cell", "value"]
      }
    }
  ]
});
```

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

### 前端工具定义

```typescript
import { useCopilotAction } from "@copilotkit/core";

useCopilotAction({
  name: "update_spreadsheet",
  description: "更新电子表格中的单元格值",
  available: "remote",
  parameters: [
    {
      name: "cell",
      type: "string",
      required: true,
      description: "单元格引用"
    },
    {
      name: "value", 
      type: "string",
      required: true,
      description: "要写入的值"
    }
  ],
  handler: ({ cell, value }) => {
    // 在前端执行实际更新
    return updateCell(cell, value);
  }
});
```

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

## MCP 服务器集成

CopilotRuntime 支持连接外部 Model Context Protocol (MCP) 服务器，获取外部工具定义：

```typescript
import { experimental_createMCPClient } from "ai"; // 从 vercel ai 库导入

const copilotKit = new CopilotRuntime({
  mcpServers: [
    {
      id: "tavily-search",
      serverUrl: "https://api.tavily.com/mcp",
      headers: {
        "Authorization": `Bearer ${process.env.TAVILY_API_KEY}`
      }
    }
  ],
  experimental_createMCPClient: async (config) => {
    return await experimental_createMCPClient({
      ...config,
      // 额外的 MCP 客户端配置
    });
  }
});
```

**MCP 集成特性：**

- 自动获取远程服务器的工具定义
- 标准化工具参数验证
- 支持自定义请求头和认证
- 实验性功能，需启用 `experimental_createMCPClient`

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:80-110]()

## Agent 集成

### 与 LangGraph 集成

```python
from copilotkit import CopilotKitMiddleware
from langgraph.checkpoint.memory import MemorySaver
from langchain_openai import ChatOpenAI

agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-4"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

### 与 LlamaIndex 集成

```python
from llama_index.core.workflow import DrawableWorkflow
from llama_index.core.workflow.events import StartEvent, StopEvent
from copilotkit import copilotkit_emit_event

class MyWorkflow(DrawableWorkflow):
    @step
    async def process(self, ev: StartEvent) -> StopEvent:
        result = f"Processing: {ev.input}"
        await copilotkit_emit_event(
            event_name="progress",
            data={"message": "处理中..."}
        )
        return StopEvent(result=result)
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

### 与 A2A 中间件集成

```typescript
import { A2AMiddlewareAgent } from "@copilotkit/plugin-a2a";

const a2aMiddlewareAgent = new A2AMiddlewareAgent({
  agentUrls: [
    "http://localhost:9001/research",
    "http://localhost:9002/analysis",
    "http://localhost:9003/new-agent",
  ],
  defaultHandoffs: [
    { agent: "research", description: "研究代理" }
  ]
});
```

资料来源：[examples/integrations/a2a-middleware/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/README.md)

## 状态管理

### 全局状态管理

CopilotRuntime 支持前端状态读取和应用状态同步：

```typescript
// 前端读取应用状态
import { useCopilotReadable } from "@copilotkit/core";

function AppComponent() {
  const appState = useMemo(() => ({
    spreadsheet: spreadsheetData,
    user: currentUser
  }), [spreadsheetData, currentUser]);

  useCopilotReadable({
    description: "当前应用状态",
    value: appState
  });

  return <SpreadsheetUI />;
}
```

```typescript
// 前端修改应用状态
import { useCopilotAction } from "@copilotkit/core";

useCopilotAction({
  name: "updateSpreadsheet",
  description: "更新电子表格",
  parameters: [
    { name: "cell", type: "string" },
    { name: "value", type: "string" }
  ],
  handler: ({ cell, value }) => {
    return updateSpreadsheet(cell, value);
  }
});
```

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

### 状态流图

```mermaid
graph LR
    subgraph Frontend ["前端状态"]
        UI[用户界面]
        READ[useCopilotReadable]
        ACT[useCopilotAction]
    end

    subgraph Runtime ["CopilotRuntime"]
        SYNC[状态同步]
        ROUTE[请求路由]
    end

    subgraph Backend ["后端状态"]
        AGENT[AI Agent]
        TOOLS[工具执行]
    end

    READ --> SYNC
    SYNC --> AGENT
    ACT --> ROUTE
    ROUTE --> TOOLS
    TOOLS --> SYNC
    SYNC --> UI
```

## 框架适配

### Vue 集成

```vue
<script setup lang="ts">
import { CopilotKitProvider } from "@copilotkit/vue";

function onProviderError(event: {
  code: string;
  error: Error;
  context: Record<string, any>;
}) {
  console.error("Provider error:", event);
}

const debug = { events: true, lifecycle: true, verbose: false };
</script>

<template>
  <CopilotKitProvider
    runtime-url="/api/copilotkit"
    :self-managed-agents="{}"
    :on-error="onProviderError"
    :debug="debug"
  >
    <slot />
  </CopilotKitProvider>
</template>
```

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

### Angular 集成

```typescript
import { provideCopilotKit } from "@copilotkit/angular";

@Component({
  selector: "app-root",
  standalone: true,
  providers: [
    provideCopilotKit({
      runtimeUrl: "/api/copilotkit",
      licenseKey: "ck_pub_...",
      agents: {},
      tools: [],
      renderToolCalls: [],
      frontendTools: [],
      humanInTheLoop: []
    })
  ],
  template: `<ng-content />`
})
export class AppComponent {}
```

资料来源：[packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)

## 版本演进

CopilotRuntime 正在从 v1 版本向 v2 版本迁移，提供新的 API 和功能：

```typescript
import { 
  CopilotRuntime as CopilotRuntimeVNext,
  InMemoryAgentRunner,
  type AgentsConfig,
  type AgentsFactory 
} from "@copilotkit/runtime/v2";

const config: AgentsConfig = {
  // 新的 Agent 配置格式
};

const runtime = new CopilotRuntimeVNext({
  agents: config
});
```

**v2 新特性：**

- 改进的 Agent 配置系统
- 支持更多中间件类型
- 增强的类型安全性
- 更好的性能优化

资料来源：[packages/runtime/src/lib/runtime/copilot-runtime.ts:200-250]()

## 最佳实践

### 生产环境配置

| 配置项 | 推荐值 | 说明 |
|--------|--------|------|
| `licenseKey` | 必填 | 使用 Copilot Cloud 功能必需 |
| `observability_c.logging.enabled` | true | 生产环境建议启用 |
| `observability_c.logging.progressive` | true | 实时日志便于调试 |
| 错误处理 | 必需 | 实现 `onError` 回调 |

### 性能优化

1. **工具定义精简**：只暴露必要的工具，减少 LLM 上下文
2. **状态同步控制**：合理使用 `useCopilotReadable` 避免过度同步
3. **MCP 连接池**：复用 MCP 客户端连接
4. **消息压缩**：大响应启用流式处理

### 安全考虑

```typescript
const copilotKit = new CopilotRuntime({
  headers: {
    "Authorization": `Bearer ${validateToken()}`,
    "X-Request-ID": generateRequestId()
  },
  properties: {
    "userId": sanitize(userId),
    "sessionId": sessionId
  }
});
```

- 始终验证和清理用户输入
- 使用安全的认证头传递凭证
- 限制暴露给 Agent 的系统属性

## 相关资源

- [CopilotRuntime API 参考](https://docs.copilotkit.ai/reference/v1/classes/CopilotRuntime)
- [Copilot Runtime 概念文档](https://docs.copilotkit.ai/concepts/copilot-runtime)
- [LangGraph 集成指南](https://docs.copilotkit.ai/integrations/langgraph)
- [A2A 协议集成](https://docs.copilotkit.ai/integrations/a2a)

---

<a id='backend-tools'></a>

## 后端工具系统

### 相关页面

相关主题：[CopilotRuntime 后端运行时](#copilot-runtime), [生成式 UI](#generative-ui)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [examples/integrations/langgraph-fastapi/agent/src/todos.py](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/agent/src/todos.py)
- [examples/integrations/langgraph-fastapi/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/README.md)
- [examples/integrations/a2a-middleware/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/README.md)
</details>

# 后端工具系统

## 概述

后端工具系统是 CopilotKit 架构中连接 AI Agent 与外部服务、业务逻辑的桥梁。该系统允许在服务器端（Python/Node.js）定义工具函数，使 AI Agent 能够执行复杂的后端操作，如数据库查询、API 调用、文件处理等。与前端工具不同，后端工具由 Agent 在推理过程中调用，结果通过 CopilotKit Runtime 同步回前端界面。

## 核心概念

### 后端工具 vs 前端工具

| 特性 | 后端工具 | 前端工具 |
|------|---------|---------|
| 执行位置 | 服务器端（Agent 运行时） | 浏览器端 |
| 调用时机 | Agent 推理过程中自动调用 | 需显式定义 `handler` |
| 适用场景 | 数据库操作、外部 API、复杂计算 | UI 交互、状态更新、本地计算 |
| 状态管理 | 通过 `useCoAgent` 同步状态 | 直接操作 React 状态 |

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

### 工具注册流程

```mermaid
graph TD
    A[定义后端工具函数] --> B[注册到 Agent 框架]
    B --> C[生成工具 Schema]
    C --> D[CopilotKit Runtime 暴露工具]
    D --> E[前端通过 useCopilotAction 渲染]
```

## LlamaIndex 集成

### 基本用法

使用 `get_ag_ui_workflow_router` 可以快速定义后端工具。以下示例展示了一个问候语工具的定义：

```python
def hello_world(name: str) -> str:
    return f"Hello, {str}"  # 工具返回结果

agentic_chat_router = get_ag_ui_workflow_router(
    llm=OpenAI(model="gpt-4.1"),
    backend_tools=[hello_world]
)
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

### 工具参数定义

后端工具支持类型化的参数定义，参数规范会自动生成给 LLM 使用：

```python
def create_task(
    title: str,           # 必需参数
    description: str = "", # 可选参数
    priority: int = 1     # 带默认值的参数
) -> dict:
    return {"status": "created", "title": title}
```

### 工具结果处理

工具执行完成后，结果通过 AG-UI 协议返回前端。前端可以使用 `useCopilotAction` 渲染工具调用界面：

```tsx
useCopilotAction({
    name: "hello_world",
    render: () => {
        return <div>Called hello_world tool...</div>
    }
})
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

## LangGraph 集成

### FastAPI + LangGraph 架构

```mermaid
graph TB
    subgraph "Frontend"
        UI[Next.js UI]
        CK[CopilotKit]
    end
    
    subgraph "Backend"
        FA[FastAPI Server]
        LG[LangGraph Agent]
        Tools[Backend Tools]
    end
    
    UI <--> CK
    CK <--> FA
    FA <--> LG
    LG --> Tools
```

在 LangGraph 集成中，后端工具通过 `CopilotKitMiddleware` 与图节点交互：

```python
from copilotkit import CopilotKitMiddleware

agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-5.2"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

### 任务管理工具示例

```python
# examples/integrations/langgraph-fastapi/agent/src/todos.py

from pydantic import BaseModel, Field
from typing import Optional

class TodoItem(BaseModel):
    id: str = Field(description="唯一标识符")
    title: str = Field(description="任务标题")
    completed: bool = Field(default=False, description="完成状态")

class TodoInput(BaseModel):
    title: str = Field(description="新建任务的标题")

def get_todos() -> list[dict]:
    """获取所有待办事项"""
    return [{"id": "1", "title": "示例任务", "completed": False}]

def create_todo(input: TodoInput) -> dict:
    """创建新的待办事项"""
    return {"id": "new-1", "title": input.title, "completed": False}
```

资料来源：[examples/integrations/langgraph-fastapi/agent/src/todos.py](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/agent/src/todos.py)

## 工具执行流程

```mermaid
sequenceDiagram
    participant User
    participant UI as 前端 UI
    participant CK as CopilotKit Runtime
    participant Agent as AI Agent
    participant Tool as 后端工具

    User->>UI: 发送自然语言请求
    UI->>CK: 转发消息
    CK->>Agent: 传递消息和上下文
    Agent->>Agent: 推理并决定调用工具
    Agent->>Tool: 执行工具函数
    Tool-->>Agent: 返回执行结果
    Agent->>CK: 返回更新后的状态
    CK->>UI: 同步状态变化
    UI->>User: 显示结果
```

## 外部工具集成

### Composio 集成

CopilotKit 支持通过 Composio 集成外部服务（如 Google Sheets）：

```python
from composio import Composio

composio = Composio()

def sheets_sync_all(data: list[dict]) -> str:
    """同步数据到 Google Sheets"""
    action = composio.action("sheets_sync_all")
    result = action.execute(data=data)
    return result

def sheets_create_new(title: str) -> str:
    """创建新的电子表格"""
    action = composio.action("sheets_create_new")
    result = action.execute(title=title)
    return result

def sheets_get_url(spreadsheet_id: str) -> str:
    """获取电子表格 URL"""
    return f"https://docs.google.com/spreadsheets/d/{spreadsheet_id}"
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

### Tavily 搜索工具

```python
# examples/showcases/deep-agents/agent/tools.py

from langchain.tools import tool
from tavily import TavilyClient

tavily_client = TavilyClient()

@tool
def research(query: str) -> str:
    """根据查询进行网络研究并返回摘要"""
    results = tavily_client.search(query=query, max_results=5)
    summaries = [r['content'] for r in results]
    return "\n\n".join(summaries)
```

资料来源：[examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

## A2A 协议工具调用

CopilotKit 支持通过 A2A（Agent-to-Agent）协议调用外部代理服务：

```python
# 在路由中注册外部代理
const newAgentUrl = "http://localhost:9003";

const a2aMiddlewareAgent = new A2AMiddlewareAgent({
    agentUrls: [
        researchAgentUrl,
        analysisAgentUrl,
        newAgentUrl,
    ],
});

# 外部代理定义工具能力
agent = new Agent(
    name="research_agent",
    description="Deep research with web search",
    skills=[web_search_skill],  # 定义可调用工具
    port=9001,
);
```

资料来源：[examples/integrations/a2a-middleware/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/a2a-middleware/README.md)

## 最佳实践

### 1. 工具命名规范

| 规范 | 说明 | 示例 |
|------|------|------|
| 动词短语 | 工具名应描述操作 | `create_task`, `update_status` |
| 小写下划线 | 使用 snake_case | `sync_sheets`, `get_user_data` |
| 清晰描述 | 添加 docstring 说明 | `"""获取用户信息"""` |

### 2. 参数类型提示

始终使用类型提示，使 LLM 能够正确理解参数：

```python
def process_data(
    data: list[str],      # 列表类型
    options: dict = {},   # 可选字典
    limit: int = 10       # 带默认值的整数
) -> dict:                # 明确返回值类型
    ...
```

### 3. 错误处理

```python
def safe_operation(input_data: str) -> dict:
    try:
        result = risky_operation(input_data)
        return {"success": True, "data": result}
    except ValidationError as e:
        return {"success": False, "error": str(e)}
    except Exception as e:
        logger.error(f"Unexpected error: {e}")
        return {"success": False, "error": "Internal error"}
```

## 总结

后端工具系统是 CopilotKit 实现 Agent 能力扩展的核心组件。通过标准化的工具定义接口，开发者可以：

- 将任意后端逻辑暴露给 AI Agent
- 通过 Composio 等集成服务连接外部 API
- 使用 A2A 协议实现多 Agent 协作
- 利用 LangGraph、LlamaIndex 等框架构建复杂的工作流

该系统与前端工具形成互补，共同支撑 CopilotKit 的端到端 AI 辅助能力。

---

<a id='generative-ui'></a>

## 生成式 UI

### 相关页面

相关主题：[Chat UI 组件](#chat-ui-components), [通信协议](#protocols)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [docs/content/docs/(root)/generative-ui/display.mdx](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/generative-ui/display.mdx)
- [docs/content/docs/(root)/generative-ui/interactive.mdx](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/generative-ui/interactive.mdx)
- [docs/content/docs/(root)/generative-ui/tool-rendering.mdx](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/generative-ui/tool-rendering.mdx)
- [examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx)
- [examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)
- [packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)
- [packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

</details>

# 生成式 UI

## 概述

生成式 UI（Generative UI）是 CopilotKit 的核心特性之一，它使 AI 代理能够在运行时动态生成和渲染用户界面组件。与传统的固定 UI 模式不同，生成式 UI 允许 AI 根据对话上下文和工具执行结果，实时生成丰富的可视化内容、交互式表单、图表等复杂 UI 元素。

CopilotKit 提供了完整的生成式 UI 技术栈，包括：

- **组件渲染**：AI 可生成任意 React/Vue/Angular 组件
- **工具调用渲染**：为特定工具绑定自定义 UI 展示
- **交互式组件**：支持人机协作的工具执行模式
- **状态同步**：前后端状态的双向实时同步

资料来源：[examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md)

---

## 核心架构

### 系统架构图

```mermaid
graph TD
    subgraph 前端 [前端层 - CopilotKit SDK]
        UI[用户界面]
        CK[CopilotKit Provider]
        Hooks[Hooks API]
        Renderer[组件渲染器]
    end

    subgraph 中间层 [CopilotKit Runtime]
        Runtime[Runtime Service]
        StateSync[状态同步]
        MessageProc[消息处理]
    end

    subgraph 后端 [Agent 后端]
        Agent[AI Agent]
        Tools[工具定义]
        LLM[大语言模型]
    end

    UI --> Hooks
    Hooks --> Renderer
    Renderer --> CK
    CK --> Runtime
    Runtime --> StateSync
    Runtime --> MessageProc
    MessageProc --> Agent
    Agent --> Tools
    Agent --> LLM

    style 前端 fill:#e1f5fe
    style 中间层 fill:#fff3e0
    style 后端 fill:#e8f5e9
```

### 数据流

```mermaid
sequenceDiagram
    participant User as 用户
    participant UI as 前端组件
    participant Hooks as CopilotKit Hooks
    participant Runtime as CopilotKit Runtime
    participant Agent as AI Agent
    participant LLM as 大语言模型

    User->>UI: 输入请求
    UI->>Hooks: useAgent / useCopilotAction
    Hooks->>Runtime: 发送消息
    Runtime->>Agent: 转发请求
    Agent->>LLM: 调用 LLM
    LLM-->>Agent: 返回生成结果
    Agent-->>Runtime: 返回工具调用/组件
    Runtime-->>Hooks: 同步状态更新
    Hooks-->>UI: 触发重新渲染
    UI-->>User: 显示生成式 UI
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

---

## 工具渲染

### 工具渲染配置

工具渲染（Tool Rendering）允许为特定的 AI 工具绑定自定义的 UI 展示组件。当 AI 调用某个工具时，系统会自动使用对应的渲染器来展示结果，而不是显示默认的文本格式。

#### React 工具渲染配置

```typescript
// 定义渲染工具调用的配置
interface RenderToolCallConfig<Args> {
  name: string;              // 工具名称，或 "*" 匹配所有
  args: z.ZodType<Args>;     // 参数的 Zod schema
  component: Type<ToolRenderer<Args>>;  // 渲染器组件
  agentId?: string;          // 可选的代理作用域
}
```

#### 渲染器组件示例

```typescript
// 示例：天气卡片渲染器
// 资料来源：examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx

import React from "react";

interface WeatherCardProps {
  toolCall: {
    args: { city: string; temperature: number; condition: string };
    status: "in-progress" | "executing" | "complete";
    result?: string;
  };
}

export const WeatherCard: React.FC<WeatherCardProps> = ({ toolCall }) => {
  const { args, status } = toolCall;
  
  return (
    <div className="weather-card">
      <h3>{args.city}</h3>
      <div className="temperature">{args.temperature}°C</div>
      <div className="condition">{args.condition}</div>
      {status === "in-progress" && <div className="loading">加载中...</div>}
    </div>
  );
};
```

### 工具渲染注册

```typescript
import { CopilotKit } from "@copilotkit/react-core";
import { WeatherCard } from "./components/WeatherCard";

function App() {
  return (
    <CopilotKit
      renderToolCall={[
        {
          name: "get_weather",
          args: z.object({
            city: z.string(),
            temperature: z.number(),
            condition: z.string(),
          }),
          component: WeatherCard,
        },
        {
          name: "get_stock_price",
          args: z.object({
            symbol: z.string(),
            price: z.number(),
            change: z.number(),
          }),
          component: StockCard,
        },
      ]}
    >
      {/* 应用内容 */}
    </CopilotKit>
  );
}
```

### 后端工具定义

```python
# 使用 LlamaIndex 定义后端工具
# 资料来源：examples/canvas/llamaindex-composio/README.md

from llama_index.core.tools import FunctionTool

def hello_world(name: str) -> str:
    """获取问候语"""
    return f"Hello, {name}"

backend_tools = [
    FunctionTool.from_defaults(
        fn=hello_world,
        name="hello_world",
        description="生成问候语"
    )
]

# 使用 CopilotKit 中间件
agentic_chat_router = get_ag_ui_workflow_router(
    llm=OpenAI(model="gpt-4"),
    backend_tools=backend_tools,
    middleware=[CopilotKitMiddleware()]
)
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

---

## 交互式组件

### 人机协作模式

人机协作（Human-in-the-Loop）工具允许 AI 生成需要用户确认或交互的组件。这种模式下，工具执行会暂停等待用户输入。

#### Angular 人机协作配置

```typescript
// 资料来源：packages/angular/README.md

export interface HumanInTheLoopConfig<Args> {
  name: string;
  description: string;
  parameters: z.ZodType<Args>;
  component: Type<HumanInTheLoopToolRenderer<Args>>;
  agentId?: string;
}

export interface HumanInTheLoopToolRenderer<Args> {
  toolCall: Signal<HumanInTheLoopToolCall<Args>>;
  // 包含 respond(result) 方法供用户确认
}
```

### 交互式工具渲染器

```typescript
interface HumanInTheLoopToolCall<Args> {
  args: Args;
  status: "in-progress" | "executing" | "complete";
  respond: (result: unknown) => void;  // 用户响应方法
}
```

### 前端工具

前端工具在浏览器端执行，不需要与后端通信。

#### React 前端工具配置

```typescript
export interface FrontendToolConfig<Args> {
  name: string;
  description: string;
  parameters: z.ZodType<Args>;
  component?: Type<ToolRenderer<Args>>;  // 可选的 UI 渲染器
  handler: (args: Args, context: FrontendToolHandlerContext) => Promise<unknown>;
  agentId?: string;
}
```

#### 前端工具示例

```tsx
// 资料来源：examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md

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

function ChatInterface() {
  // 注册高亮文本的前端工具
  useCopilotAction({
    name: "highlight_note",
    description: "将指定文本高亮显示",
    parameters: z.object({
      text: z.string(),
      color: z.string().optional().default("yellow"),
    }),
    render: ({ args, status }) => (
      <div style={{ backgroundColor: args.color }}>
        高亮文本: {args.text}
        {status === "in-progress" && <span>处理中...</span>}
      </div>
    ),
  });

  return <ChatUI />;
}
```

资料来源：[examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md)

---

## 显示组件

### Headless 聊天界面

CopilotKit 提供了完整的 Headless API，允许开发者完全自定义聊天界面的每一个细节。

#### 核心 Hooks

| Hook 名称 | 功能描述 |
|-----------|----------|
| `useAgent` | 获取原始代理句柄，包含 messages、isRunning、addMessage 等 |
| `useCopilotKit` | 暴露 connectAgent、runAgent、stopAgent 方法 |
| `useRenderTool` | 为特定工具注册自定义渲染器 |
| `useCopilotReadable` | 将前端状态共享给 AI 代理 |

#### Headless 实现示例

```tsx
// 资料来源：examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md

import { useAgent, useCopilotKit, useRenderTool } from "@copilotkit/react-core";
import { WeatherCard } from "./components/WeatherCard";

function HeadlessChat() {
  const { messages, isRunning, addMessage, stop } = useAgent({ 
    agentId: "main-agent",
    threadId: "user-thread-1" 
  });
  const { connectAgent, runAgent, stopAgent } = useCopilotKit();

  // 注册天气工具的渲染器
  useRenderTool(
    "get_weather",
    ({ args, status, result }) => {
      if (status === "in-progress") {
        return <div className="loading">获取天气信息...</div>;
      }
      return <WeatherCard args={args} result={result} />;
    }
  );

  return (
    <div className="chat-container">
      <MessageList messages={messages} />
      <TypingIndicator visible={isRunning} />
      <Composer 
        onSend={(text) => addMessage({ role: "user", content: text })}
      />
    </div>
  );
}
```

### 消息列表渲染

```tsx
// 消息列表组件
// 资料来源：examples/showcases/integrations/claude-sdk-typescript/src/app/demos/headless-complete/README.md

function MessageList({ messages }) {
  return (
    <div className="message-list">
      {messages.map((message, index) => (
        <MessageBubble
          key={index}
          role={message.role}
          content={message.content}
          toolCalls={message.toolCalls}
          reasoning={message.reasoning}
          status={message.status}
        />
      ))}
    </div>
  );
}

// 消息气泡组件
function MessageBubble({ role, content, toolCalls, reasoning, status }) {
  return (
    <div className={`message message-${role}`}>
      {role === "user" && <UserMessage content={content} />}
      
      {role === "assistant" && (
        <>
          {reasoning && <ReasoningBlock content={reasoning} />}
          <AssistantMessage content={content} />
          
          {toolCalls?.map((toolCall, idx) => (
            <ToolCallCard
              key={idx}
              name={toolCall.name}
              args={toolCall.args}
              status={toolCall.status}
              result={toolCall.result}
            />
          ))}
          
          <ActivityIndicator status={status} />
        </>
      )}
    </div>
  );
}
```

---

## 上下文同步

### 状态共享机制

CopilotKit 提供了 `useCopilotReadable` 和 `useCopilotAction` 两个核心 Hook，用于在前后端之间同步应用状态。

```tsx
// 资料来源：examples/showcases/spreadsheet/README.md

import { useCopilotReadable, useCopilotAction } from "@copilotkit/react-core";

function SpreadsheetApp() {
  const [spreadsheetData, setSpreadsheetData] = useState([]);

  // 将电子表格数据共享给 AI
  useCopilotReadable({
    name: "spreadsheet_data",
    description: "当前电子表格的所有数据",
    value: spreadsheetData,
  });

  // 注册更新电子表格的操作
  useCopilotAction({
    name: "updateSpreadsheet",
    description: "更新电子表格中的单元格",
    parameters: z.object({
      cell: z.string(),
      value: z.any(),
    }),
    handler: async ({ cell, value }) => {
      // 更新电子表格逻辑
      setSpreadsheetData(prev => updateCell(prev, cell, value));
      return `已更新单元格 ${cell}`;
    },
  });

  useCopilotAction({
    name: "createSpreadsheet",
    description: "创建一个新的电子表格",
    parameters: z.object({
      name: z.string(),
      columns: z.array(z.string()),
    }),
    handler: async ({ name, columns }) => {
      // 创建电子表格逻辑
      return "电子表格已创建";
    },
  });
}
```

### 状态同步流程

```mermaid
sequenceDiagram
    participant Frontend as 前端应用
    participant Hooks as CopilotKit Hooks
    participant Runtime as Runtime Service
    participant Agent as AI Agent

    Note over Frontend: useCopilotReadable
    Frontend->>Hooks: 共享状态数据
    Hooks->>Runtime: 序列化状态
    Runtime->>Agent: 注入上下文

    Note over Frontend: useCopilotAction
    Agent-->>Runtime: 返回操作指令
    Runtime-->>Hooks: 触发处理器
    Hooks->>Frontend: 执行 handler
    Frontend-->>Hooks: 返回结果
    Hooks-->>Agent: 反馈执行结果
```

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

---

## 框架支持

### React 集成

React 是 CopilotKit 的主要支持框架，提供完整的生成式 UI 能力。

**核心组件：**

- `<CopilotKit>` - 根 Provider 组件
- `<CopilotSidebar>` - 侧边栏式对话界面
- `<CopilotChat>` - 完整聊天界面
- `<CopilotChatMessageView>` - 消息视图组件

**核心 Hooks：**

- `useAgent` - 代理操作
- `useCopilotKit` - 工具函数
- `useCopilotReadable` - 状态共享
- `useCopilotAction` - 操作注册
- `useRenderTool` - 工具渲染

### Vue 3 集成

Vue 包通过插槽机制提供高度可定制的生成式 UI。

```vue
<!-- 资料来源：packages/vue/README.md -->

<template>
  <CopilotChatMessageView>
    <!-- 工具调用插槽 -->
    <template #tool-call-search_docs="{ args, status, result }">
      <SearchDocsToolCall 
        :args="args" 
        :status="status" 
        :result="result" 
      />
    </template>

    <template #tool-call="{ name, args, status }">
      <GenericToolCall :name="name" :args="args" :status="status" />
    </template>
  </CopilotChatMessageView>
</template>
```

**支持的消息级插槽：**

| 插槽名称 | 描述 |
|----------|------|
| `message-before` | 消息前内容 |
| `assistant-message` | 助手消息 |
| `user-message` | 用户消息 |
| `reasoning-message` | 推理过程 |
| `activity-<type>` | 动态活动类型 |
| `message-after` | 消息后内容 |

**支持的工具级插槽：**

| 插槽名称 | 描述 |
|----------|------|
| `tool-call-<toolName>` | 特定工具渲染 |
| `tool-call` | 通用工具渲染（降级） |

### Angular 集成

Angular 包使用信号（Signals）和依赖注入提供类型安全的生成式 UI。

```typescript
// 资料来源：packages/angular/README.md

import { provideCopilotKit } from "@copilotkit/angular";

@Component({
  selector: "app-root",
  standalone: true,
  providers: [
    provideCopilotKit({
      runtimeUrl: "/api/copilotkit",
      tools: [
        {
          name: "get_weather",
          args: WeatherSchema,
          component: WeatherCardComponent,
        },
      ],
      renderToolCalls: [
        {
          name: "search_docs",
          args: SearchArgsSchema,
          component: SearchDocsRenderer,
        },
      ],
    }),
  ],
})
export class AppComponent {}
```

---

## 图表渲染

### 动态图表组件

CopilotKit 支持 AI 动态生成图表组件。

```tsx
// 资料来源：examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx

import React from "react";
import { Bar } from "react-chartjs-2";
import {
  Chart as ChartJS,
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";

ChartJS.register(
  CategoryScale,
  LinearScale,
  BarElement,
  Title,
  Tooltip,
  Legend
);

interface BarChartProps {
  data: {
    labels: string[];
    values: number[];
    title?: string;
  };
}

export const BarChart: React.FC<BarChartProps> = ({ data }) => {
  const chartData = {
    labels: data.labels,
    datasets: [
      {
        label: data.title || "数据",
        data: data.values,
        backgroundColor: [
          "rgba(255, 99, 132, 0.5)",
          "rgba(54, 162, 235, 0.5)",
          "rgba(255, 206, 86, 0.5)",
          "rgba(75, 192, 192, 0.5)",
          "rgba(153, 102, 255, 0.5)",
        ],
        borderColor: [
          "rgba(255, 99, 132, 1)",
          "rgba(54, 162, 235, 1)",
          "rgba(255, 206, 86, 1)",
          "rgba(75, 192, 192, 1)",
          "rgba(153, 102, 255, 1)",
        ],
        borderWidth: 1,
      },
    ],
  };

  const options = {
    responsive: true,
    plugins: {
      legend: { position: "top" as const },
      title: { display: !!data.title, text: data.title },
    },
  };

  return <Bar data={chartData} options={options} />;
};
```

### AI 生成图表流程

```mermaid
graph LR
    A[用户请求] --> B[AI Agent]
    B --> C[数据查询工具]
    C --> D[图表数据]
    D --> E[BarChart 组件]
    E --> F[渲染图表]
    
    style B fill:#e1f5fe
    style E fill:#fff3e0
```

资料来源：[examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/src/components/generative-ui/charts/bar-chart.tsx)

---

## 配置选项

### CopilotKit 配置

| 参数 | 类型 | 必需 | 描述 |
|------|------|------|------|
| `runtimeUrl` | `string` | 是 | CopilotKit Runtime 服务地址 |
| `headers` | `Record<string, string>` | 否 | 默认请求头 |
| `licenseKey` | `string` | 否 | Copilot Cloud 公钥 (`ck_pub_...`) |
| `properties` | `Record<string, unknown>` | 否 | 转发给代理的属性 |
| `agents` | `Record<string, AbstractAgent>` | 否 | 本地浏览器代理 |
| `tools` | `ClientTool[]` | 否 | 工具定义（无处理器） |
| `renderToolCalls` | `RenderToolCallConfig[]` | 否 | 工具调用渲染器 |
| `frontendTools` | `FrontendToolConfig[]` | 否 | 客户端工具 |
| `humanInTheLoop` | `HumanInTheLoopConfig[]` | 否 | 人机协作工具 |

### 调试配置

```typescript
interface DebugConfig {
  events?: boolean;      // 事件日志
  lifecycle?: boolean;  // 生命周期日志
  verbose?: boolean;    // 详细日志（包含完整载荷）
}
```

---

## 最佳实践

### 1. 组件设计原则

- **单一职责**：每个渲染器组件只负责一种工具的展示
- **状态同步**：正确处理 `in-progress`、`executing`、`complete` 三种状态
- **类型安全**：使用 Zod schema 定义工具参数

### 2. 性能优化

- 对复杂组件使用 `React.memo` 避免不必要的重渲染
- 工具渲染器应保持轻量
- 大量数据使用虚拟列表

### 3. 用户体验

- 始终显示加载状态（`in-progress`）
- 提供清晰的错误处理
- 使用渐进式展示（先显示骨架屏，再渲染实际内容）

---

## 相关资源

- [CopilotKit 文档 - 生成式 UI](https://docs.copilotkit.ai)
- [Deep Agents 示例](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [LangGraph 集成](https://github.com/CopilotKit/CopilotKit/blob/main/examples/integrations/langgraph-fastapi/README.md)
- [LlamaIndex 集成](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

---

<a id='human-in-the-loop'></a>

## 人在回路 (Human-in-the-Loop)

<details>
<summary>相关源码文件</summary>

以下源码文件用于生成本页说明：

- [examples/showcases/scene-creator/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/scene-creator/README.md)
- [examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)
- [packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)
- [packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)
- [examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)
- [examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)
</details>

# 人在回路 (Human-in-the-Loop)

## 概述

人在回路（Human-in-the-Loop，HitL）是一种设计模式，允许 AI 代理在执行关键操作前暂停执行流程，等待人类用户确认或提供额外输入。这种机制确保了 AI 系统在执行敏感操作时的安全性和可控性，特别适用于需要人工审批的业务场景。

在 CopilotKit 架构中，人在回路通过以下核心机制实现：

- **工具级中断**：Agent 调用特定工具时暂停，等待用户响应
- **实时 UI 渲染**：在等待期间向用户展示操作详情和审批界面
- **状态同步**：用户的决策结果实时同步回 Agent 继续执行

资料来源：[examples/showcases/scene-creator/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/scene-creator/README.md)

## 核心概念

### 与前端工具的区别

| 特性 | 前端工具 (Frontend Tools) | 人在回路 (HitL) |
|------|---------------------------|-----------------|
| 执行时机 | 立即执行，无需等待 | 暂停等待用户确认 |
| 用户交互 | 可选 UI 渲染 | 必须有审批 UI |
| 状态转换 | 异步完成 | 同步等待响应 |
| 典型场景 | 数据查询、格式化 | 预算审批、敏感操作确认 |

资料来源：[packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)

### 工作流程

```mermaid
graph TD
    A[Agent 决策] --> B{需要人工确认?}
    B -->|否| C[继续执行]
    B -->|是| D[触发 HitL 工具]
    D --> E[渲染审批 UI]
    E --> F[等待用户响应]
    F --> G{用户决策}
    G -->|批准| H[返回批准结果]
    G -->|拒绝| I[返回拒绝结果]
    G -->|修改参数| J[返回修改后参数]
    H --> K[Agent 继续执行]
    I --> L[Agent 取消操作]
    J --> K
```

## Angular 集成

### HumanInTheLoopConfig 接口

```typescript
export interface HumanInTheLoopConfig<Args> {
  name: string;              // 工具名称
  description: string;      // 工具描述
  parameters: z.ZodType<Args>;  // 参数 Schema
  component: Type<HumanInTheLoopToolRenderer<Args>>;  // 审批 UI 组件
  agentId?: string;         // 可选的 Agent 作用域
}
```

资料来源：[packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)

### HumanInTheLoopToolRenderer 组件

```typescript
export interface HumanInTheLoopToolRenderer<Args> {
  toolCall: Signal<HumanInTheLoopToolCall<Args>>;  // 包含 respond(result) 方法
}
```

审批组件通过 `toolCall` 信号接收工具调用信息，并通过 `respond()` 方法向 Agent 返回用户的决策结果。

### 配置示例

```typescript
export const hitlConfig: HumanInTheLoopConfig<BudgetApprovalArgs> = {
  name: "approve_budget",
  description: "审批预算支出",
  parameters: budgetApprovalSchema,
  component: BudgetApprovalCard,
  agentId: "finance-agent"
};
```

资料来源：[packages/angular/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/angular/README.md)

## Vue 集成

### CopilotKitProvider 配置

在 Vue 生态中，HitL 功能通过 `CopilotKitProvider` 的配置项启用：

```vue
<CopilotKitProvider
  runtime-url="/api/copilotkit"
  :self-managed-agents="{}"
  :on-error="onProviderError"
  :a2ui="{ theme: { mode: 'light' } }"
>
  <slot />
</CopilotKitProvider>
```

### 状态信号

| 信号名称 | 类型 | 说明 |
|---------|------|------|
| `runtimeConnectionStatus` | `Signal<CopilotKitCoreRuntimeConnectionStatus>` | 运行时连接状态 |
| `runtimeUrl` | `Signal<string \| undefined>` | 运行时 URL |
| `agents` | `Signal<Record<string, AbstractAgent>>` | 可用 Agent 列表 |

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

## React 集成

### useCopilotAction Hook

在 React 中使用 HitL 功能，通过 `useCopilotAction` 定义需要审批的工具：

```typescript
useCopilotAction({
  name: "approve_budget",
  description: "Prompt the user to review and approve the budget",
  parameters: [
    {
      name: "prompt",
      type: "string",
      required: true,
      description: "The approval prompt to show the user"
    }
  ],
  render: ({ status, result, args }) => {
    // 返回审批 UI 组件
    return <BudgetApprovalCard status={status} result={result} args={args} />;
  },
});
```

资料来源：[examples/showcases/scene-creator/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/scene-creator/README.md)

### render 回调参数

| 参数 | 类型 | 说明 |
|------|------|------|
| `status` | `"in-progress" \| "executing" \| "complete"` | 工具执行状态 |
| `result` | `string \| undefined` | 工具返回结果 |
| `args` | `Record<string, unknown>` | 工具调用参数 |

## 深度 Agent 集成

### LangGraph 深度 Agent

深度 Agent（Deep Agents）模式允许构建多层级、多工具的复杂 Agent 系统，HitL 作为关键节点确保人类参与关键决策点：

```python
agent_graph = create_deep_agent(
    model=ChatOpenAI(model="gpt-5.2"),
    system_prompt=MAIN_SYSTEM_PROMPT,
    tools=[research],
    middleware=[CopilotKitMiddleware()],
    checkpointer=MemorySaver(),
)
```

资料来源：[examples/showcases/deep-agents/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/deep-agents/README.md)

### 研究工具集成

```python
@tool
async def create_character(
    name: str,
    description: str,
    prompt: str,
    state: Annotated[dict, InjectedState]  # 访问共享状态
) -> dict:
    api_key = state.get("apiKey", "")
    image_url = await generate_image(prompt, api_key=api_key)
    return {"name": name, "description": description, "imageUrl": image_url}
```

当 Agent 调用 `create_character` 时，可以在返回前插入 HitL 审批环节。

资料来源：[examples/showcases/scene-creator/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/scene-creator/README.md)

## LlamaIndex 集成

### 工具渲染配置

```typescript
export interface RenderToolCallConfig<Args> {
  name: string;              // 工具名或 "*" 通配符
  args: z.ZodType<Args>;      // Zod Schema
  component: Type<ToolRenderer<Args>>;
  agentId?: string;           // 可选的 Agent 作用域
}
```

### 数据流架构

```mermaid
sequenceDiagram
    participant User
    participant UI as Canvas UI
    participant CK as CopilotKit
    participant Agent as LlamaIndex Agent
    participant Tools
    participant Composio

    User->>UI: 交互操作
    UI->>CK: 通过 useCoAgent 更新状态
    CK->>Agent: 发送状态 + 消息
    Agent->>Agent: 使用 GPT-4o 处理
    Agent->>Tools: 执行工具
    Tools-->>Agent: 返回结果
    Agent->>CK: 返回更新后的状态
    CK->>UI: 同步状态变更
    UI->>User: 显示更新
```

资料来源：[examples/canvas/llamaindex-composio/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/canvas/llamaindex-composio/README.md)

## 预算审批实战案例

### BudgetApprovalCard 组件

在实际业务场景中，预算审批是最常见的 HitL 用例。以下是典型实现结构：

```typescript
interface BudgetApprovalProps {
  status: "in-progress" | "executing" | "complete";
  result?: string;
  args: {
    amount: number;
    category: string;
    description: string;
  };
}

// 组件应处理三种状态：
// 1. in-progress: 显示审批表单
// 2. executing: 显示处理中指示器
// 3. complete: 显示审批结果
```

### 状态机设计

```mermaid
stateDiagram-v2
    [*] --> Pending: 用户发起请求
    Pending --> Reviewing: 渲染审批 UI
    Reviewing --> Approved: 用户点击批准
    Reviewing --> Rejected: 用户点击拒绝
    Reviewing --> Modifying: 用户修改参数
    Approved --> [*]: 返回结果给 Agent
    Rejected --> [*]: 取消操作
    Modifying --> Reviewing: 重新提交
```

## 应用场景

### 1. 财务审批

- 预算支出审批
- 费用报销确认
- 付款授权

资料来源：[examples/showcases/spreadsheet/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/examples/showcases/spreadsheet/README.md)

### 2. 内容生成确认

- AI 生成内容的审核
- 图像生成参数确认
- 文档内容校正

### 3. 数据操作审批

- 数据库修改确认
- 文件删除审批
- 配置变更确认

## 最佳实践

### 设计原则

1. **明确性**：工具描述应清晰说明需要用户确认什么
2. **最小化干预**：只在必要时使用 HitL，避免过度打断流程
3. **快速响应**：审批 UI 应简洁，减少用户等待时间
4. **可追溯性**：记录所有审批决策，便于审计

### 错误处理

```typescript
function onProviderError(event: {
  code: string;
  error: Error;
  context: Record<string, any>;
}) {
  console.error(
    "CopilotKit provider error",
    event.code,
    event.context,
    event.error,
  );
}
```

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

## 调试与日志

### debug 配置选项

| 选项 | 类型 | 说明 |
|------|------|------|
| `events` | `boolean` | 启用事件日志 |
| `lifecycle` | `boolean` | 启用生命周期日志 |
| `verbose` | `boolean` | 启用完整事件负载 |

```typescript
const debug: DebugConfig = {
  events: true,
  lifecycle: true,
  verbose: false
};
```

资料来源：[packages/vue/README.md](https://github.com/CopilotKit/CopilotKit/blob/main/packages/vue/README.md)

## 相关资源

- [CopilotKit 文档](https://docs.copilotkit.ai)
- [LangGraph 深度 Agent 集成](https://docs.copilotkit.ai/integrations/langgraph/deep-agents)
- [构建深度 Agent 前端](https://www.copilotkit.ai/blog/how-to-build-a-frontend-for-langchain-deep-agents-with-copilotkit)

---

---

## Doramagic 踩坑日志

项目：CopilotKit/CopilotKit

摘要：发现 28 个潜在踩坑项，其中 5 个为 high/blocking；最高优先级：安装坑 - 来源证据：@copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never rende…。

## 1. 安装坑 · 来源证据：@copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never rende…

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：@copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never render) — missing post-apply onStateChanged s…
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_409f46a5944945278264fc47e297b72a | https://github.com/CopilotKit/CopilotKit/issues/4885 | 来源类型 github_issue 暴露的待验证使用条件。

## 2. 安装坑 · 来源证据：LangGraph thread history is not hydrated after cold restart until first new message

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：LangGraph thread history is not hydrated after cold restart until first new message
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_e6230695b9a44704927b31badcc61437 | https://github.com/CopilotKit/CopilotKit/issues/3454 | 来源讨论提到 python 相关条件，需在安装/试用前复核。

## 3. 安装坑 · 来源证据：🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install
- 对用户的影响：可能影响升级、迁移或版本选择。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_93af324180434026b3961aff8938714f | https://github.com/CopilotKit/CopilotKit/issues/4911 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 4. 安装坑 · 来源证据：🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_0efd9d1f363946d48e1168b691b0ad4c | https://github.com/CopilotKit/CopilotKit/issues/4893 | 来源类型 github_issue 暴露的待验证使用条件。

## 5. 维护坑 · 来源证据：🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.

- 严重度：high
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个维护/版本相关的待验证问题：🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.
- 对用户的影响：可能阻塞安装或首次运行。
- 建议检查：来源问题仍为 open，Pack Agent 需要复核是否仍影响当前版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_f934812319464fb5acab93b86e00ed00 | https://github.com/CopilotKit/CopilotKit/issues/2481 | 来源讨论提到 node 相关条件，需在安装/试用前复核。

## 6. 安装坑 · 失败模式：installation: v1.55.3

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.55.3
- 对用户的影响：Upgrade or migration may change expected behavior: v1.55.3
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.55.3. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_67f1e990977177cadc4a1a612db8df88 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.55.3 | v1.55.3

## 7. 安装坑 · 失败模式：installation: v1.56.0

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.0
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.0
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.0. Context: Observed when using node, python
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_8ede7507e3ef26c20ae94eb3ff6a0f6f | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.0 | v1.56.0

## 8. 安装坑 · 失败模式：installation: v1.56.1

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.1
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.1
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.1. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_7a12898a84c35b19ec1421880ce10e28 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.1 | v1.56.1

## 9. 安装坑 · 失败模式：installation: v1.56.2

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.2
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.2
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.2. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_7a917a302b0681683ac2482e6cdefd4b | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.2 | v1.56.2

## 10. 安装坑 · 失败模式：installation: v1.56.3

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.3
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.3
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.3. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_386de57caa0b418e81af496ef3e832e1 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.3 | v1.56.3

## 11. 安装坑 · 失败模式：installation: v1.56.4

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.4
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.4
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.4. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_ba48c40eb329f48223cab1a600a088ca | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.4 | v1.56.4

## 12. 安装坑 · 失败模式：installation: v1.56.5

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.56.5
- 对用户的影响：Upgrade or migration may change expected behavior: v1.56.5
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.56.5. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_985bd4475e66904ba7c8c53ae2d6f26a | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.56.5 | v1.56.5

## 13. 安装坑 · 失败模式：installation: v1.57.0

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.57.0
- 对用户的影响：Upgrade or migration may change expected behavior: v1.57.0
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.57.0. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_60e47d47ceb61ba142df495e376e2453 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.57.0 | v1.57.0

## 14. 安装坑 · 失败模式：installation: v1.57.1

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.57.1
- 对用户的影响：Upgrade or migration may change expected behavior: v1.57.1
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.57.1. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_ddfe5da6e5463254a7ca21a7897af5c7 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.57.1 | v1.57.1

## 15. 安装坑 · 失败模式：installation: v1.57.2

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: v1.57.2
- 对用户的影响：Upgrade or migration may change expected behavior: v1.57.2
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: v1.57.2. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_release | fmev_90e0287612ace3e3e390a222dfb52f45 | https://github.com/CopilotKit/CopilotKit/releases/tag/v1.57.2 | v1.57.2

## 16. 安装坑 · 失败模式：installation: 🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: 🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install
- 对用户的影响：Developers may fail before the first successful local run: 🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: 🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_3b813b40a8ae8f0fbc8b566627e75943 | https://github.com/CopilotKit/CopilotKit/issues/4911 | 🐛 Bug: @copilotkit/web-inspector@1.57.2 publishes "workspace:*" reference, breaks pnpm install

## 17. 安装坑 · 失败模式：installation: 🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Functio...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: 🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Backend Tool Calls
- 对用户的影响：Developers may fail before the first successful local run: 🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Backend Tool Calls
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: 🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Backend Tool Calls. Context: Observed when using node
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_ad59dd9220304dfaf2d38e53d40c383e | https://github.com/CopilotKit/CopilotKit/issues/2622 | 🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Backend Tool Calls

## 18. 安装坑 · 失败模式：installation: 🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this installation risk before relying on the project: 🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)
- 对用户的影响：Developers may fail before the first successful local run: 🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: 🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB). Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_bc9acdf64647823252fafc35e7d96b1a | https://github.com/CopilotKit/CopilotKit/issues/4893 | 🐛 Bug: v2 barrel bundles streamdown/mermaid/shiki into all consumers (~+15MB)

## 19. 安装坑 · 来源证据：🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Back…

- 严重度：medium
- 证据强度：source_linked
- 发现：GitHub 社区证据显示该项目存在一个安装相关的待验证问题：🐛 Bug: useRenderToolCall, useFrontendTool, useCopilotAction(disabled, remote ) Render Function Never Triggered for Backend Tool Calls
- 对用户的影响：可能增加新用户试用和生产接入成本。
- 建议检查：来源显示可能已有修复、规避或版本变化，说明书中必须标注适用版本。
- 防护动作：不得脱离来源链接放大为确定性结论；需要标注适用版本和复核状态。
- 证据：community_evidence:github | cevd_36feede08b6a456fa0702692343460fa | https://github.com/CopilotKit/CopilotKit/issues/2622 | 来源讨论提到 npm 相关条件，需在安装/试用前复核。

## 20. 能力坑 · 能力判断依赖假设

- 严重度：medium
- 证据强度：source_linked
- 发现：README/documentation is current enough for a first validation pass.
- 对用户的影响：假设不成立时，用户拿不到承诺的能力。
- 建议检查：将假设转成下游验证清单。
- 防护动作：假设必须转成验证项；没有验证结果前不能写成事实。
- 证据：capability.assumptions | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | README/documentation is current enough for a first validation pass.

## 21. 运行坑 · 失败模式：runtime: LangGraph thread history is not hydrated after cold restart until first new message

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this runtime risk before relying on the project: LangGraph thread history is not hydrated after cold restart until first new message
- 对用户的影响：Developers may hit a documented source-backed failure mode: LangGraph thread history is not hydrated after cold restart until first new message
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: LangGraph thread history is not hydrated after cold restart until first new message. Context: Observed when using python, docker
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_0bf1b00ba8b8f47db81aeaa235b28a67 | https://github.com/CopilotKit/CopilotKit/issues/3454 | LangGraph thread history is not hydrated after cold restart until first new message

## 22. 运行坑 · 失败模式：runtime: 🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it w...

- 严重度：medium
- 证据强度：source_linked
- 发现：Developers should check this runtime risk before relying on the project: 🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.
- 对用户的影响：Developers may hit a documented source-backed failure mode: 🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: 🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.. Context: Observed during installation or first-run setup.
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_96f6f8c3f4d6fc2c196cdd9c8b7b7356 | https://github.com/CopilotKit/CopilotKit/issues/2481 | 🐛 Bug: Cannot send 'TOOL_CALL_START' event: A tool call is already in progress. Complete it with 'TOOL_CALL_END' first.

## 23. 维护坑 · 维护活跃度未知

- 严重度：medium
- 证据强度：source_linked
- 发现：未记录 last_activity_observed。
- 对用户的影响：新项目、停更项目和活跃项目会被混在一起，推荐信任度下降。
- 建议检查：补 GitHub 最近 commit、release、issue/PR 响应信号。
- 防护动作：维护活跃度未知时，推荐强度不能标为高信任。
- 证据：evidence.maintainer_signals | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | last_activity_observed missing

## 24. 安全/权限坑 · 下游验证发现风险项

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：下游已经要求复核，不能在页面中弱化。
- 建议检查：进入安全/权限治理复核队列。
- 防护动作：下游风险存在时必须保持 review/recommendation 降级。
- 证据：downstream_validation.risk_items | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | no_demo; severity=medium

## 25. 安全/权限坑 · 存在评分风险

- 严重度：medium
- 证据强度：source_linked
- 发现：no_demo
- 对用户的影响：风险会影响是否适合普通用户安装。
- 建议检查：把风险写入边界卡，并确认是否需要人工复核。
- 防护动作：评分风险必须进入边界卡，不能只作为内部分数。
- 证据：risks.scoring_risks | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | no_demo; severity=medium

## 26. 能力坑 · 失败模式：capability: @copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / termin...

- 严重度：low
- 证据强度：source_linked
- 发现：Developers should check this capability risk before relying on the project: @copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never render) — missing post-apply onStateChanged subscriber
- 对用户的影响：Developers may hit a documented source-backed failure mode: @copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never render) — missing post-apply onStateChanged subscriber
- 建议检查：Before packaging this project, run the relevant install/config/quickstart check for: @copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never render) — missing post-apply onStateChanged subscriber. Context: Observed when using python
- 防护动作：State this as source-backed community evidence, not as Doramagic reproduction.
- 证据：failure_mode_cluster:github_issue | fmev_0d7ae1046b9b8f5803ce38f0cd0f6a38 | https://github.com/CopilotKit/CopilotKit/issues/4885 | @copilotkitnext/web-inspector: Current State is stale-by-one (connect STATE_SNAPSHOT / terminal STATE_DELTA never render) — missing post-apply onStateChanged subscriber

## 27. 维护坑 · issue/PR 响应质量未知

- 严重度：low
- 证据强度：source_linked
- 发现：issue_or_pr_quality=unknown。
- 对用户的影响：用户无法判断遇到问题后是否有人维护。
- 建议检查：抽样最近 issue/PR，判断是否长期无人处理。
- 防护动作：issue/PR 响应未知时，必须提示维护风险。
- 证据：evidence.maintainer_signals | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | issue_or_pr_quality=unknown

## 28. 维护坑 · 发布节奏不明确

- 严重度：low
- 证据强度：source_linked
- 发现：release_recency=unknown。
- 对用户的影响：安装命令和文档可能落后于代码，用户踩坑概率升高。
- 建议检查：确认最近 release/tag 和 README 安装命令是否一致。
- 防护动作：发布节奏未知或过期时，安装说明必须标注可能漂移。
- 证据：evidence.maintainer_signals | github_repo:655515393 | https://github.com/CopilotKit/CopilotKit | release_recency=unknown

<!-- canonical_name: CopilotKit/CopilotKit; human_manual_source: deepwiki_human_wiki -->
