> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Workflow\.agent() `.agent()` 方法會將 Agent 新增為宣告式步驟。此步驟接受 `{ prompt: string }` 作為輸入,預設回傳 `{ text: string }`。請在 Agent 之前使用 `.map()`,根據 Workflow 資料建立 prompt。 與使用 `createStep()` 包裝 Agent 不同,`.agent()` 會在 Workflow 圖中記錄宣告式項目。這能讓 Workflow 具備可攜性:同一個圖可以序列化,並保存為[動態 Workflow](https://mastra.zisheng.pro/zh-TW/docs/workflows/dynamic-workflows)。 ## 使用範例 ```typescript workflow .map({ prompt: mapVariable({ initData: workflow, path: "topic" }) }) .agent(testAgent) .commit(); ``` ## 參數 **agentOrId** (`Agent | string`): Agent 執行個體,或已在 Mastra 執行個體上註冊的 Agent ID。傳入 ID 時,系統會在執行階段從登錄檔解析 Agent。 **options** (`AgentStepOptions & { structuredOutput?: { schema }, retries?: number, scorers?: DynamicArgument, metadata?: StepMetadata }`): Agent 呼叫選項,例如 maxSteps、modelSettings、memory 與 providerOptions,以及步驟層級的 retries、scorers 和 metadata。requestContext、resourceId、threadId 與 onStepFinish 等逐次請求欄位由 Workflow 引擎管理,因此會排除。 **stepOptions** (`{ id?: string }`): 此步驟在 Workflow 中呼叫位置的 ID。預設為 Agent 的 ID。同一個 Agent 在同一個 Workflow 中出現多次時,請設定此值。 ## 回傳值 **workflow** (`Workflow`): 可供方法連結使用的 Workflow 執行個體 ## 結構化輸出 此步驟預設輸出 `{ text: string }`。傳入 `structuredOutput.schema`,即可改為回傳該結構。此 schema 會成為步驟的輸出 schema,因此後續步驟能以完整的型別安全機制接續處理: ```typescript workflow .agent(testAgent, { structuredOutput: { schema: z.object({ subtopics: z.array(z.string()), }), }, }) .commit(); ``` ## 透過 ID 參照 Agent 傳入字串,即可在不匯入 Agent 的情況下參照已註冊的 Agent。Workflow 執行時,該 Agent 必須已註冊於 Mastra 執行個體: ```typescript workflow.agent("test-agent", { maxSteps: 3 }).commit(); ``` ## 保存 Agent 步驟 使用 `.agent()` 建立的 Workflow,會序列化為與[動態 Workflow](https://mastra.zisheng.pro/zh-TW/docs/workflows/dynamic-workflows) 相同的宣告式項目。只有 `retries` 與 `metadata` 能完整寫入儲存空間後再還原。保存 Workflow 時,`onFinish` 或值為函式的 `toolChoice` 等含有函式的選項會擲回錯誤。 ## 相關內容 - [Agent 與 Tool](https://mastra.zisheng.pro/zh-TW/docs/workflows/agents-and-tools) - [動態 Workflow](https://mastra.zisheng.pro/zh-TW/docs/workflows/dynamic-workflows) - [Workflow.tool()](https://mastra.zisheng.pro/zh-TW/reference/workflows/workflow-methods/tool)