loading experience

AI & agents

Semantic Kernel: bringing AI into .NET applications with plugins

Kernel, plugins and automatic function calling: how a language model uses your application's code.

Semantic Kernel: bringing AI into .NET applications with plugins

Semantic Kernel is Microsoft's open-source SDK for integrating language models into applications. Its central concept is the kernel: a container that brings together the AI service, the plugins with the application's functions and the configuration.

The model decides what it needs, the application's code provides the data.
The model decides what it needs, the application's code provides the data.

Creating the kernel

var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion(
    modelId: "gpt-4o-mini",
    apiKey: configuration["OpenAI:ApiKey"]!);
builder.Plugins.AddFromType<WarehousePlugin>();

Kernel kernel = builder.Build();

A plugin

A plugin is a class with methods decorated with [KernelFunction]. Descriptions are essential: by reading them the model decides when to call a function.

public class WarehousePlugin(IWarehouse warehouse)
{
    [KernelFunction, Description("Returns the available quantity of an item given its code")]
    public Task<int> Stock([Description("Item code, e.g. ABC-123")] string code) =>
        warehouse.QuantityAsync(code);
}

Automatic function calling

var settings = new OpenAIPromptExecutionSettings
{
    FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};

var answer = await kernel.InvokePromptAsync(
    "Do we have enough units of item ABC-123 for an order of 40?",
    new KernelArguments(settings));

Console.WriteLine(answer);

The model understands that it needs the stock level, calls Stock("ABC-123"), receives the number and formulates the answer. The application's code remains the one deciding and controlling the data.

Good practices

  • Expose few functions, with clear names and descriptions: too many functions confuse the model.
  • Always validate arguments and enforce the user's permissions inside the functions.
  • For operations that modify data, ask the user for confirmation before executing them.
  • Record traces and costs of calls: Semantic Kernel integrates with OpenTelemetry.

Semantic Kernel coexists with the Microsoft.Extensions.AI abstractions, and its evolution towards agents continues in the Microsoft Agent Framework.

Comments (0)

No comments yet.

Leave a comment