Skip to content

Commit

Permalink
.Net: Removed Kernel events (#9748)
Browse files Browse the repository at this point in the history
### Motivation and Context

<!-- Thank you for your contribution to the semantic-kernel repo!
Please help reviewers and future users, providing the following
information:
  1. Why is this change required?
  2. What problem does it solve?
  3. What scenario does it contribute to?
  4. If it fixes an open issue, please link to the issue here.
-->

Related: #9499

Removed the usage of obsolete Kernel Events in favor of Filters as part
of Filters graduation process.

### Contribution Checklist

<!-- Before submitting this PR, please make sure: -->

- [x] The code builds clean without any errors or warnings
- [x] The PR follows the [SK Contribution
Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md)
and the [pre-submission formatting
script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts)
raises no violations
- [x] All unit tests pass, and I have added new tests where possible
- [x] I didn't break anyone 😄
  • Loading branch information
dmytrostruk authored Nov 19, 2024
1 parent 297eb16 commit e6413c3
Show file tree
Hide file tree
Showing 9 changed files with 2 additions and 969 deletions.
278 changes: 0 additions & 278 deletions dotnet/samples/Concepts/Filtering/Legacy_KernelHooks.cs

This file was deleted.

55 changes: 0 additions & 55 deletions dotnet/samples/GettingStarted/Step7_Observability.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,61 +37,6 @@ public async Task ObservabilityWithFiltersAsync()
Console.WriteLine(await kernel.InvokePromptAsync("How many days until Christmas? Explain your thinking.", new(settings)));
}

/// <summary>
/// Shows how to observe the execution of a <see cref="KernelPlugin"/> instance with hooks.
/// </summary>
[Fact]
[Obsolete("Events are deprecated in favor of filters.")]
public async Task ObservabilityWithHooksAsync()
{
// Create a kernel with OpenAI chat completion
IKernelBuilder kernelBuilder = Kernel.CreateBuilder();
kernelBuilder.AddOpenAIChatCompletion(
modelId: TestConfiguration.OpenAI.ChatModelId,
apiKey: TestConfiguration.OpenAI.ApiKey);

kernelBuilder.Plugins.AddFromType<TimeInformation>();

Kernel kernel = kernelBuilder.Build();

// Handler which is called before a function is invoked
void MyInvokingHandler(object? sender, FunctionInvokingEventArgs e)
{
Console.WriteLine($"Invoking {e.Function.Name}");
}

// Handler which is called before a prompt is rendered
void MyRenderingHandler(object? sender, PromptRenderingEventArgs e)
{
Console.WriteLine($"Rendering prompt for {e.Function.Name}");
}

// Handler which is called after a prompt is rendered
void MyRenderedHandler(object? sender, PromptRenderedEventArgs e)
{
Console.WriteLine($"Rendered prompt: {e.RenderedPrompt}");
}

// Handler which is called after a function is invoked
void MyInvokedHandler(object? sender, FunctionInvokedEventArgs e)
{
if (e.Result.Metadata is not null && e.Result.Metadata.ContainsKey("Usage"))
{
Console.WriteLine("Token usage: {0}", e.Result.Metadata?["Usage"]?.AsJson());
}
}

// Add the handlers to the kernel
kernel.FunctionInvoking += MyInvokingHandler;
kernel.PromptRendering += MyRenderingHandler;
kernel.PromptRendered += MyRenderedHandler;
kernel.FunctionInvoked += MyInvokedHandler;

// Invoke the kernel with a prompt and allow the AI to automatically invoke functions
OpenAIPromptExecutionSettings settings = new() { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };
Console.WriteLine(await kernel.InvokePromptAsync("How many days until Christmas? Explain your thinking.", new(settings)));
}

/// <summary>
/// A plugin that returns the current time.
/// </summary>
Expand Down
36 changes: 0 additions & 36 deletions dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunction.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,16 +240,6 @@ public async Task<FunctionResult> InvokeAsync(
// Quick check for cancellation after logging about function start but before doing any real work.
cancellationToken.ThrowIfCancellationRequested();

// Invoke pre-invocation event handler. If it requests cancellation, throw.
#pragma warning disable CS0618 // Events are deprecated
var invokingEventArgs = kernel.OnFunctionInvoking(this, arguments);
#pragma warning restore CS0618 // Events are deprecated

if (invokingEventArgs?.Cancel is true)
{
throw new OperationCanceledException($"A {nameof(Kernel)}.{nameof(Kernel.FunctionInvoking)} event handler requested cancellation before function invocation.");
}

var invocationContext = await kernel.OnFunctionInvocationAsync(this, arguments, functionResult, isStreaming: false, async (context) =>
{
// Invoking the function and updating context with result.
Expand All @@ -259,22 +249,6 @@ public async Task<FunctionResult> InvokeAsync(
// Apply any changes from the function filters context to final result.
functionResult = invocationContext.Result;

// Invoke the post-invocation event handler. If it requests cancellation, throw.
#pragma warning disable CS0618 // Events are deprecated
var invokedEventArgs = kernel.OnFunctionInvoked(this, arguments, functionResult);
#pragma warning restore CS0618 // Events are deprecated

if (invokedEventArgs is not null)
{
// Apply any changes from the event handlers to final result.
functionResult = new FunctionResult(this, invokedEventArgs.ResultValue, functionResult.Culture, invokedEventArgs.Metadata ?? functionResult.Metadata);
}

if (invokedEventArgs?.Cancel is true)
{
throw new OperationCanceledException($"A {nameof(Kernel)}.{nameof(Kernel.FunctionInvoked)} event handler requested cancellation after function invocation.");
}

logger.LogFunctionInvokedSuccess(this.PluginName, this.Name);

this.LogFunctionResult(logger, this.PluginName, this.Name, functionResult);
Expand Down Expand Up @@ -370,16 +344,6 @@ public async IAsyncEnumerable<TResult> InvokeStreamingAsync<TResult>(
// Quick check for cancellation after logging about function start but before doing any real work.
cancellationToken.ThrowIfCancellationRequested();

// Invoke pre-invocation event handler. If it requests cancellation, throw.
#pragma warning disable CS0618 // Events are deprecated
var invokingEventArgs = kernel.OnFunctionInvoking(this, arguments);
#pragma warning restore CS0618 // Events are deprecated

if (invokingEventArgs?.Cancel is true)
{
throw new OperationCanceledException($"A {nameof(Kernel)}.{nameof(Kernel.FunctionInvoking)} event handler requested cancellation before function invocation.");
}

FunctionResult functionResult = new(this, culture: kernel.Culture);

var invocationContext = await kernel.OnFunctionInvocationAsync(this, arguments, functionResult, isStreaming: true, (context) =>
Expand Down
Loading

0 comments on commit e6413c3

Please sign in to comment.