> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # Workflows 舊版 Workflow 功能已移除。 ## 已變更 ### `getWorkflows` 改為 `listWorkflows` `mastra.getWorkflows()` 方法已重新命名為 `mastra.listWorkflows()`。這項變更與整個 API 所採用的命名慣例一致:傳回多個項目的 getter 方法會使用 `list` 前綴。 如要遷移,請將所有 `mastra.getWorkflows()` 呼叫替換為 `mastra.listWorkflows()`。 ```diff - const workflows = mastra.getWorkflows(); + const workflows = mastra.listWorkflows(); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新 import: > > ```bash > npx @mastra/codemod@latest v1/mastra-plural-apis . > ``` ### 步驟上下文中的 `RuntimeContext` 改為 `RequestContext` Workflow 步驟執行上下文中的參數名稱 `runtimeContext` 已改為 `requestContext`。這項變更配合全域重新命名,令含義更清晰。 如要遷移,請在步驟執行函數中,將 `runtimeContext` 的參照更新為 `requestContext`。 ```diff createStep({ - execute: async ({ runtimeContext } ) => { - const userTier = context.runtimeContext.get('userTier'); + execute: async ({ requestContext } ) => { + const userTier = requestContext.get('userTier'); return { result: userTier }; }, }); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新 import: > > ```bash > npx @mastra/codemod@latest v1/runtime-context . > ``` ### `createRunAsync` 改為 `createRun` `createRunAsync()` 方法已重新命名為 `createRun()`。由於所有 run 的建立操作都是非同步,這項變更移除了多餘的「Async」後綴,令 API 更簡潔。 如要遷移,請將方法呼叫由 `createRunAsync` 重新命名為 `createRun`。 ```diff - await workflow.createRunAsync({ input: { ... } }); + await workflow.createRun({ input: { ... } }); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新程式碼: > > ```bash > npx @mastra/codemod@latest v1/workflow-create-run-async . > ``` ### `runCount` 改為 `retryCount`(已棄用) Workflow 步驟執行中的 `runCount` 參數已棄用,請改用 `retryCount`。新名稱明確表示此值是重試次數。舊有的 `runCount` 仍可使用,但會顯示棄用警告。 如要遷移,請在步驟執行函數中,將 `runCount` 重新命名為 `retryCount`。 ```diff createStep({ execute: async (inputData, context) => { - console.log(`Step run ${context.runCount} times`); + console.log(`Step retry count: ${context.retryCount}`); }, }); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新程式碼: > > ```bash > npx @mastra/codemod@latest v1/workflow-run-count . > ``` ### `getInitData` 傳回 unknown 執行函數中的 `getInitData` 函數現在會傳回 unknown,而非 any。你需要自行指定其型別。 如要遷移,請將 `getInitData()` 改為 `getInitData()` ```diff createStep({ execute: async ({ getInitData }) => { - const initData = getInitData(); - if (initData.key === 'value') {} + const initData = getInitData(); + if (initData.key === 'value') {} }, }); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新程式碼: > > ```bash > npx @mastra/codemod@latest v1/workflow-get-init-data . > ``` ### `getWorkflowRuns` 改為 `listWorkflowRuns` `getWorkflowRuns()` 方法已重新命名為 `listWorkflowRuns()`。這項變更與 `list*` 方法傳回集合的慣例一致。 如要遷移,請將方法呼叫由 `getWorkflowRuns` 重新命名為 `listWorkflowRuns`。 ```diff - const runs = await workflow.getWorkflowRuns({ fromDate, toDate }); + const runs = await workflow.listWorkflowRuns({ fromDate, toDate }); ``` > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新程式碼: > > ```bash > npx @mastra/codemod@latest v1/workflow-list-runs . > ``` ### 預設驗證輸入 以往預設不會驗證輸入。[`validateInputs`](https://mastra.zisheng.pro/zh-HK/reference/workflows/workflow) 旗標決定是否驗證 Workflow 輸入。這個布林值的預設值已改為 `true`。如果你想沿用舊有行為,或有部分 Workflow 的 schema 不需要驗證,請設定 `validateInputs: false`。 ```diff createWorkflow({ + options: { + validateInputs: false + } }) ``` ### 步驟 `suspendPayload` 驗證 如果步驟已定義 `suspendSchema`,現在會驗證該步驟的 `suspendPayload`。這項驗證亦會使用 `validateInputs` 旗標,決定是否驗證 `suspendPayload`。 ```diff createStep({ id: "suspend-resume-step", // ... other step properties suspendSchema: z.object({ reason: z.string(), otherReason: z.string() }), execute: async ({ suspend, resumeData}) => { if (!resumeData) { - return suspend({ reason: "Suspension reason" }); // Missing otherReason + return suspend({ reason: "Suspension reason", otherReason: "Other reason" }); } }, }); ``` ### Branch 結果欄位現在為選填 `.branch()` 方法現在傳回的 schema 中,所有 branch 輸出欄位均為選填。這反映了執行階段的行為:每個 branch 只會在其條件為 truthy 時執行,因此任何 branch 的輸出都可能是 undefined。 如要遷移,請更新所有使用 branch 輸出的程式碼,以處理選填值。 ```diff const workflow = createWorkflow({...}) .branch([ [condition1, stepA], // outputSchema: { result: z.string() } [condition2, stepB], // outputSchema: { data: z.number() } ]) - // Previously: stepA.result typed as string, stepB.data typed as number + // Now: stepA.result typed as string | undefined, stepB.data typed as number | undefined .then(nextStep); ``` 如果你的程式碼依賴非選填型別,請在存取 branch 輸出時加入執行階段檢查,或提供預設值。 ### `Run.start()` 及 `Run.timeTravel()` 中的 `writableStream` 改為 `outputWriter` `Run.start()` 及 `Run.timeTravel()` 中的 `writableStream` 參數已由 `outputWriter` 取代。現在不再傳入 `WritableStream`,而是傳入一個非同步回呼函數,直接接收每個 Workflow 事件區塊。 這項變更令 API 更簡潔:你無須建立 `WritableStream` 包裝器,而可直接在回呼函數中處理區塊。 **範例:** 將 Workflow 事件串流至 HTTP 回應(SSE): ```diff const run = await workflow.createRun(); - const stream = new WritableStream({ - write(chunk) { - response.write(`data: ${JSON.stringify(chunk)}\n\n`); - } - }); - await run.start({ inputData, writableStream: stream }); + await run.start({ + inputData, + outputWriter: async (chunk) => { + response.write(`data: ${JSON.stringify(chunk)}\n\n`); + }, + }); ``` > **備註:** 這項變更不影響傳入步驟 `execute` 函數的 `writer` 參數。它仍是擴充 `WritableStream` 的 `ToolStream`,並提供 `.write()` 及 `.custom()` 方法: > > ```ts > createStep({ > id: 'my-step', > execute: async ({ writer }) => { > // This API is unchanged > await writer.write({ data: 'some output' }) > await writer.custom({ type: 'custom-event', payload: {} }) > }, > }) > ``` ### `setState()` 現為非同步,並會驗證傳入的資料 `setState()` 函數現在為非同步。傳入的資料現在會根據步驟中定義的 `stateSchema` 進行驗證。狀態資料驗證亦會使用 `validateInputs` 旗標,決定是否驗證狀態資料。此外,呼叫 `setState()` 時,你現在只需傳入正在更新的狀態資料,無須再加入先前狀態的展開運算 `(...state)`。 如要遷移,請更新 `setState()` 函數,令其以非同步方式呼叫。 ```diff - setState({ ...state, sharedCounter: state.sharedCounter + 1 }); + await setState({ sharedCounter: state.sharedCounter + 1 }); + // await setState({ ...state, sharedCounter: state.sharedCounter + 1 }); + // this also works, as the previous state spread remains supported ``` ## 已移除 ### `streamVNext`、`resumeStreamVNext` 及 `observeStreamVNext` 方法 實驗性的 `streamVNext()`、`resumeStreamVNext()` 及 `observeStreamVNext()` 方法已移除。這些方法現在已成為標準實作,並採用更新後的事件結構及傳回型別。 如要遷移,請使用標準的 `stream()`、`resumeStream()` 及 `observeStream()` 方法。請更新事件型別檢查,改用帶有 Workflow 前綴的名稱,並直接存取串流屬性。 詳情請參閱 [`Run.stream()`](https://mastra.zisheng.pro/zh-HK/reference/streaming/workflows/stream)、[`Run.resumeStream()`](https://mastra.zisheng.pro/zh-HK/reference/streaming/workflows/resumeStream) 及 [`Run.observeStream()`](https://mastra.zisheng.pro/zh-HK/reference/streaming/workflows/observeStream)。 > **Codemod:** 你可以使用 Mastra 的 codemod CLI 自動更新程式碼: > > ```bash > npx @mastra/codemod@latest v1/workflow-stream-vnext . > ``` ### 步驟條件函數的參數中不再提供 `suspend()` 及 `setState()` 步驟條件函數的參數中不再提供 `suspend()` 及 `setState()` 函數。 如要遷移,請改為在步驟的 execute 函數中使用 `suspend()` 函數。 ```diff .dowhile(step, async ({ suspend, state, setState }) => { - setState({...state, updatedState: "updated state"}) - await suspend({ reason: "Suspension reason" }); + // Use the suspend/setState in the step execute function instead }); ``` `dountil` 及 `branch` 條件函數的參數亦同樣如此。 ### 舊版 Workflow export `@mastra/core` 中的 `./workflows/legacy` export 路徑已移除。不再支援舊版 Workflow。 如要遷移,請使用新的 Workflow API。舊版 Workflow 並無直接遷移途徑。 ```diff - import { LegacyWorkflow } from '@mastra/core/workflows/legacy'; + // Legacy workflows are no longer supported + // Migrate to the new workflow API ``` ### `WorkflowRunOutput` 的 `pipeThrough` 及 `pipeTo` 方法 `WorkflowRunOutput` 上的 `pipeThrough()` 及 `pipeTo()` 方法已棄用。這些方法仍可使用,但會在主控台顯示警告。 如要遷移,請使用 `fullStream` 屬性,而非直接在 run 輸出上呼叫方法。 ```diff const run = await workflow.createRun({ input: { ... } }); - await run.pipeTo(writableStream); - const transformed = run.pipeThrough(transformStream); + await run.fullStream.pipeTo(writableStream); + const transformed = run.fullStream.pipeThrough(transformStream); ``` ### Watch 事件 API 舊版 Watch 事件已移除,並整合至 v2 事件 API。`watch()` 方法及相關 Watch 端點已不再提供。 如要遷移,請使用 Workflow 事件 API 或串流,而非 Watch 事件。 ```diff - const workflow = mastraClient.getWorkflow('my-workflow'); - const run = await workflow.createRun(); - await run.watch((event) => { - console.log('Step completed:', event); - }); + const workflow = mastraClient.getWorkflow('my-workflow'); + const run = await workflow.createRun(); + const stream = await run.stream({ inputData: { ... } }); + for await (const chunk of stream) { + console.log('Step completed:', chunk); + } ``` ### `waitForEvent` API Workflow 中的 `waitForEvent` API 已移除。請改用 suspend/resume API。 如要遷移,請使用 suspend/resume API 等待 Workflow 執行里程碑。 ```diff - workflow.waitForEvent('step-complete', step1).commit(); + workflow.then(step1).commit(); + // Use suspend/resume API instead, in step1 execute function createStep({ - execute: async (inputData, context) => { - // ... execution logic - } + execute: async (inputData, context) => { + if (!context.resumeData) { + return context.suspend({}) + } + } }); + + // after workflow is suspended, you can resume it + const result = await run.start({ inputData: { ... } }); + if (result.status === 'suspended') { + const resumedResult = await run.resume({ + resumeData: { + event: 'step-complete', + }, + step: 'step1', + }); + } ``` ### `sendEvent` API Workflow 中的 `sendEvent` API 已移除。請改用 suspend/resume API。