> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # CopilotKit を使用する [CopilotKit](https://www.copilotkit.ai/) は、カスタマイズ可能な AI Copilot をアプリケーションへすばやく統合するための React コンポーネントを提供します。Mastra と組み合わせることで、双方向の状態同期と対話型 UI を備えた AI アプリを構築できます。 CopilotKit は [AG-UI プロトコル](https://docs.ag-ui.com/)を通じて Mastra と通信します。`@ag-ui/mastra` パッケージが Mastra Agent を AG-UI エンドポイントとして公開し、CopilotKit の React フックとコンポーネントがそれを使用します。これにより、通常のチャットに加えて、[Generative UI、Human-in-the-loop、Frontend Tool](https://mastra.zisheng.pro/ja/guides/build-your-ui/copilotkit/generative-ui) や、同じ Agent の [Slack などのメッセージング Channel](https://mastra.zisheng.pro/ja/guides/build-your-ui/copilotkit/channels)へのデプロイなど、さまざまな体験を実現できます。 CopilotKit のコンセプト、コンポーネント、高度な使用パターンについては、[CopilotKit ドキュメント](https://docs.copilotkit.ai/)を参照してください。 > **情報:** Mastra を Next.js API Route 内で直接実行するフルスタック統合については、[CopilotKit クイックスタート](https://docs.copilotkit.ai/mastra/quickstart)を参照してください。 Mastra の [「UI Dojo」](https://ui-dojo.mastra.ai/)では、Mastra と CopilotKit を統合した実用的な例を確認できます。 ## 統合ガイド 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', }), ], }, }) ``` これにより、Mastra インスタンス上の Agent が `/copilotkit` に CopilotKit 互換形式で公開されます。フロントエンドは、後述の `agent` Prop で通信する Agent を選択します。CopilotKit フロントエンドが Mastra サーバーにアクセスできるように CORS 設定を追加してください。本番環境では、CORS のオリジンをフロントエンドのドメインに制限します。 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. 1 つ上のプロジェクトルートディレクトリに移動します。 ```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 にあるキーと一致する必要があります。 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 を使用できる 2 つの画面も提供します。 - `CopilotSidebar`:アプリの側面に配置される折りたたみ可能なパネル。 - `CopilotPopup`:チャットウィンドウを開くフローティングボタン。 コンポーネントを置き換えると画面を変更できます。3 つとも同じ `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 としてレンダリングする機能([Generative UI](https://mastra.zisheng.pro/ja/guides/build-your-ui/copilotkit/generative-ui)を参照)に加えて、CopilotKit では Agent がアプリケーションを操作したり、ユーザーのために一時停止したりできます。どちらのパターンも同じ Mastra 設定で動作します。 ### Frontend 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 を Run の途中で一時停止し、続行前にユーザーの承認、編集、拒否を待ちます。`useHumanInTheLoop` を使用します。その `render` 関数は `respond` Callback を受け取り、呼び出されるまで Agent の Run は一時停止したままになります。 ```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` 内でユーザーが Step を切り替えられるようにし、`respond({ accepted: true, steps })` を呼び出して Agent を再開するか、`respond({ accepted: false })` で拒否します。Agent は返された値を読み取り、それに応じて続行します。完全なコンポーネントは [UI Dojo](https://ui-dojo.mastra.ai/) で確認できます。 上記の例では Client Tool を使用します。Agent が `generate_task_steps` を呼び出し、フロントエンドが `respond` を介して処理します。Mastra はサーバー側で一時停止し、人間が承認または入力を提供するまで Tool 呼び出しの実行を保留することもできます。この方法については、バックエンド側は Mastra の [Agent 承認](https://mastra.zisheng.pro/ja/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 の実行前に、認証情報やユーザーごとの Resource ID などを Request Context に設定します。 | | `agents` | Mastra インスタンスに登録された Agent の代わりに、事前構築済みの AG-UI Agent を指定します。 | | `tracingOptions` | Mastra の Trace オプションを各 Agent の Run に転送します。 | デフォルトでは、エンドポイントは Mastra インスタンスに登録されたすべての Agent を公開し、フロントエンドが `agent` Prop で 1 つを選択します。その他の CopilotKit Runtime オプションは、基盤となる Runtime に転送されます。たとえば `mcpApps` については、[Open-ended Generative UI](https://mastra.zisheng.pro/ja/guides/build-your-ui/copilotkit/generative-ui) を参照してください。 ## デプロイ CopilotKit とともに Mastra サーバーをデプロイする場合は、`@copilotkit/runtime` をバンドルから除外する必要があります。このパッケージにはバンドルと互換性のない依存関係が含まれており、含めると 500 エラーが発生します。 > **注記:** `mastra dev` はバンドルを必要としないため、開発中にこの問題は発生しません。ただし、デプロイ用に `mastra build` を実行すると、この問題が発生します。 Bundler の Externals 設定に `@copilotkit/runtime` パッケージを追加します。 ```typescript export const mastra = new Mastra({ bundler: { externals: ['@copilotkit/runtime'], }, }) ```