> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Workflow\.agent() `.agent()` 方法會加入 Agent 作為宣告式步驟。步驟預設接受 `{ prompt: string }` 作為輸入,並傳回 `{ text: string }`。在 Agent 前使用 `.map()`,即可根據 Workflow 資料建立 prompt。 與使用 `createStep()` 包裝 Agent 不同,`.agent()` 會在 Workflow graph 中記錄宣告式項目,令 Workflow 可移植:同一個 graph 可序列化並保存為 [dynamic Workflow](https://mastra.zisheng.pro/zh-HK/docs/workflows/dynamic-workflows)。 ## 使用範例 ```typescript workflow .map({ prompt: mapVariable({ initData: workflow, path: "topic" }) }) .agent(testAgent) .commit(); ``` ## 參數 **agentOrId** (`Agent | string`): Agent 實例,或在 Mastra 實例上註冊的 Agent ID。傳入 ID 時,系統會在執行階段從 registry 解析 Agent。 **options** (`AgentStepOptions & { structuredOutput?: { schema }, retries?: number, scorers?: DynamicArgument, metadata?: StepMetadata }`): Agent 呼叫選項,例如 maxSteps、modelSettings、memory 及 providerOptions,以及步驟層級的 retries、scorers 及 metadata。requestContext、resourceId、threadId 及 onStepFinish 等每次請求欄位由 Workflow engine 管理,因此不包括在內。 **stepOptions** (`{ id?: string }`): 步驟在 Workflow 內呼叫位置的 ID。預設為 Agent 的 ID。當同一 Agent 在一個 Workflow 中出現多次時,請設定此項。 ## 傳回值 **workflow** (`Workflow`): 用於串連方法的 Workflow 實例 ## Structured output 步驟的輸出預設為 `{ text: string }`。傳入 `structuredOutput.schema`,可令步驟改為傳回該結構。此 schema 會成為步驟的輸出 schema,讓後續步驟以完整類型安全串連: ```typescript workflow .agent(testAgent, { structuredOutput: { schema: z.object({ subtopics: z.array(z.string()), }), }, }) .commit(); ``` ## 以 ID 引用 Agent 傳入字串即可引用已註冊的 Agent,毋須匯入。執行 Workflow 時,Agent 必須已在 Mastra 實例上註冊: ```typescript workflow.agent("test-agent", { maxSteps: 3 }).commit(); ``` ## 保存 Agent 步驟 使用 `.agent()` 建立的 Workflow 會序列化成與 [dynamic Workflow](https://mastra.zisheng.pro/zh-HK/docs/workflows/dynamic-workflows) 所用相同的宣告式項目。透過儲存空間來回保存時,只會保留 `retries` 及 `metadata`。儲存 Workflow 時,如 `onFinish` 或值為 function 的 `toolChoice` 等包含 function 的選項,便會擲回錯誤。 ## 相關內容 - [Agent 及 Tool](https://mastra.zisheng.pro/zh-HK/docs/workflows/agents-and-tools) - [Dynamic Workflow](https://mastra.zisheng.pro/zh-HK/docs/workflows/dynamic-workflows) - [Workflow.tool()](https://mastra.zisheng.pro/zh-HK/reference/workflows/workflow-methods/tool)