-
Run the following command on
PowerShell
to create a new .NET web application named HelloBuildMinimalWebAp.dotnet new webapp -n HelloBuildMinimalWebAp
-
Switch to the newly created
HelloBuildMinimalWebAp
directory.cd 07 - Using Semantic Kernel in WebApp
-
Install Semantic Kernel nuget package
dotnet add package Microsoft.SemanticKernel
-
Install Swashbuckle.AspNetCore nuget package
dotnet add package Swashbuckle.AspNetCore
-
Open the project in VS Code or Visual Studio.
-
In the Program.cs file, delete all the existing code.
-
Add the following using statments at the top of
Program.cs
file.using Microsoft.SemanticKernel;
-
Add model name and initialize web application builder
var openAIChatCompletionModelName = "gpt-4-turbo"; // this could be other models like "gpt-4o". var builder = WebApplication.CreateBuilder(args);
-
Add Kernel to web builder
builder.Services.AddKernel();
-
Add
AddOpenAIChatCompletion
service to the web builder and build the app// This should work for any other service you can decided to use E.g Mistral. var kernel = builder.Services.AddOpenAIChatCompletion(openAIChatCompletionModelName, Environment.GetEnvironmentVariable("OPENAI_API_KEY")); var app = builder.Build();
-
Run the web app for returning
WeatherForecast
containing today’s data for a temperature with a short summary of the weather. The short summary of the weather is generated by AI by providing a prompt with a temperature.app.MapGet("/WeatherForecast", async (Kernel kernel) => { int temp = Random.Shared.Next(-20, 55); return new WeatherForecast ( DateOnly.FromDateTime(DateTime.Now), temp, await kerel.InvokePromptAsync<string>($"Short description of weather at {temp} degrees Celsius") // This description will be generated by the AI model for the given temperature. ); }); app.Run(); internal record WeatherForecast(DateOnly Date, int TempratureC, string Summary);
-
Run the application by entering
dotnet run
into the terminal You will get an output similar to the following
Building...
info: Microsoft.Hosting.Lifetime[14]
Now listening on: http://localhost:<your port>
info: Microsoft.Hosting.Lifetime[0]
Application started. Press Ctrl+C to shut down.
info: Microsoft.Hosting.Lifetime[0]
Hosting environment: Development
info: Microsoft.Hosting.Lifetime[0]
Content root path:<your path>
-
Open your web browser and navigate to
http://localhost:<your-port>/WeatherForecast
, you will get json output similar to the following{ "date": "2024-06-17", "tempratureC": 4, "summary": "At 4 degrees Celsius, the weather is cool and slightly chilly. It is above freezing, so there is no ice, but it's cold enough that you might want a jacket or sweater when outdoors. This temperature is typical for late autumn or early spring in temperate regions." }
View the completed sample in the 07 Using Semantic Kernel in WebApp) project.