> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt
# CopilotKit 生成式 UI
生成式 UI 是指由 Agent 協助建立、且使用者可與之互動的介面。CopilotKit 以單一軸線,也就是**生成式 UI 光譜**,來組織這些介面;光譜的一端由作者控制(每個像素都由你決定),另一端則由 Agent 自行設計(轉譯出的介面由 Agent 掌控)。你在軸線上的位置,代表可預測性與涵蓋廣度之間的取捨。
此光譜分為三個層級:
| 層級 | 介面控制者 | 基礎功能 |
| ------- | ------------------------------------- | ---------------------------- |
| **受控式** | 元件由你撰寫。Agent 選擇要使用的元件及要傳入的資料。 | Tool 呼叫轉譯、狀態轉譯、推理、以元件作為 Tool |
| **宣告式** | Agent 發出結構化規格。前端使用你註冊的目錄加以組合。 | A2UI(固定 schema 與彈性變體) |
| **開放式** | UI 在其他位置(MCP server)產生,再由你放入 Sandbox。 | MCP Apps |
每個層級都由透過 `registerCopilotKit()` 公開的 Mastra Agent(請參閱 [CopilotKit 概觀](https://mastra.zisheng.pro/zh-TW/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 註冊 renderer。它只負責轉譯(不會執行 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 tree。CopilotKit 將此機制稱為 **A2UI**(Agent-to-UI),並提供固定 schema 與彈性變體。它適合涵蓋面比像素級精準度更重要的長尾次要互動。
最簡便的方式是將目錄傳入 `` 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)與 renderer(各基礎功能的顯示方式)。在固定 schema 變體中,元件會預先撰寫完成,Agent 的 Tool 只提供資料。彈性變體則讓 Agent 能更自由地組合 tree。請參閱 CopilotKit 的 [A2UI 文件](https://docs.copilotkit.ai/a2a/generative-ui/a2ui)。
## 開放式
在光譜的最遠端,整個介面由 Agent 掌控:UI 在其他位置產生,再放入應用程式的 Sandbox 中。CopilotKit 透過 **MCP Apps** 支援此模式,由 MCP server 提供 UI,並在你的應用程式內轉譯。此層級以確定性換取創新,也是光譜中最具實驗性的位置。
最簡便的方式完全不需變更前端:現有的 `` Provider 就已足夠。在後端,使用 `mcpApps` 選項讓 `registerCopilotKit()` 指向一或多個 MCP server(此選項會轉送至 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-TW/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-TW/docs/agents/agent-approval);前端部分請參閱 CopilotKit 的 [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/useHumanInTheLoop)。