> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt
# 使用 CopilotKit
[CopilotKit](https://www.copilotkit.ai/) 提供 React 元件,讓你快速將可自訂的 AI copilots 整合至應用程式。配合 Mastra,你可建立具雙向狀態同步及互動式 UI 的 AI 應用程式。
CopilotKit 透過 [AG-UI 協議](https://docs.ag-ui.com/)與 Mastra 通訊。`@ag-ui/mastra` 套件會將 Mastra agents 公開為 AG-UI 端點,再由 CopilotKit 的 React hooks 及元件使用。除一般聊天外,這亦帶來多種體驗:[generative UI、human-in-the-loop 及前端 tools](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/generative-ui),以及將同一個 agent 部署至 [Slack 等訊息 channels](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/channels)。
前往 [CopilotKit 文件](https://docs.copilotkit.ai/),進一步了解 CopilotKit 概念、元件及進階使用模式。
> **資訊:** 如要採用全端整合方式,讓 Mastra 直接在 Next.js API routes 中執行,請參閱 [CopilotKit 快速入門](https://docs.copilotkit.ai/mastra/quickstart)指南。
前往 Mastra 的 [「UI Dojo」](https://ui-dojo.mastra.ai/),查看 CopilotKit 與 Mastra 整合的實際範例。
## 整合指南
以獨立伺服器方式執行 Mastra,並將 Next.js 前端(使用 CopilotKit)連接至其 API 端點。
1. 設定目錄結構。可採用以下目錄結構:
```bash
project-root
├── mastra-server
│ ├── src
│ │ └── mastra
│ └── package.json
└── my-copilot-app
└── package.json
```
建立 Mastra 伺服器的初始結構:
**npm**:
```bash
npx create-mastra@latest
```
**pnpm**:
```bash
pnpm dlx create-mastra@latest
```
**Yarn**:
```bash
yarn dlx create-mastra@latest
```
**Bun**:
```bash
bun x create-mastra@latest
```
此命令會開啟互動式精靈,建立新的 Mastra 項目結構。依照提示建立伺服器項目。
前往新建立的 Mastra 伺服器目錄:
```bash
cd mastra-server # Replace with the actual directory name you provided
```
現在你已有可用的基本 Mastra 伺服器項目。
> **備註:** 請確保已在 `.env` 檔案中為 LLM Provider 設定適當的環境變數。
2. 使用 `@ag-ui/mastra` 的 `registerCopilotKit()` 輔助函數,為 CopilotKit 前端建立聊天 route。將它及 peer 依賴套件加入 Mastra 項目:
**npm**:
```bash
npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**pnpm**:
```bash
pnpm add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Yarn**:
```bash
yarn add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
**Bun**:
```bash
bun add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime
```
在 `src/mastra/index.ts` 檔案中註冊聊天 route:
```typescript
import { Mastra } from '@mastra/core/mastra'
import { registerCopilotKit } from '@ag-ui/mastra/copilotkit'
// Rest of the imports...
export const mastra = new Mastra({
// Rest of the configuration...
server: {
cors: {
origin: '*',
allowMethods: ['*'],
allowHeaders: ['*'],
},
apiRoutes: [
registerCopilotKit({
path: '/copilotkit',
resourceId: 'weatherAgent',
}),
],
},
})
```
這會在 `/copilotkit` 以 CopilotKit 相容格式公開 Mastra 實例上的 agents。前端使用下方所示的 `agent` prop 選擇要通訊的 agent。加入 CORS 配置,讓 CopilotKit 前端可存取 Mastra 伺服器。正式部署時,請將 CORS origins 限制為前端網域。
3. 使用以下命令執行 Mastra 伺服器:
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
Mastra 伺服器預設在 `http://localhost:4111` 執行。設定 CopilotKit 前端期間,請保持伺服器運作。
4. 返回上一層的項目根目錄。
```bash
cd ..
```
建立名為 `my-copilot-app` 的 Next.js 項目:
**npm**:
```bash
npx create-next-app@latest my-copilot-app
```
**pnpm**:
```bash
pnpm dlx create-next-app@latest my-copilot-app
```
**Yarn**:
```bash
yarn dlx create-next-app@latest my-copilot-app
```
**Bun**:
```bash
bun x create-next-app@latest my-copilot-app
```
前往新建立的 Next.js 項目目錄:
```bash
cd my-copilot-app
```
5. 安裝用來顯示聊天介面的 CopilotKit UI 套件:
**npm**:
```bash
npm install @copilotkit/react-ui @copilotkit/react-core
```
**pnpm**:
```bash
pnpm add @copilotkit/react-ui @copilotkit/react-core
```
**Yarn**:
```bash
yarn add @copilotkit/react-ui @copilotkit/react-core
```
**Bun**:
```bash
bun add @copilotkit/react-ui @copilotkit/react-core
```
開啟 Next.js 應用程式的首頁 route(通常是 `app/page.tsx` 或 `src/app/page.tsx`),並以下列程式碼取代現有內容,設定基本 CopilotKit 聊天介面:
```typescript
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
)
}
```
`agent` prop 指定要路由至的 Mastra agent,其值必須與 Mastra 實例 `agents` map 中的 key 相符。
6. 確保 Mastra 伺服器及 CopilotKit 前端都正在執行,然後啟動 Next.js 開發伺服器:
**npm**:
```bash
npm run dev
```
**pnpm**:
```bash
pnpm run dev
```
**Yarn**:
```bash
yarn dev
```
**Bun**:
```bash
bun run dev
```
在瀏覽器中開啟應用程式,並與 agent 對話。
CopilotKit 前端現在會與獨立的 Mastra agent 伺服器通訊。
## 聊天 UI 選項
`CopilotChat` 會算繪行內、全高度的聊天介面。CopilotKit 另外提供兩個可直接替換並共用相同 props 的介面:
- `CopilotSidebar`:停靠在應用程式側邊的可摺疊面板。
- `CopilotPopup`:開啟聊天視窗的浮動按鈕。
替換元件即可更改介面。三者都透過相同的 `CopilotKit` Provider 連接:
```typescript
import { CopilotSidebar } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
{/* your app */}
)
}
```
如要完全自訂聊天 UI(使用自己的元件),請參閱 [CopilotKit headless UI 指南](https://docs.copilotkit.ai/)。
## 應用程式控制及互動
除了將 agent 輸出算繪成 UI(請參閱 [generative UI](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/generative-ui)),CopilotKit 亦可讓 agent 操作應用程式,並暫停以等待使用者。兩種模式均使用相同的 Mastra 設定。
### 前端 tools
讓 agent 能夠操作應用程式。使用 `useFrontendTool` 在前端註冊 Tool;agent 呼叫 Tool 時,`handler` 會在瀏覽器中執行:
```tsx
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useFrontendTool } from '@copilotkit/react-core'
function Chat() {
useFrontendTool({
name: 'colorChangeTool',
description: 'Changes the background color',
parameters: [
{ name: 'color', type: 'string', description: 'The color to change to', required: true },
],
handler: ({ color }) => {
document.body.style.setProperty('--background', color)
},
})
return
}
export default function Page() {
return (
)
}
```
相應的 Mastra agent 是一般 agent,其 instructions 要求它以指定顏色呼叫 `colorChangeTool`。
### Human-in-the-loop
在 agent 執行期間暫停,等待使用者核准、編輯或拒絕後再繼續。使用 `useHumanInTheLoop`:其 `render` 函數會接收 `respond` callback,而 agent 會一直暫停,直至你呼叫它。
```tsx
import { CopilotChat } from '@copilotkit/react-ui'
import { CopilotKit, useHumanInTheLoop } from '@copilotkit/react-core'
import { StepsFeedback } from '@/components/steps-feedback'
function Chat() {
useHumanInTheLoop({
name: 'generate_task_steps',
description: 'Generates a list of steps for the user to perform',
parameters: [
{
name: 'steps',
type: 'object[]',
attributes: [
{ name: 'description', type: 'string' },
{ name: 'status', type: 'string', enum: ['enabled', 'disabled', 'executing'] },
],
},
],
available: 'enabled',
// `respond` resumes the agent with the user's edited selection.
render: ({ args, respond, status }) => (
),
})
return
}
export default function Page() {
return (
)
}
```
在 `StepsFeedback` 內,讓使用者切換 steps,然後呼叫 `respond({ accepted: true, steps })` 以繼續 agent,或呼叫 `respond({ accepted: false })` 拒絕。Agent 會讀取傳回值並繼續執行。完整元件請參閱 [UI Dojo](https://ui-dojo.mastra.ai/)。
以上範例使用用戶端 Tool:agent 呼叫 `generate_task_steps`,前端則透過 `respond` 完成它。Mastra 亦可在伺服器上暫停,在 Tool 執行前暫停其呼叫,讓使用者核准或提供輸入。此方式的後端設定請參閱 Mastra 的 [Agent 核准](https://mastra.zisheng.pro/zh-HK/docs/agents/agent-approval)指南;前端設定則請參閱 CopilotKit 的 [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/useHumanInTheLoop) 參考。
## 配置選項
以下 `registerCopilotKit()` 選項適用於常見整合點:
| 選項 | 用途 |
| ---------------- | --------------------------------------------- |
| `path` | 設定 route 路徑,例如 `/copilotkit`。 |
| `resourceId` | 限定對話的 Mastra 記憶體範圍。 |
| `cors` | 除 `server.cors` 外,再配置每個 route 的 CORS。 |
| `setContext` | 在 agents 執行前填入請求上下文,例如驗證或每個使用者的 resource ID。 |
| `agents` | 使用預先建立的 AG-UI agents,而非 Mastra 實例上註冊的 agents。 |
| `tracingOptions` | 將 Mastra tracing 選項轉交每次 agent 執行。 |
端點預設公開 Mastra 實例上註冊的每個 agent,前端則使用 `agent` prop 選擇。其他 CopilotKit runtime 選項會轉交底層 runtime。例如,請參閱 [Open-ended generative UI](https://mastra.zisheng.pro/zh-HK/guides/build-your-ui/copilotkit/generative-ui) 的 `mcpApps`。
## 部署
部署配合 CopilotKit 的 Mastra 伺服器時,必須從 bundle 排除 `@copilotkit/runtime`。此套件包含與 bundling 不相容的依賴套件;如包含在內,會導致 500 錯誤。
> **備註:** 使用 `mastra dev` 開發時不會出現此問題,因為它毋須 bundling。不過,任何使用 `mastra build` 部署的人都會遇到此問題。
將 `@copilotkit/runtime` 套件加入 bundler externals 配置:
```typescript
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})
```