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

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
.NET
pg

Value Objects: Solving Primitive Obsession in .NET

Overusing primitive types like string or int for domain concepts ("primitive obsession") causes bugs from missed validation, like invalid emails or negative monetary values. This article explores Value Objects as a .NET solution. Learn how these self-validating, immutable types prevent entire classes of errors, make code more expressive, and reduce developer overhead. We'll demonstrate creating robust domain models with minimal boilerplate, improving code quality without necessarily adopting full Domain-Driven Design, and see how Roslyn Source Generators make this practical.
03.06.2025
AI
mf

Die Llama 4-Revolution: Wie Metas neue KI-Familie den Open-Source-Markt neu definiert

Meta hat mit der Llama 4-Familie eine neue Generation von KI-Modellen vorgestellt, die durch zwei wesentliche Innovationen hervorsticht: ein 10-Millionen-Token-Kontextfenster und native Multimodalität. Die Familie besteht aus Scout (109 Milliarden Parameter), Maverick (400 Milliarden Parameter) und dem noch in Entwicklung befindlichen Behemoth (2 Billionen Parameter). Durch die Mixture-of-Experts-Architektur und Unterstützung für 200 Sprachen bieten diese Modelle europäischen Unternehmen eine attraktive Alternative zu proprietären Lösungen. Trotz hoher Hardware-Anforderungen und einiger Lizenzeinschränkungen ermöglichen sie eine souveräne KI-Strategie ohne Vendor Lock-in bei gleichzeitig wettbewerbsfähiger Leistung und Kosteneffizienz.
06.04.2025
Low-angle photography of metal structure
AI
cl-neu

AI-Funktionen zu Angular-Apps hinzufügen: lokal und offlinefähig

Künstliche Intelligenz (KI) ist spätestens seit der Veröffentlichung von ChatGPT in aller Munde. Wit WebLLM können Sie einen KI-Chatbot in Ihre eigenen Angular-Anwendungen integrieren. Wie das funktioniert und welche Vor- und Nachteile WebLLM hat, lesen Sie hier.
26.02.2024
Database Access with Sessions
.NET
kp_300x300

Data Access in .NET Native AOT with Sessions

.NET 8 brings Native AOT to ASP.NET Core, but many frameworks and libraries rely on unbound reflection internally and thus cannot support this scenario yet. This is true for ORMs, too: EF Core and Dapper will only bring full support for Native AOT in later releases. In this post, we will implement a database access layer with Sessions using the Humble Object pattern to get a similar developer experience. We will use Npgsql as a plain ADO.NET provider targeting PostgreSQL.
15.11.2023