Agent.스트림()
그만큼.stream()이 방법을 사용하면 향상된 기능과 형식 유연성을 통해 Agent의 응답을 실시간 스트리밍할 수 있습니다. 이 방법은 메시지와 선택적 스트리밍 옵션을 허용하여 Mastra의 기본 형식과 AI SDK v5+ 호환성을 모두 지원하는 현재 스트리밍 환경을 제공합니다.
사용예사용예에 대한 직접 링크
const stream = await agent.stream('message for agent')
Model 호환성: 이 메서드는 V2 Model용으로 설계되었습니다. V1 Model에는 .streamLegacy() 메서드를 사용하세요. 프레임워크가 Model 버전을 자동으로 감지하며 버전이 일치하지 않으면 오류를 발생시킵니다.
매개변수매개변수에 대한 직접 링크
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 실행의 요청 컨텍스트에 항목을 추가할 수 있습니다.onDelegationComplete?:
bail() 메서드가 포함되며, { feedback }을 반환하여 감독자의 다음 작업을 안내할 수 있습니다. 피드백은 어시스턴트 메시지로 감독자의 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이 활성화되어 있고 스레드에 기존 제목이 없을 때만 실행됩니다.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?:
확장된 사용 예확장된 사용 예에 대한 직접 링크
마스트라 형식(기본값)마스트라 형식(기본값)에 대한 직접 링크
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 }),
],
})
응답 WebSocket 전송응답 WebSocket 전송에 대한 직접 링크
공급자 옵션을 사용하여 응답 WebSocket 스트리밍을 선택합니다. 이는 스트리밍 호출에만 적용되며 직접 OpenAI Model 및 Azure OpenAI 응답 배포에 지원됩니다. 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를 사용하여 게이트웨이를 구성한 다음 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 연결은 한 번에 하나의 응답만 실행합니다. Mastra는 동일한 WebSocket 전송에서 previous_response_id를 포함하는 중복 후속 요청을 거부합니다. 응답 체인의 다음 턴을 보내기 전에 활성 스트림이 완료될 때까지 기다리세요.