AstroプロジェクトにMastraを統合する
MastraはAstroと統合されており、次のことが簡単に行えます:
- AI機能を提供する柔軟なAPIの構築
- フロントエンドとバックエンドを単一のコードベースで統合し、デプロイを簡素化
- 効率的なサーバー・クライアント間のワークフローのために、Astroの組み込みのActions やServer Endpoints を活用
このガイドでは、AstroプロジェクトでMastraのひな型作成と統合を行う手順を説明します。
Actions
このガイドは、Astro の Actions を React と Vercel アダプターと組み合わせて使用していることを前提としています。
Mastra のインストール
必要な Mastra パッケージをインストールします:
npm
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.json
に dev
と build
のスクリプトを追加します:
{
"scripts": {
...
"dev:mastra": "mastra dev",
"build:mastra": "mastra build"
}
}
TypeScript を設定する
プロジェクトのルートにある tsconfig.json
ファイルを編集します:
{
...
"exclude": ["dist", ".mastra"]
}
API キーを設定する
OPENAI_API_KEY=<your-api-key>
.gitignore を更新する
.gitignore
ファイルに .mastra
と .vercel
を追加します:
.mastra
.vercel
Mastra Agent を更新する
Astro は Vite を使用しており、環境変数には process.env
ではなく import.meta.env
を通じてアクセスします。したがって、モデルのコンストラクターは、次のように Vite の環境から明示的に apiKey
を受け取る必要があります:
- 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
npm run dev:mastra
起動後、エージェントはローカル環境で利用可能になります。詳しくは ローカル開発環境 を参照してください。
Astro Dev サーバーを起動する
Mastra Dev Server が起動していれば、通常どおり Astro サイトを起動できます。
Actions ディレクトリを作成
mkdir src/actions
テスト用の Action を作成
新しい Action を作成し、次のサンプルコードを追加します:
touch 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
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>}
</>
);
};
テスト用ページを作成
新しい Page を作成し、次のサンプルコードを追加します:
touch 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!