使用 CopilotKit
CopilotKit 提供 React 元件,讓你快速將可自訂的 AI copilot 整合至應用程式。搭配 Mastra 使用,即可建構具有雙向狀態同步與互動式 UI 的 AI 應用程式。
CopilotKit 透過 AG-UI protocol 與 Mastra 通訊。@ag-ui/mastra 套件會將 Mastra Agent 公開為 AG-UI 端點,再由 CopilotKit 的 React hook 與元件使用。除了普通聊天外,這還能解鎖一系列體驗:生成式 UI、human-in-the-loop 與前端 Tool,以及將同一個 Agent 部署至 Slack 等訊息 channel。
前往 CopilotKit 文件,進一步瞭解 CopilotKit 的概念、元件及進階使用模式。
若要採用直接在 Next.js API 路由中執行 Mastra 的全端整合方式,請參閱 CopilotKit 快速入門指南。
前往 Mastra 的 「UI Dojo」,查看 CopilotKit 與 Mastra 整合的實際範例。
整合指南「整合指南」的直接連結
將 Mastra 作為獨立伺服器執行,並把使用 CopilotKit 的 Next.js 前端連接至其 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 前端建立聊天路由。將它與 peer dependency 一併加入 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檔案中註冊聊天路由: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 執行個體上的 Agent。前端會使用下方所示的agentprop,選擇要與哪個 Agent 通訊。加入 CORS 組態,讓 CopilotKit 前端可存取 Mastra 伺服器。在正式環境部署時,請將 CORS origin 限制為前端網域。使用下列命令執行 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 應用程式的首頁路由(通常是
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(請參閱生成式 UI)之外,CopilotKit 還能讓 Agent 操作你的應用程式,並暫停等候使用者。這兩種模式都使用相同的 Mastra 設定。
前端 Tool「前端 Tool」的直接連結
讓 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,指示內容要求它使用指定的顏色呼叫 colorChangeTool。
Human-in-the-loop「Human-in-the-loop」的直接連結
在 Agent 執行途中暫停,等待使用者核准、編輯或拒絕後再繼續。使用 useHumanInTheLoop:其 render 函式會接收 respond callback,而 Agent 的執行會保持暫停,直到你呼叫該 callback。
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 中,讓使用者切換步驟,然後呼叫 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 | 設定路由路徑,例如 /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中的 mcpApps。
部署「部署」的直接連結
使用 CopilotKit 部署 Mastra 伺服器時,必須從 bundle 中排除 @copilotkit/runtime。此套件包含與 bundling 不相容的 dependency;若納入其中,將會造成 500 錯誤。
使用 mastra dev 開發時不會發生此問題,因為該命令不需要 bundling。不過,凡是為部署而執行 mastra build,都會遇到此問題。
將 @copilotkit/runtime 套件加入 bundler 的 externals 組態:
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})