跳至主要內容

建置 AI 主廚助理

在本指南中,你將建立一個「主廚助理」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 伺服器
「執行 Agent 伺服器」的直接連結

了解如何透過 Mastra 的 API 與 Agent 互動。

  1. 你可以使用 mastra dev 指令,將 Agent 作為服務執行:

    mastra dev

    這會啟動伺服器,公開可與已註冊 Agent 互動的端點。在 Studio 中,你可以透過使用者介面測試 Agent。

  2. mastra dev 預設會在 http://localhost:4111 上執行。你的主廚助理 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..."
    }