跳到主要内容

构建 AI 厨师助手

在本指南中,你将创建一个“Chef Assistant”Agent,帮助用户利用手头现有食材烹饪餐点。

你将学习如何创建 Agent 并将其注册到 Mastra。接下来,你会通过终端与 Agent 交互,并了解不同的响应格式。然后,你会通过 Mastra 的本地 API 端点访问 Agent。

前提条件
前提条件的直接链接

  • 已安装 Node.js v22.13.0 或更高版本
  • 受支持的 Model Provider 提供的 API 密钥
  • 现有的 Mastra 项目(按照安装指南设置新项目)

创建 Agent
创建 Agent的直接链接

要在 Mastra 中创建 Agent,请使用 Agent 类进行定义,然后将其注册到 Mastra。

  1. 新建文件 src/mastra/agents/chefAgent.ts 并定义 Agent:

    src/mastra/agents/chefAgent.ts
    import { 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',
    })
  2. src/mastra/index.ts 文件中注册 Agent:

    src/mastra/index.ts
    import { Mastra } from '@mastra/core'
    import { chefAgent } from './agents/chefAgent'

    export const mastra = new Mastra({
    agents: { chefAgent },
    })

与 Agent 交互
与 Agent 交互的直接链接

根据你的需求,可以使用不同格式与 Agent 交互并获取响应。接下来的步骤将介绍如何生成、流式传输和获取结构化输出。

  1. 新建文件 src/index.ts 并添加 main() 函数。在函数中构造一个询问 Agent 的查询,并记录其响应。

    src/index.ts
    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...
  2. 在上一个示例中,你可能等待了一段时间才收到响应,其间看不到任何进度。要在 Agent 创建输出时立即显示内容,应改为将其响应流式传输到终端。

    src/index.ts
    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!
  3. 有时你可能不想把 Agent 响应直接展示给用户,而是将其传给代码的其他部分。在这些情况下,Agent 应返回结构化输出

    src/index.ts 更改为以下内容:

    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}`)

    // 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()

    再次运行脚本后,你应该会看到类似下面的输出:

    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 server
运行 Agent server的直接链接

了解如何通过 Mastra API 与 Agent 交互。

  1. 你可以使用 mastra dev 命令,将 Agent 作为服务运行:

    mastra dev

    该命令会启动一个 server,开放用于与已注册 Agent 交互的端点。在 Studio 中,你可以通过 UI 测试 Agent。

  2. 默认情况下,mastra dev 运行在 http://localhost:4111。Chef Assistant Agent 可通过以下地址访问:

    POST http://localhost:4111/api/agents/chefAgent/generate
  3. 你可以在命令行中使用 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..."
    }