Now we have an understanding of semantic kernel library and chat completions,let's create a basic console application that uses them.
-
Run the following command on
PowerShellto create a new .NET application named HelloBuild but you can substitute the name of your choice.dotnet new console -n HelloBuild
-
Switch to the newly created
HelloBuilddirectory.cd HelloBuild -
Install Semantic Kernel nuget package
dotnet add package Microsoft.SemanticKernel
-
Open the project in VS Code or Visual Studio.
-
In the Program.cs file, delete all the existing code.
-
Add
using Microsoft.SemanticKernel;to the top of Program.cs. -
Add a model to use for chat completions Learn more about OpenAI model versions and their capabilities.
string openAIChatCompletionModelName = "gpt-3.5-turbo"; // this could be other models like "gpt-4o".
-
Initialize the kernel and add the OpenAI chat completion service to it
var kernel = Kernel.CreateBuilder() .AddOpenAIChatCompletion(openAIChatCompletionModelName, Environment.GetEnvironmentVariable("OPENAI_API_KEY")) .Build();
-
Receive the user's request and send it to the kernel to obtain a response from the LLM.
// Basic chat // This is zero memory or stateless chat. The AI will not remember anything from the previous messages. while (true) { Console.Write("Q: "); Console.WriteLine(await kernel.InvokePromptAsync(Console.ReadLine()!)); }
- This loop continuously prompts the user for input, sends the input to the OpenAI model, and prints the AI's response.
-
Let's see what we have so far, you can run the application by entering
dotnet runinto the terminal. Experiment with a user prompt "Hi my name is Alice" and a follow-up question "what is my name?" your output may vary, but it will be similar to what is shown below.Q: Hi my name is Alice Hello Alice, pleased to meet you! How can I assist you today? Q: What is my name? I'm sorry, I cannot provide your name as I do not have that information. If you would like me to refer to you by a specific name during our conversation, please let me know. Q:
You can view the completed project in the 01 Hello Semantic Kernel folder.
This application is stateless, meaning the AI does not remember any previous interactions. Each input is treated independently.