Skip to Content
ドキュメントフレームワークエージェンティックUICopilotKitを使用

ReactでCopilotKitを使用する

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

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

npx create-mastra@latest

プロジェクトをスキャフォールディングする際は、agentの例を選択してください。これにより、天気エージェントが提供されます。

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

基本セットアップ

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

npm install @copilotkit/runtime

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

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

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

npm install @mastra/agui@alpha

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

src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra"; import { PinoLogger } from "@mastra/loggers"; import { LibSQLStore } from "@mastra/libsql"; import { CopilotRuntime, copilotRuntimeNodeHttpEndpoint, ExperimentalEmptyAdapter } from "@copilotkit/runtime"; import { registerCopilotKit } from "@mastra/agui"; import { weatherAgent } from "./agents/weather-agent"; 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: new PinoLogger({ name: "Mastra", level: "info" }), server: { // We will be calling this from a Vite App. Allow CORS cors: { origin: "*", allowMethods: ["*"], allowHeaders: ["*"] }, apiRoutes: [ registerCopilotKit({ path: "/copilotkit", resourceId: "weatherAgent", setContext: (c, runtimeContext) => { // Add whatever you need to the runtimeContext runtimeContext.set("user-id", c.req.header("X-User-ID")); runtimeContext.set("temperature-scale", "celsius"); } }) ] } });

このセットアップにより、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 output

他のフレームワークでの使用 (NextJS)

Mastra Serverを経由せずにAGUIを活用することも可能です。

// import your mastra instance from dir import { mastra } from "../path/to/mastra"; import { CopilotRuntime, ExperimentalEmptyAdapter, copilotRuntimeNextJSAppRouterEndpoint, } from "@copilotkit/runtime"; import { NextRequest } from "next/server"; export const POST = async (req: NextRequest) => { // Clone the request before reading the body const clonedReq = req.clone(); const body = await clonedReq.json(); const resourceId = body.resourceId || "TEST"; const mastraAgents = getAGUI({ mastra, resourceId, }); const runtime = new CopilotRuntime({ agents: mastraAgents, }); const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ runtime, serviceAdapter: new ExperimentalEmptyAdapter(), endpoint: "/api/copilotkit", }); // Use the original request for handleRequest return handleRequest(req); };

型付きランタイムコンテキストの使用

より良い型安全性のために、ランタイムコンテキストの型を指定できます:

src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra"; import { PinoLogger } from "@mastra/loggers"; import { LibSQLStore } from "@mastra/libsql"; import { registerCopilotKit } from "@mastra/agui"; import { weatherAgent } from "./agents"; // Define your runtime context type type WeatherRuntimeContext = { "user-id": string; "temperature-scale": "celsius" | "fahrenheit"; "api-key": string; }; export const mastra = new Mastra({ agents: { weatherAgent }, storage: new LibSQLStore({ url: ":memory:", }), logger: new PinoLogger({ name: "Mastra", level: "info", }), server: { cors: { origin: "*", allowMethods: ["*"], allowHeaders: ["*"], }, apiRoutes: [ registerCopilotKit<WeatherRuntimeContext>({ path: "/copilotkit", resourceId: "weatherAgent", setContext: (c, runtimeContext) => { // TypeScript will enforce the correct types here runtimeContext.set("user-id", c.req.header("X-User-ID") || "anonymous"); runtimeContext.set("temperature-scale", "celsius"); // Only "celsius" | "fahrenheit" allowed runtimeContext.set("api-key", process.env.WEATHER_API_KEY || ""); // This would cause a TypeScript error: // runtimeContext.set("invalid-key", "value"); // ❌ Error: invalid key // runtimeContext.set("temperature-scale", "kelvin"); // ❌ Error: invalid value } }), ], }, });

さらに詳しく