File tree 3 files changed +33
-10
lines changed
3 files changed +33
-10
lines changed Original file line number Diff line number Diff line change @@ -93,7 +93,7 @@ export const streamQueryV1 = async (
93
93
94
94
const url = config . endpoint ?? `${ DEFAULT_DOMAIN } /v1/stream-query` ;
95
95
96
- const stream = await generateStream ( requestHeaders , requestBody , url ) ;
96
+ const { stream } = await generateStream ( requestHeaders , requestBody , url ) ;
97
97
98
98
let previousAnswerText = "" ;
99
99
Original file line number Diff line number Diff line change @@ -143,17 +143,32 @@ export const streamQueryV2 = async (
143
143
const url = `${ endpoint ?? DEFAULT_DOMAIN } ${ path } ` ;
144
144
145
145
try {
146
- const stream = await generateStream ( headers , JSON . stringify ( body ) , url ) ;
147
- const buffer = new EventBuffer ( onStreamEvent ) ;
146
+ const { cancelStream, stream } = await generateStream (
147
+ headers ,
148
+ JSON . stringify ( body ) ,
149
+ url
150
+ ) ;
148
151
149
- for await ( const chunk of stream ) {
152
+ new Promise ( async ( resolve , reject ) => {
150
153
try {
151
- buffer . consumeChunk ( chunk ) ;
152
- buffer . drainEvents ( ) ;
154
+ const buffer = new EventBuffer ( onStreamEvent ) ;
155
+
156
+ for await ( const chunk of stream ) {
157
+ try {
158
+ buffer . consumeChunk ( chunk ) ;
159
+ buffer . drainEvents ( ) ;
160
+ } catch ( error ) {
161
+ console . log ( "error" , error ) ;
162
+ }
163
+ }
164
+
165
+ resolve ( undefined ) ;
153
166
} catch ( error ) {
154
- console . log ( "error" , error ) ;
167
+ reject ( error ) ;
155
168
}
156
- }
169
+ } ) ;
170
+
171
+ return { cancelStream } ;
157
172
} catch ( error ) {
158
173
console . log ( "error" , error ) ;
159
174
}
Original file line number Diff line number Diff line change @@ -2,15 +2,23 @@ export const generateStream = async (
2
2
headers : Record < string , string > ,
3
3
body : string ,
4
4
url : string
5
- ) : Promise < AsyncIterable < string > > => {
5
+ ) => {
6
+ let controller = new AbortController ( ) ;
7
+
6
8
const response = await fetch ( url , {
7
9
method : "POST" ,
8
10
headers,
9
11
body,
12
+ signal : controller . signal ,
10
13
} ) ;
14
+
11
15
if ( response . status !== 200 ) throw new Error ( response . status . toString ( ) ) ;
12
16
if ( ! response . body ) throw new Error ( "Response body does not exist" ) ;
13
- return getIterableStream ( response . body ) ;
17
+
18
+ return {
19
+ stream : getIterableStream ( response . body ) ,
20
+ cancelStream : ( ) => controller . abort ( ) ,
21
+ } ;
14
22
} ;
15
23
16
24
async function * getIterableStream (
You can’t perform that action at this time.
0 commit comments