question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

[BUG] Cancelling GetChatCompletionsStreaming throws error

See original GitHub issue

Library name and version

Azure.AI.OpenAI 1.0.0-beta.5

Describe the bug

I’m streaming the response from GetChatCompletionsStreamingAsync through a WebAPI endpoint. The stream is consumed from web client using const reader = response.body?.getReader(); and if I call reader.cancel() I will get an exception in IIS server.

Simplified my code looks something like this in a service method

            await foreach (var choice in streamingResponse.GetChoicesStreaming(cancellationToken))
            {
                await foreach (var message in choice.GetMessageStreaming(cancellationToken))
                {
                    yield return message;
                }
            }

which is then further filtered down to IAsyncEnumerable<string> at the endpoint using

            await foreach (var message in _openAiService.GetChatChoiceStreamingAsync(prompt, cancellationToken)
                .Where(m => m.Content is not null))
            {
                yield return message.Content;
            }

Cancellation works fine, but I am concerned about the exception. Is it expected behaviour or am I using the stream/CancellationToken wrong somehow? The documentation/samples on how to properly stream data using the streaming methods are a bit thin so I might have missed something along the way.

A sidenote, I found that I had to use …

            var bodyFeature = HttpContext.Features.GetRequiredFeature<IHttpResponseBodyFeature>();
            bodyFeature.DisableBuffering();

… to actually make the streaming work properly, perhaps this should be noted somewhere in the docs/examples as well.

Expected behavior

No exceptions thrown

Actual behavior

Microsoft.AspNetCore.Server.IIS.Core.IISHttpServer: Error: Connection ID "18302628886439002211", Request ID "40000064-0000-fe00-b63f-84710c7967bb": An unhandled exception was thrown by the application.

System.AggregateException: One or more errors occurred. (An attempt was made to transition a task to a final state when it had already completed.) (An attempt was made to transition a task to a final state when it had already completed.) (An attempt was made to transition a task to a final state when it had already completed.)
 ---> System.InvalidOperationException: An attempt was made to transition a task to a final state when it had already completed.
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled(CancellationToken cancellationToken)
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled()
   at Azure.AI.OpenAI.AsyncAutoResetEvent.<>c__DisplayClass3_0.<WaitAsync>b__0()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   --- End of inner exception stack trace ---
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)
   at Microsoft.AspNetCore.Server.IIS.Core.IISHttpContext.<CancelRequestAbortedToken>b__390_0(IISHttpContext ctx)
 ---> (Inner Exception #1) System.InvalidOperationException: An attempt was made to transition a task to a final state when it had already completed.
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled(CancellationToken cancellationToken)
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled()
   at Azure.AI.OpenAI.AsyncAutoResetEvent.<>c__DisplayClass3_0.<WaitAsync>b__0()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)<---

 ---> (Inner Exception #2) System.InvalidOperationException: An attempt was made to transition a task to a final state when it had already completed.
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled(CancellationToken cancellationToken)
   at System.Threading.Tasks.TaskCompletionSource`1.SetCanceled()
   at Azure.AI.OpenAI.AsyncAutoResetEvent.<>c__DisplayClass3_0.<WaitAsync>b__0()
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
--- End of stack trace from previous location ---
   at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
   at System.Threading.CancellationTokenSource.ExecuteCallbackHandlers(Boolean throwOnFirstException)<---

Reproduction Steps

See description

Environment

.NET SDK: Version: 7.0.302 Commit: 990cf98a27

Runtime Environment: OS Name: Windows OS Version: 10.0.23481 OS Platform: Windows RID: win10-x64 Base Path: C:\Program Files\dotnet\sdk\7.0.302\

Host: Version: 7.0.7 Architecture: x64 Commit: 5b20af47d9

Issue Analytics

  • State:closed
  • Created 3 months ago
  • Comments:5 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
anthonypuppocommented, Jul 20, 2023

Was having the same issue in beta 5, updating to beta 6 fixed it.

#35593

0reactions
leewsimpson-Deloittecommented, Aug 6, 2023

when will this fix be released?

Read more comments on GitHub >

github_iconTop Results From Across the Web

[BUG] Exception Multi-lilne data not supported in streaming ...
Describe the bug Sometimes, during the streaming of a chat result, the following error message is thrown: The issue is happening here: ...
Read more >
Chatgpt turbo streaming always ends in error - API
I'm trying to use the new chat completion endpoint with streaming set to true. It seems to work, but I'm always getting an...
Read more >
Alamofire stream requests consistently fail if invoked after 1 ...
I've built a macOS app that integrates with ChatGPT. To support the model's streaming responses, I'm using Alamofire's AF.
Read more >
OpenAI Completions API — Complete Guide
The Completions API is the most fundamental OpenAI model that provides a simple interface that's extremely flexible and powerful.
Read more >
Chat completions API fails consistently with a 500 error ...
Chat completions API fails consistently with a 500 error when using functions in combination with names. When using the /v1/chat/completions ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found