Integrating AI Power into Your .NET Applications with the Semantic Kernel Toolkit – an Early View

With the rise of powerful AI models and services, questions come up on how to integrate those into our applications and make reasonable use of them. While other languages like Python already have popular and feature-rich libraries like LangChain, we are missing these in .NET and C#. But there is a new kid on the block that might change this situation. Welcome Semantic Kernel by Microsoft!

In diesem Artikel:

Version information: Semantic Kernel .NET 0.13.277.1-preview

What is Semantic Kernel?

Semantic Kernel (SK) is an SDK, available for .NET and Python, that lets you easily integrate Large Language Models (LLM) in your application. It comes with building blocks and abstractions like

  • Memory: for storing and querying embeddings
  • Skills: let you define AI prompts or connect to external systems
  • Planner: for building AI agents that can execute multiple steps

Since SK is still in early development (at the time of writing, the .NET version is at 0.13.277.1-preview) it currently lacks support for a number of things that tools like LangChain are already offering. Currently, the only supported Vector Database is Qdrant (they are working on supporting many more, though), and it only supports remote models like the OpenAI APIAzure OpenAI API, and Huggingface Inference API.

Using Semantic Kernel: first steps

So, let’s check out how we can use SK in .NET with C#. Before we start, we need to add the Microsoft.SemanticKernel NuGet package:
				
					dotnet add package Microsoft.SemanticKernel --prerelease
				
			

After that, we are able to create a kernel object, which is the orchestrator of our AI application. In this example, we use the OpenAI API Text-Completion API.

				
					var kernel = new KernelBuilder()
    .Configure(c => c.AddOpenAITextCompletionService("davinci-openai", "text-davinci-003", config["OpenAi:ApiKey"]))
    .Build();
				
			

Having the kernel at hand, we now need to define a prompt and create a so called semantic function which let’s us use the prompt.

				
					var prompt = @"Create a single sentence TLDR for the input.
Input: {{$input}}";

var tldr = kernel.CreateSemanticFunction(prompt);
				
			

We can now use the tldr object and invoke the prompt with input:

				
					var input = @"With SK, you can now build AI-first apps faster by design while also having a front-row peek at how 
the SDK is being built. SK has been released as open-source so that more pioneering developers can join us in crafting 
the future of this landmark moment in the history of computing. SK has been engineered to flexibly integrate LLM AI 
into existing apps. With SK, it's easier to accelerate your innovations' time to market, and to manage for reliability 
and performance in the long run.";

Console.WriteLine(await tldr.InvokeAsync(input));
				
			

As you can see, with these four simple steps, we are able to create a simple summarizer application.

Advanced sample: Question & Answer flow with Semantic Kernel

While this example shows how easily we can integrate an LLM into our application, a lot of integration scenarios will have the need to work with data present in the application. A more advanced example can be found in this GitHub repo, which implements a simple question & answer flow. In that example, we use text embeddings to find text that is related to a user’s question. After that, the text will be sent to OpenAI in order to create an answer to the question.

To be able to use embeddings and a store to store them, we need to adjust the kernel like this:

				
					var store = await SqliteMemoryStore.ConnectAsync("index.db");
var kernel = new KernelBuilder()
    .Configure(c =>
    {
        c.AddOpenAITextEmbeddingGenerationService("ada", "text-embedding-ada-002", config["OpenAi:ApiKey"]);
        c.AddOpenAITextCompletionService("davinci-openai", "text-davinci-003", config["OpenAi:ApiKey"]);
    })
    .WithMemoryStorage(store)
    .Build();
				
			

Our kernel now has a memory, and we are now able to store text in this memory. The following method downloads an HTML page, extracts the main contents of the page, and stores the contents in the kernel’s memory.

				
					async Task IndexUrl(HttpClient client, string url, string contentSelector)
{
    var content = await client.GetStringAsync(url);
    var title = string.Empty;
    
    var doc = new HtmlDocument();
    doc.LoadHtml(content);
    var mainElement = doc.DocumentNode.SelectSingleNode(contentSelector);
    title = mainElement.SelectSingleNode("//h1").InnerText;
    content = mainElement.InnerText

    await kernel.Memory.SaveInformationAsync(COLLECTION, content, url, title);
}
				
			

Once we have the data in the memory, we again need to define a prompt. In this example, the prompt is stored in a skill in the repo and will be imported with this line:

				
					kernel.ImportSemanticSkillFromDirectory("skills", "qa");
				
			

After we import the text into the memory and skill into the kernel, we can query the memory and let us create an answer to a question based on the stored text.

				
					async Task<string> Answer(string question)
{
    var results = await kernel.Memory.SearchAsync(COLLECTION, question, limit: 2).ToListAsync();
    var variables = new ContextVariables(question)
    {
        ["context"] = results.Any() 
            ? string.Join("\n", results.Select(r => r.Metadata.Text)) 
            : "No context found for this question."
    };
    
    var result = await kernel.RunAsync(variables, kernel.Skills.GetFunction("qa", "answer"));
    return result.Result;    
}
				
			

In the code, first, we do a semantic search and retrieve the top two results. These are concatenated and will be used as the context for the AI to answer the question of the user.

Conclusion

Although Semantic Kernel (SK) is in a very early stage of development and still needs to fill a lot of gaps, we are already able to use this library and integrate Large Language Models (LLMs) into our .NET applications. This lets application developers use the power of AI and natural language processing (NLP) without the need to build LLMs from scratch. With SK, developers can focus on building and improving their applications, while SK handles the heavy lifting of language processing.

Furthermore, SK allows developers to work with application data to fulfill AI tasks, as demonstrated in the advanced example. This means that developers can use their existing data to improve the natural language processing capabilities of their applications and enable powerful features like semantic search and question-answering.

Overall, SK shows great potential for integrating LLMs into .NET and C# applications, and its early development stage should not discourage developers from exploring its capabilities. As SK continues to evolve and mature, we can expect it to become an increasingly valuable tool for building advanced AI applications.

Mehr Artikel zu AI, .NET, LLM, Semantic Kernel
Kostenloser
Newsletter

Aktuelle Artikel, Screencasts, Webinare und Interviews unserer Experten für Sie

Verpassen Sie keine Inhalte zu Angular, .NET Core, Blazor, Azure und Kubernetes und melden Sie sich zu unserem kostenlosen monatlichen Dev-Newsletter an.

Newsletter Anmeldung
Diese Artikel könnten Sie interessieren
.NET
pg

Pattern Matching with Discriminated Unions in .NET

Traditional C# pattern matching with switch statements and if/else chains is error-prone and doesn't guarantee exhaustive handling of all cases. When you add new types or states, it's easy to miss updating conditional logic, leading to runtime bugs. The library Thinktecture.Runtime.Extensions solves this with built-in Switch and Map methods for discriminated unions that enforce compile-time exhaustiveness checking.
26.08.2025
.NET
pg

Value Objects in .NET: Integration with Frameworks and Libraries

Value Objects in .NET provide a structured way to improve consistency and maintainability in domain modeling. This article examines their integration with popular frameworks and libraries, highlighting best practices for seamless implementation. From working with Entity Framework to leveraging their advantages in ASP.NET, we explore how Value Objects can be effectively incorporated into various architectures. By understanding their role in framework integration, developers can optimize data handling and enhance code clarity without unnecessary complexity.
12.08.2025
.NET
pg

Smart Enums: Adding Domain Logic to Enumerations in .NET

This article builds upon the introduction of Smart Enums by exploring their powerful capability to encapsulate behavior, a significant limitation of traditional C# enums. We delve into how Thinktecture.Runtime.Extensions enables embedding domain-specific logic directly within Smart Enum definitions. This co-location of data and behavior promotes more cohesive, object-oriented, and maintainable code, moving beyond scattered switch statements and extension methods. Discover techniques to make your enumerations truly "smart" by integrating behavior directly where it belongs.
29.07.2025
.NET
pg

Discriminated Unions: Representation of Alternative Types in .NET

Representing values that may take on multiple distinct types or states is a common challenge in C#. Traditional approaches—like tuples, generics, or exceptions—often lead to clumsy and error-prone code. Discriminated unions address these issues by enabling clear, type-safe modeling of “one-of” alternatives. This article examines pitfalls of conventional patterns and introduces discriminated unions with the Thinktecture.Runtime.Extensions library, demonstrating how they enhance code safety, prevent invalid states, and improve maintainability—unlocking powerful domain modeling in .NET with minimal boilerplate.
15.07.2025
.NET
pg

Handling Complexity: Introducing Complex Value Objects in .NET

While simple value objects wrap single primitives, many domain concepts involve multiple related properties (e.g., a date range's start and end). This article introduces Complex Value Objects in .NET, which group these properties into a cohesive unit. This ensures internal consistency, centralizes validation, and encapsulates behavior. Discover how to implement these for clearer, safer code using the library Thinktecture.Runtime.Extensions, which minimizes boilerplate when handling such related data.
01.07.2025
.NET
pg

Smart Enums: Beyond Traditional Enumerations in .NET

Traditional C# enums often fall short when needing to associate data or behavior with constants, or ensure strong type safety. This article explores the "Smart Enum" pattern as a superior alternative. Leveraging the library Thinktecture.Runtime.Extensions and Roslyn Source Generators, developers can easily implement Smart Enums. These provide a robust, flexible, and type-safe way to represent fixed sets of related options, encapsulating both data and behavior directly within the Smart Enum. This results in more maintainable, expressive, and resilient C# code, overcoming the limitations of basic enums.
17.06.2025