Agent.streamUntilIdle()
新增於: @mastra/core@1.29.0
streamUntilIdle() 已棄用。請改用搭配 untilIdle 選項的 stream():
const result = await agent.stream('Research solana for me', {
untilIdle: true,
memory: { thread: 't1', resource: 'u1' },
})
傳入 untilIdle: { maxIdleMs: 60_000 } 可設定閒置逾時。
streamUntilIdle() 會串流 Agent 的回應,並持續保持串流開啟,直到執行期間派送的每個背景任務都完成。任務完成時,其結果會寫入 memory,agentic 迴圈也會自動再次進入,讓 LLM 能對結果做出反應。沒有任務正在執行,且沒有完成事件排入佇列後,串流便會關閉。
當 Agent 派送背景任務(通常是長時間執行的 Tool 或 subagent),而你希望單一串流涵蓋初始回應,加上每次任務完成所觸發的所有接續回合時,請使用此方法。若執行只包含前景任務,或你偏好手動管理接續回合(手動提示 Agent 處理結果),請使用 Agent.stream()。
使用範例「使用範例」的直接連結
const stream = await agent.streamUntilIdle('Research solana for me', {
memory: { thread: 't1', resource: 'u1' },
})
for await (const chunk of stream.fullStream) {
// chunks from the initial turn AND any continuation turns triggered by
// background task completions flow through here
}
streamUntilIdle() 同時需要 BackgroundTaskManager 與 memory 後端。缺少任一項時,會改用一般的 agent.stream() 呼叫。
參數「參數」的直接連結
messages:
options?:
maxIdleMs?:
memory?:
structuredOutput?:
其他所有選項(maxSteps、modelSettings、toolChoice、outputProcessors、onFinish、onChunk 等)請參閱 Agent.stream() 參數。streamUntilIdle() 會將這些選項轉送至初始回合。
回傳值「回傳值」的直接連結
stream:
彙總屬性的注意事項「彙總屬性的注意事項」的直接連結
streamUntilIdle() 會回傳第一個回合之 MastraModelOutput 的 proxy。只有 fullStream 會替換為涵蓋每個接續回合的合併串流。其他所有屬性(text、toolCalls、toolResults、finishReason、messageList 與 getFullOutput())都會依第一個回合的內部緩衝區解析。
若需要涵蓋所有接續回合的彙總檢視,請自行取用 fullStream 並累積結果。
接續行為「接續行為」的直接連結
streamUntilIdle() 內部會:
- 透過
agent.stream(...)執行初始回合,並將其fullStream導入外層串流。 - 訂閱已解析 memory 範圍中的背景任務完成事件。
- 將每個終止事件(
background-task-completed、background-task-failed、background-task-cancelled)排入佇列;當外層 wrapper 在回合之間閒置時,使用列出已完成toolCallId的指示重新叫用agent.stream([], ...)。接續回合會流入同一個外層串流。 - 沒有任務正在執行,且沒有完成事件排入佇列後,關閉外層串流。
進階使用範例「進階使用範例」的直接連結
限制回合之間的閒置時間「限制回合之間的閒置時間」的直接連結
const stream = await agent.streamUntilIdle('Kick off the long jobs', {
memory: { thread: 't1', resource: 'u1' },
maxIdleMs: 60_000, // close the stream after 1 minute of idleness between turns
})
for await (const chunk of stream.fullStream) {
if (chunk.type === 'background-task-completed') {
console.log('Task complete:', chunk.payload.taskId)
}
}
彙總所有接續回合的文字「彙總所有接續回合的文字」的直接連結
const stream = await agent.streamUntilIdle('Research and summarize', {
memory: { thread: 't1', resource: 'u1' },
})
let fullText = ''
for await (const chunk of stream.fullStream) {
if (chunk.type === 'text-delta') {
fullText += chunk.payload.text
}
}