> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # 使用 CopilotKit [CopilotKit](https://www.copilotkit.ai/) 提供 React 组件,可将可自定义的 AI copilot 快速集成到应用中。结合 Mastra,你可以构建具备双向状态同步和交互式 UI 的 AI 应用。 CopilotKit 通过 [AG-UI 协议](https://docs.ag-ui.com/)与 Mastra 通信。`@ag-ui/mastra` 包将 Mastra Agent 暴露为 AG-UI 端点,再由 CopilotKit 的 React hook 和组件使用。这在普通聊天之上解锁了一系列体验,包括[生成式 UI、人在回路和前端 Tool](https://mastra.zisheng.pro/guides/build-your-ui/copilotkit/generative-ui),还可以将同一个 Agent 部署到 [Slack 等消息 Channel](https://mastra.zisheng.pro/guides/build-your-ui/copilotkit/channels)。 访问 [CopilotKit 文档](https://docs.copilotkit.ai/),进一步了解 CopilotKit 的概念、组件和高级用法模式。 > **信息:** 如需让 Mastra 直接运行在 Next.js API 路由中的全栈集成方式,请参阅 [CopilotKit 快速入门](https://docs.copilotkit.ai/mastra/quickstart)指南。 访问 Mastra 的 [“UI Dojo”](https://ui-dojo.mastra.ai/),查看 CopilotKit 与 Mastra 集成的实际示例。 ## 集成指南 将 Mastra 作为独立 Server 运行,并把使用 CopilotKit 的 Next.js 前端连接到其 API 端点。 1. 设置目录结构。可以采用如下目录结构: ```bash project-root ├── mastra-server │ ├── src │ │ └── mastra │ └── package.json └── my-copilot-app └── package.json ``` 初始化 Mastra Server: **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 项目。按照提示创建 Server 项目。 进入新创建的 Mastra Server 目录: ```bash cd mastra-server # Replace with the actual directory name you provided ``` 现在,基础 Mastra Server 项目已准备就绪。 > **备注:** 请确保已在 `.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 Server。在生产部署中,请将 CORS 来源限制为你的前端域名。 3. 使用以下命令运行 Mastra Server: **npm**: ```bash npm run dev ``` **pnpm**: ```bash pnpm run dev ``` **Yarn**: ```bash yarn dev ``` **Bun**: ```bash bun run dev ``` 默认情况下,Mastra Server 在 `http://localhost:4111` 上运行。设置 CopilotKit 前端期间,请保持该 Server 运行。 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 Server 和 CopilotKit 前端均在运行,然后启动 Next.js 开发 Server: **npm**: ```bash npm run dev ``` **pnpm**: ```bash pnpm run dev ``` **Yarn**: ```bash yarn dev ``` **Bun**: ```bash bun run dev ``` 在浏览器中打开应用,与 Agent 聊天。 CopilotKit 前端现在可以与独立的 Mastra Agent Server 通信。 ## 聊天 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 的无头 UI 指南](https://docs.copilotkit.ai/)。 ## 应用控制与交互 除了将 Agent 输出渲染为 UI(参阅[生成式 UI](https://mastra.zisheng.pro/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`。 ### 人在回路 在 Agent 运行过程中暂停,等待用户批准、编辑或拒绝后再继续。使用 `useHumanInTheLoop`:其 `render` 函数会接收 `respond` 回调,在调用该回调之前,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` 中,让用户切换步骤,然后调用 `respond({ accepted: true, steps })` 恢复 Agent,或调用 `respond({ accepted: false })` 拒绝。Agent 会读取返回值并据此继续。完整组件请参阅 [UI Dojo](https://ui-dojo.mastra.ai/)。 上例使用客户端 Tool:Agent 调用 `generate_task_steps`,前端通过 `respond` 完成该调用。Mastra 也可以在 Server 上暂停,在 Tool 调用执行前将其挂起,以便由人工批准或提供输入。对于这种方式,后端请参阅 Mastra 的 [Agent 审批](https://mastra.zisheng.pro/docs/agents/agent-approval)指南,前端请参阅 CopilotKit 的 [`useHumanInTheLoop`](https://docs.copilotkit.ai/reference/hooks/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](https://mastra.zisheng.pro/guides/build-your-ui/copilotkit/generative-ui)。 ## 部署 部署集成 CopilotKit 的 Mastra Server 时,必须从 bundle 中排除 `@copilotkit/runtime`。该包包含与 bundling 不兼容的依赖;如果将其打包,会导致 500 错误。 > **备注:** 使用 `mastra dev` 开发时不会出现此问题,因为它不需要 bundling。但在部署时运行 `mastra build` 则会遇到此问题。 将 `@copilotkit/runtime` 包添加到 bundler 的 externals 配置中: ```typescript export const mastra = new Mastra({ bundler: { externals: ['@copilotkit/runtime'], }, }) ```