> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Workflow\.agent() `.agent()` 方法将 agent 添加为声明式步骤。该步骤接受 `{ prompt: string }` 作为输入,默认返回 `{ text: string }`。在 agent 之前使用 `.map()`,可根据 workflow 数据构建 prompt。 与使用 `createStep()` 包装 agent 不同,`.agent()` 会在 workflow 图中记录一个声明式条目。这使 workflow 可移植:同一个图可以序列化并持久化为[动态 workflow](https://mastra.zisheng.pro/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,而无需导入它。workflow 运行时,该 agent 必须已在 Mastra 实例上注册: ```typescript workflow.agent("test-agent", { maxSteps: 3 }).commit(); ``` ## 持久化 agent 步骤 使用 `.agent()` 构建的 workflow 会序列化为[动态 workflow](https://mastra.zisheng.pro/docs/workflows/dynamic-workflows)使用的同一种声明式条目。只有 `retries` 和 `metadata` 可以通过存储往返保留。包含函数的选项,例如 `onFinish` 或值为函数的 `toolChoice`,会在存储 workflow 时抛出错误。 ## 相关内容 - [Agents 和 Tools](https://mastra.zisheng.pro/docs/workflows/agents-and-tools) - [动态 workflow](https://mastra.zisheng.pro/docs/workflows/dynamic-workflows) - [Workflow.tool()](https://mastra.zisheng.pro/reference/workflows/workflow-methods/tool)