Skip to Content

AstroプロジェクトにMastraを統合する

MastraはAstroと統合し、以下を簡単に実現できます:

  • AI機能を提供する柔軟なAPIの構築
  • フロントエンドとバックエンドの統一されたコードベースによるデプロイメントの簡素化
  • 効率的なサーバー・クライアントワークフローのためのAstroの組み込みActionsまたはServer Endpointsの活用

このガイドを使用して、AstroプロジェクトでMastraをスキャフォールドし統合してください。

⚠️

このガイドでは、ReactとVercelアダプターを使用したAstroのActionsを使用していることを前提としています。

Mastraをインストール

必要なMastraパッケージをインストールします:

npm install mastra@latest @mastra/core@latest @mastra/libsql@latest

Mastraを統合する

プロジェクトにMastraを統合するには、2つのオプションがあります:

1. ワンライナーを使用する

以下のコマンドを実行して、合理的なデフォルト設定でデフォルトのWeatherエージェントを素早くスキャフォールドします:

npx mastra@latest init --default

詳細についてはmastra initを参照してください。

2. インタラクティブCLIを使用する

セットアップをカスタマイズしたい場合は、initコマンドを実行し、プロンプトが表示されたときにオプションから選択してください:

npx mastra@latest init

package.jsondevbuildスクリプトを追加します:

package.json
{ "scripts": { ... "dev:mastra": "mastra dev", "build:mastra": "mastra build" } }

TypeScriptを設定する

プロジェクトルートのtsconfig.jsonファイルを修正します:

tsconfig.json
{ ... "exclude": ["dist", ".mastra"] }

API キーの設定

.env
OPENAI_API_KEY=<your-api-key>

.gitignoreを更新

.mastra.vercel.gitignoreファイルに追加してください:

.gitignore
.mastra .vercel

Mastra Agentを更新する

AstroはViteを使用しており、process.envではなくimport.meta.envを通じて環境変数にアクセスします。そのため、モデルコンストラクタは次のようにVite環境から明示的にapiKeyを受け取る必要があります:

src/mastra/agents/weather-agent.ts
- import { openai } from "@ai-sdk/openai"; + import { createOpenAI } from "@ai-sdk/openai"; + const openai = createOpenAI({ + apiKey: import.meta.env?.OPENAI_API_KEY, + compatibility: "strict" + });

より詳細な設定についてはAI SDKドキュメントで確認できます。詳細についてはProvider Instanceを参照してください。

Mastra Dev Serverを開始する

Mastra Dev Serverを開始して、エージェントをRESTエンドポイントとして公開します:

npm run dev:mastra

実行すると、エージェントがローカルで利用可能になります。詳細についてはローカル開発環境を参照してください。

Astro Dev Serverを開始

Mastra Dev Serverが実行されている状態で、通常の方法でAstroサイトを開始できます。

Actionsディレクトリの作成

mkdir src/actions

テストActionの作成

新しいActionを作成し、サンプルコードを追加します:

touch src/actions/index.ts
src/actions/index.ts
import { defineAction } from "astro:actions"; import { z } from "astro:schema"; import { mastra } from "../mastra"; export const server = { getWeatherInfo: defineAction({ input: z.object({ city: z.string() }), handler: async (input) => { const city = input.city; const agent = mastra.getAgent("weatherAgent"); const result = await agent.generate(`What's the weather like in ${city}?`); return result.text; } }) };

テストフォームの作成

新しいFormコンポーネントを作成し、サンプルコードを追加します:

touch src/components/form.tsx
src/components/form.tsx
import { actions } from "astro:actions"; import { useState } from "react"; export const Form = () => { const [result, setResult] = useState<string | null>(null); async function handleSubmit(formData: FormData) { const city = formData.get("city")!.toString(); const { data } = await actions.getWeatherInfo({ city }); setResult(data || null); } return ( <> <form action={handleSubmit}> <input name="city" placeholder="Enter city" required /> <button type="submit">Get Weather</button> </form> {result && <pre>{result}</pre>} </> ); };

テストページの作成

新しいページを作成し、サンプルコードを追加します:

touch src/pages/test.astro
src/pages/test.astro
--- import { Form } from '../components/form' --- <h1>Test</h1> <Form client:load />

ブラウザで /test にアクセスして試すことができます。

都市として London を送信すると、以下のような結果が返されます:

Agent response: The current weather in London is as follows: - **Temperature:** 12.9°C (Feels like 9.7°C) - **Humidity:** 63% - **Wind Speed:** 14.7 km/h - **Wind Gusts:** 32.4 km/h - **Conditions:** Overcast Let me know if you need more information!

次のステップ