[Question] How to interrupt the streaming output? #567
Answered
by
kayhantolga
MayDay-wpf
asked this question in
Q&A
-
Beta Was this translation helpful? Give feedback.
Answered by
kayhantolga
May 21, 2024
Replies: 1 comment
-
Hi, you can pass a cancellation token and cancel the token if you want to stop streaming. Here is a sample from the playground (the sample is for legacy completion, but chat completion should work the same way). public static async Task RunSimpleCompletionStreamTestWithCancellationToken(IOpenAIService sdk)
{
ConsoleExtensions.WriteLine("Completion Stream Testing is starting:", ConsoleColor.Cyan);
var cancellationToken = new CancellationTokenSource(TimeSpan.FromSeconds(2)).Token;
cancellationToken.Register(() => Console.WriteLine("Cancellation Token has been cancelled."));
try
{
ConsoleExtensions.WriteLine("Completion Stream Test:", ConsoleColor.DarkCyan);
var completionResult = sdk.Completions.CreateCompletionAsStream(new CompletionCreateRequest
{
Prompt = "Once upon a time",
MaxTokens = 100
}, Models.Davinci, cancellationToken);
try
{
await foreach (var completion in completionResult.WithCancellation(cancellationToken))
{
if (completion.Successful)
{
Console.Write(completion.Choices.FirstOrDefault()?.Text);
}
else
{
if (completion.Error == null)
{
throw new Exception("Unknown Error");
}
Console.WriteLine($"{completion.Error.Code}: {completion.Error.Message}");
}
}
}
catch (OperationCanceledException)
{
ConsoleExtensions.WriteLine("Operation Cancelled", ConsoleColor.Green);
}
Console.WriteLine("");
Console.WriteLine("Complete");
}
catch (Exception e)
{
Console.WriteLine(e);
throw;
}
} |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
MayDay-wpf
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, you can pass a cancellation token and cancel the token if you want to stop streaming. Here is a sample from the playground (the sample is for legacy completion, but chat completion should work the same way).