Skip to Content

Workflow.while()

.while() メソッドは、指定した条件が真である限り、ステップを繰り返します。これにより、条件が偽になるまで指定したステップを実行し続けるループが作成されます。

使い方

workflow.step(incrementStep).while(condition, incrementStep).then(finalStep);

パラメーター

condition:

Function | ReferenceCondition
ループを継続するかどうかを判定する関数または参照条件

step:

Step
条件が真の間に繰り返すステップ

条件タイプ

関数条件

真偽値を返す関数を使用できます:

workflow .step(incrementStep) .while(async ({ context }) => { const result = context.getStepResult<{ value: number }>("increment"); return (result?.value ?? 0) < 10; // valueが10未満の間は継続 }, incrementStep) .then(finalStep);

参照条件

比較演算子を使った参照ベースの条件を使用できます:

workflow .step(incrementStep) .while( { ref: { step: incrementStep, path: "value" }, query: { $lt: 10 }, // valueが10未満の間は継続 }, incrementStep, ) .then(finalStep);

比較演算子

参照ベースの条件を使用する場合、次の比較演算子を使用できます。

演算子説明
$eq等しい{ $eq: 10 }
$ne等しくない{ $ne: 0 }
$gtより大きい{ $gt: 5 }
$gte以上{ $gte: 10 }
$ltより小さい{ $lt: 20 }
$lte以下{ $lte: 15 }

戻り値

workflow:

Workflow
連鎖処理のためのワークフローインスタンス

import { Workflow, Step } from "@mastra/core"; import { z } from "zod"; // Create a step that increments a counter const incrementStep = new Step({ id: "increment", description: "Increments the counter by 1", outputSchema: z.object({ value: z.number(), }), execute: async ({ context }) => { // Get current value from previous execution or start at 0 const currentValue = context.getStepResult<{ value: number }>("increment")?.value || context.getStepResult<{ startValue: number }>("trigger")?.startValue || 0; // Increment the value const value = currentValue + 1; console.log(`Incrementing to ${value}`); return { value }; }, }); // Create a final step const finalStep = new Step({ id: "final", description: "Final step after loop completes", execute: async ({ context }) => { const finalValue = context.getStepResult<{ value: number }>( "increment", )?.value; console.log(`Loop completed with final value: ${finalValue}`); return { finalValue }; }, }); // Create the workflow const counterWorkflow = new Workflow({ name: "counter-workflow", triggerSchema: z.object({ startValue: z.number(), targetValue: z.number(), }), }); // Configure the workflow with a while loop counterWorkflow .step(incrementStep) .while(async ({ context }) => { const targetValue = context.triggerData.targetValue; const currentValue = context.getStepResult<{ value: number }>("increment")?.value ?? 0; return currentValue < targetValue; }, incrementStep) .then(finalStep) .commit(); // Execute the workflow const run = counterWorkflow.createRun(); const result = await run.start({ triggerData: { startValue: 0, targetValue: 5 }, }); // Will increment from 0 to 4, then stop and execute finalStep

関連