Skip to content

Commit 60e4c78

Browse files
committed
Fixes #184, no longer call API twice for Chat streaming
1 parent b824ac5 commit 60e4c78

File tree

1 file changed

+8
-30
lines changed

1 file changed

+8
-30
lines changed

OpenAI_API/Chat/Conversation.cs

Lines changed: 8 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -254,7 +254,7 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
254254

255255
bool retrying = true;
256256
ChatResult firstStreamedResult = null;
257-
257+
IAsyncEnumerator<ChatResult> enumerator = null;
258258
while (retrying)
259259
{
260260
retrying = false;
@@ -263,14 +263,9 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
263263
try
264264
{
265265
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;
274269
}
275270
catch (HttpRequestException ex)
276271
{
@@ -329,26 +324,9 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
329324
throw new Exception("The chat result stream is null, but it shouldn't be");
330325
}
331326

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
351328
{
329+
ChatResult res = enumerator.Current;
352330
if (res.Choices.FirstOrDefault()?.Delta is ChatMessage delta)
353331
{
354332
if (delta.Role != null)
@@ -363,8 +341,8 @@ public async IAsyncEnumerable<string> StreamResponseEnumerableFromChatbotAsync()
363341
}
364342
}
365343
MostRecentApiResult = res;
366-
}
367-
344+
} while (await enumerator.MoveNextAsync());
345+
368346
if (responseRole != null)
369347
{
370348
AppendMessage(responseRole, responseStringBuilder.ToString());

0 commit comments

Comments
 (0)