メインコンテンツへ移動

CopilotKit を使用する

CopilotKit は、カスタマイズ可能な AI Copilot をアプリケーションへすばやく統合するための React コンポーネントを提供します。Mastra と組み合わせることで、双方向の状態同期と対話型 UI を備えた AI アプリを構築できます。

CopilotKit は AG-UI プロトコルを通じて Mastra と通信します。@ag-ui/mastra パッケージが Mastra Agent を AG-UI エンドポイントとして公開し、CopilotKit の React フックとコンポーネントがそれを使用します。これにより、通常のチャットに加えて、Generative UI、Human-in-the-loop、Frontend Tool や、同じ Agent の Slack などのメッセージング Channelへのデプロイなど、さまざまな体験を実現できます。

CopilotKit のコンセプト、コンポーネント、高度な使用パターンについては、CopilotKit ドキュメントを参照してください。

情報

Mastra を Next.js API Route 内で直接実行するフルスタック統合については、CopilotKit クイックスタートを参照してください。

Mastra の 「UI Dojo」では、Mastra と CopilotKit を統合した実用的な例を確認できます。

統合ガイド
統合ガイドへの直接リンク

Mastra をスタンドアロンサーバーとして実行し、CopilotKit を使用する Next.js フロントエンドを API エンドポイントに接続します。

  1. ディレクトリ構造を設定します。たとえば、次のような構成にできます。

    project-root
    ├── mastra-server
    │ ├── src
    │ │ └── mastra
    │ └── package.json
    └── my-copilot-app
    └── package.json

    Mastra サーバーを作成します。

    npx create-mastra@latest

    このコマンドは、新しい Mastra プロジェクトを作成する対話形式のウィザードを開きます。案内に従ってサーバープロジェクトを作成してください。

    新しく作成した Mastra サーバーのディレクトリに移動します。

    cd mastra-server # Replace with the actual directory name you provided

    これで基本的な Mastra サーバープロジェクトが準備できました。

    注記

    .env ファイルに LLM Provider 用の適切な環境変数が設定されていることを確認してください。

  2. @ag-ui/mastraregisterCopilotKit() ヘルパーを使用して、CopilotKit フロントエンド用のチャットルートを作成します。このパッケージと Peer Dependency を Mastra プロジェクトに追加します。

    npm install @ag-ui/mastra @mastra/client-js @mastra/core @ag-ui/core @ag-ui/client @copilotkit/runtime

    src/mastra/index.ts ファイルでチャットルートを登録します。

    src/mastra/index.ts
    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 run dev

    デフォルトでは、Mastra サーバーは http://localhost:4111 で動作します。CopilotKit フロントエンドの設定中も、サーバーを実行したままにしてください。

  4. 1 つ上のプロジェクトルートディレクトリに移動します。

    cd ..

    my-copilot-app という名前で新しい Next.js プロジェクトを作成します。

    npx create-next-app@latest my-copilot-app

    新しく作成した Next.js プロジェクトのディレクトリに移動します。

    cd my-copilot-app
  5. チャットインターフェースの表示に使用する CopilotKit UI パッケージをインストールします。

    npm install @copilotkit/react-ui @copilotkit/react-core

    Next.js アプリのホームルート(通常は app/page.tsx または src/app/page.tsx)を開き、既存の内容を次のコードに置き換えて、基本的な CopilotKit チャットインターフェースを設定します。

    app/page.tsx
    import { 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">
    <CopilotChat
    labels={{
    title: 'Weather Agent',
    initial: 'Hi! 👋 Ask me about the weather, forecasts, and climate.',
    }}
    />
    </CopilotKit>
    )
    }

    agent Prop には、ルーティング先の Mastra Agent 名を指定します。Mastra インスタンスの agents Map にあるキーと一致する必要があります。

  6. Mastra サーバーと CopilotKit フロントエンドの両方が実行されていることを確認します。Next.js 開発サーバーを起動します。

    npm run dev

    ブラウザーでアプリを開き、Agent とチャットします。

これで、CopilotKit フロントエンドがスタンドアロンの Mastra Agent サーバーと通信するようになりました。

チャット UI のオプション
チャット UI のオプションへの直接リンク

CopilotChat はインラインで高さ全体を使うチャットをレンダリングします。CopilotKit は、同じ Props を使用できる 2 つの画面も提供します。

  • CopilotSidebar:アプリの側面に配置される折りたたみ可能なパネル。
  • CopilotPopup:チャットウィンドウを開くフローティングボタン。

コンポーネントを置き換えると画面を変更できます。3 つとも同じ CopilotKit Provider を介して接続します。

app/page.tsx
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 設定で動作します。

Frontend Tool
Frontend Toolへの直接リンク

Agent がアプリを操作できるようにします。useFrontendTool を使ってフロントエンドに Tool を登録します。Agent が Tool を呼び出すと、handler がブラウザー内で実行されます。

app/page.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 <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 を Run の途中で一時停止し、続行前にユーザーの承認、編集、拒否を待ちます。useHumanInTheLoop を使用します。その render 関数は respond Callback を受け取り、呼び出されるまで Agent の Run は一時停止したままになります。

app/page.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 }) => (
<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 内でユーザーが Step を切り替えられるようにし、respond({ accepted: true, steps }) を呼び出して Agent を再開するか、respond({ accepted: false }) で拒否します。Agent は返された値を読み取り、それに応じて続行します。完全なコンポーネントは UI Dojo で確認できます。

上記の例では Client Tool を使用します。Agent が generate_task_steps を呼び出し、フロントエンドが respond を介して処理します。Mastra はサーバー側で一時停止し、人間が承認または入力を提供するまで Tool 呼び出しの実行を保留することもできます。この方法については、バックエンド側は Mastra の Agent 承認ガイド、フロントエンド側は CopilotKit の useHumanInTheLoop リファレンスを参照してください。

設定オプション
設定オプションへの直接リンク

一般的な統合ポイントでは、次の registerCopilotKit() オプションを使用します。

オプション用途
path/copilotkit などのルートパスを設定します。
resourceId会話用の Mastra Memory の範囲を指定します。
corsserver.cors に加えて、ルートごとの CORS を設定します。
setContextAgent の実行前に、認証情報やユーザーごとの Resource ID などを Request Context に設定します。
agentsMastra インスタンスに登録された Agent の代わりに、事前構築済みの AG-UI Agent を指定します。
tracingOptionsMastra の Trace オプションを各 Agent の Run に転送します。

デフォルトでは、エンドポイントは Mastra インスタンスに登録されたすべての Agent を公開し、フロントエンドが agent Prop で 1 つを選択します。その他の CopilotKit Runtime オプションは、基盤となる Runtime に転送されます。たとえば mcpApps については、Open-ended Generative UI を参照してください。

デプロイ
デプロイへの直接リンク

CopilotKit とともに Mastra サーバーをデプロイする場合は、@copilotkit/runtime をバンドルから除外する必要があります。このパッケージにはバンドルと互換性のない依存関係が含まれており、含めると 500 エラーが発生します。

注記

mastra dev はバンドルを必要としないため、開発中にこの問題は発生しません。ただし、デプロイ用に mastra build を実行すると、この問題が発生します。

Bundler の Externals 設定に @copilotkit/runtime パッケージを追加します。

src/mastra/index.ts
export const mastra = new Mastra({
bundler: {
externals: ['@copilotkit/runtime'],
},
})