Agent.stream()
.stream() メソッドは、高度な機能と柔軟な形式により、Agent からのレスポンスをリアルタイムでストリーミングできます。このメソッドはメッセージと省略可能なストリーミングオプションを受け取り、Mastra ネイティブ形式と AI SDK v5 以降の両方に対応した最新のストリーミング機能を提供します。
使用例使用例への直接リンク
const stream = await agent.stream('message for agent')
モデルの互換性: このメソッドは V2 モデル向けに設計されています。V1 モデルでは .streamLegacy() メソッドを使用してください。フレームワークはモデルのバージョンを自動的に検出し、不一致がある場合はエラーをスローします。
パラメーターパラメーターへの直接リンク
messages:
options?:
maxSteps?:
scorers?:
scorer:
sampling?:
type:
rate?:
onIterationComplete?:
context.iteration:
context.maxIterations:
context.text:
context.isFinal:
context.finishReason:
context.toolCalls:
context.messages:
return.continue?:
return.feedback?:
isTaskComplete?:
scorers:
strategy?:
onComplete?:
parallel?:
timeout?:
suppressFeedback?:
delegation?:
onDelegationStart?:
context.requestContext の変更によるサブ Agent 実行の Request Context への項目追加に使用します。onDelegationComplete?:
bail() メソッドが含まれ、{ feedback } を返して supervisor の次のアクションを導くことができます。フィードバックは assistant メッセージとして supervisor の Memory に保存されます。messageFilter?:
tracingContext?:
returnScorerData?:
onChunk?:
onError?:
onAbort?:
abortSignal?:
activeTools?:
prepareStep?:
context?:
structuredOutput?:
schema:
model?:
errorStrategy?:
fallbackValue?:
instructions?:
jsonPromptInjection?:
providerOptions?:
{ openai: { reasoningEffort: 'low' } })。outputProcessors?:
processOutputResult 関数と processOutputStream 関数のいずれか、または両方を実装する必要があります。includeRawChunks?:
inputProcessors?:
processInput 関数を実装する必要があります。instructions?:
system?:
output?:
memory?:
thread:
id と省略可能な metadata を持つオブジェクトとして指定します。resource:
options?:
onTitleGenerated?:
generateTitle が有効で、thread に既存のタイトルがない場合にのみ呼び出されます。onFinish?:
onStepFinish?:
telemetry?:
isEnabled?:
recordInputs?:
recordOutputs?:
functionId?:
modelSettings?:
temperature?:
maxOutputTokens?:
maxRetries?:
topP?:
topK?:
presencePenalty?:
frequencyPenalty?:
stopSequences?:
toolChoice?:
'auto':
'none':
'required':
{ type: 'tool'; toolName: string }:
toolsets?:
clientTools?:
hooks?:
beforeToolCall は { proceed: false, output } を返して Tool 呼び出しをスキップできます。savePerStep?:
requireToolApproval?:
tool-call-approval チャンクを発行し、approveToolCall() または declineToolCall() が呼び出されるまで一時停止します。autoResumeSuspendedTools?:
resumeSchema に基づき、ユーザーのメッセージから resumeData を抽出します。Memory の設定が必要です。toolCallConcurrency?:
providerOptions?:
{ providerName: { optionKey: value } } です。例: { openai: { reasoningEffort: 'high' }, anthropic: { maxTokens: 1000 } }。openai?:
{ reasoningEffort: 'high' }anthropic?:
{ maxTokens: 1000 }google?:
{ safetySettings: [...] }[providerName]?:
runId?:
requestContext?:
tracingContext?:
currentSpan?:
tracingOptions?:
metadata?:
requestContextKeys?:
traceId?:
parentSpanId?:
tags?:
versions?:
agents?:
versionId?:
status?:
untilIdle?:
fullStream を通じて継続ターンをストリーミングします。デフォルト設定(アイドルタイムアウト 5 分)を使用するには true を、設定を変更するには maxIdleMs を持つオブジェクトを渡します。Memory が必要です。独立した streamUntilIdle() メソッドを置き換えるものです。maxIdleMs?:
戻り値戻り値への直接リンク
stream:
traceId?:
spanId?:
詳細な使用例詳細な使用例への直接リンク
Mastra 形式(デフォルト)Mastra 形式(デフォルト)への直接リンク
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 以降の形式への直接リンク
AI SDK v5 以降でストリームを使用するには、ユーティリティ関数 toAISdkStream で変換します。
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 がより扱いやすくなりました。
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)
}
オプションを使用する高度な例オプションを使用する高度な例への直接リンク
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 transportResponses WebSocket transportへの直接リンク
Provider オプションを指定して、Responses WebSocket ストリーミングを有効にします。これはストリーミング呼び出しにのみ適用され、OpenAI の直接モデルと Azure OpenAI Responses のデプロイでサポートされています。WebSocket ストリーミングを利用できない場合、Mastra は HTTP ストリーミングへフォールバックします。デフォルトでは、ストリームの終了時に Mastra が WebSocket を閉じます。
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 では、useResponsesAPI: true を指定して gateway を設定し、providerOptions.azure.transport を使用します。
const stream = await agent.stream('Hello', {
providerOptions: {
azure: {
transport: 'websocket',
store: false,
websocket: { closeOnFinish: true },
},
},
})
ストリームの終了後も接続を開いたままにするには、closeOnFinish: false を設定し、手動で閉じます。
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 接続では、一度に 1 つのレスポンスを実行します。同じ WebSocket transport 上で previous_response_id を含む継続リクエストが重複すると、Mastra はそのリクエストを拒否します。レスポンスチェーンの次のターンを送信する前に、実行中のストリームが終了するまで待ってください。