> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Workflow 類別 `Workflow` 類別可讓你為包含條件分支與資料驗證的複雜操作序列建立狀態機。 ## 使用範例 ```typescript import { createWorkflow } from '@mastra/core/workflows' import { z } from 'zod' export const workflow = createWorkflow({ id: 'test-workflow', inputSchema: z.object({ value: z.string(), }), outputSchema: z.object({ value: z.string(), }), }) ``` ## 定義 schema 你可以使用任何支援 [Standard JSON Schema](https://standardschema.dev/json-schema) 的程式庫,定義 Workflow 的 `inputSchema` 與 `outputSchema`。包括 [Zod](https://zod.dev/)、[Valibot](https://valibot.dev/) 和 [ArkType](https://arktype.io/) 等程式庫。 **Zod**: ```typescript import { createWorkflow, createStep } from "@mastra/core/workflows"; import { z } from "zod"; const step1 = createStep({...}); export const testWorkflow = createWorkflow({ id: "test-workflow", inputSchema: z.object({ message: z.string() }), outputSchema: z.object({ output: z.string() }) }) .then(step1) .commit(); ``` **Valibot**: ```typescript import { createWorkflow, createStep } from "@mastra/core/workflows"; import * as v from "valibot"; import { toStandardJsonSchema } from "@valibot/to-json-schema"; const step1 = createStep({...}); export const testWorkflow = createWorkflow({ id: "test-workflow", inputSchema: toStandardJsonSchema(v.object({ message: v.string() })), outputSchema: toStandardJsonSchema(v.object({ output: v.string() })) }) .then(step1) .commit(); ``` **ArkType**: ```typescript import { createWorkflow, createStep } from "@mastra/core/workflows"; import { type } from "arktype"; const step1 = createStep({...}); export const testWorkflow = createWorkflow({ id: "test-workflow", inputSchema: type({ message: "string" }), outputSchema: type({ output: "string" }) }) .then(step1) .commit(); ``` ## 建構函式參數 **id** (`string`): Workflow 的唯一識別碼 **inputSchema** (`StandardJSONSchemaV1`): 定義 Workflow 輸入結構的 Standard JSON Schema **outputSchema** (`StandardJSONSchemaV1`): 定義 Workflow 輸出結構的 Standard JSON Schema **stateSchema** (`StandardJSONSchemaV1`): Workflow 狀態的選用 Standard JSON Schema。使用 Mastra 的狀態系統時會自動注入。若未指定,型別為 'any'。 **requestContextSchema** (`StandardJSONSchemaV1`): 用於驗證 request context 值的 Standard JSON Schema。提供此項目時,系統會在 run.start() 開始時驗證 context;驗證失敗會擲回錯誤。 **schedule** (`WorkflowScheduleConfig | WorkflowScheduleConfig[]`): Workflow 的選用 cron 排程。接受單一設定或設定陣列,以多種頻率觸發。設定此項目會自動將 Workflow 升級為事件式執行引擎。用法請參閱排程 Workflow 指南。 **schedule.id** (`string`): 排程的穩定識別碼。傳入排程陣列時為必填。傳入單一排程物件時,預設為 Workflow ID。 **schedule.cron** (`string`): 由 5、6 或 7 個部分組成的 cron 運算式。建立 Workflow 時會進行驗證。 **schedule.timezone** (`string`): IANA 時區,例如 "America/New\_York"。預設為主機的本地時區。在正式環境中請明確設定,以免觸發時間取決於伺服器 locale。 **schedule.inputData** (`TInput`): 每次觸發時,作為 Workflow 輸入傳入的 payload。 **schedule.initialState** (`TState`): Run 的初始狀態。 **schedule.requestContext** (`Record`): 附加至 run 的 request context。 **schedule.metadata** (`Record`): 與排程資料列一併保存的任意中繼資料。 **options** (`WorkflowOptions`): Workflow 的選用選項 **options.tracingPolicy** (`TracingPolicy`): Workflow 的選用 tracing 政策 **options.validateInputs** (`boolean`): 是否驗證 Workflow 輸入的選用旗標。這也會在 Workflow/步驟的輸入/繼續資料中套用 zodSchema 的預設值。若在 start/resume 時輸入/繼續資料驗證失敗,Workflow 不會啟動/繼續,而會擲回錯誤。若步驟執行時輸入資料驗證失敗,該步驟及 Workflow 都會失敗,並回傳錯誤。 **options.shouldPersistSnapshot** (`(params: { stepResults: Record>; workflowStatus: WorkflowRunStatus }) => boolean`): 是否保存 Workflow 快照的選用旗標 **options.pruneSnapshot** (`(params: { snapshot: WorkflowRunState; workflowStatus: WorkflowRunStatus }) => WorkflowRunState`): 在保存 Workflow 快照前立即轉換快照的選用 hook。必須回傳可序列化為 JSON 的資料,並保留 Workflow 繼續執行所需的一切(已暫停步驟的 suspendPayload、suspendedPaths、executionPath 等)。Agent run 在內部會用它縮減快照;使用者 Workflow 預設會保存完整快照。 **options.onFinish** (`(result: WorkflowFinishCallbackResult) => void | Promise`): Workflow 以任何狀態(success、failed、suspended、tripwire)完成時叫用的回呼函式。會收到包含狀態、輸出、錯誤與步驟結果的 Workflow 結果。此回呼函式擲回的錯誤會被攔截並記錄,不會向外傳播。 **options.onFinish.status** (`WorkflowRunStatus`): Workflow 狀態:'success'、'failed'、'suspended' 或 'tripwire' **options.onFinish.result** (`any`): Workflow 輸出(status 為 'success' 時) **options.onFinish.error** (`SerializedError`): 錯誤詳細資料(status 為 'failed' 時) **options.onFinish.steps** (`Record`): 包含狀態與輸出的個別步驟結果 **options.onFinish.tripwire** (`StepTripwireInfo`): Tripwire 資訊(status 為 'tripwire' 時) **options.onFinish.runId** (`string`): 此 Workflow run 的唯一識別碼 **options.onFinish.workflowId** (`string`): Workflow 的識別碼 **options.onFinish.resourceId** (`string`): 選用資源識別碼(建立 run 時若有提供) **options.onFinish.getInitData** (`() => any`): 回傳傳給 Workflow 之初始輸入資料的函式 **options.onFinish.mastra** (`Mastra`): Mastra 執行個體(若 Workflow 已向 Mastra 註冊) **options.onFinish.requestContext** (`RequestContext`): 以請求為範圍的 context 資料 **options.onFinish.logger** (`IMastraLogger`): Workflow 的 logger 執行個體 **options.onFinish.state** (`Record`): Workflow 目前的狀態物件 **options.onError** (`(errorInfo: WorkflowErrorCallbackInfo) => void | Promise`): 只在 Workflow 失敗(failed 或 tripwire 狀態)時叫用的回呼函式。會收到錯誤詳細資料與步驟結果。此回呼函式擲回的錯誤會被攔截並記錄,不會向外傳播。 **options.onError.status** (`'failed' | 'tripwire'`): Workflow 狀態('failed' 或 'tripwire') **options.onError.error** (`SerializedError`): 錯誤詳細資料 **options.onError.steps** (`Record`): 包含狀態與輸出的個別步驟結果 **options.onError.tripwire** (`StepTripwireInfo`): Tripwire 資訊(status 為 'tripwire' 時) **options.onError.runId** (`string`): 此 Workflow run 的唯一識別碼 **options.onError.workflowId** (`string`): Workflow 的識別碼 **options.onError.resourceId** (`string`): 選用資源識別碼(建立 run 時若有提供) **options.onError.getInitData** (`() => any`): 回傳傳給 Workflow 之初始輸入資料的函式 **options.onError.mastra** (`Mastra`): Mastra 執行個體(若 Workflow 已向 Mastra 註冊) **options.onError.requestContext** (`RequestContext`): 以請求為範圍的 context 資料 **options.onError.logger** (`IMastraLogger`): Workflow 的 logger 執行個體 **options.onError.state** (`Record`): Workflow 目前的狀態物件 ## 使用初始狀態執行 啟動 Workflow run 時,可以傳入 `initialState`,設定 Workflow 狀態的起始值: ```typescript const run = await workflow.createRun() const result = await run.start({ inputData: { value: 'hello' }, initialState: { counter: 0, items: [], }, }) ``` `initialState` 物件應符合 Workflow `stateSchema` 所定義的結構。更多詳細資料請參閱 [Workflow 狀態](https://mastra.zisheng.pro/zh-TW/docs/workflows/workflow-state)。 ## Workflow 狀態 Workflow 的 `status` 代表目前的執行狀態。可能的值如下: **success** (`string`): 所有步驟都已成功執行完畢,並產生有效的結果輸出 **failed** (`string`): Workflow 執行期間發生錯誤,並可取得錯誤詳細資料 **suspended** (`string`): Workflow 執行已暫停並等待繼續,且包含已暫停步驟的資訊 **tripwire** (`string`): Workflow 已由 processor tripwire 終止。Workflow 中的 Agent 步驟觸發 tripwire(例如內容遭 guardrail 封鎖)時,就會發生此情況。結果中可取得 tripwire 資訊。 ### 處理 tripwire 狀態 Workflow 包含的 Agent 步驟觸發 tripwire 時,Workflow 會以 `status: 'tripwire'` 回傳,並包含 tripwire 詳細資料: ```typescript const run = await workflow.createRun() const result = await run.start({ inputData: { message: 'Hello' } }) if (result.status === 'tripwire') { console.log('Workflow terminated by tripwire:', result.tripwire?.reason) console.log('Processor ID:', result.tripwire?.processorId) console.log('Retry requested:', result.tripwire?.retry) } ``` 這不同於表示非預期錯誤的 `status: 'failed'`。Tripwire 狀態表示 processor 刻意停止執行(例如為了內容審核)。 ## 相關內容 - [Step 類別](https://mastra.zisheng.pro/zh-TW/reference/workflows/step) - [Workflow 狀態](https://mastra.zisheng.pro/zh-TW/docs/workflows/workflow-state) - [控制流程](https://mastra.zisheng.pro/zh-TW/docs/workflows/control-flow)