跳到主要内容

Workflow.map()

.map() 方法将前一个步骤的输出数据映射到后续步骤的输入,让你能够在步骤之间转换数据。

使用示例
使用示例的直接链接

workflow.map(async ({ inputData }) => `${inputData.value} - map`)

参数
参数的直接链接

mappingFunction:

(params: { inputData: any }) => any
转换输入数据并返回映射结果的函数

返回值
返回值的直接链接

workflow:

Workflow
用于方法链式调用的 workflow 实例

使用 inputData
using-inputdata的直接链接

使用 inputData 访问前一个步骤的完整输出。

.then(step1)
.map(({ inputData }) => {
console.log(inputData);
})

使用 getStepResult()
using-getstepresult的直接链接

使用 getStepResult(),通过引用步骤实例来访问特定步骤的完整输出。

.then(step1)
.map(async ({ getStepResult }) => {
console.log(getStepResult(step1));
})

使用 getInitData()
using-getinitdata的直接链接

使用 getInitData<typeof workflow>() 访问提供给 workflow 的初始输入数据。

.then(step1)
.map(async ({ getInitData }) => {
console.log(getInitData<any>());
})

使用 mapVariable()
using-mapvariable的直接链接

.map() 的对象形式提供了用于映射字段的另一种声明式语法。你无需编写函数,而是定义一个对象,其中每个键都是新字段名,每个值使用 mapVariable() 从前面的步骤或 workflow 输入中提取数据。请从 workflows 模块导入 mapVariable()

import { mapVariable } from '@mastra/core/workflows'

从步骤输出提取字段
从步骤输出提取字段的直接链接

使用带有 stepmapVariable(),从步骤输出中提取特定字段并将其映射为新字段名。path 参数指定要提取的字段。在此示例中,step1 输出中的 value 字段会被提取并映射到名为 details 的新字段:

.then(step1)
.map({
details: mapVariable({
step: step1,
path: "value"
})
})

从 workflow 输入提取字段
从 workflow 输入提取字段的直接链接

使用带有 initDatamapVariable(),从 workflow 的初始输入数据中提取特定字段。当你需要将原始 workflow 输入传递给后续步骤时,这很有用。在此示例中,workflow 输入中的 value 字段会被提取并映射到名为 details 的字段:

export const testWorkflow = createWorkflow({...});

testWorkflow
.then(step1)
.map({
details: mapVariable({
initData: testWorkflow,
path: "value"
})
})