Skip to content

Commit 2023812

Browse files
markwallace-microsoftpull[bot]
authored andcommitted
.Net: Change IKernelPlugin to be abstract class KernelPlugin (#4084)
### Motivation and Context Changing `IKernelPlugin` to be abstract class `KernelPluginBase` so that we have the flexibility to extend that we get from abstract classes. ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [ ] The code builds clean without any errors or warnings - [ ] 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 - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone 😄
1 parent 91355d3 commit 2023812

34 files changed

Lines changed: 453 additions & 526 deletions

‎dotnet/samples/KernelSyntaxExamples/Example13_ConversationSummaryPlugin.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -129,7 +129,7 @@ private static async Task ConversationSummaryPluginAsync()
129129
Console.WriteLine("======== SamplePlugins - Conversation Summary Plugin - Summarize ========");
130130
Kernel kernel = InitializeKernel();
131131

132-
IKernelPlugin conversationSummaryPlugin = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
132+
KernelPlugin conversationSummaryPlugin = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
133133

134134
FunctionResult summary = await kernel.InvokeAsync(
135135
conversationSummaryPlugin["SummarizeConversation"], new(ChatTranscript));
@@ -143,7 +143,7 @@ private static async Task GetConversationActionItemsAsync()
143143
Console.WriteLine("======== SamplePlugins - Conversation Summary Plugin - Action Items ========");
144144
Kernel kernel = InitializeKernel();
145145

146-
IKernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
146+
KernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
147147

148148
FunctionResult summary = await kernel.InvokeAsync(
149149
conversationSummary["GetConversationActionItems"], new(ChatTranscript));
@@ -157,7 +157,7 @@ private static async Task GetConversationTopicsAsync()
157157
Console.WriteLine("======== SamplePlugins - Conversation Summary Plugin - Topics ========");
158158
Kernel kernel = InitializeKernel();
159159

160-
IKernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
160+
KernelPlugin conversationSummary = kernel.ImportPluginFromType<ConversationSummaryPlugin>();
161161

162162
FunctionResult summary = await kernel.InvokeAsync(
163163
conversationSummary["GetConversationTopics"], new(ChatTranscript));

‎dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public static async Task RunAsync()
7878
await GetSecretFromAzureKeyVaultWithRetryAsync(kernel, plugin);
7979
}
8080

81-
public static async Task AddSecretToAzureKeyVaultAsync(Kernel kernel, IKernelPlugin plugin)
81+
public static async Task AddSecretToAzureKeyVaultAsync(Kernel kernel, KernelPlugin plugin)
8282
{
8383
// Add arguments for required parameters, arguments for optional ones can be skipped.
8484
var arguments = new KernelArguments
@@ -97,7 +97,7 @@ public static async Task AddSecretToAzureKeyVaultAsync(Kernel kernel, IKernelPlu
9797
Console.WriteLine("SetSecret function result: {0}", result?.Content?.ToString());
9898
}
9999

100-
public static async Task GetSecretFromAzureKeyVaultWithRetryAsync(Kernel kernel, IKernelPlugin plugin)
100+
public static async Task GetSecretFromAzureKeyVaultWithRetryAsync(Kernel kernel, KernelPlugin plugin)
101101
{
102102
// Add arguments for required parameters, arguments for optional ones can be skipped.
103103
var arguments = new KernelArguments();

‎dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ public static async Task RunAsync()
3636
// Change <your-domain> to a jira instance you have access to with your authentication credentials
3737
string serverUrl = $"https://{TestConfiguration.Jira.Domain}.atlassian.net/rest/api/latest/";
3838

39-
IKernelPlugin jiraFunctions;
39+
KernelPlugin jiraFunctions;
4040
var tokenProvider = new BasicAuthenticationProvider(() =>
4141
{
4242
string s = $"{TestConfiguration.Jira.Email}:{TestConfiguration.Jira.ApiKey}";

‎dotnet/samples/KernelSyntaxExamples/Example42_KernelBuilder.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -69,8 +69,8 @@ public static Task RunAsync()
6969
services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information));
7070
services.AddHttpClient();
7171
services.AddKernel().AddAzureOpenAIChatCompletion(azureOpenAIChatDeploymentName, azureOpenAIChatModelId, azureOpenAIEndpoint, azureOpenAIKey);
72-
services.AddSingleton<IKernelPlugin>(sp => KernelPluginFactory.CreateFromType<TimePlugin>(serviceProvider: sp));
73-
services.AddSingleton<IKernelPlugin>(sp => KernelPluginFactory.CreateFromType<HttpPlugin>(serviceProvider: sp));
72+
services.AddSingleton<KernelPlugin>(sp => KernelPluginFactory.CreateFromType<TimePlugin>(serviceProvider: sp));
73+
services.AddSingleton<KernelPlugin>(sp => KernelPluginFactory.CreateFromType<HttpPlugin>(serviceProvider: sp));
7474
Kernel kernel6 = services.BuildServiceProvider().GetRequiredService<Kernel>();
7575

7676
return Task.CompletedTask;

‎dotnet/samples/KernelSyntaxExamples/Example70_Assistant.cs‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ private static async Task RunWithMethodFunctionsAsync()
7373
{
7474
Console.WriteLine("======== Run:WithMethodFunctions ========");
7575

76-
IKernelPlugin plugin = KernelPluginFactory.CreateFromType<MenuPlugin>();
76+
KernelPlugin plugin = KernelPluginFactory.CreateFromType<MenuPlugin>();
7777

7878
// Call the common chat-loop
7979
await ChatAsync(
@@ -94,12 +94,12 @@ private static async Task RunWithPromptFunctionsAsync()
9494
Console.WriteLine("======== WithPromptFunctions ========");
9595

9696
// Create a prompt function.
97-
var plugin = new KernelPlugin("spelling");
98-
plugin.AddFunctionFromPrompt(
97+
var function = KernelFunctionFactory.CreateFromPrompt(
9998
"Correct any misspelling or gramatical errors provided in input: {{$input}}",
10099
functionName: "spellChecker",
101100
description: "Correct the spelling for the user input."
102101
);
102+
var plugin = KernelPluginFactory.CreateFromFunctions("spelling", "Spelling functions", new[] { function });
103103

104104
// Call the common chat-loop
105105
await ChatAsync(
@@ -159,7 +159,7 @@ await Task.WhenAll(
159159
/// </summary>
160160
private static async Task ChatAsync(
161161
string resourcePath,
162-
IKernelPlugin? plugin = null,
162+
KernelPlugin? plugin = null,
163163
params string[] messages)
164164
{
165165
// Read assistant resource
Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System;
4+
using System.Collections.Generic;
5+
using System.Diagnostics.CodeAnalysis;
6+
using System.Threading.Tasks;
7+
using Microsoft.SemanticKernel;
8+
9+
/**
10+
* This example shows how to create a mutable <see cref="KernelPlugin"/>.
11+
*/
12+
// ReSharper disable once InconsistentNaming
13+
public static class Example73_MutableKernelPlugin
14+
{
15+
/// <summary>
16+
/// Show how to create a mutable <see cref="KernelPlugin"/>.
17+
/// </summary>
18+
public static async Task RunAsync()
19+
{
20+
var plugin = new MutableKernelPlugin("Plugin");
21+
plugin.AddFunction(KernelFunctionFactory.CreateFromMethod(() => "Plugin.Function", "Function"));
22+
23+
var kernel = new Kernel();
24+
kernel.Plugins.Add(plugin);
25+
26+
var result = await kernel.InvokeAsync(kernel.Plugins["Plugin"]["Function"]);
27+
28+
Console.WriteLine($"Result: {result}");
29+
}
30+
31+
/// <summary>
32+
/// Provides an <see cref="KernelPlugin"/> implementation around a collection of functions.
33+
/// </summary>
34+
public class MutableKernelPlugin : KernelPlugin
35+
{
36+
/// <summary>The collection of functions associated with this plugin.</summary>
37+
private readonly Dictionary<string, KernelFunction> _functions;
38+
39+
/// <summary>Initializes the new plugin from the provided name, description, and function collection.</summary>
40+
/// <param name="name">The name for the plugin.</param>
41+
/// <param name="description">A description of the plugin.</param>
42+
/// <param name="functions">The initial functions to be available as part of the plugin.</param>
43+
/// <exception cref="ArgumentNullException"><paramref name="functions"/> contains a null function.</exception>
44+
/// <exception cref="ArgumentException"><paramref name="functions"/> contains two functions with the same name.</exception>
45+
public MutableKernelPlugin(string name, string? description = null, IEnumerable<KernelFunction>? functions = null) : base(name, description)
46+
{
47+
this._functions = new Dictionary<string, KernelFunction>(StringComparer.OrdinalIgnoreCase);
48+
if (functions is not null)
49+
{
50+
foreach (KernelFunction f in functions)
51+
{
52+
ArgumentNullException.ThrowIfNull(f);
53+
this._functions.Add(f.Name, f);
54+
}
55+
}
56+
}
57+
58+
/// <inheritdoc/>
59+
public override int FunctionCount => this._functions.Count;
60+
61+
/// <inheritdoc/>
62+
public override bool TryGetFunction(string name, [NotNullWhen(true)] out KernelFunction? function) =>
63+
this._functions.TryGetValue(name, out function);
64+
65+
/// <summary>Adds a function to the plugin.</summary>
66+
/// <param name="function">The function to add.</param>
67+
/// <exception cref="ArgumentNullException"><paramref name="function"/> is null.</exception>
68+
/// <exception cref="ArgumentNullException"><paramref name="function"/>'s <see cref="KernelFunction.Name"/> is null.</exception>
69+
/// <exception cref="ArgumentException">A function with the same <see cref="KernelFunction.Name"/> already exists in this plugin.</exception>
70+
public void AddFunction(KernelFunction function)
71+
{
72+
ArgumentNullException.ThrowIfNull(function);
73+
this._functions.Add(function.Name, function);
74+
}
75+
76+
/// <inheritdoc/>
77+
public override IEnumerator<KernelFunction> GetEnumerator() => this._functions.Values.GetEnumerator();
78+
}
79+
}

‎dotnet/src/Experimental/Assistants.UnitTests/Extensions/KernelExtensionTests.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public static void InvokeTwoPartTool()
2020
var function = KernelFunctionFactory.CreateFromMethod(() => { }, functionName: "Bogus");
2121

2222
var kernel = new Kernel();
23-
kernel.Plugins.Add(new KernelPlugin("Fake", new[] { function }));
23+
kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("Fake", "Fake functions", new[] { function }));
2424

2525
//Act
2626
var tool = kernel.GetAssistantTool(TwoPartToolName);

‎dotnet/src/Experimental/Assistants/AssistantBuilder.Static.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ public static async Task<IAssistant> NewAsync(
4848
public static async Task<IAssistant> GetAssistantAsync(
4949
string apiKey,
5050
string assistantId,
51-
IEnumerable<IKernelPlugin>? plugins = null,
51+
IEnumerable<KernelPlugin>? plugins = null,
5252
CancellationToken cancellationToken = default)
5353
{
5454
var restContext = new OpenAIRestContext(apiKey);

‎dotnet/src/Experimental/Assistants/AssistantBuilder.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ public AssistantBuilder WithName(string? name)
173173
/// Define functions associated with assistant instance (optional).
174174
/// </summary>
175175
/// <returns><see cref="AssistantBuilder"/> instance for fluid expression.</returns>
176-
public AssistantBuilder WithPlugin(IKernelPlugin? plugin)
176+
public AssistantBuilder WithPlugin(KernelPlugin? plugin)
177177
{
178178
if (plugin != null)
179179
{
@@ -187,7 +187,7 @@ public AssistantBuilder WithPlugin(IKernelPlugin? plugin)
187187
/// Define functions associated with assistant instance (optional).
188188
/// </summary>
189189
/// <returns><see cref="AssistantBuilder"/> instance for fluid expression.</returns>
190-
public AssistantBuilder WithPlugins(IEnumerable<IKernelPlugin> plugins)
190+
public AssistantBuilder WithPlugins(IEnumerable<KernelPlugin> plugins)
191191
{
192192
this._plugins.AddRange(plugins);
193193

‎dotnet/src/Experimental/Assistants/IAssistant.cs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ public interface IAssistant
6262
/// <summary>
6363
/// Expose the assistant as a plugin.
6464
/// </summary>
65-
public IKernelPlugin AsPlugin();
65+
public KernelPlugin AsPlugin();
6666

6767
/// <summary>
6868
/// Creates a new assistant chat thread.

0 commit comments

Comments
 (0)