AI シェフアシスタントを構築する
このガイドでは、手元にある食材で料理を作れるようユーザーを支援する「Chef Assistant」Agent を作成します。
Agent を作成し、Mastra に登録する方法を学びます。次に、ターミナルから Agent と対話して、さまざまなレスポンス形式を確認します。その後、Mastra のローカル API エンドポイントを介して Agent にアクセスします。
前提条件前提条件への直接リンク
- Node.js
v22.13.0以降がインストールされていること - サポートされているモデル Provider の API キー
- 既存の Mastra プロジェクト(新しいプロジェクトをセットアップするには、インストールガイドに従ってください)
Agent を作成するAgent を作成するへの直接リンク
Mastra で Agent を作成するには、Agent クラスで定義してから Mastra に登録します。
新しいファイル
src/mastra/agents/chefAgent.tsを作成し、Agent を定義します。src/mastra/agents/chefAgent.tsimport { Agent } from '@mastra/core/agent'export const chefAgent = new Agent({id: 'chef-agent',name: 'chef-agent',instructions:'You are Michel, a practical and experienced home chef' +'You help people cook with whatever ingredients they have available.',model: 'openai/gpt-5.6-sol',})src/mastra/index.tsファイルで Agent を登録します。src/mastra/index.tsimport { Mastra } from '@mastra/core'import { chefAgent } from './agents/chefAgent'export const mastra = new Mastra({agents: { chefAgent },})
Agent と対話するAgent と対話するへの直接リンク
要件に応じて、Agent と対話し、さまざまな形式でレスポンスを取得できます。以下の手順では、生成、ストリーミング、構造化出力の取得方法を学びます。
新しいファイル
src/index.tsを作成し、main()関数を追加します。その中で Agent に送る質問を作成し、レスポンスをログに出力します。src/index.tsimport { chefAgent } from './mastra/agents/chefAgent'async function main() {const query ='In my kitchen I have: pasta, canned tomatoes, garlic, olive oil, and some dried herbs (basil and oregano). What can I make?'console.log(`Query: ${query}`)const response = await chefAgent.generate([{ role: 'user', content: query }])console.log('\n👨🍳 Chef Michel:', response.text)}main()続いて、スクリプトを実行します。
npx bun src/index.ts次のような出力が得られます。
Query: In my kitchen I have: pasta, canned tomatoes, garlic, olive oil, and some dried herbs (basil and oregano). What can I make?👨🍳 Chef Michel: You can make a delicious pasta al pomodoro! Here's how...前の例では、処理が進んでいる表示がないまま、レスポンスをしばらく待ったかもしれません。Agent がレスポンスを生成する過程を表示するには、代わりにレスポンスをターミナルへストリーミングします。
src/index.tsimport { chefAgent } from './mastra/agents/chefAgent'async function main() {const query ="Now I'm over at my friend's house, and they have: chicken thighs, coconut milk, sweet potatoes, and some curry powder."console.log(`Query: ${query}`)const stream = await chefAgent.stream([{ role: 'user', content: query }])console.log('\n Chef Michel: ')for await (const chunk of stream.textStream) {process.stdout.write(chunk)}console.log('\n\n✅ Recipe complete!')}main()続いて、スクリプトをもう一度実行します。
npx bun src/index.ts次のような出力が得られます。今回は、大きな 1 つのブロックではなく、行ごとに読み進められます。
Query: Now I'm over at my friend's house, and they have: chicken thighs, coconut milk, sweet potatoes, and some curry powder.👨🍳 Chef Michel:Great! You can make a comforting chicken curry...✅ Recipe complete!Agent のレスポンスを人に見せるのではなく、コードの別の部分に渡したい場合があります。そのような場合、Agent は構造化出力を返す必要があります。
src/index.tsを次のように変更します。src/index.tsimport { chefAgent } from './mastra/agents/chefAgent'import { z } from 'zod'async function main() {const query = 'I want to make lasagna, can you generate a lasagna recipe for me?'console.log(`Query: ${query}`)// Define the Zod schemaconst schema = z.object({ingredients: z.array(z.object({name: z.string(),amount: z.string(),}),),steps: z.array(z.string()),})const response = await chefAgent.generate([{ role: 'user', content: query }], {structuredOutput: {schema,},})console.log('\n👨🍳 Chef Michel:', response.object)}main()スクリプトをもう一度実行すると、次のような出力が得られます。
Query: I want to make lasagna, can you generate a lasagna recipe for me?👨🍳 Chef Michel: {ingredients: [{ name: "Lasagna noodles", amount: "12 sheets" },{ name: "Ground beef", amount: "1 pound" },],steps: ["Preheat oven to 375°F (190°C).","Cook the lasagna noodles according to package instructions.",]}
Agent サーバーを実行するAgent サーバーを実行するへの直接リンク
Mastra の API を介して Agent と対話する方法を学びます。
mastra devコマンドを使用して、Agent をサービスとして実行できます。mastra dev登録済みの Agent と対話するためのエンドポイントを公開するサーバーが起動します。Studio では、UI から Agent をテストできます。
デフォルトでは、
mastra devはhttp://localhost:4111で実行されます。Chef Assistant Agent は次の場所で利用できます。POST http://localhost:4111/api/agents/chefAgent/generateコマンドラインから
curlを使用して Agent と対話できます。curl -X POST http://localhost:4111/api/agents/chefAgent/generate \-H "Content-Type: application/json" \-d '{"messages": [{"role": "user","content": "I have eggs, flour, and milk. What can I make?"}]}'レスポンス例:
{"text": "You can make delicious pancakes! Here's a simple recipe..."}