Vite/ReactプロジェクトにMastraを統合する
MastraはViteと統合し、以下を簡単に実現できます:
- AI機能を提供する柔軟なAPIの構築
- フロントエンドとバックエンドの統一されたコードベースによるデプロイメントの簡素化
- MastraのClient SDKの活用
このガイドを使用して、Vite/ReactプロジェクトでMastraをスキャフォールドし統合してください。
このガイドでは、プロジェクトのルート(例:app
)でReact Router v7を使用したVite/Reactを使用していることを前提としています。
Mastraをインストール
必要なMastraパッケージをインストールします:
npm
npm install mastra@latest @mastra/core@latest @mastra/libsql@latest @mastra/client-js@latest
Mastraを統合する
プロジェクトにMastraを統合するには、2つのオプションがあります:
1. ワンライナーを使用する
以下のコマンドを実行して、合理的なデフォルト設定でデフォルトのWeatherエージェントを素早くスキャフォールドします:
npx mastra@latest init --dir . --components agents,tools --example --llm openai
詳細についてはmastra initを参照してください。
2. インタラクティブCLIを使用する
セットアップをカスタマイズしたい場合は、init
コマンドを実行し、プロンプトが表示されたときにオプションから選択してください:
npx mastra@latest init
package.json
にdev
とbuild
スクリプトを追加します:
{
"scripts": {
...
"dev:mastra": "mastra dev --dir mastra",
"build:mastra": "mastra build --dir mastra"
}
}
TypeScriptを設定する
プロジェクトルートのtsconfig.json
ファイルを修正してください:
{
...
"exclude": ["dist", ".mastra"]
}
API キーの設定
OPENAI_API_KEY=<your-api-key>
各LLMプロバイダーは異なる環境変数を使用します。詳細についてはモデル機能を参照してください。
.gitignoreを更新する
.gitignore
ファイルに.mastra
を追加してください:
.mastra
Mastra Dev Serverを開始する
エージェントをREST エンドポイントとして公開するために、Mastra Dev Serverを開始します:
npm
npm run dev:mastra
実行すると、エージェントがローカルで利用可能になります。詳細についてはLocal Development Environmentを参照してください。
Vite Dev Serverを開始する
Mastra Dev Serverが実行されている状態で、通常の方法でViteアプリを開始できます。
Mastraクライアントを作成する
新しいディレクトリとファイルを作成します。その後、サンプルコードを追加します:
mkdir lib
touch lib/mastra.ts
import { MastraClient } from "@mastra/client-js";
export const mastraClient = new MastraClient({
baseUrl: import.meta.env.VITE_MASTRA_API_URL || "http://localhost:4111",
});
テストルート設定を作成
設定に新しいroute
を追加します:
import { type RouteConfig, index, route } from "@react-router/dev/routes";
export default [
index("routes/home.tsx"),
route("test", "routes/test.tsx"),
] satisfies RouteConfig;
テストルートを作成
新しいルートを作成し、サンプルコードを追加します:
touch app/routes/test.tsx
import { useState } from "react";
import { mastraClient } from "../../lib/mastra";
export default function Test() {
const [result, setResult] = useState<string | null>(null);
async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
event.preventDefault();
const formData = new FormData(event.currentTarget);
const city = formData.get("city")?.toString();
const agent = mastraClient.getAgent("weatherAgent");
const response = await agent.generate({
messages: [{ role: "user", content: `What's the weather like in ${city}?` }]
});
setResult(response.text);
}
return (
<>
<h1>Test</h1>
<form onSubmit={handleSubmit}>
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{result && <pre>{result}</pre>}
</>
);
}
ブラウザで
/test
にアクセスして試すことができます。
都市として London を送信すると、以下のような結果が返されます:
The current weather in London is partly cloudy with a temperature of 19.3°C, feeling like 17.4°C. The humidity is at 53%, and there is a wind speed of 15.9 km/h, with gusts up to 38.5 km/h.