Semantic Kernel vs AI library in .NET

Views: 55
Comments: 0
Like/Unlike: 0
Posted On: 19-Jun-2025 03:01 

Share:   fb twitter linkedin
Rahul M...
4950 Points
30 Posts

Semantic Kernel and Microsoft.Extensions.AI are both .NET libraries for AI applications, but with different roles. Microsoft.Extensions.AI offers core abstractions to connect with AI services, while Semantic Kernel builds on it by adding higher-level features like plugins, prompt templates, and orchestration for advanced AI workflows.

 

🔷 What is Semantic Kernel?

 

[Semantic Kernel (SK)] is an open-source SDK by Microsoft to integrate AI models like OpenAI or Azure OpenAI into your .NET apps using a plugin-based and planner-style approach.

  • Purpose: Bridge AI models with traditional programming.
  • Design: Composable skills and planners (semantic + native functions).
  • Use Case: Goal-oriented tasks, intelligent orchestration (e.g., summarization + email send + file read, etc.)
  • Key Features:
    • Model Flexibility: Connect to any LLM with built-in support for OpenAI, Azure OpenAI, Hugging Face, NVidia and more
    • Agent Framework: Build modular AI agents with access to tools/plugins, memory, and planning capabilities
    • Multi-Agent Systems: Orchestrate complex workflows with collaborating specialist agents
    • Plugin Ecosystem: Extend with native code functions, prompt templates, OpenAPI specs, or Model Context Protocol (MCP)
    • Vector DB Support: Seamless integration with Azure AI Search, Elasticsearch, Chroma, and more
    • Multimodal Support: Process text, vision, and audio inputs
    • Local Deployment: Run with Ollama, LMStudio, or ONNX
    • Process Framework: Model complex business processes with a structured workflow approach
    • Enterprise Ready: Built for observability, security, and stable APIs
  • Example:
    • using Microsoft.SemanticKernel;
      using Microsoft.SemanticKernel.Agents;

      var builder = Kernel.CreateBuilder();
      builder.AddAzureOpenAIChatCompletion(
                      Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT"),
                      Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT"),
                      Environment.GetEnvironmentVariable("AZURE_OPENAI_API_KEY")
                      );
      var kernel = builder.Build();

      ChatCompletionAgent agent =
          new()
          {
              Name = "SK-Agent",
              Instructions = "You are a helpful assistant.",
              Kernel = kernel,
          };

      await foreach (AgentResponseItem<ChatMessageContent> response
          in agent.InvokeAsync("Write a haiku about Semantic Kernel."))
      {
          Console.WriteLine(response.Message);
      }

      // Output:
      // Language's essence,
      // Semantic threads intertwine,
      // Meaning's core revealed.

 

🔶 What is a .NET AI Library?

 

.NET AI libraries are general-purpose tools for machine learning, inference, or model integration. Examples include

  • ML.NET – Traditional ML in .NET (classification, regression, etc.)
  • Microsoft.ML.OnnxRuntime – Run pre-trained models (including AI models) in ONNX format.
  • OpenAI .NET SDK – Directly call OpenAI APIs (text/image completion).
  • Hugging Face API wrappers – Use AI models via REST or client libraries.
  • Example - ML.NET
    • using Microsoft.ML;
      using Microsoft.ML.Data;

      public class CustomerData
      {
          public float Age;
          public float Income;
          public bool Purchased;
      }

      public class Prediction
      {
          [ColumnName("PredictedLabel")]
          public bool Purchased;
      }

      var context = new MLContext();

      // Load data
      var data = context.Data.LoadFromEnumerable(new[]
      {
          new CustomerData { Age = 25, Income = 50000, Purchased = true },
          new CustomerData { Age = 45, Income = 80000, Purchased = false }
      });

      // Build pipeline
      var pipeline = context.Transforms.Concatenate("Features", "Age", "Income")
          .Append(context.BinaryClassification.Trainers.SdcaLogisticRegression());

      // Train
      var model = pipeline.Fit(data);

      // Predict
      var predictionEngine = context.Model.CreatePredictionEngine<CustomerData, Prediction>(model);
      var prediction = predictionEngine.Predict(new CustomerData { Age = 30, Income = 60000 });

      Console.WriteLine($"Predicted: {(prediction.Purchased ? "Will Purchase" : "Won't Purchase")}");
  • Example - OpenAI .NET SDK
    • using Microsoft.Extensions.AI;
      using Microsoft.Extensions.Configuration;
      using OpenAI;

      var config = new ConfigurationBuilder().AddUserSecrets<Program>().Build();
      string model = config["ModelName"];
      string key = config["OpenAIKey"];

      // Create the IChatClient
      IChatClient chatClient =
          new OpenAIClient(key).GetChatClient(model).AsIChatClient();

      // Start the conversation with context for the AI model
      List<ChatMessage> chatHistory = new List<ChatMessage>() {
              new ChatMessage(ChatRole.System, """
                  You are a friendly hiking enthusiast who helps people discover fun hikes in their area.
                  You introduce yourself when first saying hello.
                  When helping people out, you always ask them for this information
                  to inform the hiking recommendation you provide:

                  1. The location where they would like to hike
                  2. What hiking intensity they are looking for

                  You will then provide three suggestions for nearby hikes that vary in length
                  after you get that information. You will also share an interesting fact about
                  the local nature on the hikes when making a recommendation. At the end of your
                  response, ask if there is anything else you can help with.
              """)
          };

      while (true)
      {
          // Get user prompt and add to chat history
          Console.WriteLine("Your prompt:");
          string? userPrompt = Console.ReadLine();
          chatHistory.Add(new ChatMessage(ChatRole.User, userPrompt));

          // Stream the AI response and add to chat history
          Console.WriteLine("AI Response:");
          string response = "";
          await foreach (ChatResponseUpdate item in
              chatClient.GetStreamingResponseAsync(chatHistory))
          {
              Console.Write(item.Text);
              response += item.Text;
          }
          chatHistory.Add(new ChatMessage(ChatRole.Assistant, response));
          Console.WriteLine();
      }

 

 

✅ When to Use What?

 

Scenario Recommended Tool
Build intelligent workflows (e.g., "Read email → Summarize → Reply") Semantic Kernel
Train a custom model for predictions ML.NET
Run pre-trained models (e.g., ONNX BERT) ONNX Runtime
Need full control over OpenAI API OpenAI .NET SDK
Build a smart assistant or Copilot Semantic Kernel

 

📌 Summary

 

  • Use Semantic Kernel when you want to build AI-powered apps with task planning, prompt chaining, memory, and orchestration of skills.

  • Use .NET AI libraries when you're doing traditional ML tasks or want fine control over model loading, inference, or training.

 

0 Comments
 Log In to Chat