打造人工智能厨师助手
🌐 Building an AI Chef Assistant
在本指南中,你将创建一个“厨师助手”代理,帮助用户使用现有食材烹饪餐点。
🌐 In this guide, you'll create a "Chef Assistant" agent that helps users cook meals with available ingredients.
你将学习如何创建代理并将其注册到 Mastra。接下来,你将通过终端与代理进行互动,并了解不同的响应格式。最后,你将通过 Mastra 的本地 API 端点访问代理。
🌐 You'll learn how to create the agent and register it with Mastra. Next, you'll interact with the agent through your terminal and get to know different response formats. Lastly, you'll access the agent through Mastra's local API endpoints.
先决条件Direct link to 先决条件
🌐 Prerequisites
创建代理Direct link to 创建代理
🌐 Creating the Agent
要在 Mastra 中创建一个代理,使用 Agent 类来定义它,然后将其注册到 Mastra。
🌐 To create an agent in Mastra use the Agent class to define it and then register it with Mastra.
创建一个新文件
src/mastra/agents/chefAgent.ts并定义你的代理:🌐 Create a new file
src/mastra/agents/chefAgent.tsand define your 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.1",
});在你的
src/mastra/index.ts文件中,注册代理:🌐 In your
src/mastra/index.tsfile, register the agent:src/mastra/index.tsimport { Mastra } from "@mastra/core";
import { chefAgent } from "./agents/chefAgent";
export const mastra = new Mastra({
agents: { chefAgent },
});
与代理互动Direct link to 与代理互动
🌐 Interacting with the Agent
根据你的需求,你可以以不同的格式与代理进行交互并获取响应。在接下来的步骤中,你将学习如何生成、流式传输以及获取结构化输出。
🌐 Depending on your requirements you can interact and get responses from the agent in different formats. In the following steps you'll learn how to generate, stream, and get structured output.
创建一个新文件
src/index.ts并向其中添加main()函数。在函数内,编写一个查询以向代理提问并记录其响应。🌐 Create a new file
src/index.tsand add amain()function to it. Inside, craft a query to ask the agent and log its response.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();之后,运行脚本:
🌐 Afterwards, run the script:
npx bun src/index.ts你应该得到类似这样的输出:
🌐 You should get an output similar to this:
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...在前面的例子中,你可能会等待一会儿才能看到响应,而没有任何进展的迹象。为了在代理生成输出时显示它的内容,你应该改为将其响应流式传输到终端。
🌐 In the previous example you might have waited a bit for the response without any sign of progress. To show the agent's output as it creates it you should instead stream its response to the terminal.
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();之后,再次运行脚本:
🌐 Afterwards, run the script again:
npx bun src/index.ts你应该得到类似下面的输出。不过这一次,你可以逐行读取,而不是一次读取整块内容。
🌐 You should get an output similar to the one below. This time though you can read it line by line instead of one large block.
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!你可能希望将代理的回应传递给代码的其他部分,而不是展示给人类。在这种情况下,你的代理应返回结构化输出。
🌐 Instead of showing the agent's response to a human you might want to pass it along to another part of your code. For these instances your agent should return structured output.
将你的
src/index.ts更改为以下内容:🌐 Change your
src/index.tsto the following: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 schema
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 }],
{
structuredOutput: {
schema,
},
},
);
console.log("\n👨🍳 Chef Michel:", response.object);
}
main();再次运行脚本后,你应该会得到类似这样的输出:
🌐 After running the script again you should get an output similar to this:
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.",
]
}
运行代理服务器Direct link to 运行代理服务器
🌐 Running the Agent Server
了解如何通过 Mastra 的 API 与你的代理进行交互。
🌐 Learn how to interact with your agent through Mastra's API.
你可以使用
mastra dev命令将你的代理作为服务运行:🌐 You can run your agent as a service using the
mastra devcommand:mastra dev这将启动一个服务器,开放端点以便与你注册的代理进行交互。在 Studio 中,你可以通过用户界面测试你的代理。
🌐 This will start a server exposing endpoints to interact with your registered agents. Within Studio you can test your agent through a UI.
默认情况下,
mastra dev在http://localhost:4111上运行。你的 Chef Assistant 代理将可用于:🌐 By default,
mastra devruns onhttp://localhost:4111. Your Chef Assistant agent will be available at:POST http://localhost:4111/api/agents/chefAgent/generate你可以使用
curl在命令行与代理进行交互:🌐 You can interact with the agent using
curlfrom the command line: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..."
}