AIシェフアシスタントの構築
このガイドでは、手元の食材で料理を作るのを手助けする「Chef Assistant」エージェントを作成します。
まず、エージェントを作成して Mastra に登録する方法を学びます。次に、ターミナルからエージェントとやり取りし、さまざまな応答形式を確認します。最後に、Mastra のローカル API エンドポイントを通じてエージェントにアクセスします。
前提条件
- Node.js
v20.0
以降がインストールされていること - サポート対象のモデルプロバイダーから取得した API キー
- 既存の Mastra プロジェクト(新規プロジェクトのセットアップはインストールガイドに従ってください)
エージェントの作成
Mastraでエージェントを作成するには、Agent
クラスで定義し、その後Mastraに登録します。
エージェントを定義する
新規ファイル src/mastra/agents/chefAgent.ts
を作成し、次のようにエージェントを定義します:
import { openai } from "@ai-sdk/openai";
import { Agent } from "@mastra/core/agent";
export const chefAgent = new 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-4o-mini"),
});
エージェントをMastraに登録する
src/mastra/index.ts
ファイルでエージェントを登録します:
import { Mastra } from "@mastra/core";
import { chefAgent } from "./agents/chefAgent";
export const mastra = new Mastra({
agents: { chefAgent },
});
エージェントとのやり取り
要件に応じて、エージェントと対話し、さまざまな形式で応答を受け取れます。以下の手順では、生成、ストリーミング、構造化出力の取得方法を学びます。
テキスト応答の生成
新しいファイル src/index.ts
を作成し、main()
関数を追加します。関数内でエージェントへの質問(クエリ)を作成し、その応答をログに出力します。
import { 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...
ストリーミング応答
前の例では、進捗が見えないまま応答を少し待ったかもしれません。エージェントが出力を生成するのに合わせて表示するには、応答をターミナルにストリーミングします。
import { 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
下記のような出力が得られるはずです。今回は一つの大きな塊ではなく、行ごとに読めます。
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!
構造化データでレシピを生成する
エージェントの応答を人に見せる代わりに、コードの別の部分に渡したい場合があります。こうしたケースでは、エージェントは構造化出力を返すべきです。
src/index.ts
を次のように変更します:
import { 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}`);
// Zod スキーマを定義
const 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 }],
{ output: 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.",
// ...
]
}
エージェントサーバーの実行
Mastra の API を通じてエージェントとやり取りする方法を説明します。
mastra dev
の利用
mastra dev
コマンドで、エージェントをサービスとして起動できます:
mastra dev
これにより、登録済みのエージェントとやり取りするためのエンドポイントを公開するサーバーが起動します。playground では、UI からエージェントをテストできます。
Chef Assistant API へのアクセス
デフォルトでは、mastra dev
は http://localhost:4111
で実行されます。Chef Assistant エージェントには次のエンドポイントからアクセスできます:
POST http://localhost:4111/api/agents/chefAgent/generate
curl
でのエージェントとのやり取り
コマンドラインから curl
を使ってエージェントとやり取りできます:
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..."
}