chore: import upstream snapshot with attribution
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:21:23 +08:00
commit b957a53def
5423 changed files with 863745 additions and 0 deletions
@@ -0,0 +1,55 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
namespace Examples;
/// <summary>
/// This example demonstrates how to add AI services to a kernel as described at
/// https://learn.microsoft.com/semantic-kernel/agents/kernel/adding-services
/// </summary>
public class AIServices(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== AI Services ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? textModelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || textModelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
string? openAImodelId = TestConfiguration.OpenAI.ChatModelId;
string? openAItextModelId = TestConfiguration.OpenAI.ChatModelId;
string? openAIapiKey = TestConfiguration.OpenAI.ApiKey;
if (openAImodelId is null || openAItextModelId is null || openAIapiKey is null)
{
Console.WriteLine("OpenAI credentials not found. Skipping example.");
return;
}
// Create a kernel with an Azure OpenAI chat completion service
// <TypicalKernelCreation>
Kernel kernel = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey)
.Build();
// </TypicalKernelCreation>
// You can also create a kernel with a (non-Azure) OpenAI chat completion service
// <OpenAIKernelCreation>
kernel = Kernel.CreateBuilder()
.AddOpenAIChatCompletion(openAImodelId, openAIapiKey)
.Build();
// </OpenAIKernelCreation>
}
}
@@ -0,0 +1,124 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Plugins.Core;
namespace Examples;
/// <summary>
/// This example demonstrates how to configure prompts as described at
/// https://learn.microsoft.com/semantic-kernel/prompts/configure-prompts
/// </summary>
public class ConfiguringPrompts(ITestOutputHelper output) : LearnBaseTest(["Who were the Vikings?"], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Configuring Prompts ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Plugins.AddFromType<ConversationSummaryPlugin>();
Kernel kernel = builder.Build();
// <FunctionFromPrompt>
// Create a template for chat with settings
var chat = kernel.CreateFunctionFromPrompt(
new PromptTemplateConfig()
{
Name = "Chat",
Description = "Chat with the assistant.",
Template = @"{{ConversationSummaryPlugin.SummarizeConversation $history}}
User: {{$request}}
Assistant: ",
TemplateFormat = "semantic-kernel",
InputVariables =
[
new() { Name = "history", Description = "The history of the conversation.", IsRequired = false, Default = "" },
new() { Name = "request", Description = "The user's request.", IsRequired = true }
],
ExecutionSettings =
{
{
"default",
new OpenAIPromptExecutionSettings()
{
MaxTokens = 1000,
Temperature = 0
}
},
{
"gpt-3.5-turbo", new OpenAIPromptExecutionSettings()
{
ModelId = "gpt-3.5-turbo-0613",
MaxTokens = 4000,
Temperature = 0.2
}
},
{
"gpt-4",
new OpenAIPromptExecutionSettings()
{
ModelId = "gpt-4-1106-preview",
MaxTokens = 8000,
Temperature = 0.3
}
}
}
}
);
// </FunctionFromPrompt>
// Create chat history and choices
ChatHistory history = [];
// Start the chat loop
Console.Write("User > ");
string? userInput;
while ((userInput = Console.ReadLine()) is not null)
{
// Get chat response
var chatResult = kernel.InvokeStreamingAsync<StreamingChatMessageContent>(
chat,
new()
{
{ "request", userInput },
{ "history", string.Join("\n", history.Select(x => x.Role + ": " + x.Content)) }
}
);
// Stream the response
string message = "";
await foreach (var chunk in chatResult)
{
if (chunk.Role.HasValue)
{
Console.Write(chunk.Role + " > ");
}
message += chunk;
Console.Write(chunk);
}
Console.WriteLine();
// Append to history
history.AddUserMessage(userInput);
history.AddAssistantMessage(message);
// Get user input again
Console.Write("User > ");
}
}
}
@@ -0,0 +1,98 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
using Plugins;
namespace Examples;
/// <summary>
/// This example demonstrates how to create native functions for AI to call as described at
/// https://learn.microsoft.com/semantic-kernel/agents/plugins/using-the-KernelFunction-decorator
/// </summary>
public class CreatingFunctions(ITestOutputHelper output) : LearnBaseTest(["What is 49 diivided by 37?"], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Creating native functions ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
// <RunningNativeFunction>
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Plugins.AddFromType<MathPlugin>();
Kernel kernel = builder.Build();
// Test the math plugin
double answer = await kernel.InvokeAsync<double>(
"MathPlugin", "Sqrt", new()
{
{ "number1", 12 }
});
Console.WriteLine($"The square root of 12 is {answer}.");
// </RunningNativeFunction>
// Create chat history
ChatHistory history = [];
// <Chat>
// Get chat completion service
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
// Start the conversation
Console.Write("User > ");
string? userInput;
while ((userInput = Console.ReadLine()) is not null)
{
history.AddUserMessage(userInput);
// Enable auto function calling
OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};
// Get the response from the AI
var result = chatCompletionService.GetStreamingChatMessageContentsAsync(
history,
executionSettings: openAIPromptExecutionSettings,
kernel: kernel);
// Stream the results
string fullMessage = "";
var first = true;
await foreach (var content in result)
{
if (content.Role.HasValue && first)
{
Console.Write("Assistant > ");
first = false;
}
Console.Write(content.Content);
fullMessage += content.Content;
}
Console.WriteLine();
// Add the message from the agent to the chat history
history.AddAssistantMessage(fullMessage);
// Get user input again
Console.Write("User > ");
}
// </Chat>
}
}
@@ -0,0 +1,153 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Plugins.Core;
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
namespace Examples;
/// <summary>
/// This example demonstrates how to call functions within prompts as described at
/// https://learn.microsoft.com/semantic-kernel/prompts/calling-nested-functions
/// </summary>
public class FunctionsWithinPrompts(ITestOutputHelper output) : LearnBaseTest([
"Can you send an approval to the marketing team?",
"That is all, thanks."], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Functions within Prompts ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
// <KernelCreation>
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Plugins.AddFromType<ConversationSummaryPlugin>();
Kernel kernel = builder.Build();
// </KernelCreation>
List<string> choices = ["ContinueConversation", "EndConversation"];
// Create few-shot examples
List<ChatHistory> fewShotExamples =
[
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
],
[
new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
]
];
// Create handlebars template for intent
// <IntentFunction>
var getIntent = kernel.CreateFunctionFromPrompt(
new()
{
Template = """
<message role="system">Instructions: What is the intent of this request?
Do not explain the reasoning, just reply back with the intent. If you are unsure, reply with {{choices.[0]}}.
Choices: {{choices}}.</message>
{{#each fewShotExamples}}
{{#each this}}
<message role="{{role}}">{{content}}</message>
{{/each}}
{{/each}}
{{ConversationSummaryPlugin-SummarizeConversation history}}
<message role="user">{{request}}</message>
<message role="system">Intent:</message>
""",
TemplateFormat = "handlebars"
},
new HandlebarsPromptTemplateFactory()
);
// </IntentFunction>
// Create a Semantic Kernel template for chat
// <FunctionFromPrompt>
var chat = kernel.CreateFunctionFromPrompt(
@"{{ConversationSummaryPlugin.SummarizeConversation $history}}
User: {{$request}}
Assistant: "
);
// </FunctionFromPrompt>
// <Chat>
// Create chat history
ChatHistory history = [];
// Start the chat loop
while (true)
{
// Get user input
Console.Write("User > ");
var request = Console.ReadLine();
// Invoke handlebars prompt
var intent = await kernel.InvokeAsync(
getIntent,
new()
{
{ "request", request },
{ "choices", choices },
{ "history", history },
{ "fewShotExamples", fewShotExamples }
}
);
// End the chat if the intent is "Stop"
if (intent.ToString() == "EndConversation")
{
break;
}
// Get chat response
var chatResult = kernel.InvokeStreamingAsync<StreamingChatMessageContent>(
chat,
new()
{
{ "request", request },
{ "history", string.Join("\n", history.Select(x => x.Role + ": " + x.Content)) }
}
);
// Stream the response
string message = "";
await foreach (var chunk in chatResult)
{
if (chunk.Role.HasValue)
{
Console.Write(chunk.Role + " > ");
}
message += chunk;
Console.Write(chunk);
}
Console.WriteLine();
// Append to history
history.AddUserMessage(request!);
history.AddAssistantMessage(message);
}
// </Chat>
}
}
@@ -0,0 +1,51 @@
// Copyright (c) Microsoft. All rights reserved.
namespace Examples;
public abstract class LearnBaseTest : BaseTest
{
protected List<string> SimulatedInputText = [];
protected int SimulatedInputTextIndex = 0;
protected LearnBaseTest(List<string> simulatedInputText, ITestOutputHelper output) : base(output)
{
SimulatedInputText = simulatedInputText;
}
protected LearnBaseTest(ITestOutputHelper output) : base(output)
{
}
/// <summary>
/// Simulates reading input strings from a user for the purpose of running tests.
/// </summary>
/// <returns>A simulate user input string, if available. Null otherwise.</returns>
public string? ReadLine()
{
if (SimulatedInputTextIndex < SimulatedInputText.Count)
{
return SimulatedInputText[SimulatedInputTextIndex++];
}
return null;
}
}
public static class BaseTestExtensions
{
/// <summary>
/// Simulates reading input strings from a user for the purpose of running tests.
/// </summary>
/// <returns>A simulate user input string, if available. Null otherwise.</returns>
public static string? ReadLine(this BaseTest baseTest)
{
var learnBaseTest = baseTest as LearnBaseTest;
if (learnBaseTest is not null)
{
return learnBaseTest.ReadLine();
}
return null;
}
}
@@ -0,0 +1,108 @@
// Copyright (c) Microsoft. All rights reserved.
using System.ComponentModel;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Connectors.OpenAI;
namespace Examples;
/// <summary>
/// This example shows how to create a plugin class and interact with as described at
/// https://learn.microsoft.com/semantic-kernel/overview/
/// This sample uses function calling, so it only works on models newer than 0613.
/// </summary>
public class Plugin(ITestOutputHelper output) : LearnBaseTest([
"Hello",
"Can you turn on the lights"], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Plugin ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
// Create kernel
// <KernelCreation>
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Plugins.AddFromType<LightPlugin>();
Kernel kernel = builder.Build();
// </KernelCreation>
// <Chat>
// Create chat history
var history = new ChatHistory();
// Get chat completion service
var chatCompletionService = kernel.GetRequiredService<IChatCompletionService>();
// Start the conversation
Console.Write("User > ");
string? userInput;
while ((userInput = Console.ReadLine()) is not null)
{
// Add user input
history.AddUserMessage(userInput);
// Enable auto function calling
OpenAIPromptExecutionSettings openAIPromptExecutionSettings = new()
{
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto()
};
// Get the response from the AI
var result = await chatCompletionService.GetChatMessageContentAsync(
history,
executionSettings: openAIPromptExecutionSettings,
kernel: kernel);
// Print the results
Console.WriteLine("Assistant > " + result);
// Add the message from the agent to the chat history
history.AddMessage(result.Role, result.Content ?? string.Empty);
// Get user input again
Console.Write("User > ");
}
// </Chat>
}
}
// <LightPlugin>
public class LightPlugin
{
public bool IsOn { get; set; } = false;
#pragma warning disable CA1024 // Use properties where appropriate
[KernelFunction]
[Description("Gets the state of the light.")]
public string GetState() => IsOn ? "on" : "off";
#pragma warning restore CA1024 // Use properties where appropriate
[KernelFunction]
[Description("Changes the state of the light.'")]
public string ChangeState(bool newState)
{
this.IsOn = newState;
var state = GetState();
// Print the state to the console
Console.WriteLine($"[Light is now {state}]");
return state;
}
}
// </LightPlugin>
@@ -0,0 +1,241 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
namespace Examples;
/// <summary>
/// This example demonstrates how to use prompts as described at
/// https://learn.microsoft.com/semantic-kernel/prompts/your-first-prompt
/// </summary>
public class Prompts(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Prompts ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
// <KernelCreation>
Kernel kernel = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey)
.Build();
// </KernelCreation>
// 0.0 Initial prompt
//////////////////////////////////////////////////////////////////////////////////
string request = "I want to send an email to the marketing team celebrating their recent milestone.";
string prompt = $"What is the intent of this request? {request}";
/* Uncomment this code to make this example interactive
// <InitialPrompt>
Console.Write("Your request: ");
string request = ReadLine()!;
string prompt = $"What is the intent of this request? {request}";
// </InitialPrompt>
*/
Console.WriteLine("0.0 Initial prompt");
// <InvokeInitialPrompt>
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// </InvokeInitialPrompt>
// 1.0 Make the prompt more specific
//////////////////////////////////////////////////////////////////////////////////
// <MoreSpecificPrompt>
prompt = @$"What is the intent of this request? {request}
You can choose between SendEmail, SendMessage, CompleteTask, CreateDocument.";
// </MoreSpecificPrompt>
Console.WriteLine("1.0 Make the prompt more specific");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 2.0 Add structure to the output with formatting
//////////////////////////////////////////////////////////////////////////////////
// <StructuredPrompt>
prompt = @$"Instructions: What is the intent of this request?
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument.
User Input: {request}
Intent: ";
// </StructuredPrompt>
Console.WriteLine("2.0 Add structure to the output with formatting");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 2.1 Add structure to the output with formatting (using Markdown and JSON)
//////////////////////////////////////////////////////////////////////////////////
// <FormattedPrompt>
prompt = $$"""
## Instructions
Provide the intent of the request using the following format:
```json
{
"intent": {intent}
}
```
## Choices
You can choose between the following intents:
```json
["SendEmail", "SendMessage", "CompleteTask", "CreateDocument"]
```
## User Input
The user input is:
```json
{
"request": "{{request}}"
}
```
## Intent
""";
// </FormattedPrompt>
Console.WriteLine("2.1 Add structure to the output with formatting (using Markdown and JSON)");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 3.0 Provide examples with few-shot prompting
//////////////////////////////////////////////////////////////////////////////////
// <FewShotPrompt>
prompt = @$"Instructions: What is the intent of this request?
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
User Input: {request}
Intent: ";
// </FewShotPrompt>
Console.WriteLine("3.0 Provide examples with few-shot prompting");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 4.0 Tell the AI what to do to avoid doing something wrong
//////////////////////////////////////////////////////////////////////////////////
// <AvoidPrompt>
prompt = $"""
Instructions: What is the intent of this request?
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
User Input: {request}
Intent:
""";
// </AvoidPrompt>
Console.WriteLine("4.0 Tell the AI what to do to avoid doing something wrong");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 5.0 Provide context to the AI
//////////////////////////////////////////////////////////////////////////////////
// <ContextPrompt>
string history = """
User input: I hate sending emails, no one ever reads them.
AI response: I'm sorry to hear that. Messages may be a better way to communicate.
""";
prompt = $"""
Instructions: What is the intent of this request?
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.
User Input: Can you send a very quick approval to the marketing team?
Intent: SendMessage
User Input: Can you send the full update to the marketing team?
Intent: SendEmail
{history}
User Input: {request}
Intent:
""";
// </ContextPrompt>
Console.WriteLine("5.0 Provide context to the AI");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 6.0 Using message roles in chat completion prompts
//////////////////////////////////////////////////////////////////////////////////
// <RolePrompt>
history = """
<message role="user">I hate sending emails, no one ever reads them.</message>
<message role="assistant">I'm sorry to hear that. Messages may be a better way to communicate.</message>
""";
prompt = $"""
<message role="system">Instructions: What is the intent of this request?
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.</message>
<message role="user">Can you send a very quick approval to the marketing team?</message>
<message role="system">Intent:</message>
<message role="assistant">SendMessage</message>
<message role="user">Can you send the full update to the marketing team?</message>
<message role="system">Intent:</message>
<message role="assistant">SendEmail</message>
{history}
<message role="user">{request}</message>
<message role="system">Intent:</message>
""";
// </RolePrompt>
Console.WriteLine("6.0 Using message roles in chat completion prompts");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
// 7.0 Give your AI words of encouragement
//////////////////////////////////////////////////////////////////////////////////
// <BonusPrompt>
history = """
<message role="user">I hate sending emails, no one ever reads them.</message>
<message role="assistant">I'm sorry to hear that. Messages may be a better way to communicate.</message>
""";
prompt = $"""
<message role="system">Instructions: What is the intent of this request?
If you don't know the intent, don't guess; instead respond with "Unknown".
Choices: SendEmail, SendMessage, CompleteTask, CreateDocument, Unknown.
Bonus: You'll get $20 if you get this right.</message>
<message role="user">Can you send a very quick approval to the marketing team?</message>
<message role="system">Intent:</message>
<message role="assistant">SendMessage</message>
<message role="user">Can you send the full update to the marketing team?</message>
<message role="system">Intent:</message>
<message role="assistant">SendEmail</message>
{history}
<message role="user">{request}</message>
<message role="system">Intent:</message>
""";
// </BonusPrompt>
Console.WriteLine("7.0 Give your AI words of encouragement");
Console.WriteLine(await kernel.InvokePromptAsync(prompt));
}
}
@@ -0,0 +1,4 @@
# Semantic Kernel Microsoft Learn Documentation examples
This project contains a collection of examples used in documentation on [learn.microsoft.com](https://learn.microsoft.com/).
@@ -0,0 +1,125 @@
// Copyright (c) Microsoft. All rights reserved.
using System.Reflection;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.Plugins.Core;
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
namespace Examples;
/// <summary>
/// This example demonstrates how to serialize prompts as described at
/// https://learn.microsoft.com/semantic-kernel/prompts/saving-prompts-as-files
/// </summary>
public class SerializingPrompts(ITestOutputHelper output) : LearnBaseTest([
"Can you send an approval to the marketing team?",
"That is all, thanks."], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Serializing Prompts ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Plugins.AddFromType<ConversationSummaryPlugin>();
Kernel kernel = builder.Build();
// Load prompts
var prompts = kernel.CreatePluginFromPromptDirectory("./../../../Plugins/Prompts");
// Load prompt from YAML
using StreamReader reader = new(Assembly.GetExecutingAssembly().GetManifestResourceStream("Resources.getIntent.prompt.yaml")!);
KernelFunction getIntent = kernel.CreateFunctionFromPromptYaml(
await reader.ReadToEndAsync(),
promptTemplateFactory: new HandlebarsPromptTemplateFactory()
);
// Create choices
List<string> choices = ["ContinueConversation", "EndConversation"];
// Create few-shot examples
List<ChatHistory> fewShotExamples =
[
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
],
[
new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
]
];
// Create chat history
ChatHistory history = [];
// Start the chat loop
Console.Write("User > ");
string? userInput;
while ((userInput = Console.ReadLine()) is not null)
{
// Invoke handlebars prompt
var intent = await kernel.InvokeAsync(
getIntent,
new()
{
{ "request", userInput },
{ "choices", choices },
{ "history", history },
{ "fewShotExamples", fewShotExamples }
}
);
// End the chat if the intent is "Stop"
if (intent.ToString() == "EndConversation")
{
break;
}
// Get chat response
var chatResult = kernel.InvokeStreamingAsync<StreamingChatMessageContent>(
prompts["chat"],
new()
{
{ "request", userInput },
{ "history", string.Join("\n", history.Select(x => x.Role + ": " + x.Content)) }
}
);
// Stream the response
string message = "";
await foreach (var chunk in chatResult)
{
if (chunk.Role.HasValue)
{
Console.Write(chunk.Role + " > ");
}
message += chunk;
Console.Write(chunk);
}
Console.WriteLine();
// Append to history
history.AddUserMessage(userInput);
history.AddAssistantMessage(message);
// Get user input again
Console.Write("User > ");
}
}
}
@@ -0,0 +1,144 @@
// Copyright (c) Microsoft. All rights reserved.
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.ChatCompletion;
using Microsoft.SemanticKernel.PromptTemplates.Handlebars;
namespace Examples;
/// <summary>
/// This example demonstrates how to templatize prompts as described at
/// https://learn.microsoft.com/semantic-kernel/prompts/templatizing-prompts
/// </summary>
public class Templates(ITestOutputHelper output) : LearnBaseTest([
"Can you send an approval to the marketing team?",
"That is all, thanks."], output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Templates ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
Kernel kernel = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey)
.Build();
// Create a Semantic Kernel template for chat
var chat = kernel.CreateFunctionFromPrompt(
@"{{$history}}
User: {{$request}}
Assistant: ");
// Create choices
List<string> choices = ["ContinueConversation", "EndConversation"];
// Create few-shot examples
List<ChatHistory> fewShotExamples =
[
[
new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation")
],
[
new ChatMessageContent(AuthorRole.User, "Thanks, I'm done for now"),
new ChatMessageContent(AuthorRole.System, "Intent:"),
new ChatMessageContent(AuthorRole.Assistant, "EndConversation")
]
];
// Create handlebars template for intent
var getIntent = kernel.CreateFunctionFromPrompt(
new()
{
Template = """
<message role="system">Instructions: What is the intent of this request?
Do not explain the reasoning, just reply back with the intent. If you are unsure, reply with {{choices.[0]}}.
Choices: {{choices}}.</message>
{{#each fewShotExamples}}
{{#each this}}
<message role="{{role}}">{{content}}</message>
{{/each}}
{{/each}}
{{#each chatHistory}}
<message role="{{role}}">{{content}}</message>
{{/each}}
<message role="user">{{request}}</message>
<message role="system">Intent:</message>
""",
TemplateFormat = "handlebars"
},
new HandlebarsPromptTemplateFactory()
);
ChatHistory history = [];
// Start the chat loop
while (true)
{
// Get user input
Console.Write("User > ");
var request = Console.ReadLine();
// Invoke prompt
var intent = await kernel.InvokeAsync(
getIntent,
new()
{
{ "request", request },
{ "choices", choices },
{ "history", history },
{ "fewShotExamples", fewShotExamples }
}
);
// End the chat if the intent is "Stop"
if (intent.ToString() == "EndConversation")
{
break;
}
// Get chat response
var chatResult = kernel.InvokeStreamingAsync<StreamingChatMessageContent>(
chat,
new()
{
{ "request", request },
{ "history", string.Join("\n", history.Select(x => x.Role + ": " + x.Content)) }
}
);
// Stream the response
string message = "";
await foreach (var chunk in chatResult)
{
if (chunk.Role.HasValue)
{
Console.Write(chunk.Role + " > ");
}
message += chunk;
Console.Write(chunk);
}
Console.WriteLine();
// Append to history
history.AddUserMessage(request!);
history.AddAssistantMessage(message);
}
}
}
@@ -0,0 +1,59 @@
// Copyright (c) Microsoft. All rights reserved.
// <NecessaryPackages>
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Plugins.Core;
// </NecessaryPackages>
namespace Examples;
/// <summary>
/// This example demonstrates how to interact with the kernel as described at
/// https://learn.microsoft.com/semantic-kernel/agents/kernel
/// </summary>
public class UsingTheKernel(ITestOutputHelper output) : BaseTest(output)
{
[Fact]
public async Task RunAsync()
{
Console.WriteLine("======== Kernel ========");
string? endpoint = TestConfiguration.AzureOpenAI.Endpoint;
string? modelId = TestConfiguration.AzureOpenAI.ChatModelId;
string? apiKey = TestConfiguration.AzureOpenAI.ApiKey;
if (endpoint is null || modelId is null || apiKey is null)
{
Console.WriteLine("Azure OpenAI credentials not found. Skipping example.");
return;
}
// Create a kernel with a logger and Azure OpenAI chat completion service
// <KernelCreation>
var builder = Kernel.CreateBuilder()
.AddAzureOpenAIChatCompletion(modelId, endpoint, apiKey);
builder.Services.AddLogging(c => c.AddDebug().SetMinimumLevel(LogLevel.Trace));
builder.Plugins.AddFromType<TimePlugin>();
builder.Plugins.AddFromPromptDirectory("./../../../Plugins/WriterPlugin");
Kernel kernel = builder.Build();
// </KernelCreation>
// Get the current time
// <InvokeUtcNow>
var currentTime = await kernel.InvokeAsync("TimePlugin", "UtcNow");
Console.WriteLine(currentTime);
// </InvokeUtcNow>
// Write a poem with the WriterPlugin.ShortPoem function using the current time as input
// <InvokeShortPoem>
var poemResult = await kernel.InvokeAsync("WriterPlugin", "ShortPoem", new()
{
{ "input", currentTime }
});
Console.WriteLine(poemResult);
// </InvokeShortPoem>
}
}