@@ -3,13 +3,17 @@ import {
33 WorkflowContext ,
44 WorkflowEvent ,
55} from "@llamaindex/workflow" ;
6- import { StreamData , createStreamDataTransformer } from "ai" ;
7- import { ChatResponseChunk } from "llamaindex" ;
6+ import {
7+ StreamData ,
8+ createStreamDataTransformer ,
9+ parseDataStreamPart ,
10+ } from "ai" ;
11+ import { ChatResponseChunk , EngineResponse } from "llamaindex" ;
812import { AgentRunEvent } from "./type" ;
913
1014export async function createStreamFromWorkflowContext < Input , Output , Context > (
1115 context : WorkflowContext < Input , Output , Context > ,
12- ) : Promise < { stream : ReadableStream < string > ; dataStream : StreamData } > {
16+ ) : Promise < { stream : AsyncIterable < EngineResponse > ; dataStream : StreamData } > {
1317 const dataStream = new StreamData ( ) ;
1418 const encoder = new TextEncoder ( ) ;
1519 let generator : AsyncGenerator < ChatResponseChunk > | undefined ;
@@ -47,10 +51,14 @@ export async function createStreamFromWorkflowContext<Input, Output, Context>(
4751 } ,
4852 } ) ;
4953
54+ const stream = mainStream
55+ . pipeThrough ( createStreamDataTransformer ( ) )
56+ . pipeThrough ( new TextDecoderStream ( ) ) ;
57+
58+ const streamIterable = streamToAsyncIterable ( stream ) ;
59+
5060 return {
51- stream : mainStream
52- . pipeThrough ( createStreamDataTransformer ( ) )
53- . pipeThrough ( new TextDecoderStream ( ) ) ,
61+ stream : streamIterable ,
5462 dataStream,
5563 } ;
5664}
@@ -71,3 +79,25 @@ function handleEvent(
7179 } ) ;
7280 }
7381}
82+
83+ function streamToAsyncIterable ( stream : ReadableStream < string > ) {
84+ const streamIterable : AsyncIterable < EngineResponse > = {
85+ [ Symbol . asyncIterator ] ( ) {
86+ const reader = stream . getReader ( ) ;
87+ return {
88+ async next ( ) {
89+ const { done, value } = await reader . read ( ) ;
90+ if ( done ) {
91+ return { done : true , value : undefined } ;
92+ }
93+ const delta = parseDataStreamPart ( value ) ?. value . toString ( ) || "" ;
94+ return {
95+ done : false ,
96+ value : { delta } as unknown as EngineResponse ,
97+ } ;
98+ } ,
99+ } ;
100+ } ,
101+ } ;
102+ return streamIterable ;
103+ }
0 commit comments