使用 CopilotKit
CopilotKit 提供 React 组件,可将可自定义的 AI copilot 快速集成到应用中。结合 Mastra,你可以构建具备双向状态同步和交互式 UI 的 AI 应用。
CopilotKit 通过 AG-UI 协议与 Mastra 通信。@ag-ui/mastra 包将 Mastra Agent 暴露为 AG-UI 端点,再由 CopilotKit 的 React hook 和组件使用。这在普通聊天之上解锁了一系列体验,包括生成式 UI、人在回路和前端 Tool,还可以将同一个 Agent 部署到 Slack 等消息 Channel。
访问 CopilotKit 文档,进一步了解 CopilotKit 的概念、组件和高级用法模式。
如需让 Mastra 直接运行在 Next.js API 路由中的全栈集成方式,请参阅 CopilotKit 快速入门指南。
访问 Mastra 的 “UI Dojo”,查看 CopilotKit 与 Mastra 集成的实际示例。
集成指南集成指南的直接链接
将 Mastra 作为独立 Server 运行,并把使用 CopilotKit 的 Next.js 前端连接到其 API 端点。
设置目录结构。可以采用如下目录结构:
project-root├── mastra-server│ ├── src│ │ └── mastra│ └── package.json└── my-copilot-app└── package.json初始化 Mastra Server:
- npm
- pnpm
- Yarn
- Bun
npx create-mastra@latestpnpm dlx create-mastra@latestyarn dlx create-mastra@latestbun x create-mastra@latest该命令会打开交互式向导,用于搭建新的 Mastra 项目。按照提示创建 Server 项目。
进入新创建的 Mastra Server 目录:
cd mastra-server # Replace with the actual directory name you provided现在,基础 Mastra Server 项目已准备就绪。
备注请确保已在
.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 Server。在生产部署中,请将 CORS 来源限制为你的前端域名。使用以下命令运行 Mastra Server:
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run dev默认情况下,Mastra Server 在
http://localhost:4111上运行。设置 CopilotKit 前端期间,请保持该 Server 运行。向上一级返回项目根目录。
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 Server 和 CopilotKit 前端均在运行,然后启动 Next.js 开发 Server:
- npm
- pnpm
- Yarn
- Bun
npm run devpnpm run devyarn devbun run dev在浏览器中打开应用,与 Agent 聊天。
CopilotKit 前端现在可以与独立的 Mastra Agent Server 通信。
聊天 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 的无头 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。
人在回路人在回路的直接链接
在 Agent 运行过程中暂停,等待用户批准、编辑或拒绝后再继续。使用 useHumanInTheLoop:其 render 函数会接收 respond 回调,在调用该回调之前,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 中,让用户切换步骤,然后调用 respond({ accepted: true, steps }) 恢复 Agent,或调用 respond({ accepted: false }) 拒绝。Agent 会读取返回值并据此继续。完整组件请参阅 UI Dojo。
上例使用客户端 Tool:Agent 调用 generate_task_steps,前端通过 respond 完成该调用。Mastra 也可以在 Server 上暂停,在 Tool 调用执行前将其挂起,以便由人工批准或提供输入。对于这种方式,后端请参阅 Mastra 的 Agent 审批指南,前端请参阅 CopilotKit 的 useHumanInTheLoop Reference。
配置选项配置选项的直接链接
常见集成点可使用以下 registerCopilotKit() 选项:
| 选项 | 用途 |
|---|---|
path | 设置路由路径,例如 /copilotkit。 |
resourceId | 限定对话使用的 Mastra Memory 范围。 |
cors | 除 server.cors 外,再配置每个路由的 CORS。 |
setContext | 在 Agent 运行前填充请求上下文,例如身份验证信息或每用户资源 ID。 |
agents | 提供预先构造的 AG-UI Agent,而不是使用已在 Mastra 实例上注册的 Agent。 |
tracingOptions | 将 Mastra tracing 选项转发给每次 Agent 运行。 |
默认情况下,该端点会暴露 Mastra 实例中注册的所有 Agent,前端通过 agent prop 选择其中一个。其他 CopilotKit Runtime 选项会转发到底层 Runtime。例如,有关 mcpApps 的信息,请参阅开放式生成式 UI。
部署部署的直接链接
部署集成 CopilotKit 的 Mastra Server 时,必须从 bundle 中排除 @copilotkit/runtime。该包包含与 bundling 不兼容的依赖;如果将其打包,会导致 500 错误。
使用 mastra dev 开发时不会出现此问题,因为它不需要 bundling。但在部署时运行 mastra build 则会遇到此问题。
将 @copilotkit/runtime 包添加到 bundler 的 externals 配置中:
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})