@@ -254,7 +254,7 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
254
254
255
255
bool retrying = true ;
256
256
ChatResult firstStreamedResult = null ;
257
-
257
+ IAsyncEnumerator < ChatResult > enumerator = null ;
258
258
while ( retrying )
259
259
{
260
260
retrying = false ;
@@ -263,14 +263,9 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
263
263
try
264
264
{
265
265
resStream = _endpoint . StreamChatEnumerableAsync ( req ) ;
266
- await foreach ( var res in resStream )
267
- {
268
- if ( res != null )
269
- {
270
- firstStreamedResult = res ;
271
- break ;
272
- }
273
- }
266
+ enumerator = resStream . GetAsyncEnumerator ( ) ;
267
+ await enumerator . MoveNextAsync ( ) ;
268
+ firstStreamedResult = enumerator . Current ;
274
269
}
275
270
catch ( HttpRequestException ex )
276
271
{
@@ -329,26 +324,9 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
329
324
throw new Exception ( "The chat result stream is null, but it shouldn't be" ) ;
330
325
}
331
326
332
- if ( firstStreamedResult != null )
333
- {
334
- if ( firstStreamedResult . Choices . FirstOrDefault ( ) ? . Delta is ChatMessage delta )
335
- {
336
- if ( delta . Role != null )
337
- responseRole = delta . Role ;
338
-
339
- string deltaContent = delta . Content ;
340
-
341
- if ( ! string . IsNullOrEmpty ( deltaContent ) )
342
- {
343
- responseStringBuilder . Append ( deltaContent ) ;
344
- yield return deltaContent ;
345
- }
346
- }
347
- MostRecentApiResult = firstStreamedResult ;
348
- }
349
-
350
- await foreach ( var res in resStream )
327
+ do
351
328
{
329
+ ChatResult res = enumerator . Current ;
352
330
if ( res . Choices . FirstOrDefault ( ) ? . Delta is ChatMessage delta )
353
331
{
354
332
if ( delta . Role != null )
@@ -363,8 +341,8 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
363
341
}
364
342
}
365
343
MostRecentApiResult = res ;
366
- }
367
-
344
+ } while ( await enumerator . MoveNextAsync ( ) ) ;
345
+
368
346
if ( responseRole != null )
369
347
{
370
348
AppendMessage ( responseRole , responseStringBuilder . ToString ( ) ) ;
0 commit comments