使用 CopilotKit
CopilotKit 提供 React 元件,讓你快速將可自訂的 AI copilots 整合至應用程式。配合 Mastra,你可建立具雙向狀態同步及互動式 UI 的 AI 應用程式。
CopilotKit 透過 AG-UI 協議與 Mastra 通訊。@ag-ui/mastra 套件會將 Mastra agents 公開為 AG-UI 端點,再由 CopilotKit 的 React hooks 及元件使用。除一般聊天外,這亦帶來多種體驗:generative UI、human-in-the-loop 及前端 tools,以及將同一個 agent 部署至 Slack 等訊息 channels。
前往 CopilotKit 文件,進一步了解 CopilotKit 概念、元件及進階使用模式。
如要採用全端整合方式,讓 Mastra 直接在 Next.js API routes 中執行,請參閱 CopilotKit 快速入門指南。
前往 Mastra 的 「UI Dojo」,查看 CopilotKit 與 Mastra 整合的實際範例。
整合指南整合指南 的直接連結
以獨立伺服器方式執行 Mastra,並將 Next.js 前端(使用 CopilotKit)連接至其 API 端點。
設定目錄結構。可採用以下目錄結構:
project-root├── mastra-server│ ├── src│ │ └── mastra│ └── package.json└── my-copilot-app└── package.json建立 Mastra 伺服器的初始結構:
- npm
- pnpm
- Yarn
- Bun
npx create-mastra@latestpnpm dlx create-mastra@latestyarn dlx create-mastra@latestbun x create-mastra@latest此命令會開啟互動式精靈,建立新的 Mastra 項目結構。依照提示建立伺服器項目。
前往新建立的 Mastra 伺服器目錄:
cd mastra-server # Replace with the actual directory name you provided現在你已有可用的基本 Mastra 伺服器項目。
備註請確保已在
.env檔案中為 LLM Provider 設定適當的環境變數。使用
@ag-ui/mastra的registerCopilotKit()輔助函數,為 CopilotKit 前端建立聊天 route。將它及 peer 依賴套件加入 Mastra 項目:- npm
- pnpm
- Yarn
- Bun
npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimepnpm add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimeyarn add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtimebun add @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime在
src/mastra/index.ts檔案中註冊聊天 route:src/mastra/index.tsimport { 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。前端使用下方所示的agentprop 選擇要通訊的 agent。加入 CORS 配置,讓 CopilotKit 前端可存取 Mastra 伺服器。正式部署時,請將 CORS origins 限制為前端網域。使用以下命令執行 Mastra 伺服器:
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run devMastra 伺服器預設在
http://localhost:4111執行。設定 CopilotKit 前端期間,請保持伺服器運作。返回上一層的項目根目錄。
cd ..建立名為
my-copilot-app的 Next.js 項目:- npm
- pnpm
- Yarn
- Bun
npx create-next-app@latest my-copilot-apppnpm dlx create-next-app@latest my-copilot-appyarn dlx create-next-app@latest my-copilot-appbun x create-next-app@latest my-copilot-app前往新建立的 Next.js 項目目錄:
cd my-copilot-app安裝用來顯示聊天介面的 CopilotKit UI 套件:
- npm
- pnpm
- Yarn
- Bun
npm install @copilotkit/react-ui @copilotkit/react-corepnpm add @copilotkit/react-ui @copilotkit/react-coreyarn add @copilotkit/react-ui @copilotkit/react-corebun add @copilotkit/react-ui @copilotkit/react-core開啟 Next.js 應用程式的首頁 route(通常是
app/page.tsx或src/app/page.tsx),並以下列程式碼取代現有內容,設定基本 CopilotKit 聊天介面:app/page.tsximport { CopilotChat } from '@copilotkit/react-ui'import { CopilotKit } from '@copilotkit/react-core'import '@copilotkit/react-ui/styles.css'export default function Home() {return (<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="weatherAgent"><CopilotChatlabels={{title: 'Weather Agent',initial: 'Hi! 👋 Ask me about the weather, forecasts, and climate.',}}/></CopilotKit>)}agentprop 指定要路由至的 Mastra agent,其值必須與 Mastra 實例agentsmap 中的 key 相符。確保 Mastra 伺服器及 CopilotKit 前端都正在執行,然後啟動 Next.js 開發伺服器:
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run dev在瀏覽器中開啟應用程式,並與 agent 對話。
CopilotKit 前端現在會與獨立的 Mastra agent 伺服器通訊。
聊天 UI 選項聊天 UI 選項 的直接連結
CopilotChat 會算繪行內、全高度的聊天介面。CopilotKit 另外提供兩個可直接替換並共用相同 props 的介面:
CopilotSidebar:停靠在應用程式側邊的可摺疊面板。CopilotPopup:開啟聊天視窗的浮動按鈕。
替換元件即可更改介面。三者都透過相同的 CopilotKit Provider 連接:
import { CopilotSidebar } from '@copilotkit/react-ui'
import { CopilotKit } from '@copilotkit/react-core'
import '@copilotkit/react-ui/styles.css'
export default function Home() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="weatherAgent">
<CopilotSidebar
labels={{
title: 'Weather Agent',
initial: 'Hi! 👋 Ask me about the weather.',
}}
/>
{/* your app */}
</CopilotKit>
)
}
如要完全自訂聊天 UI(使用自己的元件),請參閱 CopilotKit headless UI 指南。
應用程式控制及互動應用程式控制及互動 的直接連結
除了將 agent 輸出算繪成 UI(請參閱 generative UI),CopilotKit 亦可讓 agent 操作應用程式,並暫停以等待使用者。兩種模式均使用相同的 Mastra 設定。
前端 tools前端 tools 的直接連結
讓 agent 能夠操作應用程式。使用 useFrontendTool 在前端註冊 Tool;agent 呼叫 Tool 時,handler 會在瀏覽器中執行:
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 <CopilotChat labels={{ title: 'Background Color Changer' }} />
}
export default function Page() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="bgColorAgent">
<Chat />
</CopilotKit>
)
}
相應的 Mastra agent 是一般 agent,其 instructions 要求它以指定顏色呼叫 colorChangeTool。
Human-in-the-loopHuman-in-the-loop 的直接連結
在 agent 執行期間暫停,等待使用者核准、編輯或拒絕後再繼續。使用 useHumanInTheLoop:其 render 函數會接收 respond callback,而 agent 會一直暫停,直至你呼叫它。
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 }) => (
<StepsFeedback args={args} respond={respond} status={status} />
),
})
return <CopilotChat labels={{ title: 'Planning Agent' }} />
}
export default function Page() {
return (
<CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="planningAgent">
<Chat />
</CopilotKit>
)
}
在 StepsFeedback 內,讓使用者切換 steps,然後呼叫 respond({ accepted: true, steps }) 以繼續 agent,或呼叫 respond({ accepted: false }) 拒絕。Agent 會讀取傳回值並繼續執行。完整元件請參閱 UI Dojo。
以上範例使用用戶端 Tool:agent 呼叫 generate_task_steps,前端則透過 respond 完成它。Mastra 亦可在伺服器上暫停,在 Tool 執行前暫停其呼叫,讓使用者核准或提供輸入。此方式的後端設定請參閱 Mastra 的 Agent 核准指南;前端設定則請參閱 CopilotKit 的 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 的 mcpApps。
部署部署 的直接連結
部署配合 CopilotKit 的 Mastra 伺服器時,必須從 bundle 排除 @copilotkit/runtime。此套件包含與 bundling 不相容的依賴套件;如包含在內,會導致 500 錯誤。
使用 mastra dev 開發時不會出現此問題,因為它毋須 bundling。不過,任何使用 mastra build 部署的人都會遇到此問題。
將 @copilotkit/runtime 套件加入 bundler externals 配置:
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})