Run.stream()
.stream() 方法可即時串流傳輸 Workflow 的回應。它會直接回傳事件的 ReadableStream。
使用範例「使用範例」的直接連結
const run = await workflow.createRun()
const stream = await run.stream({
inputData: {
value: 'initial data',
},
})
for await (const chunk of stream) {
console.log(chunk)
}
參數「參數」的直接連結
inputData?:
z.infer<TInput>
符合 Workflow 輸入 schema 的輸入資料
requestContext?:
RequestContext
Workflow 執行期間要使用的 Request Context 資料
tracingContext?:
TracingContext
用於建立子 span 及新增中繼資料的 Tracing context。
currentSpan?:
Span
用於建立子 span 及新增中繼資料的目前 span。
tracingOptions?:
TracingOptions
Tracing 設定選項。
metadata?:
Record<string, any>
要新增至根 Trace span 的中繼資料。
requestContextKeys?:
string[]
要擷取為此 Trace 中繼資料的其他 RequestContext key。巢狀值支援點記法(例如 'user.id')。
traceId?:
string
此次執行要使用的 Trace ID(1 至 32 個十六進位字元)。若有提供,此 Trace 將成為指定 Trace 的一部分。
parentSpanId?:
string
此次執行要使用的父 span ID(1 至 16 個十六進位字元)。若有提供,根 span 將建立為此 span 的子項。
tags?:
string[]
要套用至此 Trace 的標籤。這些字串標籤可用於分類及篩選 Trace。
closeOnSuspend?:
boolean
是否在 Workflow 暫停時關閉串流,或讓串流維持開啟,直到 Workflow 成功完成或發生錯誤為止。預設值為 true。
回傳值「回傳值」的直接連結
回傳實作非同步可迭代介面的 WorkflowRunOutput 物件(可直接用於 for await...of 迴圈),並提供串流與 Workflow 執行結果的存取方式。
fullStream:
ReadableStream<WorkflowStreamEvent>
可迭代以即時追蹤進度的 Workflow 事件 ReadableStream。你也可以直接迭代 WorkflowRunOutput 物件。
result:
Promise<WorkflowResult<TState, TInput, TOutput, TSteps>>
會解析為最終 Workflow 結果的 Promise
status:
WorkflowRunStatus
目前的 Workflow 執行狀態('running'、'suspended'、'success'、'failed'、'canceled' 或 'tripwire')
usage:
Promise<{ inputTokens: number; outputTokens: number; totalTokens: number, reasoningTokens?: number, cachedInputTokens?: number }>
會解析為 token 用量統計資料的 Promise
進階使用範例「進階使用範例」的直接連結
const run = await workflow.createRun()
const stream = run.stream({
inputData: {
value: 'initial data',
},
})
// Iterate over stream events (you can iterate over stream directly or use stream.fullStream)
for await (const chunk of stream) {
console.log(chunk)
}
// Access the final result
const result = await stream.result
console.log('Final result:', result)
// Access token usage
const usage = await stream.usage
console.log('Token usage:', usage)
// Check current status
console.log('Status:', stream.status)
串流事件「串流事件」的直接連結
串流會在 Workflow 執行期間輸出各種事件類型。每個事件都有 type 欄位,以及包含相關資料的 payload:
workflow-start:Workflow 開始執行workflow-step-start:步驟開始執行workflow-step-output:步驟的自訂輸出workflow-step-progress:foreach 步驟回報各次迭代的進度(包括completedCount、totalCount、currentIndex、iterationStatus,以及選用的iterationOutput)workflow-step-result:步驟執行完成並產生結果workflow-finish:Workflow 執行完成,並提供用量統計資料。若執行成功,payload.finalWorkflowResult會包含 Workflow 的最終結果,因此串流使用者端不需要再提出擷取請求