MastraM
Mastra4mo ago
Saulved

How to use StreamV2 with @mastra/client-js using the aisdk format?

My goal is to return:

return stream.toUIMessageStreamResponse();


The mastra docs show this:

const stream = await agent.streamVNext("Tell me a story", {
  format: 'aisdk',
  stopWhen: stepCountIs(3), // Stop after 3 steps
  modelSettings: {
    temperature: 0.7,
  },
});
 
// Use with AI SDK v5 compatible interfaces
for await (const part of stream.fullStream) {
  if (part.type === 'text-delta') {
    console.log(part.text);
  }
}
 
// In an API route for frontend integration
return stream.toUIMessageStreamResponse();


BUT with the client-js,

  • the streamVNext does not have a stream.fullStream
  • it also does not have toUImessageStreamResponse()
So I am doing this instead:

myAgent = mastraClient.getAgent("agent");
mastraResponse = myagent.streamVNext({

})

// Simplified
mastraResponse.processDataStream({
        onChunk: async (chunk) => {
          try {
            // Extract text content from chunk based on its type
            if (chunk.type === "text-delta" && "text" in chunk.payload) {
              console.log("📝 Text delta:", chunk.payload.text);
              // Don't write to process.stdout in web API context - just log
            }
            if (chunk.type === "tool-call" && "toolName" in chunk.payload) {
              // Don't write to process.stdout in web API context - just log
            }
            // Log other chunk types for debugging
            if (chunk.type === "response-metadata") {
              console.log("📊 Response metadata received");
            }
          } catch (error) {
            console.error("❌ Error processing chunk:", error);
            // Don't log the entire chunk as it might be too large or cause circular reference issues
          }
        },


Am I missing an equivalent to fullStream / toUIMessageStreamResponse() in client-js, or is processDataStream the intended path? Any pointers appreciated. Thanks!

Thanks everyone! I really appreciate your help.
Was this page helpful?