Skip to content

Instantly share code, notes, and snippets.

@gbaeke
Created May 28, 2023 20:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gbaeke/57be0a2d53dde0009fdbc99a407d6d03 to your computer and use it in GitHub Desktop.
Save gbaeke/57be0a2d53dde0009fdbc99a407d6d03 to your computer and use it in GitHub Desktop.
Semantic Kernel Demo
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.AI.ImageGeneration;
using System.Diagnostics;
using Microsoft.SemanticKernel.Planning;
using System.Text.Json;
var kernelSettings = KernelSettings.LoadSettings();
var kernelConfig = new KernelConfig();
kernelConfig.AddCompletionBackend(kernelSettings);
using ILoggerFactory loggerFactory = LoggerFactory.Create(builder =>
{
builder
.SetMinimumLevel(kernelSettings.LogLevel ?? LogLevel.Warning)
.AddConsole()
.AddDebug();
});
IKernel kernel = new KernelBuilder()
.WithLogger(loggerFactory.CreateLogger<IKernel>())
.WithConfiguration(kernelConfig)
.Configure(c =>
{
c.AddOpenAIImageGenerationService(kernelSettings.ApiKey);
})
.Build();
// used later to generate image with dallE
var dallE = kernel.GetService<IImageGeneration>();
// use SKs planner
var planner = new SequentialPlanner(kernel);
// depends on MySkills skill which has two semantic fucntions
// skills will be renamed to plugins in the future
var skillsDirectory = Path.Combine(System.IO.Directory.GetCurrentDirectory(), "skills");
var skill = kernel.ImportSemanticSkillFromDirectory(skillsDirectory, "MySkills");
// ask for starter ingredients
Console.Write("Enter ingredients: ");
string? input = Console.ReadLine();
if (!string.IsNullOrEmpty(input))
{
// define the ASK for the planner; the two semantic functions should be used by the plan
// note that these functions are too simple to be useful in a real application
// a single prompt to the model would be enough
var ask = "I need an image description of a recipe with these starter ingredients: " + input;
// create the plan and print it to see if the functions are used correctly
var newPlan = await planner.CreatePlanAsync(ask);
Console.WriteLine("Updated plan:\n");
Console.WriteLine(JsonSerializer.Serialize(newPlan, new JsonSerializerOptions { WriteIndented = true }));
// run the plan; result should be an image description
var newPlanResult = await newPlan.InvokeAsync();
// generate the url to the images created by dalle
var imageURL = await dallE.GenerateImageAsync(newPlanResult.ToString(), 512, 512);
// display image in browser (MacOS!!!)
Process.Start("open", imageURL);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment