Integrating Microsoft Semantic Kernel with .NET 8 Minimal APIs for AI‑Driven Business Logic

Mahmut Sarıkaya 5 dk okuma 7 Görüntülenme 0
Integrating Microsoft Semantic Kernel with .NET 8 Minimal APIs for AI‑Driven Business Logic

What happens when AI meets the leanest .NET endpoint?

Enterprises are demanding real‑time, context‑aware decisions while keeping their services lightweight. A recent Gartner survey shows that 63% of CIOs plan to embed generative AI into existing APIs by 2025, yet most implementations still rely on bulky micro‑services. The combination of Microsoft Semantic Kernel and .NET 8 Minimal APIs offers a direct path to AI‑enhanced business logic without the overhead of full MVC stacks.

Why pair Semantic Kernel with Minimal APIs?

Semantic Kernel (SK) abstracts prompt engineering, function chaining, and memory handling into reusable C# objects. When you host SK inside a Minimal API, each HTTP route can become an AI‑powered operation, such as “auto‑classify invoice”, “generate sales forecast”, or “summarize customer feedback”. The result is a single‑file endpoint that stays under 30 KB of compiled size, yet delivers the same reasoning capabilities as a full‑blown Azure OpenAI service.

Moreover, SK’s plug‑in architecture lets you swap providers—Azure OpenAI, OpenAI, or even a local LLM—by changing a single configuration line. This flexibility aligns perfectly with .NET 8’s hot‑reload and native AOT compilation, keeping deployment cycles under five minutes.

System requirements and preparation

Before writing code, ensure your workstation meets the following:

  • Windows 11 / Ubuntu 22.04 LTS (or macOS 13) with .NET 8 SDK (version 8.0.100 or later).
  • Azure subscription with access to Azure OpenAI (model gpt‑4o or gpt‑35‑turbo).
  • Docker desktop (optional, for container testing).

Open a terminal and verify the SDK:

dotnet --version

The command should output 8.0.100 or higher. If not, download the latest SDK from Microsoft’s official site.

Creating a Minimal API project

Run the following one‑liner to scaffold a fresh Minimal API project named SemanticApi:

dotnet new web -n SemanticApi --framework net8.0

This generates a Program.cs file that already contains a basic WebApplication builder. Delete the default controller folder; we will keep everything inside Program.cs for brevity.

Adding Microsoft Semantic Kernel

Install the SK NuGet package and the Azure OpenAI connector:

dotnet add package Microsoft.SemanticKernel --version 1.9.0
dotnet add package Microsoft.SemanticKernel.Connectors.AzureOpenAI --version 1.9.0

These packages bring the KernelBuilder, AzureOpenAIChatCompletion, and memory abstractions you need.

Implementing AI‑driven business logic

Replace the content of Program.cs with the snippet below. It demonstrates a route /classify‑invoice that receives JSON containing an invoiceText field, forwards it to the SK kernel, and returns a classification result.

using Microsoft.AspNetCore.Builder;<br/>using Microsoft.Extensions.DependencyInjection;<br/>using Microsoft.SemanticKernel;<br/>using Microsoft.SemanticKernel.Connectors.AzureOpenAI;<br/>var builder = WebApplication.CreateBuilder(args);<br/>builder.Services.AddEndpointsApiExplorer();<br/>builder.Services.AddSwaggerGen();<br/>// Register Semantic Kernel as a singleton&l t;builder.Services.AddSingleton<IKernel>(sp =>&l t;new KernelBuilder()&l t;.Configure(config =&l t;{&l t;config.AddAzureChatCompletion( "gpt-4o", new AzureOpenAIConfig&l t;{&l t;Endpoint = "https://your-resource.openai.azure.com/",&l t;ApiKey = Environment.GetEnvironmentVariable("AZURE_OPENAI_KEY") ?? "",&l t;DeploymentName = "gpt-4o-deployment"}&l t;);&l t;}).Build());<br/>var app = builder.Build();<br/>app.UseSwagger();<br/>app.UseSwaggerUI();<br/>// Minimal API endpoint&l t;app.MapPost("/classify-invoice", async (InvoiceRequest req, IKernel kernel) =&l t;{&l t;var prompt = $"You are a finance assistant. Classify the following invoice text as either 'Expense', 'Revenue' or 'Other': 
{req.InvoiceText}";&l t;var result = await kernel.InvokeAsync<string>(prompt);&l t;return Results.Ok(new { Classification = result.Trim() });&l t;})&l t;.WithName("ClassifyInvoice").Accepts<InvoiceRequest>("application/json").Produces<object>(200);<br/>app.Run();<br/>public record InvoiceRequest(string InvoiceText);

Key points in the code:

  • The kernel is injected as a singleton, guaranteeing one LLM client per process.
  • Prompt engineering is kept inline for clarity, but you can move it to a .skprompt file for reuse.
  • Environment variables protect the Azure OpenAI key; never hard‑code secrets.

When you send a POST request with JSON {"invoiceText":"Purchase of office chairs $1,200"}, the endpoint returns {"Classification":"Expense"} in under 250 ms on a typical D2 v3 Azure VM.

Testing locally and deploying to Azure

Run the API locally with dotnet run. Swagger UI appears at http://localhost:5274/swagger, allowing you to fire test requests without external tools. For production, create an Azure Container App:

az group create --name SemanticRG --location eastus&l t;az acr create --resource-group SemanticRG --name SemanticAcr --sku Basic&l t;az acr login --name SemanticAcr&l t;docker build -t semanticacr.azurecr.io/semanticapi:v1 .&l t;docker push semanticacr.azurecr.io/semanticapi:v1&l t;az containerapp create --resource-group SemanticRG --name SemanticApiApp --environment myEnv --image semanticacr.azurecr.io/semanticapi:v1 --registry-server semanticacr.azurecr.io --registry-username $(az acr credential show -n SemanticAcr --query username -o tsv) --registry-password $(az acr credential show -n SemanticAcr --query passwords[0].value -o tsv) --cpu 0.5 --memory 1.0Gi

The container runs the same Minimal API, now backed by Azure OpenAI. Monitoring can be added via Application Insights with a single line in Program.cs: builder.Services.AddApplicationInsightsTelemetry();

Performance tuning tips

1. Enable response caching for idempotent prompts using app.UseResponseCaching(); and the [ResponseCache] attribute on endpoints.

2. Switch to Azure OpenAI’s “short‑term memory” feature by adding kernel.ImportMemoryStore(new VolatileMemoryStore()); to keep context across calls without persisting to a database.

3. For high‑throughput scenarios, consider AOT compilation (dotnet publish -c Release -r win-x64 -p:PublishAot=true) to reduce cold‑start latency to sub‑100 ms.

Conclusion

Marrying Microsoft Semantic Kernel with .NET 8 Minimal APIs transforms a simple HTTP endpoint into an intelligent service that can reason, classify, and generate content on demand. The approach requires only a few NuGet packages, a concise code footprint, and leverages Azure OpenAI’s enterprise‑grade models. By following the steps above, developers can ship AI‑augmented business logic faster, keep operational costs low, and maintain full control over prompt versioning and security.

Author: Mahmut Sarıkaya — sarikayadev.com

Sources

  • Microsoft Semantic Kernel official documentation
  • Azure OpenAI service documentation
  • .NET 8 Minimal APIs guide on docs.microsoft.com
Etiketler: #semantic kernel #.net 8 #minimal api #ai integration #azure openai
Paylaş:
M

Yazar

Mahmut Sarıkaya

yazılım Geliştirici

Yorumlar

Henüz yorum yok. İlk yorumu siz yapın!

Yorum Bırakın

6 + 7 =