> Discover all available pages from the documentation index: https://mastra.zisheng.pro/llms.txt # Step 类 Step 类定义 workflow 中的各个工作单元,封装执行逻辑、数据验证以及输入/输出处理。 它可以接受 tool 或 agent 作为参数,并根据它们自动创建步骤。 ## 使用示例 ```typescript import { createWorkflow, createStep } from '@mastra/core/workflows' import { z } from 'zod' const step1 = createStep({ id: 'step-1', description: 'passes value from input to output', inputSchema: z.object({ value: z.number(), }), outputSchema: z.object({ value: z.number(), }), execute: async ({ inputData }) => { const { value } = inputData return { value, } }, }) ``` ## 定义 schema 可以使用任何支持 [Standard JSON Schema](https://standardschema.dev/json-schema) 的库定义步骤的 `inputSchema` 和 `outputSchema`,包括 [Zod](https://zod.dev/)、[Valibot](https://valibot.dev/) 和 [ArkType](https://arktype.io/) 等库。 **Zod**: ```typescript import { createStep } from '@mastra/core/workflows' import { z } from 'zod' const step1 = createStep({ id: 'step-1', inputSchema: z.object({ message: z.string(), }), outputSchema: z.object({ formatted: z.string(), }), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` **Valibot**: ```typescript import { createStep } from '@mastra/core/workflows' import * as v from 'valibot' import { toStandardJsonSchema } from '@valibot/to-json-schema' const step1 = createStep({ id: 'step-1', inputSchema: toStandardJsonSchema( v.object({ message: v.string(), }), ), outputSchema: toStandardJsonSchema( v.object({ formatted: v.string(), }), ), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` **ArkType**: ```typescript import { createStep } from '@mastra/core/workflows' import { type } from 'arktype' const step1 = createStep({ id: 'step-1', inputSchema: type({ message: 'string', }), outputSchema: type({ formatted: 'string', }), execute: async ({ inputData }) => { const { message } = inputData return { formatted: message.toUpperCase(), } }, }) ``` ## 从 agent 创建步骤 可以直接根据 agent 创建步骤。该步骤会使用 agent 的名称作为 ID。 ### 基本 agent 步骤 ```typescript import { testAgent } from '../agents/test-agent' const agentStep = createStep(testAgent) // inputSchema: { prompt: string } // outputSchema: { text: string } ``` ### 带结构化输出的 agent 步骤 传入 `structuredOutput` 可让 agent 返回带类型的结构化数据: ```typescript const articleSchema = z.object({ title: z.string(), summary: z.string(), tags: z.array(z.string()), }) const agentStep = createStep(testAgent, { structuredOutput: { schema: articleSchema }, }) // inputSchema: { prompt: string } // outputSchema: { title: string, summary: string, tags: string[] } ``` ### Agent 步骤选项 **structuredOutput** (`{ schema: StandardJSONSchemaV1 }`): 提供后,agent 会返回与此 schema 匹配的结构化数据,而不是纯文本。步骤的 outputSchema 会设置为提供的 schema。 **onFinish** (`(result: AgentResult) => void`): agent 完成生成时调用的回调。 ## 构造函数参数 **id** (`string`): 步骤的唯一标识符 **description** (`string`): 关于步骤功能的可选描述 **inputSchema** (`StandardJSONSchemaV1`): 定义输入结构的 Standard JSON Schema **outputSchema** (`StandardJSONSchemaV1`): 定义输出结构的 Standard JSON Schema **resumeSchema** (`StandardJSONSchemaV1`): 用于恢复步骤的可选 Standard JSON Schema **suspendSchema** (`StandardJSONSchemaV1`): 用于暂停步骤的可选 Standard JSON Schema **stateSchema** (`StandardJSONSchemaV1`): 用于步骤状态的可选 Standard JSON Schema。使用 Mastra 的状态系统时会自动注入。stateSchema 必须是 workflow stateSchema 的子集。若未指定,类型为 'any'。 **requestContextSchema** (`StandardJSONSchemaV1`): 用于验证请求上下文值的 Standard JSON Schema。提供后,会在步骤的 execute() 运行前验证上下文;验证失败时,步骤也会失败。 **execute** (`(params: ExecuteParams) => Promise`): 包含步骤逻辑的异步函数 **execute.inputData** (`z.infer`): 与 inputSchema 匹配的输入数据 **execute.resumeData** (`z.infer`): 从暂停状态恢复步骤时,与 resumeSchema 匹配的恢复数据。仅在恢复该步骤时存在。 **execute.suspendData** (`z.infer`): 步骤暂停时最初传给 suspend() 的暂停数据。仅在恢复步骤且该步骤之前使用数据暂停时存在。 **execute.mastra** (`Mastra`): 访问 Mastra 服务(agents、tools 等) **execute.getStepResult** (`(step: Step | string) => any`): 用于访问其他步骤结果的函数 **execute.getInitData** (`() => any`): 用于在任意步骤中访问 workflow 初始输入数据的函数 **execute.suspend** (`(suspendPayload: any, suspendOptions?: { resumeLabel?: string }) => Promise`): 用于暂停 workflow 执行的函数 **execute.state** (`z.infer`): 当前 workflow 状态,包含在所有步骤及暂停/恢复周期中持久保留的共享值。其结构由步骤的 stateSchema 定义。 **execute.setState** (`(state: z.infer) => void`): 用于设置 workflow 状态的函数。请通过类似 reducer 的模式注入,例如 'setState({ ...state, ...newState })' **execute.runId** (`string`): 当前 run ID **execute.requestContext** (`RequestContext`): 用于依赖注入和上下文信息的 Request Context。 **execute.retryCount** (`number`): 此特定步骤的重试次数,每次重试步骤时都会自动增加 **scorers** (`MastraScorers | (({ requestContext }) => MastraScorers | Promise)`): 步骤成功完成后自动运行的 scorers。每个 scorer 都会评估该步骤自身的输入和输出,结果会存储并附加到步骤的 trace。请提供 { \[name]: { scorer, sampling? } } 映射或返回该映射的函数。评分异步运行,不会阻塞 workflow。请参阅为步骤输出评分。 **retries** (`number`): 步骤的 execute 函数抛出错误时的重试次数。 **metadata** (`Record`): 用于存储其他步骤信息的可选键值对。值必须可序列化(不得包含函数、循环引用等)。 ## 为步骤输出评分 将 `scorers` 附加到步骤,可在该步骤运行时自动评估其输出,而不必只为 workflow 的最终答案评分。这适用于多步骤和 RAG workflow,例如,你可以在后续步骤对检索结果进行推理之前,判断检索步骤是否返回了相关 chunk,从而了解是哪个步骤降低了质量。 每个 scorer 都会接收该步骤自身的 `input` 和 `output`。步骤成功后会异步运行评分,并将结果存储到步骤的 trace 中。使用 `sampling` 控制 scorer 的运行频率。 以下示例将 scorer 附加到检索步骤,使每次执行都得到评分: ```typescript import { createStep } from '@mastra/core/workflows' import { z } from 'zod' import { retrievalRelevanceScorer } from '../scorers/retrieval-relevance' const retrievalStep = createStep({ id: 'retrieval', inputSchema: z.object({ query: z.string() }), outputSchema: z.object({ query: z.string(), chunks: z.array(z.string()) }), scorers: { retrievalRelevance: { scorer: retrievalRelevanceScorer(), sampling: { type: 'ratio', rate: 1 }, }, }, execute: async ({ inputData }) => { const chunks = await retrieve(inputData.query) return { query: inputData.query, chunks } }, }) ``` 将 scorer 附加到你要衡量的每个步骤,可以为多步骤 workflow 构建逐步骤评分。由于评分范围限定在单个步骤内,因此无需专用的跨步骤指标也能了解质量在何处发生变化。 通过 [`Workflow.agent()`](https://mastra.zisheng.pro/reference/workflows/workflow-methods/agent) 和 [`Workflow.tool()`](https://mastra.zisheng.pro/reference/workflows/workflow-methods/tool) 添加的 agent 和 tool 步骤,在其步骤选项中也接受相同的 `scorers` 选项。 > **备注:** 请访问 [Scorers 概览](https://mastra.zisheng.pro/docs/evals/overview),了解实时评估如何运行以及结果存储在哪里;请参阅[自定义 scorers](https://mastra.zisheng.pro/docs/evals/custom-scorers),了解如何构建自己的 scorer。 ## 相关内容 - [Workflow 状态](https://mastra.zisheng.pro/docs/workflows/workflow-state) - [控制流](https://mastra.zisheng.pro/docs/workflows/control-flow) - [使用 agents 和 tools](https://mastra.zisheng.pro/docs/workflows/agents-and-tools)