Semantic Kernel Plugins in C#: Function Calling and Filters

Last updated: November 10, 2026 · Tested with Microsoft.SemanticKernel 1.82.0 (Microsoft.Extensions.AI 10.5.0), .NET 10.0.12 (SDK 10.0.401), Windows 11

Short answer: a Semantic Kernel plugin is a C# class whose methods carry [KernelFunction] and [Description]. You add it with kernel.Plugins.AddFromType<T>("Orders"), then call the model with FunctionChoiceBehavior.Auto(). Semantic Kernel sends each function to the model as a tool named Orders_get_order_status, runs your method when the model asks for it, and sends the result back. Leave out FunctionChoiceBehavior and the model never sees your tools. Filters let you log every call or block one before it runs. A tool loop can make 129 model calls before Semantic Kernel stops it, and it doesn’t throw.

How I tested it: I have no OpenAI key and no Azure subscription, so the model in every run is a small scripted IChatClient. It returns fixed replies, including tool calls, so each run gives the same output every time. Everything else is the real Semantic Kernel 1.82.0 code: plugin registration, the tool schemas, automatic function invocation, the filters, ChatCompletionAgent. The output blocks are pasted from those runs. They show what Semantic Kernel does, not how good a real model’s answers are. Moving to OpenAI or Azure OpenAI changes one line, shown in section 2. I compiled that line but didn’t run it.

What I triedWhat happenedSection
Prompt without FunctionChoiceBehaviorModel gets tools: [], no error3
Plugin named order-toolsArgumentException: only ASCII letters, digits, and underscores4
Fake IChatClient without metadataArgumentNullException (Parameter ‘metadata’)2
Both SK and Microsoft.Extensions.AI namespaces in one fileCS0104 on FunctionInvocationContext7
Filter sets Terminate = trueAnswer is an empty string, the result is in a tool message8
Tool throwsModel gets Error: Function failed.9
Model keeps calling a tool129 model calls, 128 tool runs, empty answer, no exception10
Chat service called without the kernelKernelException11
RAG code from the first version of this postCS0618, then SKEXP0010 as a build error13

1. Create a Semantic Kernel Plugin from a C# Class

Start with a console app and the main package:

dotnet new console -n Demo -f net10.0
dotnet add package Microsoft.SemanticKernel --version 1.82.0

Microsoft.SemanticKernel is a meta-package. It brings in Microsoft.SemanticKernel.Core and the Azure OpenAI connector, and that connector depends on a beta Azure.AI.OpenAI (2.9.0-beta.1 in my restore). If your build must not have prerelease packages, reference Microsoft.SemanticKernel.Core and the one connector you need.

A plugin is an ordinary class. Each [KernelFunction] method becomes one tool. The model doesn’t read your code, only the names and descriptions, so the [Description] text works like part of the prompt:

public sealed class OrderPlugin
{
    private static readonly Dictionary<string, (string Status, decimal Total)> Orders = new()
    {
        ["A-1001"] = ("Shipped", 129.99m),
        ["A-1002"] = ("Processing", 49.50m),
    };

    [KernelFunction("get_order_status")]
    [Description("Returns the shipping status and total for an order ID such as A-1001.")]
    public string GetOrderStatus([Description("The order ID, e.g. A-1001")] string orderId)
    {
        ArgumentException.ThrowIfNullOrEmpty(orderId);
        return Orders.TryGetValue(orderId, out var o)
            ? $"Order {orderId} is {o.Status}. Total: ${o.Total}."
            : $"No order found with ID {orderId}.";
    }

    [KernelFunction("cancel_order")]
    [Description("Cancels an order that has not shipped yet.")]
    public string CancelOrder(string orderId)
    {
        return $"Order {orderId} cancelled.";
    }
}

Register it on the kernel and ask a question with automatic function calling on:

var auto = new PromptExecutionSettings { FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() };

var kernel = BuildKernel(model);
kernel.Plugins.AddFromType<OrderPlugin>("Orders");

foreach (var f in kernel.Plugins.GetFunctionsMetadata())
    Console.WriteLine($"  registered {f.PluginName}.{f.Name}({string.Join(", ", f.Parameters.Select(p => $"{p.ParameterType?.Name} {p.Name}"))})");

var answer = await kernel.InvokePromptAsync("Where is order A-1001?", new(auto));
Console.WriteLine($"  answer: {answer}");

The [tool ran] lines come from a Console.WriteLine in the plugin method. I left it out of the listing above. The [model ...] lines are what the scripted model received:

  registered Orders.get_order_status(String orderId)
  registered Orders.cancel_order(String orderId)
  [model call 1] 1 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [tool ran] get_order_status(A-1001)
  [model call 2] 3 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [model sees tool result] Order A-1001 is Shipped. Total: $129.99.
  answer: Order A-1001 has shipped. Total: $129.99.

That’s the whole loop. The model gets both tools and asks for Orders_get_order_status. Semantic Kernel runs your method, adds the call and its result to the conversation (1 message becomes 3), and calls the model again for the final answer. The tool name is the plugin name and the function name joined with an underscore. Keep that in mind when you read logs or traces.

2. The Scripted Model, and the One-Line Swap to OpenAI

Every example uses this helper. It puts the model behind Semantic Kernel’s function-invoking client, which is the same wrapper the OpenAI connector uses:

// The scripted model goes where a real one would: an IChatClient wrapped with SK's function invocation.
Kernel BuildKernel(IChatClient model, Action<IKernelBuilder>? configure = null)
{
    var builder = Kernel.CreateBuilder();
    builder.Services.AddSingleton<IChatClient>(
        new ChatClientBuilder(model).UseKernelFunctionInvocation().Build());
    configure?.Invoke(builder);
    return builder.Build();
}

For a real model, replace that registration with one call:

// OpenAI
builder.AddOpenAIChatClient("gpt-4o-mini", Environment.GetEnvironmentVariable("OPENAI_API_KEY")!);

// or Azure OpenAI
builder.AddAzureOpenAIChatClient("my-gpt-4o-mini-deployment", "https://my-resource.openai.azure.com/", Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")!);

Both compile against 1.82.0 with no warnings. To check that my setup matches the real one, I built a kernel with AddOpenAIChatClient and walked its IChatClient pipeline without sending a request:

  Microsoft.Extensions.AI.KernelFunctionInvokingChatClient
  Microsoft.Extensions.AI.OpenTelemetryChatClient
  Microsoft.Extensions.AI.OpenAIChatClient

It’s the same KernelFunctionInvokingChatClient on the outside. The real pipeline adds an OpenTelemetry layer, and the OpenAI client sits where my scripted one does. The plugin, filter and loop behaviour below comes from that outer layer, so it should be the same with a real model.

One trap if you write your own fake IChatClient for unit tests. My first version returned null from GetService for every type. Every InvokePromptAsync call then failed before it reached the model:

  ArgumentNullException: Value cannot be null. (Parameter 'metadata')

The stack trace points at the constructor of ChatClientAIService. Semantic Kernel asks the client for ChatClientMetadata and requires it. Return one and the error goes away:

    public object? GetService(Type serviceType, object? serviceKey = null) =>
        serviceType == typeof(ChatClientMetadata) ? new ChatClientMetadata("scripted", defaultModelId: "scripted-model")
        : serviceType.IsInstanceOfType(this) ? this : null;

3. Forget FunctionChoiceBehavior and Nothing Happens

The plugin is registered, but the prompt has no execution settings:

var answer = await kernel.InvokePromptAsync("Where is order A-1001?");
  [model call 1] 1 messages, tools: []
  answer: I don't have access to order data.

There’s no warning or exception. The model just gets an empty tool list and answers without your data. If an agent ignores plugins you know are registered, check this first. Registering a plugin doesn’t offer it to the model. FunctionChoiceBehavior does that.

4. Plugin and Function Name Rules

Older tutorials say SK function names may only use letters, digits and underscores. In 1.82.0 that’s only fully true for plugin names. I tried a few names:

  function 'get_order': ok
  function 'get-order': ok
  function 'get order': A function name can contain only ASCII letters, digits, and underscores: 'get order' is not a valid name. (Parameter 'functionName')
  function 'get.order': A function name can contain only ASCII letters, digits, and underscores: 'get.order' is not a valid name. (Parameter 'functionName')
  plugin 'Orders': ok
  plugin 'order-tools': A plugin name can contain only ASCII letters, digits, and underscores: 'order-tools' is not a valid name. (Parameter 'pluginName')
  plugin 'Order Tools': A plugin name can contain only ASCII letters, digits, and underscores: 'Order Tools' is not a valid name. (Parameter 'pluginName')

A function named get-order is accepted, even though the error text says it shouldn’t be. A plugin named order-tools is rejected. Both checks happen at registration, so you see them at startup and not halfway through a conversation. I use snake_case for function names and PascalCase for plugin names, and haven’t hit a problem with that.

5. Plugins with Dependencies, and Plugins Without a Class

Real plugins need services such as a repository or an HttpClient. AddFromType takes an IServiceProvider and builds the plugin with constructor injection:

public sealed class StockPlugin(IInventory inventory)
{
    [KernelFunction("get_stock"), Description("Returns how many units of a SKU are in stock.")]
    public int GetStock(string sku) => inventory.Count(sku);
}
    var kernel = BuildKernel(model, b => b.Services.AddSingleton<IInventory, FakeInventory>());
    kernel.Plugins.AddFromType<StockPlugin>("Stock", kernel.Services); // constructor gets IInventory from DI
  [model call 1] 1 messages, tools: [Stock_get_stock]
  [model call 2] 3 messages, tools: [Stock_get_stock]
  [model sees tool result] 7
  answer: KB-42: 7 left.

The method returns an int, and the model gets it as 7. You don’t have to return strings. For a quick tool you don’t need a class at all:

    kernel.Plugins.AddFromFunctions("Clock",
    [
        KernelFunctionFactory.CreateFromMethod(() => "2026-11-10T09:30:00Z", "utc_now", "Returns the current UTC time.")
    ]);
  [model call 1] 1 messages, tools: [Clock_utc_now]
  [model call 2] 3 messages, tools: [Clock_utc_now]
  [model sees tool result] 2026-11-10T09:30:00Z
  answer: It's 09:30 UTC.

In a real app the lambda would return DateTime.UtcNow. I hard-coded the value so the output stays the same between runs.

6. Prompt Functions That Call Your Plugin

A plugin function can also be a prompt template. Templates can call other functions with {{Plugin.function $arg}}, and Semantic Kernel runs those calls while it renders the prompt, before the model sees anything:

    var update = kernel.CreateFunctionFromPrompt(
        "Status: {{Orders.get_order_status $orderId}}\nWrite a one-line, friendly update for the customer.",
        functionName: "customer_update",
        description: "Writes a short customer update for an order.");

    Console.WriteLine($"  answer: {await kernel.InvokeAsync(update, new() { ["orderId"] = "A-1001" })}");
  [tool ran] get_order_status(A-1001)
  [model call 1] 1 messages, tools: []
  [model sees prompt] Status: Order A-1001 is Shipped. Total: $129.99.
Write a one-line, friendly update for the customer.
  answer: Good news: your order A-1001 is on its way.

The order lookup ran before the model call, and the model got the finished text with no tools. It’s one model call, and the model can’t pick a different tool. When you already know which data the prompt needs, this costs less than automatic function calling. Use FunctionChoiceBehavior.Auto() when the model has to decide.

7. Filters: Log Every Call, Block the Risky Ones

Semantic Kernel has two filter interfaces that matter for plugins. IFunctionInvocationFilter runs around every kernel function. IAutoFunctionInvocationFilter runs only when the model asked for the call, and it can change the result or stop the loop. Register them in DI:

public sealed class LogFilter : IFunctionInvocationFilter
{
    public async Task OnFunctionInvocationAsync(FunctionInvocationContext context, Func<FunctionInvocationContext, Task> next)
    {
        Console.WriteLine($"  [filter] before {context.Function.PluginName}.{context.Function.Name}({string.Join(", ", context.Arguments.Select(a => $"{a.Key}={a.Value}"))})");
        await next(context);
        Console.WriteLine($"  [filter] after  {context.Function.Name} -> {context.Result}");
    }
}

public sealed class ApprovalFilter : IAutoFunctionInvocationFilter
{
    public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next)
    {
        if (context.Function.Name == "cancel_order")
        {
            Console.WriteLine($"  [approval] blocked {context.Function.Name}");
            context.Result = new FunctionResult(context.Function, "Cancelling requires a human. Tell the user to contact support.");
            return; // next() not called: the method never runs
        }
        await next(context);
    }
}
        b.Services.AddSingleton<IFunctionInvocationFilter, LogFilter>();
        b.Services.AddSingleton<IAutoFunctionInvocationFilter, ApprovalFilter>();

The scripted model first looks up order A-1002, then tries to cancel it:

  [filter] before .InvokePromptAsync_ed5cea721b56496a95e4a17180f6195a()
  [model call 1] 1 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [filter] before Orders.get_order_status(orderId=A-1002)
  [tool ran] get_order_status(A-1002)
  [filter] after  get_order_status -> Order A-1002 is Processing. Total: $49.50.
  [model call 2] 3 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [model sees tool result] Order A-1002 is Processing. Total: $49.50.
  [approval] blocked cancel_order
  [model call 3] 5 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [model sees tool result] Cancelling requires a human. Tell the user to contact support.
  [filter] after  InvokePromptAsync_ed5cea721b56496a95e4a17180f6195a -> I checked A-1002, but cancelling needs a human.
  answer: I checked A-1002, but cancelling needs a human.

Three things in that log. First, the function filter also wraps the prompt itself: InvokePromptAsync creates a temporary function with a random name and no plugin. Filter on PluginName if you only want tool calls. Second, cancel_order never ran. There’s no [tool ran] cancel_order line, and the model got the text the filter set. Third, the function filter didn’t log the blocked call. The approval filter returned before next, so the function filter was never reached. If you audit tool calls, log in the auto-invocation filter, or you won’t see blocked calls.

The first time I built this file it failed:

Program.cs(269,49): error CS0104: 'FunctionInvocationContext' is an ambiguous reference between 'Microsoft.Extensions.AI.FunctionInvocationContext' and 'Microsoft.SemanticKernel.FunctionInvocationContext'

Once you work with IChatClient you need both namespaces, and both define FunctionInvocationContext (and FunctionResultContent). A using alias fixes it:

using FunctionInvocationContext = Microsoft.SemanticKernel.FunctionInvocationContext;

8. Stop After a Tool with Terminate

Sometimes the tool result is already the answer, and a second model call only costs money. An auto-invocation filter can end the loop:

public sealed class StopAfterToolFilter : IAutoFunctionInvocationFilter
{
    public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next)
    {
        await next(context);
        context.Terminate = true; // return the tool result as the answer, skip the next model call
    }
}
  [model call 1] 1 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [tool ran] get_order_status(A-1001)
  answer: ''
  last message: tool, tool result: Order A-1001 is Shipped. Total: $129.99.

The model was called once, as intended. But answer is an empty string, because the last message is a tool message, not assistant text. The data is still there. Read it from the response:

    var last = result.GetValue<ChatResponse>()!.Messages[^1];
    var toolResult = last.Contents.OfType<Microsoft.Extensions.AI.FunctionResultContent>().Single().Result;

9. When a Plugin Throws

I made the model pass an empty order ID, so ArgumentException.ThrowIfNullOrEmpty throws inside the plugin:

  [model call 1] 1 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [tool ran] get_order_status()
  [model call 2] 3 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [model sees tool result] Error: Function failed.
  answer: Sorry, I couldn't look that order up.

Your code doesn’t see the exception. The model gets a generic error and carries on. That’s safer than leaking stack traces into a prompt, but the model can’t fix its own mistake either. While you develop, you can send the exception message along:

    kernel.GetRequiredService<IChatClient>().GetService<FunctionInvokingChatClient>()!.IncludeDetailedErrors = true;
  [model sees tool result] Error: Function failed. Exception: The value cannot be an empty string. (Parameter 'orderId')

In production, I’d rather catch expected failures in the plugin and return a clear message such as “order ID is required”. Exception text can include data you don’t want to send to the model. A tool name the model invents gets the same treatment:

  [model sees tool result] Error: Requested function "get_order_status" not found.

Here the model asked for get_order_status without the plugin prefix. Semantic Kernel only knows the function as Orders_get_order_status, so the call failed and the model got an error message instead of data.

10. The Silent Loop: 129 Model Calls and an Empty Answer

This is the result to know before you ship. I scripted a model that asks for the same tool on every call. That’s a stuck model, which does happen with vague tool descriptions or tool results that contradict each other:

  model calls: 129, tool runs: 128, tools offered on the last call: 0, answer: ''

Semantic Kernel ran the tool 128 times. On the 129th call it sent no tools, which forces a final text answer. My scripted model still asked for a tool, so the answer was an empty string. A real model would most likely answer in text on that last call. Either way, 129 billed requests with a growing history don’t throw an exception. The limit is a property on the function-invoking client, and you can lower it:

    var invoker = kernel.GetRequiredService<IChatClient>().GetService<FunctionInvokingChatClient>()!;
    Console.WriteLine($"  {invoker.GetType().Name}, MaximumIterationsPerRequest = {invoker.MaximumIterationsPerRequest}");
    invoker.MaximumIterationsPerRequest = 5;
  KernelFunctionInvokingChatClient, MaximumIterationsPerRequest = 128
  model calls: 6, tool runs: 5, tools offered on the last call: 0, answer: ''

KernelFunctionInvokingChatClient derives from the Microsoft.Extensions.AI FunctionInvokingChatClient, so GetService<FunctionInvokingChatClient>() finds it. That gives you its options: MaximumIterationsPerRequest and IncludeDetailedErrors from section 9. For comparison, the same stuck-model test in Microsoft Agent Framework stopped at 41 model calls. Neither framework throws, so log the number of tool calls per request and alert on it.

11. Limit Which Plugins the Model Sees

Auto() with no arguments offers every function on the kernel, including cancel_order. For a read-only feature, pass only the functions it needs. Required() makes the model call a tool:

    var orders = kernel.Plugins.AddFromType<OrderPlugin>("Orders");
    var readOnly = new PromptExecutionSettings
    {
        FunctionChoiceBehavior = FunctionChoiceBehavior.Auto([orders["get_order_status"]])
    };
    await kernel.InvokePromptAsync("Where is order A-1001?", new(readOnly));
    var required = new PromptExecutionSettings { FunctionChoiceBehavior = FunctionChoiceBehavior.Required() };
    await kernel.InvokePromptAsync("Where is order A-1001?", new(required));
  [model call 1] 1 messages, tools: [Orders_get_order_status]
  [model call 2] 1 messages, tools: [Orders_get_order_status, Orders_cancel_order] (required)

A function the model never sees is safer than one a filter has to block. Fewer tools also means a shorter prompt on every call.

12. Chat History and a Semantic Kernel Agent

For a multi-turn chat, use the IChatCompletionService view of the same client with a ChatHistory you own:

    var chat = kernel.GetRequiredService<IChatClient>().AsChatCompletionService(kernel.Services);
    var history = new ChatHistory("You are a support assistant for an online store.");
    history.AddUserMessage("Where is order A-1001?");
    var reply = await chat.GetChatMessageContentAsync(history, auto, kernel);
    Console.WriteLine($"  reply: {reply.Content}");
    Console.WriteLine($"  history: {history.Count} messages ({string.Join(", ", history.Select(m => m.Role))})");
  reply: A-1001 has shipped.
  history: 4 messages (system, user, assistant, tool)

Semantic Kernel wrote the tool call and its result into your history (assistant and tool). The final reply is returned, not added. Append it yourself with history.Add(reply) before the next turn. Store, trim or redact the history as you need. It’s a list you control.

The first version of this post said that leaving out the kernel argument “silently disables” function calling. On this path in 1.82.0 it isn’t silent. It throws:

    var reply = await chat.GetChatMessageContentAsync(history, auto); // kernel not passed
  KernelException: Auto-invocation is not supported when no kernel is provided.

If you want an object that holds the instructions, kernel and settings together, ChatCompletionAgent from Microsoft.SemanticKernel.Agents.Core does that with the same plugins:

dotnet add package Microsoft.SemanticKernel.Agents.Core --version 1.82.0
    ChatCompletionAgent agent = new()
    {
        Name = "SupportAgent",
        Instructions = "Answer order questions with the Orders tools. Be brief.",
        Kernel = kernel,
        Arguments = new KernelArguments(auto)
    };
    ChatHistoryAgentThread thread = new();
    await foreach (var item in agent.InvokeAsync("Is order A-1002 on its way?", thread))
        Console.WriteLine($"  {item.Message.AuthorName}: {item.Message.Content}");
  [model call 1] 2 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [tool ran] get_order_status(A-1002)
  [model call 2] 4 messages, tools: [Orders_get_order_status, Orders_cancel_order]
  [model sees tool result] Order A-1002 is Processing. Total: $49.50.
  SupportAgent: A-1002 is still processing.

It built without any SKEXP warning in 1.82.0, and it worked with an IChatClient-only kernel. The first model call has 2 messages because the agent’s instructions go in as a system message.

13. What Broke in the Old Version of This Post

The first version of this tutorial had a RAG step built on the embedding service. I compiled those lines unchanged against 1.82.0:

Program.cs(16,42): warning CS0618: 'ITextEmbeddingGenerationService' is obsolete: 'Use Microsoft.Extensions.AI.IEmbeddingGenerator<string, Embedding<float>> instead.'
Program.cs(9,1): warning CS0618: 'OpenAIKernelBuilderExtensions.AddOpenAITextEmbeddingGeneration(IKernelBuilder, string, string, string?, string?, HttpClient?, int?)' is obsolete: 'Use AddOpenAIEmbeddingGenerator instead.'

Then I switched to the replacement the warning names:

Program.cs(20,1): error SKEXP0010: 'Microsoft.SemanticKernel.OpenAIKernelBuilderExtensions.AddOpenAIEmbeddingGenerator(Microsoft.SemanticKernel.IKernelBuilder, string, string, string?, int?, string?, System.Net.Http.HttpClient?)' is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.

So the obsolete API builds with a warning, and the recommended one doesn’t build at all until you opt in. SKEXP diagnostics are errors by default:

#pragma warning disable SKEXP0010
var fixedBuilder = Kernel.CreateBuilder();
fixedBuilder.AddOpenAIEmbeddingGenerator("text-embedding-3-small", apiKey);

The old chat setup (AddOpenAIChatCompletion, OpenAIPromptExecutionSettings with FunctionChoiceBehavior.Auto()) still compiles with no warnings. If you have an app built on it, you don’t need to rewrite it.

Semantic Kernel vs Microsoft Agent Framework: Should You Still Start with SK?

Here’s what Microsoft’s own sources say, as of November 2026:

  • The Semantic Kernel GitHub README now opens with a notice that Semantic Kernel is now Microsoft Agent Framework, and calls Agent Framework its “enterprise-ready successor”.
  • The October 2025 post Semantic Kernel and Microsoft Agent Framework promises to support SK v1.x and fix critical bugs and security issues. It says new projects should start with Agent Framework, while existing projects are fine to stay on SK. Support continues for at least a year after Agent Framework leaves preview and goes GA.
  • Agent Framework reached 1.0 on April 3, 2026, with stable APIs and a commitment to long-term support.
  • Semantic Kernel still ships. 1.82.0 went to NuGet on November 7, 2026, about a month after 1.81.0.

My take: for a new agent project, start with Microsoft Agent Framework in C#. It’s where new features go, and it registers tools with less ceremony: no [KernelFunction] attribute, no plugin class, no kernel. If you already run Semantic Kernel, you don’t need to rush. You also don’t have to throw your plugins away. A KernelPlugin converts to Microsoft.Extensions.AI tools, and an Agent Framework agent can call them as they are. I tested that with Microsoft.Agents.AI 1.28.0 and the same scripted client:

var kernel = new Kernel();
kernel.FunctionInvocationFilters.Add(new LogFilter());
kernel.AutoFunctionInvocationFilters.Add(new AutoLogFilter());
var orders = kernel.Plugins.AddFromType<OrderPlugin>("Orders");
IList<AITool> tools = [.. orders.AsAIFunctions(kernel)];
Console.WriteLine($"tools: {string.Join(", ", tools.Select(t => t.Name))}");

IChatClient model = new ScriptedChatClient(
    Call("Orders_get_order_status", new() { ["orderId"] = "A-1001" }),
    Text("A-1001 has shipped."));

AIAgent agent = model.AsAIAgent(instructions: "Answer order questions.", name: "OrderAgent", tools: tools);
AgentResponse response = await agent.RunAsync("Where is order A-1001?");
Console.WriteLine($"reply: {response.Text}");
tools: Orders_get_order_status
  [model call 1] 1 messages, tools: [Orders_get_order_status]
  [tool ran] get_order_status(A-1001)
  [model call 2] 3 messages, tools: [Orders_get_order_status]
  [model sees tool result] Order A-1001 is Shipped.
reply: A-1001 has shipped.

The tool keeps its SK name, so prompts and logs that mention Orders_get_order_status still work. Adding Agent Framework raised Microsoft.Extensions.AI from 10.5.0 to 10.11.0 in that project, and SK 1.82.0 still built and ran with it. Your SK filters don’t come along, though. I registered a function filter and an auto-invocation filter on that kernel (each prints a line), and neither ran when the agent called the tool. Logging and approvals in Agent Framework go through its own middleware and tool approval, so plan to rewrite your filters. Microsoft’s migration guide from Semantic Kernel maps the rest: ChatCompletionAgent to ChatClientAgent, threads to sessions, InvokeAsync to RunAsync.

Semantic Kernel still makes sense when you need its prompt templates, vector store connectors or process framework, or when your team knows it well and the app only needs plugins and function calling. Everything in this post works on a supported, regularly updated package.

What I Didn’t Test

  • A real model. The OpenAI and Azure OpenAI lines compile, but I didn’t call either service. How well a model picks tools from your descriptions has to be tested with your model and your prompts.
  • The older IChatCompletionService connectors (AddOpenAIChatCompletion) at runtime. I only compiled them. They have their own function-calling loop, so their limits and error messages may differ from the IChatClient path tested here.
  • Streaming, OpenAPI and MCP plugins, vector store search functions, and the process framework.

Plugin Checklist Before Going Live

  • Set FunctionChoiceBehavior on every call that should use tools, and log the tool count the model receives.
  • Write [Description] text for the model: what the function does, when to use it, and an example argument.
  • Offer only the functions each feature needs with Auto([...]).
  • Put destructive functions behind an IAutoFunctionInvocationFilter, and log in that filter so blocked calls appear too.
  • Lower MaximumIterationsPerRequest from 128, and alert on requests with many tool calls.
  • Return clear error text from plugins. Don’t enable IncludeDetailedErrors in production.
  • When you use Terminate, read the tool result from the response, not the answer text.
  • Pin the package version. Reference Microsoft.SemanticKernel.Core plus one connector if you need to avoid beta dependencies.

FAQ

What is a plugin in Semantic Kernel? A named group of kernel functions. Each one is a C# method marked with [KernelFunction], a lambda from KernelFunctionFactory, or a prompt template. The model sees each function as a tool named Plugin_function.

Why doesn’t the model call my plugin? In my tests the cause was a missing FunctionChoiceBehavior. The model got tools: [] and no error was raised. After that, check the descriptions, and check that the function is in the list you passed to Auto([...]).

Is Semantic Kernel deprecated? No. Microsoft calls Agent Framework its successor and recommends it for new agent projects. SK v1.x is still supported and still gets regular NuGet releases.

Can I use Semantic Kernel plugins in Agent Framework? Yes. plugin.AsAIFunctions(kernel) gives you AIFunction tools that an Agent Framework agent accepts. The output above shows it working.

Related: Microsoft Agent Framework in C# · build an MCP server in C# · Azure OpenAI in C# · local AI with Ollama and C# · Semantic Kernel plugins (Learn) · Semantic Kernel filters (Learn)

This article is part of the AI in .NET guide (LLMs, agents, RAG, ML.NET and AI coding tools).

Similar Posts

3 Comments

  1. The tutorial gives a clear progression from basic Semantic Kernel setup to building AI agents with C#. The explanation of the Kernel object, provider abstraction, function calling, memory, and planning helps show how AI capabilities can be integrated into conventional .NET applications without abandoning familiar C# patterns.

    The plugin concept is particularly useful because it allows ordinary C# methods to become tools that an AI model can invoke. Developers exploring this area can also benefit from Claude Certified Developer Training, especially when comparing different approaches to building tool-enabled AI applications.

  2. The tutorial also emphasizes practical development concerns such as dependency injection, logging, retries, telemetry, and keeping API keys outside source code. These details make the examples more relevant to real application development rather than limiting the discussion to simple AI demonstrations. For students and developers looking for practical applications, AI Projects for Final Year can provide opportunities to apply similar concepts in complete projects.

  3. The step-by-step approach makes Semantic Kernel easier to understand, particularly the transition from a simple prompt to function calling and eventually stateful AI agents. Developers interested in expanding their knowledge of AI-assisted programming can explore ChatGPT Developer Training alongside Semantic Kernel to understand how different AI development workflows can be combined with modern software engineering practices.

Leave a Reply

Your email address will not be published. Required fields are marked *