forked from microsoft/semantic-kernel
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
.Net: Add new getting started samples (microsoft#4191)
### Motivation and Context Closes microsoft#4019 ### Description <!-- Describe your changes, the overall approach, the underlying design. These notes will help understanding how your code works. Thanks! --> ### Contribution Checklist <!-- Before submitting this PR, please make sure: --> - [ ] The code builds clean without any errors or warnings - [ ] The PR follows the [SK Contribution Guidelines](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md) and the [pre-submission formatting script](https://github.com/microsoft/semantic-kernel/blob/main/CONTRIBUTING.md#development-scripts) raises no violations - [ ] All unit tests pass, and I have added new tests where possible - [ ] I didn't break anyone 😄
- Loading branch information
1 parent
cb73546
commit 4487ca3
Showing
8 changed files
with
247 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
37 changes: 37 additions & 0 deletions
37
dotnet/samples/KernelSyntaxExamples/Getting_Started/Step1_Create_Kernel.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,37 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System; | ||
using System.Threading.Tasks; | ||
using Microsoft.SemanticKernel; | ||
|
||
/** | ||
* This example shows how to create and use a <see cref="Kernel"/>. | ||
*/ | ||
public static class Step1_Create_Kernel | ||
{ | ||
/// <summary> | ||
/// Show how to create a <see cref="Kernel"/> and use it to execute prompts. | ||
/// </summary> | ||
public static async Task RunAsync() | ||
{ | ||
// Create a kernel with OpenAI chat completion | ||
Kernel kernel = Kernel.CreateBuilder() | ||
.AddOpenAIChatCompletion( | ||
modelId: TestConfiguration.OpenAI.ChatModelId, | ||
apiKey: TestConfiguration.OpenAI.ApiKey) | ||
.Build(); | ||
|
||
// Example 1. Invoke the kernel with a prompt and display the result | ||
Console.WriteLine(await kernel.InvokePromptAsync("What color is the sky?")); | ||
|
||
// Example 2. Invoke the kernel with a templated prompt and display the result | ||
KernelArguments arguments = new() { { "topic", "sea" } }; | ||
Console.WriteLine(await kernel.InvokePromptAsync("What color is the {{$topic}}?", arguments)); | ||
|
||
// Example 3. Invoke the kernel with a templated prompt and stream the results to the display | ||
await foreach (var update in kernel.InvokePromptStreamingAsync("What color is the {{$topic}}? Provide a detailed explanation.", arguments)) | ||
{ | ||
Console.Write(update); | ||
} | ||
} | ||
} |
45 changes: 45 additions & 0 deletions
45
dotnet/samples/KernelSyntaxExamples/Getting_Started/Step2_Add_Plugins.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,45 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
// ReSharper disable once InconsistentNaming | ||
using System; | ||
using System.Threading.Tasks; | ||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.Connectors.OpenAI; | ||
/** | ||
* This example shows how to load a <see cref="KernelPlugin"/> instances. | ||
*/ | ||
public static class Step2_Add_Plugins | ||
{ | ||
/// <summary> | ||
/// Shows different ways to load a <see cref="KernelPlugin"/> instances. | ||
/// </summary> | ||
public static async Task RunAsync() | ||
{ | ||
// Create a kernel with OpenAI chat completion | ||
IKernelBuilder kernelBuilder = Kernel.CreateBuilder(); | ||
kernelBuilder.AddOpenAIChatCompletion( | ||
modelId: TestConfiguration.OpenAI.ChatModelId, | ||
apiKey: TestConfiguration.OpenAI.ApiKey); | ||
kernelBuilder.Plugins.AddFromType<TimeInformation>(); | ||
Kernel kernel = kernelBuilder.Build(); | ||
|
||
// Example 1. Invoke the kernel with a prompt that asks the AI for inromation it cannot provide and may hallucinate | ||
Console.WriteLine(await kernel.InvokePromptAsync("How many days until Christmas?")); | ||
|
||
// Example 2. Invoke the kernel with a templated prompt that invokes a plugin and display the result | ||
Console.WriteLine(await kernel.InvokePromptAsync("The current time is {{TimeInformation.GetCurrentUtcTime}}. How many days until Christmas?")); | ||
|
||
// Example 3. Invoke the kernel with a prompt and allow the AI to automatically invoke functions | ||
OpenAIPromptExecutionSettings settings = new() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }; | ||
Console.WriteLine(await kernel.InvokePromptAsync("How many days until Christmas? Explain your thinking.", new(settings))); | ||
} | ||
|
||
/// <summary> | ||
/// A plugin that returns the current time. | ||
/// </summary> | ||
public class TimeInformation | ||
{ | ||
[KernelFunction] | ||
public string GetCurrentUtcTime() => DateTime.UtcNow.ToString("R"); | ||
} | ||
} |
87 changes: 87 additions & 0 deletions
87
dotnet/samples/KernelSyntaxExamples/Getting_Started/Step3_Yaml_Prompt.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,87 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System; | ||
using System.Threading.Tasks; | ||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.PromptTemplate.Handlebars; | ||
|
||
/** | ||
* This example shows how to create a prompt <see cref="KernelFunction"/> from a YAML resource. | ||
*/ | ||
public static class Step3_Yaml_Prompt | ||
{ | ||
/// <summary> | ||
/// Show how to create a prompt <see cref="KernelFunction"/> from a YAML resource. | ||
/// </summary> | ||
public static async Task RunAsync() | ||
{ | ||
// Create a kernel with OpenAI chat completion | ||
Kernel kernel = Kernel.CreateBuilder() | ||
.AddOpenAIChatCompletion( | ||
modelId: TestConfiguration.OpenAI.ChatModelId, | ||
apiKey: TestConfiguration.OpenAI.ApiKey) | ||
.Build(); | ||
|
||
// Load prompt from resource | ||
var function = kernel.CreateFunctionFromPromptYaml(GenerateStoryYaml); | ||
|
||
// Invoke the prompt function and display the result | ||
Console.WriteLine(await kernel.InvokeAsync(function, arguments: new() | ||
{ | ||
{ "topic", "Dog" }, | ||
{ "length", "3" }, | ||
})); | ||
|
||
// Load prompt from resource | ||
function = kernel.CreateFunctionFromPromptYaml(GenerateStoryHandlebarsYaml, new HandlebarsPromptTemplateFactory()); | ||
|
||
// Invoke the prompt function and display the result | ||
Console.WriteLine(await kernel.InvokeAsync(function, arguments: new() | ||
{ | ||
{ "topic", "Cat" }, | ||
{ "length", "3" }, | ||
})); | ||
} | ||
|
||
private const string GenerateStoryYaml = @" | ||
name: GenerateStory | ||
template: | | ||
Tell a story about {{$topic}} that is {{$length}} sentences long. | ||
template_format: semantic-kernel | ||
description: A function that generates a story about a topic. | ||
input_variables: | ||
- name: topic | ||
description: The topic of the story. | ||
is_required: true | ||
- name: length | ||
description: The number of sentences in the story. | ||
is_required: true | ||
output_variable: | ||
description: The generated story. | ||
execution_settings: | ||
- temperature: 0.6 | ||
"; | ||
|
||
private const string GenerateStoryHandlebarsYaml = @" | ||
name: GenerateStory | ||
template: | | ||
Tell a story about {{topic}} that is {{length}} sentences long. | ||
template_format: handlebars | ||
description: A function that generates a story about a topic. | ||
input_variables: | ||
- name: topic | ||
description: The topic of the story. | ||
is_required: true | ||
- name: length | ||
description: The number of sentences in the story. | ||
is_required: true | ||
output_variable: | ||
description: The generated story. | ||
execution_settings: | ||
- model_id: gpt-4 | ||
temperature: 0.6 | ||
- model_id: gpt-3.5-turbo | ||
temperature: 0.4 | ||
- temperature: 0.5 | ||
"; | ||
} |
71 changes: 71 additions & 0 deletions
71
dotnet/samples/KernelSyntaxExamples/Getting_Started/Step4_Dependency_Injection.cs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
// ReSharper disable once InconsistentNaming | ||
// ReSharper disable once InconsistentNaming | ||
using System; | ||
using System.Threading.Tasks; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Logging; | ||
using Microsoft.SemanticKernel; | ||
using RepoUtils; | ||
|
||
// ReSharper disable once InconsistentNaming | ||
/** | ||
* This example shows how to using Dependency Injection with the Semantic Kernel | ||
*/ | ||
public static class Step4_Dependency_Injection | ||
{ | ||
/// <summary> | ||
/// Show how to create a <see cref="Kernel"/> that participates in Dependency Injection. | ||
/// </summary> | ||
public static async Task RunAsync() | ||
{ | ||
// If an application follows DI guidelines, the following line is unnecessary because DI will inject an instance of the KernelClient class to a class that references it. | ||
// DI container guidelines - https://learn.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-guidelines#recommendations | ||
var serviceProvider = BuildServiceProvider(); | ||
var kernel = serviceProvider.GetRequiredService<Kernel>(); | ||
|
||
// Invoke the kernel with a templated prompt and stream the results to the display | ||
KernelArguments arguments = new() { { "topic", "earth when viewed from space" } }; | ||
await foreach (var update in kernel.InvokePromptStreamingAsync("What color is the {{$topic}}? Provide a detailed explanation.", arguments)) | ||
{ | ||
Console.Write(update); | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Build a ServiceProvdier that can be used to resolve services. | ||
/// </summary> | ||
private static ServiceProvider BuildServiceProvider() | ||
{ | ||
var collection = new ServiceCollection(); | ||
collection.AddSingleton<ILoggerFactory>(ConsoleLogger.LoggerFactory); | ||
|
||
var kernelBuilder = collection.AddKernel(); | ||
kernelBuilder.Services.AddOpenAITextGeneration(TestConfiguration.OpenAI.ModelId, TestConfiguration.OpenAI.ApiKey); | ||
kernelBuilder.Plugins.AddFromType<TimeInformation>(); | ||
|
||
return collection.BuildServiceProvider(); | ||
} | ||
|
||
/// <summary> | ||
/// A plugin that returns the current time. | ||
/// </summary> | ||
public class TimeInformation | ||
{ | ||
private readonly ILogger _logger; | ||
|
||
public TimeInformation(ILoggerFactory loggerFactory) | ||
{ | ||
this._logger = loggerFactory.CreateLogger(typeof(TimeInformation)); | ||
} | ||
|
||
[KernelFunction] | ||
public string GetCurrentUtcTime() | ||
{ | ||
var utcNow = DateTime.UtcNow.ToString("R"); | ||
this._logger.LogInformation("Returning current time {0}", utcNow); | ||
return utcNow; | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters