建構 AI 廚師助手
在本指南中,你會建立一個「廚師助手」Agent,協助使用者運用現有食材烹調餐點。
你會了解如何建立 Agent 並在 Mastra 中註冊。接着,你會透過終端機與 Agent 互動,並認識不同的回應格式。然後,你會透過 Mastra 的本機 API 端點存取 Agent。
先決條件先決條件 的直接連結
- 已安裝 Node.js
v22.13.0或更新版本 - 受支援的 Model 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你應該會取得類似以下的輸出。不過,這次你可以逐行閱讀,而非等待整個文字區塊一次過顯示。
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上執行。你的廚師助手 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..."}