MastraModelOutput
MastraModelOutput 類別由 .stream() 回傳,並提供串流與 Promise 兩種方式來存取模型輸出。它支援結構化輸出生成、Tool 呼叫、推理,以及詳細的用量追蹤。
// MastraModelOutput is returned by agent.stream()
const stream = await agent.stream('Hello world')
如需設定與基本用法,請參閱 .stream() 方法文件。
串流屬性「串流屬性」的直接連結
這些屬性可在模型輸出生成時即時存取:
fullStream:
ReadableStream<ChunkType<OUTPUT>>
包含文字、Tool 呼叫、推理、中繼資料與控制 chunk 等所有 chunk 類型的完整串流。可細部存取模型回應的各個層面。
ReadableStream
ChunkType:
ChunkType<OUTPUT>
串流期間可能發出的所有 chunk 類型
textStream:
ReadableStream<string>
僅包含增量文字內容的串流。它會濾除所有中繼資料、Tool 呼叫與控制 chunk,只提供正在生成的文字。
objectStream:
ReadableStream<Partial<OUTPUT>>
使用輸出 schema 時,逐步更新結構化物件的串流。它會在建構過程中發出部分物件,讓你即時呈現結構化資料的生成進度。
ReadableStream
PartialSchemaOutput:
Partial<OUTPUT>
符合所定義 schema 的部分完成物件
elementStream:
ReadableStream<OUTPUT extends (infer T)[] ? T : never>
輸出 schema 定義為陣列類型時,個別陣列元素的串流。每個元素完成後就會發出,不必等待整個陣列完成。
Promise 型屬性「Promise 型屬性」的直接連結
串流完成後,這些屬性會解析為最終值:
text:
Promise<string>
模型完整串接後的文字回應。文字生成完成時解析。
object:
Promise<OUTPUT>
使用輸出 schema 時的完整結構化物件回應。解析前會依 schema 驗證;驗證失敗時會拒絕。
Promise
InferSchemaOutput:
OUTPUT
與 schema 定義完全相符的完整型別物件
reasoning:
Promise<string>
支援推理之模型(例如 OpenAI o1 系列)的完整推理文字。對不具推理能力的模型回傳空字串。
reasoningText:
Promise<string | undefined>
存取推理內容的另一種方式。對不支援推理的模型可能為 undefined,而 'reasoning' 會回傳空字串。
toolCalls:
Promise<ToolCallChunk[]>
執行期間產生的所有 Tool 呼叫 chunk 陣列。每個 chunk 都包含 Tool 中繼資料與執行詳細資訊。
ToolCallChunk
type:
'tool-call'
chunk 類型識別碼
runId:
string
執行 run 識別碼
from:
ChunkFrom
chunk 的來源(AGENT、WORKFLOW 等)
payload:
ToolCallPayload
Tool 呼叫資料,包含 toolCallId、toolName、args 與執行詳細資訊
toolResults:
Promise<ToolResultChunk[]>
與 Tool 呼叫對應的所有 Tool 結果 chunk 陣列。包含執行結果與錯誤資訊。
ToolResultChunk
type:
'tool-result'
chunk 類型識別碼
runId:
string
執行 run 識別碼
from:
ChunkFrom
chunk 的來源(AGENT、WORKFLOW 等)
payload:
ToolResultPayload
Tool 結果資料,包含 toolCallId、toolName、result 與錯誤狀態
usage:
Promise<LanguageModelUsage>
Token 用量統計,包含輸入 token、輸出 token、token 總數,以及推理模型的推理 token。
Record
inputTokens:
number
輸入提示所耗用的 token
outputTokens:
number
回應中生成的 token
totalTokens:
number
輸入與輸出 token 的總和
reasoningTokens?:
number
隱藏的推理 token(適用於推理模型)
cachedInputTokens?:
number
命中快取的輸入 token 數量
finishReason:
Promise<string | undefined>
生成停止的原因(例如 'stop'、'length'、'tool_calls'、'content_filter')。若串流尚未完成,則為 undefined。
enum
stop:
'stop'
模型自然完成
length:
'length'
達到 token 數上限
tool_calls:
'tool_calls'
模型呼叫了 Tool
content_filter:
'content_filter'
內容已遭篩選
response:
Promise<Response>
模型 Provider 的回應中繼資料與訊息。
Response
id?:
string
模型 Provider 提供的回應 ID
timestamp?:
Date
回應時間戳記
modelId?:
string
此回應使用的模型識別碼
headers?:
Record<string, string>
模型 Provider 傳回的回應標頭
messages?:
ResponseMessage[]
模型格式的回應訊息
uiMessages?:
UIMessage[]
UI 格式的回應訊息,包含輸出 processor 加入的任何中繼資料
錯誤屬性「錯誤屬性」的直接連結
error:
string | Error | { message: string; stack: string; } | undefined
串流發生錯誤時的錯誤資訊。若未發生錯誤則為 undefined。可以是字串訊息、Error 物件,或含堆疊追蹤的序列化錯誤。
方法「方法」的直接連結
getFullOutput:
() => Promise<FullOutput>
回傳包含所有結果的完整輸出物件:文字、結構化物件、Tool 呼叫、用量統計、推理與中繼資料。這個方法能方便地一次存取所有串流結果。
FullOutput
text:
string
完整文字回應
object?:
OUTPUT
若有提供 schema,則為結構化輸出
toolCalls:
ToolCallChunk[]
所有已產生的 Tool 呼叫 chunk
toolResults:
ToolResultChunk[]
所有 Tool 結果 chunk
usage:
Record<string, number>
Token 用量統計
reasoning?:
string
可用的推理文字
finishReason?:
string
生成完成的原因
response:
Response
模型 Provider 的回應中繼資料與訊息
consumeStream:
(options?: ConsumeStreamOptions) => Promise<void>
手動取用整個串流,但不處理 chunk。適合只需要最終 Promise 結果,並想觸發串流取用時使用。
ConsumeStreamOptions
onError?:
(error: Error) => void
處理串流錯誤的回呼
使用範例「使用範例」的直接連結
基本文字串流「基本文字串流」的直接連結
const stream = await agent.stream('Write a haiku')
// Stream text as it's generated
for await (const text of stream.textStream) {
process.stdout.write(text)
}
// Or get the complete text
const fullText = await stream.text
console.log(fullText)
結構化輸出串流「結構化輸出串流」的直接連結
const stream = await agent.stream('Generate user data', {
structuredOutput: {
schema: z.object({
name: z.string(),
age: z.number(),
email: z.string(),
}),
},
})
// Stream partial objects
for await (const partial of stream.objectStream) {
console.log('Progress:', partial) // { name: "John" }, { name: "John", age: 30 }, ...
}
// Get final validated object
const user = await stream.object
console.log('Final:', user) // { name: "John", age: 30, email: "john@example.com" }
### Tool Calls and Results
```typescript
const stream = await agent.stream("What's the weather in NYC?", {
tools: { weather: weatherTool }
});
// Monitor tool calls
const toolCalls = await stream.toolCalls;
const toolResults = await stream.toolResults;
console.log("Tools called:", toolCalls);
console.log("Results:", toolResults);
Complete Output Access「Complete Output Access」的直接連結
const stream = await agent.stream('Analyze this data')
const output = await stream.getFullOutput()
console.log({
text: output.text,
usage: output.usage,
reasoning: output.reasoning,
finishReason: output.finishReason,
})
完整串流處理「完整串流處理」的直接連結
const stream = await agent.stream('Complex task')
for await (const chunk of stream.fullStream) {
switch (chunk.type) {
case 'text-delta':
process.stdout.write(chunk.payload.text)
break
case 'tool-call':
console.log(`Calling ${chunk.payload.toolName}...`)
break
case 'reasoning-delta':
console.log(`Reasoning: ${chunk.payload.text}`)
break
case 'finish':
console.log(`Done! Reason: ${chunk.payload.stepResult.reason}`)
// Access response messages with any metadata added by output processors
const uiMessages = chunk.payload.response?.uiMessages
if (uiMessages) {
console.log('Response messages:', uiMessages)
}
break
}
}
錯誤處理「錯誤處理」的直接連結
const stream = await agent.stream('Analyze this data')
try {
// Option 1: Handle errors in consumeStream
await stream.consumeStream({
onError: error => {
console.error('Stream error:', error)
},
})
const result = await stream.text
} catch (error) {
console.error('Failed to get result:', error)
}
// Option 2: Check error property
const result = await stream.getFullOutput()
if (stream.error) {
console.error('Stream had errors:', stream.error)
}