How to Use SemanticKernel with OpenAI and Azure OpenAI in C#
Published Mar 12 2024 12:00 PM 1,498 Views
Iron Contributor

Hi!

Today I’m starting a series of posts to describe an “easy way to use” AI Services with Semantic Kernel. I’m a fan of code, so I’ll focus mostly on code samples.

Semantic Kernel (via Copilot)

Semantic Kernel is a powerful tool that allows developers to integrate cutting-edge language models into their applications with ease. Semantic Kernel provides a unified interface to access various language models from different sources, such as OpenAI, AzureOpenAI, and Hugging Face. Semantic Kernel also enables developers to store and retrieve memories, create dynamic prompts, and combine functions together with planners.

With Semantic Kernel, developers can supercharge their problem-solving creativity and build AI solutions that can understand natural language, generate content, answer questions, and more. Semantic Kernel is an open-source project that can be run on any local machine or cloud environment. Semantic Kernel offers tutorials, guides, and examples to help developers get started quickly and learn how to use its features.

:globe_with_meridians: Hello World with OpenAI

Let’s start! First, lets create a Console Application using NET 8, and add the Semantic Kernel Nuget package. Current version is 1.0.4 and it looks like this in Visual Studio 2022.

 

add-semantic-kernel-package (1).png

 

Remember that you can also install the package with the command:

nuget: Microsoft.SemanticKernel, 1.4.0

 

Important: The following demo uses OpenAI APIs. You need an OpenAI Dev account. OpenAI Account page describes how to create an account. https://platform.openai.com/docs/quickstart

Once you have your OpenAI account and keys, let’s review the main steps that we need to create a “Hello World” application:

 

  • Add services to the KernelBuilder, like Chat
  • Build a Kernel
  • Run a prompt with the Kernel

Those 3 simple steps can be implemented like this.

 

//    Copyright (c) 2024
//    Author      : Bruno Capuano
//    Change Log  :
//    – Sample console application to use OpenAI and Semantic Kernel
//
//    The MIT License (MIT)
//
//    Permission is hereby granted, free of charge, to any person obtaining a copy
//    of this software and associated documentation files (the "Software"), to deal
//    in the Software without restriction, including without limitation the rights
//    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//    copies of the Software, and to permit persons to whom the Software is
//    furnished to do so, subject to the following conditions:
//
//    The above copyright notice and this permission notice shall be included in
//    all copies or substantial portions of the Software.
//
//    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//    THE SOFTWARE.

using Keys;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;

// OpenAI keys
var modelId = OpenAI.ModelId;
var apiKey = OpenAI.ApiKey;

// Create a chat completion service
var builder = Kernel.CreateBuilder();
builder.AddOpenAIChatCompletion(modelId, apiKey);

// Get the chat completion service
Kernel kernel = builder.Build();
var chat = kernel.GetRequiredService<IChatCompletionService>();

// Create a sample chat history
var history = new ChatHistory();
history.AddSystemMessage("You are a helpful assistant.");
history.AddUserMessage("Who won the world cup in 2022?");
history.AddAssistantMessage("Argentina won in 2022.");
history.AddUserMessage("Where was it played? and who was the best player?");

// run the prompt
var result = await chat.GetChatMessageContentsAsync(history);
Console.WriteLine(result[^1].Content);
 

You can use your own OpenAI keys and you will be able to run the program! The output should be similar to this one:

 

image-4.png

:cloud: Switching to Azure OpenAI

Semantic Kernel implement an interface to main AI services like Chat and AI Completion. Out of the box, it also provides these capabilities in AI Services like OpenAI APIs and Azure OpenAI Services.

So, in order to change our chat demo from using OpenAI APIs to Azure OpenAI Services, we just need to change these lines.

  • Change the specific keys to work with Azure OpenAI.
  • Add an AzureOpenAIChatCompletion service

image-5.png

 

The code is literally the same!

//    Copyright (c) 2024
//    Author      : Bruno Capuano
//    Change Log  :
//    – Sample console application to use Azure OpenAI and Semantic Kernel
//
//    The MIT License (MIT)
//
//    Permission is hereby granted, free of charge, to any person obtaining a copy
//    of this software and associated documentation files (the "Software"), to deal
//    in the Software without restriction, including without limitation the rights
//    to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//    copies of the Software, and to permit persons to whom the Software is
//    furnished to do so, subject to the following conditions:
//
//    The above copyright notice and this permission notice shall be included in
//    all copies or substantial portions of the Software.
//
//    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//    AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//    LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//    OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//    THE SOFTWARE.

using Keys;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;

// Azure OpenAI keys
var deploymentName = AzureOpenAI.DeploymentName;
var endpoint = AzureOpenAI.Endpoint;
var apiKey = AzureOpenAI.ApiKey;

// Create a chat completion service
var builder = Kernel.CreateBuilder();
builder.AddAzureOpenAIChatCompletion(deploymentName, endpoint, apiKey);

// Get the chat completion service
Kernel kernel = builder.Build();
var chat = kernel.GetRequiredService<IChatCompletionService>();

// Create a sample chat history
var history = new ChatHistory();
history.AddSystemMessage("You are a helpful assistant.");
history.AddUserMessage("Who won the world cup in 2022?");
history.AddAssistantMessage("Argentina won in 2022.");
history.AddUserMessage("Where was it played? and who was the best player?");

// run the prompt
var result = await chat.GetChatMessageContentsAsync(history);
Console.WriteLine(result[^1].Content);
 

Of course the test runs. However, it seems that the model in this scenario is a little picky to choose Messi as best player :grinning_face:.

image-6.png

Conclusion

In this article, we have explored how to use Semantic Kernel with OpenAI and Azure OpenAI in C#. We have learned how to set up the necessary tools and libraries, and how to run some examples of Semantic Kernel prompts.

By using Semantic Kernel with OpenAI and Azure OpenAI, C# programmers can leverage the power of natural language processing and artificial intelligence to work with information and solutions more efficiently and effectively.

In next post we will review other AI services, how to add specific configuration and other scenarios.

You can find the complete source here: https://aka.ms/sktutrepo

 

Happy coding!

El Bruno

More posts in my blog ElBruno.com

Co-Authors
Version history
Last update:
‎Mar 12 2024 12:00 PM
Updated by: