> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-TW/llms.txt # Agent.stream() `.stream()` 方法能以進階功能與彈性格式即時串流 Agent 的回應。此方法接受訊息與選用串流選項,提供目前的串流體驗,並同時支援 Mastra 原生格式與 AI SDK v5+ 相容性。 ## 使用範例 ```ts const stream = await agent.stream('message for agent') ``` > **資訊:** **模型相容性**:此方法專為 V2 模型設計。V1 模型應改用 [`.streamLegacy()`](https://mastra.zisheng.pro/zh-TW/reference/streaming/agents/streamLegacy) 方法。框架會自動偵測模型版本,若版本不相符便會擲回錯誤。 ## 參數 **messages** (`string | string[] | CoreMessage[] | AiMessageType[] | UIMessageWithMetadata[]`): 要傳送給 Agent 的訊息。可以是單一字串、字串陣列或結構化訊息物件。 **options** (`AgentExecutionOptions`): 串流流程的選用設定。 **options.maxSteps** (`number`): 執行期間可執行的步驟數上限。 **options.scorers** (`MastraScorers | Record`): 要針對執行結果執行的評分器。 **options.scorers.scorer** (`string`): 要使用的評分器名稱。 **options.scorers.sampling** (`ScoringSamplingConfig`): 評分器的取樣設定。 **options.scorers.sampling.type** (`'none' | 'ratio'`): 取樣策略的類型。使用 'none' 停用取樣,或使用 'ratio' 按百分比取樣。 **options.scorers.sampling.rate** (`number`): 取樣率(0–1)。type 為 'ratio' 時為必填。 **options.onIterationComplete** (`(context: IterationCompleteContext) => { continue?: boolean; feedback?: string } | void | Promise<{ continue?: boolean; feedback?: string } | void>`): 每次迭代完成後呼叫的回呼函式。可用來監控進度、提供意見以引導 Agent,或提早停止執行。此回呼會接收迭代的上下文,包含目前文字、Tool 呼叫與完成原因。 **options.onIterationComplete.context.iteration** (`number`): 目前的迭代編號(從 1 開始)。 **options.onIterationComplete.context.maxIterations** (`number | undefined`): 允許的迭代次數上限(若已設定)。 **options.onIterationComplete.context.text** (`string`): 這次迭代的文字回應。 **options.onIterationComplete.context.isFinal** (`boolean`): 這是否為最後一次迭代。 **options.onIterationComplete.context.finishReason** (`string`): 這次迭代完成的原因(例如 'stop'、'length'、'tool-calls')。 **options.onIterationComplete.context.toolCalls** (`ToolCall[]`): 這次迭代中進行的 Tool 呼叫。 **options.onIterationComplete.context.messages** (`MastraDBMessage[]`): 目前累積的所有訊息。 **options.onIterationComplete.return.continue** (`boolean`): 設為 false 可提早停止執行。 **options.onIterationComplete.return.feedback** (`string`): 用來引導 Agent 下一次迭代的意見訊息。 **options.isTaskComplete** (`IsTaskCompleteConfig`): 用於驗證任務是否完成的完成度評分設定。它會使用 Mastra 的評估評分器,自動檢查 Agent 回應是否符合完成條件。 **options.isTaskComplete.scorers** (`MastraScorer[]`): 評估任務是否完成的評分器陣列。每個評分器會回傳 0(失敗)或 1(通過)。 **options.isTaskComplete.strategy** (`'all' | 'any'`): 合併評分結果的策略。'all' 要求所有評分器都通過,'any' 則至少需有一個通過。 **options.isTaskComplete.onComplete** (`(result: IsTaskCompleteRunResult) => void | Promise`): 任務完成檢查結束時呼叫的回呼。會接收包含各評分器分數的結果。 **options.isTaskComplete.parallel** (`boolean`): 是否平行執行評分器。 **options.isTaskComplete.timeout** (`number`): 等待所有評分器完成的時間上限(毫秒)。 **options.isTaskComplete.suppressFeedback** (`boolean`): 設為 true 時,會標記完成檢查的意見,讓取用端可將其從顯示的輸出中隱藏。只有檢查失敗時才會把意見加入對話,以引導下一次迭代。 **options.delegation** (`DelegationConfig`): subagent 委派的設定。可用來控制及監控 Agent 何時將任務委派給其他 Agent,並能修改或拒絕委派,以及提供意見來引導 supervisor。 **options.delegation.onDelegationStart** (`(context: DelegationStartContext) => DelegationStartResult | void | Promise`): 委派給 subagent 前呼叫。可用來修改委派參數、完全拒絕委派,或變更 context.requestContext,將項目加入 subagent 執行的請求上下文。 **options.delegation.onDelegationComplete** (`(context: DelegationCompleteContext) => { feedback?: string } | void | Promise<{ feedback?: string } | void>`): subagent 委派完成後呼叫。上下文包含可停止後續執行的 bail() 方法;你也可以回傳 { feedback } 來引導 supervisor 的下一個動作。意見會以 assistant 訊息儲存在 supervisor memory 中。 **options.delegation.messageFilter** (`(context: MessageFilterContext) => MastraDBMessage[] | Promise`): 委派給 subagent 前呼叫的回呼函式。可用來篩選要傳給 subagent 的訊息。 **options.tracingContext** (`TracingContext`): 用於 span 階層與中繼資料的 Tracing 上下文。 **options.returnScorerData** (`boolean`): 是否在回應中傳回詳細評分資料。 **options.onChunk** (`(chunk: ChunkType) => Promise | void`): 串流期間每個 chunk 都會呼叫的回呼函式。 **options.onError** (`({ error }: { error: Error | string }) => Promise | void`): 串流期間發生錯誤時呼叫的回呼函式。 **options.onAbort** (`(event: any) => Promise | void`): 串流中止時呼叫的回呼函式。 **options.abortSignal** (`AbortSignal`): 可讓你中止 Agent 執行的 signal 物件。signal 中止時,所有進行中的作業都會終止,包含 Agent 委派且仍在執行的所有 subagent run。 **options.activeTools** (`Array | undefined`): 執行期間可使用的啟用中 Tool 名稱陣列。 **options.prepareStep** (`PrepareStepFunction`): 多步驟執行中,每個步驟開始前呼叫的回呼函式。 **options.context** (`ModelMessage[]`): 提供給 Agent 的額外上下文訊息。 **options.structuredOutput** (`StructuredOutputOptions`): 微調結構化輸出生成的選項。 **options.structuredOutput.schema** (`StandardJSONSchemaV1`): 定義預期輸出結構的標準 JSON Schema。 **options.structuredOutput.model** (`MastraLanguageModel`): 用於生成結構化輸出的語言模型。若有提供,Agent 就能以多個步驟回應 Tool 呼叫、文字與結構化輸出 **options.structuredOutput.errorStrategy** (`'strict' | 'warn' | 'fallback'`): 處理 schema 驗證錯誤的策略。'strict' 會擲回錯誤,'warn' 會記錄警告,'fallback' 則使用備援值。 **options.structuredOutput.fallbackValue** (``): schema 驗證失敗且 errorStrategy 為 'fallback' 時使用的備援值。 **options.structuredOutput.instructions** (`string`): 提供給結構化輸出模型的額外指示。 **options.structuredOutput.jsonPromptInjection** (`boolean | 'system' | 'inline' | 'auto'`): 控制 JSON schema 如何傳送至模型。設為 'auto' 時,若支援便使用原生結構化輸出,否則將其內嵌注入提示。 **options.structuredOutput.providerOptions** (`ProviderOptions`): 傳給內部結構化 Agent 的 Provider 專用選項。可用來控制模型行為,例如思考模型的推理強度(例如 { openai: { reasoningEffort: 'low' } })。 **options.outputProcessors** (`Processor[]`): 覆寫 Agent 上設定的輸出 processor。輸出 processor 可在訊息回傳給使用者前,修改或驗證 Agent 的訊息。必須實作 processOutputResult 或 processOutputStream 函式之一(也可兩者都實作)。 **options.includeRawChunks** (`boolean`): 是否在串流輸出中包含原始 chunk(並非所有模型 Provider 都支援)。 **options.inputProcessors** (`Processor[]`): 覆寫 Agent 上設定的輸入 processor。輸入 processor 可在訊息交由 Agent 處理前進行修改或驗證。必須實作 processInput 函式。 **options.instructions** (`string`): 針對這次生成覆寫 Agent 預設指示的自訂指示。適合用來動態調整 Agent 行為,而不必建立新的 Agent 執行個體。 **options.system** (`string | string[] | CoreSystemMessage | SystemModelMessage | CoreSystemMessage[] | SystemModelMessage[]`): 要納入提示的自訂 system 訊息。可以是單一字串、訊息物件,或由兩者任一組成的陣列。system 訊息會提供額外的上下文或行為指示,補充 Agent 的主要指示。 **options.output** (`Zod schema | JsonSchema7`): \*\*已棄用。\*\*請改用未指定 model 的 structuredOutput 來達成相同效果。定義預期的輸出結構。可以是 JSON Schema 物件或 Zod schema。 **options.memory** (`object`): memory 的設定。這是管理 memory 的建議方式。 **options.memory.thread** (`string | { id: string; metadata?: Record, title?: string }`): 對話 thread,可以是字串 ID,也可以是包含 id 與選用 metadata 的物件。 **options.memory.resource** (`string`): 與 thread 關聯的使用者或資源識別碼。 **options.memory.options** (`MemoryConfig`): memory 行為的設定,包含 lastMessages、readOnly、semanticRecall、workingMemory 與 filterIncompleteToolCalls。 **options.memory.onTitleGenerated** (`(title: string) => void | Promise`): thread 標題產生並持久化至儲存空間時,以非同步方式觸發的回呼。標題生成會在背景執行,可能在串流結束後才完成。只有在 memory 選項中啟用 generateTitle,且 thread 尚無標題時才會觸發。 **options.onFinish** (`StreamTextOnFinishCallback | StreamObjectOnFinishCallback`): 串流完成時呼叫的回呼函式。會接收最終結果。 **options.onStepFinish** (`StreamTextOnStepFinishCallback | never`): 每個執行步驟完成後呼叫的回呼函式。會以 JSON 字串接收步驟詳細資訊。結構化輸出無法使用此函式 **options.telemetry** (`TelemetrySettings`): 串流期間的 OTLP 遙測收集設定(不是 Tracing)。 **options.telemetry.isEnabled** (`boolean`): 啟用或停用遙測。實驗階段預設為停用。 **options.telemetry.recordInputs** (`boolean`): 啟用或停用輸入記錄。預設為啟用。為避免記錄敏感資訊,你可能需要停用輸入記錄。 **options.telemetry.recordOutputs** (`boolean`): 啟用或停用輸出記錄。預設為啟用。為避免記錄敏感資訊,你可能需要停用輸出記錄。 **options.telemetry.functionId** (`string`): 此函式的識別碼。用於依函式將遙測資料分組。 **options.modelSettings** (`CallSettings`): Model-specific settings like temperature, maxOutputTokens, topP, etc. These settings control how the language model generates responses. **options.modelSettings.temperature** (`number`): Controls randomness in generation (0-2). Higher values make output more random. **options.modelSettings.maxOutputTokens** (`number`): Maximum number of tokens to generate in the response. Note: Use maxOutputTokens (not maxTokens) as per AI SDK v5 convention. **options.modelSettings.maxRetries** (`number`): Maximum number of retry attempts for failed requests. **options.modelSettings.topP** (`number`): Nucleus sampling parameter (0-1). Controls diversity of generated text. **options.modelSettings.topK** (`number`): Top-k sampling parameter. Limits vocabulary to k most likely tokens. **options.modelSettings.presencePenalty** (`number`): Penalty for token presence (-2 to 2). Reduces repetition. **options.modelSettings.frequencyPenalty** (`number`): Penalty for token frequency (-2 to 2). Reduces repetition of frequent tokens. **options.modelSettings.stopSequences** (`string[]`): Stop sequences. If set, the model will stop generating text when one of the stop sequences is generated. **options.toolChoice** (`'auto' | 'none' | 'required' | { type: 'tool'; toolName: string }`): 控制 Agent 在串流期間如何使用 Tool。 **options.toolChoice.'auto'** (`string`): 讓模型決定是否使用 Tool(預設)。 **options.toolChoice.'none'** (`string`): 不使用任何 Tool。 **options.toolChoice.'required'** (`string`): 要求模型至少使用一個 Tool。 **options.toolChoice.{ type: 'tool'; toolName: string }** (`object`): 要求模型依名稱使用特定 Tool。 **options.toolsets** (`ToolsetsInput`): 讓 Agent 在串流期間可使用的其他 Toolset。 **options.clientTools** (`ToolsInput`): 在請求的「使用者端」執行的 Tool。這些 Tool 的定義中沒有 execute 函式。 **options.hooks** (`ToolHooks`): 每次執行專用、會在 Tool 呼叫前後執行的 hook。會覆寫這次執行中相符的 Agent 層級 hook。beforeToolCall 可以回傳 { proceed: false, output } 以略過 Tool 呼叫。 **options.savePerStep** (`boolean`): 每個串流步驟完成後逐步儲存訊息(預設:false)。 **options.requireToolApproval** (`boolean`): 設為 true 時,所有 Tool 呼叫在執行前都需要明確核准。串流會發出 tool-call-approval chunk 並暫停,直到呼叫 approveToolCall() 或 declineToolCall()。 **options.autoResumeSuspendedTools** (`boolean`): 設為 true 時,當使用者在同一個 thread 傳送新訊息,就會自動恢復已暫停的 Tool。Agent 會依據 Tool 的 resumeSchema,從使用者訊息擷取 resumeData。必須設定 memory。 **options.toolCallConcurrency** (`number`): 同時執行的 Tool 呼叫數量上限。可能需要核准時預設為 1,否則為 10。 **options.providerOptions** (`Record>`): 傳遞至底層 LLM Provider 的其他 Provider 專用選項。結構為 { providerName: { optionKey: value } }。例如:{ openai: { reasoningEffort: 'high' }, anthropic: { maxTokens: 1000 } }。 **options.providerOptions.openai** (`Record`): OpenAI 專用選項。例如:{ reasoningEffort: 'high' } **options.providerOptions.anthropic** (`Record`): Anthropic 專用選項。例如:{ maxTokens: 1000 } **options.providerOptions.google** (`Record`): Google 專用選項。例如:{ safetySettings: \[...] } **options.providerOptions.\[providerName]** (`Record`): 其他 Provider 專用選項。鍵是 Provider 名稱,值則是 Provider 專用選項的記錄。 **options.runId** (`string`): 這次生成執行的唯一 ID,適合用於追蹤與偵錯。 **options.requestContext** (`RequestContext`): 用於相依性注入與上下文資訊的 Request Context。 **options.tracingContext** (`TracingContext`): 用於建立子 span 與加入中繼資料的 Tracing 上下文。使用 Mastra 的 tracing 系統時會自動注入。 **options.tracingContext.currentSpan** (`Span`): 用於建立子 span 與加入中繼資料的目前 span。可用來建立自訂子 span,或在執行期間更新 span 屬性。 **options.tracingOptions** (`TracingOptions`): Tracing 設定選項。 **options.tracingOptions.metadata** (`Record`): 要加入根 trace span 的中繼資料。適合用來加入使用者 ID、session ID 或功能旗標等自訂屬性。 **options.tracingOptions.requestContextKeys** (`string[]`): 要擷取為此 trace 中繼資料的其他 RequestContext 鍵。巢狀值支援點記法(例如 'user.id')。 **options.tracingOptions.traceId** (`string`): 這次執行要使用的 Trace ID(1–32 個十六進位字元)。若有提供,此 trace 會成為指定 trace 的一部分。 **options.tracingOptions.parentSpanId** (`string`): 這次執行要使用的父 span ID(1–16 個十六進位字元)。若有提供,根 span 會建立為此 span 的子項。 **options.tracingOptions.tags** (`string[]`): 要套用至此 trace 的標籤。這些字串標籤用於分類與篩選 trace。 **options.versions** (`VersionOverrides`): 每次叫用時針對 sub-Agent 委派設定的版本覆寫。它會合併至 Mastra 執行個體層級版本之上,並透過 requestContext 在 sub-Agent 呼叫間自動傳遞。需要 editor 套件。請參閱 Editor 版本控制。 **options.versions.agents** (`Record`): Agent ID 與其版本選擇器的對應表。 **options.versions.agents.versionId** (`string`): 依 ID 指定特定版本。 **options.versions.agents.status** (`'draft' | 'published'`): 指定具有此發布狀態的最新版本。 **options.untilIdle** (`boolean | { maxIdleMs?: number }`): 設定後,串流會在背景任務的接續回合之間保持開啟。背景任務完成時,Agent 會自動重新叫用 LLM,並透過同一個 fullStream 串流接續回合。傳入 true 會使用預設設定(閒置逾時 5 分鐘),也可以傳入含 maxIdleMs 的物件進行設定。需要 memory。此選項取代獨立的 streamUntilIdle() 方法。 **options.untilIdle.maxIdleMs** (`number`): 回合之間閒置達指定毫秒數後關閉外層串流。計時器只會在 wrapper 位於回合之間時執行。預設:5 分鐘。 ## 回傳值 **stream** (`MastraModelOutput`): 回傳可存取串流輸出的 MastraModelOutput 執行個體。 **traceId** (`string`): 啟用 Tracing 時,與這次執行關聯的 trace ID。可用來關聯記錄及偵錯執行流程。 **spanId** (`string`): 啟用 Tracing 時,與這次執行關聯的根 span ID。可用於 span 層級的查詢與關聯。 ## 進階使用範例 ### Mastra 格式(預設) ```ts import { stepCountIs } from 'ai-v5' const stream = await agent.stream('Tell me a story', { stopWhen: stepCountIs(3), // Stop after 3 steps modelSettings: { temperature: 0.7, }, }) // Access text stream for await (const chunk of stream.textStream) { console.log(chunk) } // or access full stream for await (const chunk of stream.fullStream) { console.log(chunk) } // Get full text after streaming const fullText = await stream.text ``` ### AI SDK v5+ 格式 若要搭配 AI SDK v5(及後續版本)使用此串流,可以透過工具函式 `toAISdkStream` 進行轉換。 ```ts import { stepCountIs, createUIMessageStreamResponse } from 'ai' import { toAISdkStream } from '@mastra/ai-sdk' const stream = await agent.stream('Tell me a story', { stopWhen: stepCountIs(3), // Stop after 3 steps modelSettings: { temperature: 0.7, }, }) // In an API route for frontend integration return createUIMessageStreamResponse({ stream: toAISdkStream(stream, { from: 'agent' }), }) ``` ### 使用回呼 所有回呼函式現在都可作為頂層屬性使用,讓 API 體驗更簡潔。 ```ts const stream = await agent.stream('Tell me a story', { onFinish: result => { console.log('Streaming finished:', result) }, onStepFinish: step => { console.log('Step completed:', step) }, onChunk: chunk => { console.log('Received chunk:', chunk) }, onError: ({ error }) => { console.error('Streaming error:', error) }, onAbort: event => { console.log('Stream aborted:', event) }, }) // Process the stream for await (const chunk of stream.textStream) { console.log(chunk) } ``` ### 使用選項的進階範例 ```ts import { z } from 'zod' import { stepCountIs } from 'ai' await agent.stream('message for agent', { stopWhen: stepCountIs(3), // Stop after 3 steps modelSettings: { temperature: 0.7, }, memory: { thread: 'user-123', resource: 'test-app', }, toolChoice: 'auto', // Structured output with better DX structuredOutput: { schema: z.object({ sentiment: z.enum(['positive', 'negative', 'neutral']), confidence: z.number(), }), model: 'openai/gpt-5.6-sol', errorStrategy: 'warn', }, // Output processors for streaming response validation outputProcessors: [ new ModerationProcessor({ model: 'openrouter/openai/gpt-oss-safeguard-20b' }), new BatchPartsProcessor({ maxBatchSize: 3, maxWaitTime: 100 }), ], }) ``` ## Responses WebSocket 傳輸 透過 Provider 選項選用 Responses WebSocket 串流。此設定只適用於串流呼叫,並支援直接使用 OpenAI 模型與 Azure OpenAI Responses 部署。若無法使用 WebSocket 串流,Mastra 會改用 HTTP 串流。預設情況下,串流完成時 Mastra 會關閉 WebSocket。 ```ts const stream = await agent.stream('Hello', { providerOptions: { openai: { transport: 'websocket', // 'websocket' | 'fetch' | 'auto' websocket: { url: 'wss://api.openai.com/v1/responses', closeOnFinish: true, // default }, }, }, }) ``` 使用 Azure OpenAI 時,請為 gateway 設定 `useResponsesAPI: true`,接著使用 `providerOptions.azure.transport`。 ```ts const stream = await agent.stream('Hello', { providerOptions: { azure: { transport: 'websocket', store: false, websocket: { closeOnFinish: true }, }, }, }) ``` 若要在串流完成後維持連線開啟,請設定 `closeOnFinish: false`,並手動關閉連線。 ```ts const stream = await agent.stream('Hello', { providerOptions: { openai: { transport: 'websocket', websocket: { closeOnFinish: false }, }, }, }) // Later, when you're done with the connection: stream.transport?.close() ``` Responses WebSocket 連線一次只會執行一個回應。在同一個 WebSocket 傳輸上,Mastra 會拒絕重疊且包含 `previous_response_id` 的接續請求。請等候作用中的串流完成,再傳送回應鏈中的下一個回合。 ## 相關內容 - [生成回應](https://mastra.zisheng.pro/zh-TW/docs/agents/overview) - [串流回應](https://mastra.zisheng.pro/zh-TW/docs/agents/overview) - [Agent 核准](https://mastra.zisheng.pro/zh-TW/docs/agents/agent-approval)