Getting Started with Semantic Kernel in .NET: A Simple Guide for Developers

Getting Started with Semantic Kernel in .NET: A Simple Guide for Developers

Introduction

If you're a .NET developer stepping into the world of AI, you've probably heard about integrating large language models (LLMs) into applications but doing that in a structured, maintainable, and scalable way can feel overwhelming.

This is where Semantic Kernel becomes extremely useful.

Semantic Kernel is an open-source SDK that helps you integrate AI (like OpenAI models) into your .NET applications in a clean, organized, and developer-friendly way.

Instead of treating AI like a random external service, Semantic Kernel helps you structure AI like part of your application architecture.


What Problem Does Semantic Kernel Solve?

Before jumping into code, let’s understand the real issue.

Without Semantic Kernel

You might:

  • Call OpenAI APIs directly
  • Hardcode prompts in different places
  • Repeat logic across services
  • Lose control over scaling AI features

With Semantic Kernel

You:

  • Centralize AI logic
  • Reuse AI functions like normal methods
  • Combine AI + C# seamlessly
  • Keep your architecture clean

Think of it as dependency injection + service layer, but for AI


Step-by-Step Code with Explanation

Let’s build a simple feature: Text Summarizer


Step 1: Install Package

dotnet add package Microsoft.SemanticKernel        

Why?

This package gives you:

  • Kernel (core engine)
  • AI connectors
  • Function abstraction

Without this, you'd manually manage HTTP calls and JSON parsing.


Step 2: Create the Kernel

using Microsoft.SemanticKernel;

var builder = Kernel.CreateBuilder();

builder.AddOpenAIChatCompletion(
    modelId: "gpt-4",
    apiKey: "your-api-key"
);

var kernel = builder.Build();        

What’s Happening Here?

Let’s break it down:

1. Kernel.CreateBuilder()

  • Similar to WebApplication.CreateBuilder() in ASP.NET
  • Used to configure services before building

2. AddOpenAIChatCompletion(...)

  • Registers AI model as a service
  • Just like registering a database or logging service

Reason: This follows Dependency Injection principles. Instead of calling APIs directly, you let the kernel manage AI communication.

3. builder.Build()

  • Finalizes configuration
  • Creates a ready-to-use kernel instance

Think of kernel as your AI runtime engine


Step 3: Create a Semantic Function

var summarizeFunction = kernel.CreateFunctionFromPrompt(
    "Summarize the following text:\n{{$input}}"
);        

What’s Happening?

This is where AI becomes “programmable”.

Key Concept: Prompt Template

Summarize the following text:
{{$input}}        

  • {{$input}} is a placeholder variable
  • At runtime, you pass real data

Why This Design?

Instead of writing:

string prompt = "Summarize: " + text;        

You:

  • Separate logic from data
  • Reuse the function anywhere
  • Keep prompts maintainable

This is similar to parameterized SQL queries (cleaner, safer, reusable)


Step 4: Execute the Function

var result = await kernel.InvokeAsync(
    summarizeFunction,
    new() { ["input"] = "Long text here..." }
);

Console.WriteLine(result);        

Explanation

1. InvokeAsync(...)

  • Executes the function
  • Sends request to AI model
  • Returns processed result

2. new() { ["input"] = "..." }

  • Passing values to placeholders
  • input maps to {{$input}}

This is like calling:

MyMethod(input: "value");        

Why This Approach is Powerful

1. Reusability

You can reuse the same function:

await kernel.InvokeAsync(summarizeFunction, new() { ["input"] = article1 });
await kernel.InvokeAsync(summarizeFunction, new() { ["input"] = article2 });        

No need to rewrite prompts.


2. Clean Separation

  • Prompt = logic
  • Input = data

This avoids messy string concatenation everywhere.


3. Easy Testing

You can:

  • Test prompts independently
  • Swap models without changing business logic


Going One Level Deeper: Native Functions

You can mix AI with normal C# code.

Example

public class DiscountPlugin
{
    public double CalculateDiscount(double price)
    {
        return price * 0.1;
    }
}        

Register it:

kernel.ImportPluginFromObject(new DiscountPlugin(), "Discount");        

Why This Matters?

Now you can:

  • Combine AI + business logic
  • Use planner to call both

Example flow:

  1. AI generates product description
  2. C# calculates price discount
  3. Final result is combined


Understanding the Planner

Instead of writing:

await summarize();
await translate();
await format();        

You say:

“Summarize and translate this text”

Planner:

  • Breaks the goal into steps
  • Chooses functions
  • Executes them

This is like giving AI decision-making ability


Memory

Semantic Kernel can store context using embeddings.

Why useful?

  • Chat history
  • Smart recommendations
  • Semantic search


Real Example Architecture

In a real .NET app:

  • Controllers → handle requests
  • Services → business logic
  • Semantic Kernel → AI orchestration

Treat Semantic Kernel like a service layer for AI


Common Mistakes

1. Mixing Prompts Everywhere

Don’t do this:

var prompt1 = "...";
var prompt2 = "...";        

Use functions instead.


2. Overusing AI

Not everything needs AI:

  • Calculations → use C#
  • Logic → use code
  • Creativity → use AI


3. Ignoring Structure

If you don’t organize plugins:

  • Your AI code becomes messy fast


Semantic Kernel is not just about calling AI—it’s about engineering AI into your application properly.

To view or add a comment, sign in

More articles by Vijendra Kushwaha

Others also viewed

Explore content categories