> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt
# CopilotKit 生成式 UI
生成式 UI 是指由 Agent 協助建立、讓用戶可以互動的介面。CopilotKit 將這些介面編排在單一軸線上,稱為**生成式 UI 光譜**;它從由開發者控制(每個像素都由你決定),一路延伸至由 Agent 自行創建(呈現的介面完全由 Agent 掌控)。你在軸線上選擇的位置,就是可預測性與涵蓋範圍之間的取捨。
此光譜分為三個層級:
| 層級 | 由誰控制介面 | 基本機制 |
| ------- | ------------------------------------- | ---------------------------- |
| **受控** | 組件由你編寫。Agent 選擇要使用哪個組件,以及要傳入甚麼資料。 | Tool 呼叫呈現、狀態呈現、推理、將組件用作 Tool |
| **聲明式** | Agent 輸出結構化規格。前端使用你已註冊的目錄來組合介面。 | A2UI(固定結構及彈性變體) |
| **開放式** | UI 在其他地方(MCP 伺服器)創建,而你將它置於 Sandbox 中。 | MCP Apps |
每個層級都是一個透過 `registerCopilotKit()` 公開的 Mastra Agent(請參閱 [CopilotKit 概覽](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/overview)),並配合前端相應的 CopilotKit hook。要了解完整概念,請參閱 CopilotKit 的[生成式 UI 光譜](https://www.copilotkit.ai/generative-ui-spectrum)及[生成式 UI 概覽](https://docs.copilotkit.ai/concepts/generative-ui-overview)。
> **提示:** Mastra 的 [UI Dojo](https://ui-dojo.mastra.ai/) 提供可實際運行的 CopilotKit 範例。你可以瀏覽 `src/pages/copilot-kit` 下的原始碼。
## 受控
你提供一組固定的組件。Agent 選擇要呈現的組件,並提供所需資料。這種可預測且能保障品牌一致性的方式,很適合高流量介面。受控層級的基本機制使用 CopilotKit v2 API,並從 `@copilotkit/react-core/v2` 匯入。
### 呈現 Tool 呼叫
將 Agent 的 Tool 呼叫呈現為 React 組件。按一般方式在 Mastra 伺服器上定義 Agent 及 Tool:
```typescript
import { Agent } from '@mastra/core/agent'
import { weatherTool } from '../tools/weather-tool'
export const weatherAgent = new Agent({
id: 'weather-agent',
name: 'Weather Agent',
instructions: 'Use the weatherTool to fetch current weather data.',
model: 'openai/gpt-5.6-sol',
tools: { weatherTool },
})
```
在前端使用 `useRenderTool`,按名稱為 Tool 註冊呈現器。它只負責呈現(不會執行 Tool);`render` 函式會接收 Tool 呼叫的 `status`,而在 Agent 傳回結果後,也會接收其 `result`:
```tsx
import { z } from 'zod'
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useRenderTool } from '@copilotkit/react-core/v2'
import { Weather } from '@/components/weather'
function Chat() {
useRenderTool(
{
name: 'weatherTool',
parameters: z.object({ location: z.string() }),
render: ({ status, result }) => {
if (status !== 'complete') {
return
Retrieving weather...
}
return
},
},
[],
)
return
}
export default function Page() {
return (
)
}
```
由於 Mastra 會逐步串流 Tool 呼叫的引數,`render` 函式會在引數抵達時重複呼叫,讓 UI 可在 Agent 運作期間逐步繪製。
### 將組件用作 Tool
註冊 React 組件,讓 Agent 將它當作 Tool 呼叫。CopilotKit 會在內容中直接呈現該組件,並傳入具備類型的 props(使用 Zod schema 定義):
```tsx
import { z } from 'zod'
import { useComponent } from '@copilotkit/react-core/v2'
const schema = z.object({ text: z.string() })
function Callout({ text }: z.infer) {
return {text}
}
function Chat() {
useComponent({ name: 'callout', render: Callout, parameters: schema }, [])
return
}
```
Agent 會像呼叫任何其他 Tool 一樣呼叫 `callout`,而 CopilotKit 則使用 Agent 傳入的 props 呈現 `Callout`。
### 狀態呈現
根據 Agent 的狀態呈現 UI,並隨串流內容重新呈現。在 Mastra 中,Agent 狀態就是 Agent 的工作記憶,會隨變更串流至用戶端。使用 `useAgent` 讀取狀態;`agent.state` 具備響應性,因此組件會自動更新:
```tsx
import { useAgent } from '@copilotkit/react-core/v2'
function TaskBoard() {
const { agent } = useAgent()
const tasks = (agent.state.tasks as any[]) ?? []
return (
{tasks.map((task, i) => (
-
{task.title}: {task.status}
))}
)
}
```
### 推理
推理功能毋須配置:當你的 Mastra Agent 使用具備推理能力的模型運行時,`CopilotChat` 會以專用訊息類型,直接在內容中呈現模型的思考過程,毋須加入額外程式碼。如要自訂樣式,請將你自己的組件傳至 `CopilotChat` 的 `reasoningMessage` slot。詳情請參閱 CopilotKit 的[生成式 UI 指南](https://docs.copilotkit.ai/)。
## 聲明式
你毋須為每個 Tool 設定固定組件,而是註冊一套具備類型的基本構件目錄,再由 Agent 按每項請求將它們組合成 UI 樹。CopilotKit 將這種方式稱為 **A2UI**(Agent-to-UI),並提供固定結構及彈性兩種變體。它適合像素精準度不及涵蓋範圍重要的各種次要互動。
最簡單直接的做法,是將你的目錄傳入 `` Provider。只需這一個 prop,即可啟用 A2UI 呈現,並將 A2UI Tool 注入 Agent,因此毋須修改後端:
```tsx
import { CopilotKit } from '@copilotkit/react-core/v2'
import { myCatalog } from './a2ui-catalog'
export default function Page() {
return (
{/* your app */}
)
}
```
此目錄會定義基本構件(其 schema)及呈現器(每個基本構件的顯示方式)。在固定結構變體中,組件會預先編寫,而 Agent 的 Tool 只會提供資料。彈性變體則讓 Agent 更自由地組合 UI 樹。請參閱 CopilotKit 的 [A2UI 文件](https://docs.copilotkit.ai/a2a/generative-ui/a2ui)。
## 開放式
在光譜的最遠端,Agent 掌控整個介面:UI 在其他地方創建,並置於你應用程式的 Sandbox 內。CopilotKit 透過 **MCP Apps** 支援這種方式,由 MCP 伺服器提供 UI,並在你的應用程式內呈現。此層級以確定性換取新穎性,也是光譜上最具實驗性的一點。
最簡單直接的做法可讓前端維持不變:現有的 `` Provider 已經足夠。在後端,使用 `mcpApps` 選項,將 `registerCopilotKit()` 指向一個或多個 MCP 伺服器(此選項會轉交至 CopilotKit runtime):
```typescript
registerCopilotKit({
path: '/copilotkit',
resourceId: 'weatherAgent',
mcpApps: {
servers: [{ type: 'http', url: 'http://localhost:3108/mcp', serverId: 'my-server' }],
},
})
```
當 Agent 呼叫 MCP App Tool 時,CopilotKit 會擷取該 Tool 的 UI,並在聊天中呈現,毋須加入額外的前端程式碼。請參閱 CopilotKit 的 [MCP Apps 文件](https://docs.copilotkit.ai/agno/generative-ui/mcp-apps)。
## 應用程式控制及互動功能
有些功能位於光譜旁邊,而非光譜之上:它們控制你的應用程式,或在執行流程中加入關卡,而不是呈現 Agent 輸出。兩者均在[開始使用](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/overview)中介紹:
- **前端 Tool**(`useFrontendTool`):讓 Agent 操作你的應用程式。這屬於 CopilotKit 另一個獨立的 [App Control](https://docs.copilotkit.ai/) 概念,並包括共享狀態及 Agent context。
- **Human-in-the-loop**:暫停執行流程,等待用戶批准或修改。後端方面,請參閱 Mastra 的 [Agent 批准機制](https://mastra.zisheng.pro/zh-HK/docs/agents/agent-approval);前端方面,請參閱 CopilotKit 的 [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/useHumanInTheLoop)。