// Copyright (c) Microsoft. All rights reserved. using System.Diagnostics.CodeAnalysis; using Microsoft.Extensions.AI; using Microsoft.SemanticKernel; namespace Plugins; /// /// This example shows how to create a mutable . /// public class CustomMutablePlugin(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() { var plugin = new MutableKernelPlugin("Plugin"); plugin.AddFunction(KernelFunctionFactory.CreateFromMethod(() => "Plugin.Function", "Function")); var kernel = new Kernel(); kernel.Plugins.Add(plugin); var result = await kernel.InvokeAsync(kernel.Plugins["Plugin"]["Function"]); Console.WriteLine($"Result: {result}"); } /// /// Provides an implementation around a collection of functions. /// public class MutableKernelPlugin : KernelPlugin { /// The collection of functions associated with this plugin. private readonly Dictionary _functions; /// Initializes the new plugin from the provided name, description, and function collection. /// The name for the plugin. /// A description of the plugin. /// The initial functions to be available as part of the plugin. /// contains a null function. /// contains two functions with the same name. public MutableKernelPlugin(string name, string? description = null, IEnumerable? functions = null) : base(name, description) { this._functions = new Dictionary(StringComparer.OrdinalIgnoreCase); if (functions is not null) { foreach (KernelFunction f in functions) { ArgumentNullException.ThrowIfNull(f); var cloned = f.Clone(name); this._functions.Add(cloned.Name, cloned); } } } /// public override int FunctionCount => this._functions.Count; /// public override bool TryGetFunction(string name, [NotNullWhen(true)] out KernelFunction? function) => this._functions.TryGetValue(name, out function); /// Adds a function to the plugin. /// The function to add. /// is null. /// 's is null. /// A function with the same already exists in this plugin. public void AddFunction(KernelFunction function) { ArgumentNullException.ThrowIfNull(function); var cloned = function.Clone(this.Name); this._functions.Add(cloned.Name, cloned); } /// public override IEnumerator GetEnumerator() => this._functions.Values.GetEnumerator(); } }