|
5 | 5 | using System.Linq;
|
6 | 6 | using System.Net;
|
7 | 7 | using System.Net.Http;
|
| 8 | +using System.Threading; |
8 | 9 | using System.Threading.Tasks;
|
9 | 10 | using Microsoft.Extensions.DependencyInjection;
|
10 | 11 | using Microsoft.SemanticKernel;
|
@@ -569,6 +570,53 @@ public async Task PostFilterCanTerminateOperationOnStreamingAsync()
|
569 | 570 | Assert.Equal(AuthorRole.Tool, lastMessageContent.Role);
|
570 | 571 | }
|
571 | 572 |
|
| 573 | + [Fact] |
| 574 | + public async Task FilterContextHasCancellationTokenAsync() |
| 575 | + { |
| 576 | + // Arrange |
| 577 | + using var cancellationTokenSource = new CancellationTokenSource(); |
| 578 | + int firstFunctionInvocations = 0; |
| 579 | + int secondFunctionInvocations = 0; |
| 580 | + |
| 581 | + var function1 = KernelFunctionFactory.CreateFromMethod((string parameter) => |
| 582 | + { |
| 583 | + cancellationTokenSource.Cancel(); |
| 584 | + firstFunctionInvocations++; |
| 585 | + return parameter; |
| 586 | + }, "Function1"); |
| 587 | + |
| 588 | + var function2 = KernelFunctionFactory.CreateFromMethod((string parameter) => |
| 589 | + { |
| 590 | + secondFunctionInvocations++; |
| 591 | + return parameter; |
| 592 | + }, "Function2"); |
| 593 | + |
| 594 | + var plugin = KernelPluginFactory.CreateFromFunctions("MyPlugin", [function1, function2]); |
| 595 | + |
| 596 | + var kernel = this.GetKernelWithFilter(plugin, async (context, next) => |
| 597 | + { |
| 598 | + Assert.Equal(cancellationTokenSource.Token, context.CancellationToken); |
| 599 | + |
| 600 | + await next(context); |
| 601 | + |
| 602 | + context.CancellationToken.ThrowIfCancellationRequested(); |
| 603 | + }); |
| 604 | + |
| 605 | + using var response1 = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(OpenAITestHelper.GetTestResponse("filters_multiple_function_calls_test_response.json")) }; |
| 606 | + using var response2 = new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(OpenAITestHelper.GetTestResponse("chat_completion_test_response.json")) }; |
| 607 | + |
| 608 | + this._messageHandlerStub.ResponsesToReturn = [response1, response2]; |
| 609 | + |
| 610 | + var arguments = new KernelArguments(new OpenAIPromptExecutionSettings { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }); |
| 611 | + |
| 612 | + // Act & Assert |
| 613 | + var exception = await Assert.ThrowsAsync<KernelFunctionCanceledException>(() |
| 614 | + => kernel.InvokePromptAsync("Test prompt", arguments, cancellationToken: cancellationTokenSource.Token)); |
| 615 | + |
| 616 | + Assert.Equal(1, firstFunctionInvocations); |
| 617 | + Assert.Equal(0, secondFunctionInvocations); |
| 618 | + } |
| 619 | + |
572 | 620 | public void Dispose()
|
573 | 621 | {
|
574 | 622 | this._httpClient.Dispose();
|
|
0 commit comments