MastraM
Mastra2mo ago
Bastien

How to stream custom events from workflows using the AI SDK

Hi everyone!

I send custom events using writer.custom in a workflow used by an agent.

I stream the agent using the AI SDK as stated in the documentation :
    let uiMessageStream = createUIMessageStream({
      execute: async ({ writer }) => {
        for await (let part of toAISdkFormat(stream, { from: "agent" })!) {
          writer.write(part);
        }
      },
    });

    return createUIMessageStreamResponse({
      stream: uiMessageStream,
    });

My custom events are not sent in the response.

By analysing the stream chunks, i can see that they are available in the stream.fullStream stream but not in the parts created by the toAISdkFormat function.
In the stream.fullStream stream, I see that they are wrapped in a tool-output part, that's probably why they are not caught by the toAISdkFormat function :
{
    "type": "tool-output",
    "runId": "8129c45f-266f-41d4-ba07-1385583a6f67",
    "from": "USER",
    "payload": {
        "output": {
            "type": "data-my-custom-event",
            "data": {
                "foo": "bar"
            }
        },
        "toolCallId": "call_5BTDhkOUHMCgurN0dTwToG8D",
        "toolName": "workflow-myWorkflow"
    }
}


Is it the expected behaviour? I would kind of expect custom events to not be wrapped, as it's the case when streaming custom events from a tool.
How can I work around this issue?

Thanks for your help!
Was this page helpful?