ExpressプロジェクトにMastraを統合する
MastraはExpressと統合し、以下を簡単に実現できます:
- AI機能を提供する柔軟なAPIの構築
- サーバーロジックとルーティングの完全な制御の維持
- フロントエンドから独立したバックエンドのスケーリング
このガイドを使用して、ExpressプロジェクトでMastraをスキャフォールドし統合してください。
このセットアップは以下のパッケージバージョンと互換性があります:
express
: 4.x@types/express
: 4.x
express
と@types/express
が整合性に向けて進化している間、5.xでの型互換性は一貫していない場合があります。
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 dev",
"build": "mastra build"
}
}
プロジェクトで既に
dev
とbuild
スクリプトを使用している場合は、dev:mastra
とbuild:mastra
を使用することをお勧めします。
TypeScriptの初期化
プロジェクトルートに以下の設定でtsconfig.json
ファイルを作成してください:
{
"compilerOptions": {
"target": "ES2022",
"module": "ES2022",
"moduleResolution": "bundler",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"outDir": "dist"
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist", ".mastra"]
}
このTypeScript設定はMastraプロジェクト用に最適化されており、モダンなモジュール解決と厳密な型チェックを使用しています。
API キーの設定
OPENAI_API_KEY=<your-api-key>
各LLMプロバイダーは異なる環境変数を使用します。詳細についてはモデル機能を参照してください。
Mastra Dev Serverを開始する
Mastra dev serverを開始して、エージェントをREST エンドポイントとして公開します:
npm
npm run dev
実行すると、エージェントがローカルで利用可能になります。詳細についてはLocal Development Environmentを参照してください。
Express アプリの例
この例では、city
クエリパラメータを期待する /api/weather
エンドポイントを作成します。
import "dotenv/config";
import express, { Request, Response } from "express";
import { mastra } from "./mastra";
const app = express();
const port = process.env.PORT ?? 3000;
app.get("/api/weather", async (req: Request, res: Response) => {
const { city } = req.query as { city?: string };
if (!city) {
return res.status(400).send("Missing 'city' query parameter");
}
const agent = mastra.getAgent("weatherAgent");
try {
const result = await agent.generate(`What's the weather like in ${city}?`);
res.send(result.text);
} catch (error) {
console.error("Agent error:", error);
res.status(500).send("An error occurred while processing your request");
}
});
app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
Mastra 開発サーバーを実行した状態で、Express アプリを別途起動します。例:
npx tsx --watch src/server.ts --watch-dir src
以下のいずれかを使用してエンドポイントにリクエストを送信できます:
http
http://localhost:3000/api/weather?city=London
以下のような出力が表示されるはずです:
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!