handleChatStream()
Framework-agnostic handler for streaming agent chat in AI SDK-compatible format. Use this function directly when you need to handle chat streaming outside Hono or Mastra's own apiRoutes feature.
handleChatStream() returns a ReadableStream that you can wrap with createUIMessageStreamResponse().
handleChatStream() keeps the existing AI SDK v5/default behavior. If your app is typed against AI SDK v6, pass version: 'v6'.
Use chatRoute() if you want to create a chat route inside a Mastra server.
Structured output in UI streamsDirect link to Structured output in UI streams
When you pass structuredOutput to the underlying agent execution, the final structured output object is emitted in the AI SDK-compatible UI stream as a custom data part:
{
"type": "data-structured-output",
"data": {
"object": {}
}
}
The object field contains your full structured output value. Mastra emits this event for the final structured output object only. Partial structured output chunks are not exposed in the UI stream.
Read this event with AI SDK UI's custom data handling, such as onData, or render it from message data parts.
Usage exampleDirect link to Usage example
Next.js App Router example:
import { handleChatStream } 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,
messageMetadata: () => ({ createdAt: new Date().toISOString() }),
})
return createUIMessageStreamResponse({ stream })
}