Skip to Content

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

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

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

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

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 キーの設定

VITE_ プレフィックスは、SvelteKit が使用する Vite 環境で環境変数にアクセスできるようにするために必要です。 Vite 環境変数について詳しく読む

.env
VITE_OPENAI_API_KEY=<your-api-key>

.gitignoreを更新

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

.gitignore
.mastra

Mastra Agentを更新する

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?.VITE_OPENAI_API_KEY || process.env.VITE_OPENAI_API_KEY, + compatibility: "strict" + });

import.meta.envprocess.envの両方から環境変数を読み取ることで、SvelteKit開発サーバーとMastra Dev Serverの両方でAPIキーが利用できることを保証します。

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

Mastra Dev Serverを開始する

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

npm run dev:mastra

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

SvelteKit Dev Serverを開始

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

テストディレクトリの作成

mkdir src/routes/test

テストアクションの作成

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

touch src/routes/test/+page.server.ts
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
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!