본문으로 건너뛰기

smoothStream()

smoothStream()일관된 청크로 방출하기 전에 텍스트를 버퍼링하고 델타를 추론하는 실험적인 변환 스트림을 생성합니다. Model이 고르지 않은 델타를 방출할 때 스트리밍 응답이 보다 안정적인 속도로 나타나도록 하려면 이를 사용하십시오.

텍스트가 아닌 청크는 변경되지 않은 채 통과됩니다. 버퍼링된 콘텐츠는 Tool, 컨트롤 또는 완료 청크 이전에 내보내집니다.

사용예
사용예에 대한 직접 링크

Agent의 fullStream을 변환을 통해 파이프하세요.

src/stream-agent.ts
import { smoothStream } from '@mastra/core/stream'

const result = await agent.stream('Explain how rainbows form')

const stream = result.fullStream.pipeThrough(
smoothStream({
delayInMs: 20,
chunking: 'word',
}),
)

for await (const chunk of stream) {
if (chunk.type === 'text-delta') {
process.stdout.write(chunk.payload.text)
}
}

변환은 파이프된 스트림만 변경합니다. result.textonChunk처럼 원본 MastraModelOutput의 Promise 속성과 콜백은 Model의 원래 청크 타이밍을 유지합니다.

AI SDK 경로
AI SDK 경로에 대한 직접 링크

handleChatStream()이 Agent 출력을 AI SDK UI 청크로 변환하기 전에 출력을 매끄럽게 만들려면 @mastra/ai-sdk에서 smoothStream()을 가져오세요.

app/api/chat/route.ts
import { handleChatStream, smoothStream } from '@mastra/ai-sdk'
import { createUIMessageStreamResponse } from 'ai'
import { mastra } from '@/src/mastra'

export async function POST(req: Request) {
const params = await req.json()
const stream = await handleChatStream({
mastra,
agentId: 'weatherAgent',
params,
experimentalTransform: smoothStream({
delayInMs: 20,
chunking: 'word',
}),
})

return createUIMessageStreamResponse({ stream })
}

@mastra/ai-sdk 내보내기는 재사용 가능한 변환 팩토리를 반환하므로 라우트 구성에서 요청마다 새로운 TransformStream을 생성합니다. @mastra/core/stream 내보내기는 pipeThrough()에 직접 사용할 수 있는 TransformStream을 반환합니다. 재사용 가능한 공장은 다음으로 전달될 수도 있습니다.Agent.stream():

import { smoothStream } from '@mastra/ai-sdk'

const result = await agent.stream('Explain how rainbows form', {
experimentalTransform: smoothStream({ delayInMs: 20 }),
})

for await (const chunk of result.fullStream) {
// Consume the transformed Mastra chunks.
}

매개변수
매개변수에 대한 직접 링크

options?:

SmoothStreamOptions
변환된 스트림의 지연 시간과 청크 경계를 제어합니다.
SmoothStreamOptions

delayInMs?:

number | null
각 청크를 방출한 후의 지연 시간(밀리초)입니다. 지연을 비활성화하려면 이 값을 null로 설정하세요.

chunking?:

'word' | 'line' | RegExp | SmoothStreamChunkDetector | Intl.Segmenter
버퍼링된 텍스트와 추론을 청크로 나누는 방식을 제어합니다.

그만큼chunking option accepts:

  • 'word': 후행 공백을 포함한 완전한 단어를 방출합니다.
  • 'line': 각 줄바꿈까지의 콘텐츠를 방출합니다.
  • RegExp: 첫 번째 일치 항목까지의 콘텐츠를 방출합니다.
  • Intl.Segmenter: 단어 사이에 공백이 없는 언어에 유용한 로케일 인식 분할을 사용합니다.
  • SmoothStreamChunkDetector: 현재 버퍼를 인수로 함수를 호출합니다. 이 함수는 방출할 비어 있지 않은 접두사를 반환하며, 더 많은 콘텐츠를 기다리려면 null 또는 undefined를 반환합니다.

커스텀 청킹
커스텀 청킹에 대한 직접 링크

정규식을 사용하여 청크 경계를 정의합니다.

const stream = result.fullStream.pipeThrough(
smoothStream({
chunking: /[^,]*,\s*/,
}),
)

로케일 인식 분할에는 Intl.Segmenter를 사용하세요.

const stream = result.fullStream.pipeThrough(
smoothStream({
chunking: new Intl.Segmenter('ja', { granularity: 'word' }),
}),
)

청크 경계가 사용자 정의 논리에 따라 달라지는 경우 감지기 기능을 사용하십시오. 반환된 값은 버퍼의 접두사여야 합니다.

const stream = result.fullStream.pipeThrough(
smoothStream({
chunking: buffer => {
const boundary = buffer.indexOf('. ')
return boundary === -1 ? null : buffer.slice(0, boundary + 2)
},
}),
)

보고
보고에 대한 직접 링크

TransformStream<ChunkType<OUTPUT>, ChunkType<OUTPUT>>

변환은 text-deltareasoning-delta 청크를 매끄럽게 방출합니다. 청크 식별자, 실행 식별자, 소스 및 메타데이터는 보존됩니다.