> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt
# 使用 CopilotKit
[CopilotKit](https://www.copilotkit.ai/) 提供 React 元件,讓你快速將可自訂的 AI copilot 整合至應用程式。搭配 Mastra 使用,即可建構具有雙向狀態同步與互動式 UI 的 AI 應用程式。
CopilotKit 透過 [AG-UI protocol](https://docs.ag-ui.com/) 與 Mastra 通訊。`@ag-ui/mastra` 套件會將 Mastra Agent 公開為 AG-UI 端點,再由 CopilotKit 的 React hook 與元件使用。除了普通聊天外,這還能解鎖一系列體驗:[生成式 UI、human-in-the-loop 與前端 Tool](https://mastra.zisheng.pro/zh-TW/guides/build-your-ui/copilotkit/generative-ui),以及將同一個 Agent 部署至 [Slack 等訊息 channel](https://mastra.zisheng.pro/zh-TW/guides/build-your-ui/copilotkit/channels)。
前往 [CopilotKit 文件](https://docs.copilotkit.ai/),進一步瞭解 CopilotKit 的概念、元件及進階使用模式。
> **資訊:** 若要採用直接在 Next.js API 路由中執行 Mastra 的全端整合方式,請參閱 [CopilotKit 快速入門](https://docs.copilotkit.ai/mastra/quickstart)指南。
前往 Mastra 的 [「UI Dojo」](https://ui-dojo.mastra.ai/),查看 CopilotKit 與 Mastra 整合的實際範例。
## 整合指南
將 Mastra 作為獨立伺服器執行,並把使用 CopilotKit 的 Next.js 前端連接至其 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 前端建立聊天路由。將它與 peer dependency 一併加入 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` 檔案中註冊聊天路由:
```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 執行個體上的 Agent。前端會使用下方所示的 `agent` prop,選擇要與哪個 Agent 通訊。加入 CORS 組態,讓 CopilotKit 前端可存取 Mastra 伺服器。在正式環境部署時,請將 CORS origin 限制為前端網域。
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 應用程式的首頁路由(通常是 `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(請參閱[生成式 UI](https://mastra.zisheng.pro/zh-TW/guides/build-your-ui/copilotkit/generative-ui))之外,CopilotKit 還能讓 Agent 操作你的應用程式,並暫停等候使用者。這兩種模式都使用相同的 Mastra 設定。
### 前端 Tool
讓 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,指示內容要求它使用指定的顏色呼叫 `colorChangeTool`。
### Human-in-the-loop
在 Agent 執行途中暫停,等待使用者核准、編輯或拒絕後再繼續。使用 `useHumanInTheLoop`:其 `render` 函式會接收 `respond` callback,而 Agent 的執行會保持暫停,直到你呼叫該 callback。
```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` 中,讓使用者切換步驟,然後呼叫 `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-TW/docs/agents/agent-approval)指南,前端部分請參閱 CopilotKit 的 [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/useHumanInTheLoop)參考資料。
## 組態選項
針對常見整合點,請使用以下 `registerCopilotKit()` 選項:
| 選項 | 用途 |
| ---------------- | ------------------------------------------------------- |
| `path` | 設定路由路徑,例如 `/copilotkit`。 |
| `resourceId` | 設定對話所使用的 Mastra memory 範圍。 |
| `cors` | 除了 `server.cors` 之外,再設定各路由的 CORS。 |
| `setContext` | 在 Agent 執行前填入 request context,例如驗證資訊或各使用者的 resource ID。 |
| `agents` | 提供預先建構的 AG-UI Agent,取代在 Mastra 執行個體上註冊的 Agent。 |
| `tracingOptions` | 將 Mastra tracing 選項轉送至每次 Agent 執行。 |
端點預設會公開在 Mastra 執行個體上註冊的每個 Agent,而前端使用 `agent` prop 選擇其中一個。其他 CopilotKit runtime 選項會轉送至底層 runtime。例如,請參閱[開放式生成式 UI](https://mastra.zisheng.pro/zh-TW/guides/build-your-ui/copilotkit/generative-ui)中的 `mcpApps`。
## 部署
使用 CopilotKit 部署 Mastra 伺服器時,必須從 bundle 中排除 `@copilotkit/runtime`。此套件包含與 bundling 不相容的 dependency;若納入其中,將會造成 500 錯誤。
> **備註:** 使用 `mastra dev` 開發時不會發生此問題,因為該命令不需要 bundling。不過,凡是為部署而執行 `mastra build`,都會遇到此問題。
將 `@copilotkit/runtime` 套件加入 bundler 的 externals 組態:
```typescript
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})
```