Skip to Content

React で CopilotKit を使用する

CopilotKitは、カスタマイズ可能なAIコパイロットをアプリケーションに素早く統合するためのReactコンポーネントを提供します。 Mastraと組み合わせることで、双方向の状態同期とインタラクティブなUIを備えた高度なAIアプリを構築できます。

Mastraプロジェクトを作成する

mastra CLIを使用して新しいMastraプロジェクトを作成します:

npx create-mastra@latest

プロジェクトの構築時にエージェントの例を選択してください。これにより、天気エージェントが提供されます。

詳細なセットアップ手順については、インストールガイドを参照してください。

基本的なセットアップ

MastraとCopilotKitを統合するには、主に2つのステップがあります:バックエンドランタイムのセットアップとフロントエンドコンポーネントの設定です。

npm install @copilotkit/runtime

ランタイムのセットアップ

MastraのカスタムAPIルートを活用して、CopilotKitのランタイムをMastraサーバーに追加することができます。

現在のバージョンの統合では、MastraClientを使用してMastraエージェントをCopilotKitのAGUI形式にフォーマットしています。

npm install @mastra/client-js

次に、CopilotKit用のカスタムAPIルートでMastraインスタンスを更新しましょう。

import { Mastra } from "@mastra/core/mastra"; import { createLogger } from "@mastra/core/logger"; import { LibSQLStore } from "@mastra/libsql"; import { registerApiRoute } from "@mastra/core/server"; import { CopilotRuntime, copilotRuntimeNodeHttpEndpoint, ExperimentalEmptyAdapter, } from "@copilotkit/runtime"; import { MastraClient } from "@mastra/client-js"; import { weatherAgent } from "./agents"; const serviceAdapter = new ExperimentalEmptyAdapter(); export const mastra = new Mastra({ agents: { weatherAgent }, storage: new LibSQLStore({ // stores telemetry, evals, ... into memory storage, // if you need to persist, change to file:../mastra.db url: ":memory:", }), logger: createLogger({ name: "Mastra", level: "info", }), server: { apiRoutes: [ registerApiRoute("/copilotkit", { method: `POST`, handler: async (c) => { // N.B. Current integration leverages MastraClient to fetch AGUI. // Future versions will support fetching AGUI from mastra context. const client = new MastraClient({ baseUrl: "http://localhost:4111", }); const runtime = new CopilotRuntime({ agents: await client.getAGUI({ resourceId: "weatherAgent" }), }); const handler = copilotRuntimeNodeHttpEndpoint({ endpoint: "/copilotkit", runtime, serviceAdapter, }); return handler.handle(c.req.raw, {}); }, }), ], }, });

このセットアップにより、MastraサーバーでCopilotKitが実行されるようになりました。mastra devコマンドでMastraサーバーを起動できます。

UIのセットアップ

CopilotKitのReactコンポーネントをインストールします:

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

次に、CopilotKitのReactコンポーネントをフロントエンドに追加します。

import { CopilotChat } from "@copilotkit/react-ui"; import { CopilotKit } from "@copilotkit/react-core"; import "@copilotkit/react-ui/styles.css"; export function CopilotKitComponent() { return ( <CopilotKit runtimeUrl="http://localhost:4111/copilotkit" agent="weatherAgent" > <CopilotChat labels={{ title: "Your Assistant", initial: "Hi! 👋 How can I assist you today?", }} /> </CopilotKit> ); }

コンポーネントをレンダリングして、未来の構築を始めましょう!


CopilotKit出力

参考文献