SvelteKit プロジェクトに Mastra を統合する
Mastra は SvelteKit と統合でき、次のことが簡単に行えます:
- AI 搭載機能を提供する柔軟な API を構築する
- フロントエンドとバックエンドを単一のコードベースにまとめ、デプロイを簡素化する
- 効率的なサーバー・クライアント ワークフローのために、SvelteKit の組み込みの Actions や Server Endpoints を活用する
このガイドに従って、SvelteKit プロジェクトに Mastra をスキャフォールドし、統合してください。
Actions
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キーを設定する
SvelteKitが使用するVite環境で環境変数を参照できるようにするには、VITE_
プレフィックスが必要です。
Viteの環境変数について詳しくはこちら 。
VITE_OPENAI_API_KEY=<your-api-key>
.gitignore を更新する
.gitignore
ファイルに .mastra
を追加します:
.mastra
Mastraエージェントを更新する
- import { openai } from "@ai-sdk/openai";
+ import { createOpenAI } from "@ai-sdk/openai";
+ const openai = createOpenAI({
+ apiKey: import.meta.env?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY,
+ compatibility: "strict"
+ });
import.meta.env
と process.env
の両方から環境変数を読み込むことで、SvelteKit の開発サーバーと Mastra Dev Server の両方で API キーが利用可能になります。
さらに詳しい設定方法は AI SDK のドキュメントをご覧ください。詳しくは Provider Instance を参照してください。
Mastra Dev Server を起動する
Mastra Dev Server を起動して、エージェントを REST エンドポイントとして公開します:
npm
npm run dev:mastra
起動後、エージェントはローカル環境で利用可能になります。詳しくは ローカル開発環境 を参照してください。
SvelteKit の開発サーバーを起動する
Mastra Dev Server が稼働していれば、通常どおり SvelteKit サイトを起動できます。
テスト用ディレクトリを作成
mkdir src/routes/test
テスト用アクションを作成
新しい Action を作成し、次のサンプルコードを追加します:
touch src/routes/test/+page.server.ts
import type { Actions } from './$types';
import { mastra } from '../../mastra';
export const actions = {
default: async (event) => {
const city = (await event.request.formData()).get('city')!.toString();
const agent = mastra.getAgent('weatherAgent');
const result = await agent.generate(`What's the weather like in ${city}?`);
return { result: result.text };
}
} satisfies Actions;
テスト用ページを作成
新しい Page ファイルを作成し、次のサンプルコードを追加します:
touch src/routes/test/+page.svelte
<script lang="ts">
import type { PageProps } from './$types';
let { form }: PageProps = $props();
</script>
<h1>Test</h1>
<form method="POST">
<input name="city" placeholder="Enter city" required />
<button type="submit">Get Weather</button>
</form>
{#if form?.result}
<pre>{form.result}</pre>
{/if}
これでブラウザで
/test
にアクセスして試せます。
都市名として London を送信すると、次のような結果が返ってきます:
The current weather in London is as follows:
- **Temperature:** 16°C (feels like 13.8°C)
- **Humidity:** 62%
- **Wind Speed:** 12.6 km/h
- **Wind Gusts:** 32.4 km/h
- **Conditions:** Overcast
If you need more details or information about a different location, feel free to ask!
## Next steps