
Mastraのサンプル集を一気に紹介する
こんにちは!吉波です!
最近、AIエージェントフレームワーク「Mastra」が彗星の如く現れました。衝撃的だったのが、こちらの画像↓

「LangChainのGithubスター数を抜き去った…!?」
これを見た時、衝撃が走りました。LLMを用いたアプリケーション開発を効率的に行うためのライブラリとして、長らく君臨してきたLangChainが抜かされたという事実は、全世界が驚いたはずです。
そこで今回は、これからMastraを触ってみたいと思う方に向けて、Mastra公式が出しているサンプル集を紹介します!AIエージェントの作り方を学びたいなと思っている方はぜひ最後までご覧ください!
また、今日から「吉波塾」というAI駆動開発やAIエージェントに関する講義を開始したので、そちらも良ければご参加ください!☺️ 次回の開催はX(@yoshi8__)より共有します!
Mastraのサンプル集
今回の記事では、以下のリポジトリを紹介していきます。
※ 2025/3/20時点の情報なので、変更される可能性があります。
1. agent-network サンプル
概要
agent-networkは、Mastraを使用してエージェントネットワークを構築し、複数のエージェントが協力して情報収集や分析を行う例を示しています。
主な機能
エージェントネットワークの作成と管理
複数エージェント間の協調作業
情報収集と分析の自動化
技術的詳細
`@mastra/core`を使用(AgentNetwork)
OpenAIのAI SDKとの連携
Zodによるデータバリデーション
サンプルコード解説
サンプルでは「Research_Network」という名前のエージェントネットワークを使用して、ナポレオン・ボナパルトに関するレポートを生成しています。
// index.tsの主要部分import { mastra }from'./mastra';asyncfunctionmain(){const researchNetwork = mastra.getNetwork('Research_Network');if (!researchNetwork) {thrownewError('Research network not found'); }console.log('🔍 Starting research on Napoleon Bonaparte...\n');// ネットワークを使用してレポート生成const result =await researchNetwork.stream('Give me a report on Napoleon Bonaparte', {maxSteps:20,// LLMルーターが最適なエージェントを決定するための十分なステップ数 });// 結果のストリーミング処理forawait (const partof result.fullStream) {switch (part.type) {case'error':console.error(part.error);break;case'text-delta': process.stdout.write(part.textDelta);break;case'tool-call':console.log(`calling tool${part.toolName} with args${JSON.stringify(part.args,null,2)}`);break;case'tool-result':console.log(`tool result${JSON.stringify(part.result,null,2)}`);break; } }// エージェント間のやり取りの要約を表示console.log('\n\n📊 Agent Interaction Summary:');console.log(researchNetwork.getAgentInteractionSummary());}
使用方法
以下のコマンドで実行できます:
npx bun src/index.ts
2. ai-beats-lab サンプル
概要
AI Beats Labは、AIを使用してオリジナルの音楽やビートを作成するためのサンプルプロジェクトです。
デモ
主な機能
AIを活用した音楽生成
オリジナルビートの作成
音楽制作の自動化
技術的詳細
このサンプルはデモ、ソースコード、ブログ記事へのリンクを提供していますが、リポジトリ内の詳細な実装コードは限られています。
3. ai-sdk-useChat サンプル
概要
ai-sdk-useChatサンプルは、Next.jsフレームワークを使用して、AI SDKの`useChat`フックを実装したチャットアプリケーションの例です。
主な機能
AI SDKの`useChat`フックを使用したチャットインターフェース
Next.jsフレームワークとの統合
シンプルなチャットUIの実装
技術的詳細
Next.js(React)フレームワークを使用
`@ai-sdk/react`パッケージの`useChat`フックを活用
クライアントサイドのチャット機能実装
サンプルコード解説
このサンプルは、Next.jsプロジェクトとして構成されており、主要なコンポーネントは`app/page.tsx`ファイルに実装されています。
'use client';import { useChat } from'@ai-sdk/react';exportdefaultfunctionChat(){const { messages, input, handleInputChange, handleSubmit } = useChat();return ( <div className="flex flex-col w-full max-w-md py-24 mx-auto stretch"> {messages.map(m => ( <div key={m.id} className="whitespace-pre-wrap"> {m.role ==='user' ?'User: ' :'AI: '} {m.content} </div> ))} <form onSubmit={handleSubmit}> <input className="fixed dark:bg-zinc-900 bottom-0 w-full max-w-md p-2 mb-8 border border-zinc-300 dark:border-zinc-800 rounded shadow-xl" value={input} placeholder="Say something..." onChange={handleInputChange} /> </form> </div> );}
使用方法
READMEによると、以下のコマンドで開発サーバーを起動できます:
npm run dev# またはyarn dev# またはpnpm dev# またはbun dev
その後、ブラウザで`http://localhost:3000`にアクセスすることでアプリケーションを利用できます。
注目ポイント
このサンプルは、Mastraフレームワークと他のAI関連ライブラリ(AI SDK)との連携方法を示す良い例です。特にNext.jsのような人気のあるフレームワークとの統合は、実用的なアプリケーション開発の参考になります。
4. assistant-ui サンプル
概要
assistant-uiサンプルは、Mastraを使用してNext.jsベースのアシスタントUIを実装する例を示しています。このサンプルは、シンプルなチャットインターフェースを提供し、ユーザーがAIアシスタントと対話できるようにします。
主な機能
Next.jsフレームワークを使用したアシスタントUI
@assistant-ui/react-uiパッケージを活用したチャットインターフェース
マークダウンテキストのサポート
カスタマイズ可能なウェルカムメッセージ
技術的詳細
Next.jsフレームワークを使用
@assistant-ui/react-uiパッケージからのThreadコンポーネント
マークダウンテキストのレンダリング機能
クライアントサイドのReactコンポーネント
サンプルコード解説
このサンプルは、主に`MyAssistant.tsx`コンポーネントを中心に構成されています。
// MyAssistant.tsx'use client';import { Thread, makeMarkdownText }from'@assistant-ui/react-ui';const MarkdownText = makeMarkdownText();exportfunctionMyAssistant(){return ( <Thread strings={{ welcome: { message: 'Ask me questions about YC 2024' } }} assistantMessage={{ components: { Text: MarkdownText } }} /> );}
このコンポーネントは、Next.jsのページコンポーネントから以下のように使用されています:
// page.tsximport { MyAssistant }from'@/components/MyAssistant';exportdefaultfunctionHome(){return ( <main className="h-dvh"> <MyAssistant /> </main> );}
使用方法
READMEによると、以下の手順で実行できます:
OpenAI APIキーを`.env.local`ファイルに追加:
OPENAI_API_KEY=sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
開発サーバーを起動:
npm run dev# またはyarn dev# またはpnpm dev# またはbun dev
ブラウザで`http://localhost:3000`にアクセスして結果を確認
注目ポイント
このサンプルは、Mastraを使用してシンプルながら機能的なチャットインターフェースを構築する方法を示しています。特に、Next.jsとの統合やマークダウンテキストのサポートなど、実用的な機能が実装されています。
5. basics/agents/using-a-tool サンプル
概要
using-a-toolサンプルは、Mastraフレームワークを使用してカスタムツールを作成し、エージェントに組み込む方法を示す基本的な例です。このサンプルでは、天気情報を取得するツールを実装しています。
主な機能
カスタムツールの作成と実装
Zodを使用したスキーマ検証
外部APIとの連携(天気情報API)
エージェントへのツール組み込み
技術的詳細
`@mastra/core`パッケージの`createTool`、`Agent`、`Mastra`クラスを使用
`@ai-sdk/openai`を使用したOpenAI GPTモデルとの連携
Zodライブラリによる入出力スキーマの定義
外部APIからの天気データ取得と処理
サンプルコード解説
このサンプルでは、以下の主要なコンポーネントを実装しています:
天気ツールの作成:
const weatherTool = createTool({ id:'get-weather', description:'Get current weather for a location', inputSchema: z.object({ location: z.string().describe('City name'), }), outputSchema: z.object({ temperature: z.number(), feelsLike: z.number(), humidity: z.number(), windSpeed: z.number(), windGust: z.number(), conditions: z.string(), location: z.string(), }), execute:async ({ context }) => {returnawait getWeather(context.location); },});
天気情報取得関数:
const getWeather =async (location:string) => {// 位置情報の取得const geocodingUrl =`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(location)}&count=1`;const geocodingResponse =await fetch(geocodingUrl);const geocodingData =await geocodingResponse.json();// 天気情報の取得const weatherUrl =`https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}¤t=temperature_2m,apparent_temperature,relative_humidity_2m,wind_speed_10m,wind_gusts_10m,weather_code`;const response =await fetch(weatherUrl);const data: WeatherResponse =await response.json();// 結果の整形と返却return { temperature: data.current.temperature_2m, feelsLike: data.current.apparent_temperature, humidity: data.current.relative_humidity_2m, windSpeed: data.current.wind_speed_10m, windGust: data.current.wind_gusts_10m, conditions: getWeatherCondition(data.current.weather_code), location: name, };};
エージェントの作成と実行:
const weatherAgent =new Agent({name:'Weather Agent',instructions:`You are a helpful weather assistant that provides accurate weather information...`,model: openai('gpt-4o-mini'),tools: { weatherTool },});const mastra =new Mastra({agents: { weatherAgent },});asyncfunctionmain(){const agent = mastra.getAgent('weatherAgent');const result =await agent.generate('What is the weather in London?');console.log(result.text);}
使用方法
READMEによると、以下の手順で実行できます:
リポジトリをクローンし、プロジェクトディレクトリに移動
`.env.example`ファイルをコピーし、OpenAI APIキーを設定
依存関係をインストール:`pnpm install`
サンプルを実行:`pnpm start`
注目ポイント
このサンプルは、Mastraフレームワークの基本的な機能を示す良い例であり、特にカスタムツールの作成と組み込みに焦点を当てています。実用的なユースケース(天気情報の取得)を通じて、エージェントの拡張方法を学ぶことができます。
6. bird-checker-with-express サンプル
概要
bird-checker-with-expressサンプルは、ExpressサーバーとMastraフレームワークを組み合わせて、画像が鳥かどうかを判定するAIエージェントを実装した例です。このサンプルでは、Unsplashから画像を取得するAPIと、AIを使用して画像が鳥かどうかを判定するAPIの2つのエンドポイントを提供しています。
主な機能
Unsplashから指定クエリに一致するランダム画像を取得するAPI
画像が鳥かどうかを判定し、構造化されたレスポンスを返すAIエージェント
Anthropicの画像認識モデル(Claude 3 Haiku)の活用
Braintrustによる評価機能
技術的詳細
Express.jsを使用したWebサーバー実装
`@mastra/core`パッケージの`Agent`と`Mastra`クラスを使用
`@ai-sdk/anthropic`を使用したAnthropicモデルとの連携
Zodライブラリによる出力スキーマの定義
画像処理と分析のためのAPI実装
サンプルコード解説
このサンプルでは、以下の主要なコンポーネントを実装しています:
エージェントの定義:
exportconst birdCheckerAgent =new Agent({name:'Bird checker',instructions:'You can view an image and figure out if it is a bird or not. You can also figure out the species of the bird and where the picture was taken.',model: anthropic('claude-3-haiku-20240307'),});
Mastraインスタンスの作成:
exportconst mastra =new Mastra({agents: { birdCheckerAgent },logger: createLogger({name:'CONSOLE',level:'info', }),});
画像メタデータ取得API:
app.post('/api/image-metadata',async (req: Request, res: Response) => {try {const imageUrl = req.body?.imageUrl;if (!imageUrl) { res.status(400).send({ msg:'Image url is required' });return; }const birdCheckerAgent = mastra.getAgent('birdCheckerAgent');if (!birdCheckerAgent) { res.sendStatus(404);return; }const response =await birdCheckerAgent.generate( [ { role: 'user', content: [ { type: 'image', image: imageUrl, }, { type: 'text', text:"view this image and let me know if it's a bird or not, and the scientific name of the bird without any explanation. Also summarize the location for this picture in one or two short sentences understandable by a high school student", },], }, ], { output: z.object({ bird: z.boolean(), species: z.string(), location: z.string(), }), }, );const {object } = response; res.send(object); }catch (err) { console.log('get image metadata err===', err); res.status(400).send({ msg:'Could not fetch image metadata' }); }});
https://github.com/mastra-ai/mastra/tree/main/examples/bird-checker-with-express
注目ポイント
このサンプルは、Mastraフレームワークを実際のWebアプリケーションに統合する方法を示す良い例です。特に、画像認識機能を持つAIエージェントをExpressサーバーと組み合わせることで、実用的なAPIを構築する方法を学ぶことができます。
7. bird-checker-with-nextjs-and-eval サンプル調査
概要
Next.jsアプリケーションとして実装された鳥判定AIエージェント
Unsplashからランダムな画像を取得し、その画像が鳥かどうかを判定
Braintrustを使用してLLMプロンプトを評価する機能を追加
モダンなUIとシンタックスハイライト機能を実装
主な機能
🕊️ Unsplashから選択したクエリに一致するランダム画像を取得
🤖 構造化されたレスポンスを返すAIエージェント
🔵 プロンプトを評価するためのBraintrust評価機能
🎨 シンタックスハイライト機能を備えたモダンなUI
技術スタック
Next.js
Mastra AI
Anthropic Claude API
Unsplash API
Braintrust API
React
TypeScript
コードの特徴
`mastra/index.ts`: Mastraインスタンスの作成と設定
`agents/index.ts`: Claude-3-haikuモデルを使用した鳥判定エージェントの定義
`lib/mastra/actions.ts`: サーバーアクションとしてUnsplash画像取得とAIエージェント呼び出しを実装
`app/components/bird-checker.tsx`: UIコンポーネントとして画像表示と鳥判定結果の表示を実装
8. bird-checker-with-nextjs サンプル
概要
bird-checker-with-nextjsサンプルは、Next.jsフレームワークとMastraを組み合わせて、画像が鳥かどうかを判定するAIエージェントを実装した例です。このサンプルでは、Unsplashから画像を取得し、AIを使用して画像が鳥かどうかを判定し、鳥の種類や撮影場所などの情報を提供します。
主な機能
Next.jsを使用したモダンなUI実装
Unsplashから指定クエリに一致するランダム画像の取得
Anthropicの画像認識モデル(Claude 3 Haiku)の活用
画像が鳥かどうかの判定と、鳥の種類や撮影場所の情報提供
サーバーアクションを使用したAPIエンドポイント実装
技術的詳細
`@mastra/core`パッケージの`Agent`と`Mastra`クラスを使用
`@ai-sdk/anthropic`を使用したAnthropicモデルとの連携
Next.jsの`"use server"`ディレクティブを使用したサーバーアクション
Zodライブラリによる出力スキーマの定義
React Hooksを使用したステート管理とUIの実装
サンプルコード解説
このサンプルでは、以下の主要なコンポーネントを実装しています:
エージェントの定義:
exportconst birdAgent =new Agent({name:"Bird checker",instructions:"You can view an image and figure out if it is a bird or not. You can also figure out the species of the bird and where the picture was taken.",model: anthropic("claude-3-haiku-20240307"),});
Mastraインスタンスの作成:
exportconst mastra =new Mastra({agents: { birdAgent },});
サーバーアクション(画像メタデータ取得):
exportconst promptClaude =async ({ imageUrl,}: { imageUrl:string;}): Promise<ImageResponse<BirdResponse,string>> => {try {const birdAgent = mastra.getAgent("birdAgent");const response =await birdAgent.generate( [ { role:"user", content: [ { type:"image", image: imageUrl, }, { type:"text", text:"view this image and let me know if it's a bird or not, and the scientific name of the bird without any explanation. Also summarize the location for this picture in one or two short sentences understandable by a high school student", },], }, ], { output: z.object({ bird: z.boolean(), species: z.string(), location: z.string(), }), }, );const {object } = response;return { ok:true, data:objectas BirdResponse }; }catch (err) { console.error("Error prompting claude:", err);return { ok:false, error:"Could not fetch image metadata" }; }};
UIコンポーネント(BirdChecker):
exportconst BirdChecker =() => {const [image, setImage] = useState<Image |null>(null);const [status, setStatus] = useState<Status>("idle");const [query, setQuery] = useQueryState("query", {defaultValue:"wildlife", }); useEffect(() => {const getRandomImage =async () => { setStatus("loading");const res =await getImage({query: queryas ImageQuery });if (!res.ok) { setStatus("error"); toast.error("Failed to fetch image");return; } setImage(res.data); setStatus("success"); }; getRandomImage(); }, [query]);// ...レンダリングコード};
注目ポイント
このサンプルは、Mastraフレームワークを実際のWebアプリケーションに統合する方法を示す良い例です。特に、Next.jsのサーバーアクションと組み合わせることで、フロントエンドとバックエンドの統合が容易になっています。また、デモサイト(https://bird-checker.vercel.app)も公開されており、実際の動作を確認することができます。
9. crypto-chatbot サンプル調査
概要
Next.jsとAI SDKを使用した暗号通貨関連のチャットボットアプリケーション
OpenAI GPT-4oモデルをデフォルトとして使用
暗号通貨の検索、価格取得、履歴データ取得などの機能を提供
データ永続化のためのPostgreSQLデータベース統合
主な機能
暗号通貨に関する質問応答
暗号通貨の検索と情報取得
リアルタイムの価格情報の取得
履歴価格データのチャート表示
チャット履歴の保存と参照
技術スタック
Next.js App Router
Mastra AI
AI SDK (OpenAI, Anthropic, Cohereなどのモデルプロバイダーをサポート)
PostgreSQL (Vercel Postgres powered by Neon)
TypeScript
Tailwind CSS
shadcn/ui
NextAuth.js
コードの特徴
`mastra/index.ts`: Mastraインスタンスの作成と設定、OpenAI GPT-4o-miniモデルの使用
`agents/index.ts`: 暗号通貨エージェントの定義、PostgreSQLを使用したメモリ機能の実装
`tools/index.ts`: 暗号通貨検索、価格取得、履歴データ取得のためのツール実装
CoinGecko APIを使用した暗号通貨データの取得
実装の特徴
サーバーサイドレンダリングとサーバーアクションの活用
AI SDKを使用した統一APIによるテキスト生成
PostgreSQLを使用したチャット履歴の保存
zodを使用した型安全な入力スキーマの定義
複数のモデルプロバイダーへの切り替え機能
必要な環境変数
POSTGRES_URL: データベース接続用
COINGECKO_API_KEY: 暗号通貨データ取得用
10. dane サンプル調査
概要
AIアシスタントとして機能するCLIツール「Dane」
開発者の作業をサポートするための多機能AIコンパニオン
コミットメッセージの生成、GitHubの問題ラベル付け、コード作成・テストなど多様な機能を提供
npmからインストール可能なグローバルCLIツールとして実装
主な機能
セマンティックに正しいコミットメッセージの生成
GitHubの問題に対する自動ラベル付け
コードの作成とテストのサポート
クラウドへのアプリケーションデプロイ支援
ファイルシステム操作のサポート
Web検索による質問回答
カレンダー管理のサポート
PDFからの情報抽出
Webサイトのクローリングとデータ収集
技術スタック
TypeScript
Mastra AI
PostgreSQL (メモリストレージ用)
複数のツール統合 (ブラウザ、カレンダー、ファイルシステム、PDF読み取りなど)
CLIインターフェース (chalk for colored output)
コードの特徴
`agents/index.ts`: 複数のエージェント定義(コミットメッセージ生成、問題ラベル付け、リンクチェック、変更ログ作成など)
`tools/`: 様々なツール実装(ブラウザ、カレンダー、ファイルシステム、PDF読み取り、画像生成など)
モジュラーなワークフローシステムによるタスク実行
実装の特徴
対話型CLIインターフェース
GitHub統合(自動問題ラベル付け、コミットメッセージ生成)
FireCrawl統合によるWebクローリング
PDFリーダーツール
カレンダー管理ツール
Web検索ツール
ファイルシステム操作ツール(読み取り、書き込み、追加)
必要な環境変数
ANTHROPIC_API_KEY: AIモデル用
PostgreSQLデータベース(ローカルで実行、ポート5433:5432、データベース名「mastra」)
GitHub統合用の環境変数(ISSUE_NUMBER、OWNER、REPO)
最後に
この記事では10パターンのサンプルを紹介しました!今後もXでOpenAI Agents SDKやMastraに関する情報発信を行なっていくので、良ければいいねやフォローをお願いします!
X:吉波拓夢