-
Notifications
You must be signed in to change notification settings - Fork 4.1k
.Net: Concept sample showing how to switch deployments based on functions being called #10480
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
markwallace-microsoft
merged 15 commits into
microsoft:main
from
markwallace-microsoft:users/markwallace/concept_depoymentswitch
Feb 27, 2025
Merged
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
267babd
Concept sample showing how to switch deployments based on functions b…
markwallace-microsoft 903ca5d
Fix warning
markwallace-microsoft c3c3bbb
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft 4feb829
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft 25c16c6
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft c6b2fb8
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft 2d22fe5
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft e0a4760
Merge branch 'main' into users/markwallace/concept_depoymentswitch
markwallace-microsoft f3fe7e9
Update dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
markwallace-microsoft 2b6c16f
Merge branch 'main' into users/markwallace/concept_depoymentswitch
markwallace-microsoft 4c89e14
Merge branch 'main' into users/markwallace/concept_depoymentswitch
markwallace-microsoft 4a9ee00
Fix formatting problem
markwallace-microsoft 418d16f
Merge branch 'main' into users/markwallace/concept_depoymentswitch
markwallace-microsoft 638d3ed
Merge branch 'main' into users/markwallace/concept_depoymentswitch
markwallace-microsoft 2887a07
Switch to using execution settings
markwallace-microsoft File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
116 changes: 116 additions & 0 deletions
116
dotnet/samples/Concepts/Filtering/AzureOpenAI_DeploymentSwitch.cs
This file contains hidden or 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,116 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using Azure.Identity; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.SemanticKernel; | ||
using Microsoft.SemanticKernel.ChatCompletion; | ||
using Microsoft.SemanticKernel.Connectors.OpenAI; | ||
|
||
namespace Filtering; | ||
|
||
/// <summary> | ||
/// This sample shows how to switch between Azure OpenAI deployments based on the functions that are being called. | ||
/// This can be useful if semantic caching is enabled and you want to switch to a different deployment based on the functions that are being called. | ||
/// </summary> | ||
public class AzureOpenAI_DeploymentSwitch(ITestOutputHelper output) : BaseTest(output) | ||
{ | ||
[Fact] | ||
public async Task DeploymentSwitchAsync() | ||
{ | ||
Assert.NotNull(TestConfiguration.AzureOpenAI.ChatDeploymentName); | ||
Assert.NotNull(TestConfiguration.AzureOpenAI.Endpoint); | ||
|
||
// Create a logging handler to output HTTP requests and responses | ||
using var httpHandler = new HttpClientHandler(); | ||
using var loggingHandler = new LoggingHandler(httpHandler, this.Output); | ||
using var httpClient = new HttpClient(loggingHandler); | ||
|
||
// Create KernelBuilder with an auto function invocation filter | ||
var kernelBuilder = Kernel.CreateBuilder(); | ||
kernelBuilder.Services.AddSingleton<IAutoFunctionInvocationFilter>(new AutoFunctionInvocationFilter(this.Output)); | ||
|
||
// Define the endpoints for the two Azure OpenAI services | ||
var endpoint1 = "https://lightspeed-team-shared-openai-eastus.openai.azure.com/"; | ||
var endpoint2 = "https://lightspeed-team-shared-openai-swedencentral.openai.azure.com/"; | ||
|
||
// Add Azure OpenAI chat completion services | ||
kernelBuilder.AddAzureOpenAIChatCompletion( | ||
serviceId: "eastus", | ||
deploymentName: "gpt-4o-mini", | ||
endpoint: endpoint1, | ||
credentials: new AzureCliCredential(), | ||
httpClient: httpClient, | ||
modelId: TestConfiguration.AzureOpenAI.ChatModelId); | ||
kernelBuilder.AddAzureOpenAIChatCompletion( | ||
serviceId: "swedencentral", | ||
deploymentName: "gpt-4o", | ||
endpoint: endpoint2, | ||
credentials: new AzureCliCredential(), | ||
httpClient: httpClient, | ||
modelId: TestConfiguration.AzureOpenAI.ChatModelId); | ||
|
||
var kernel = kernelBuilder.Build(); | ||
markwallace-microsoft marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
kernel.ImportPluginFromFunctions("HelperFunctions", | ||
[ | ||
kernel.CreateFunctionFromMethod(() => "Brown", "GetEyeColor", "Retrieves eye color for the current user."), | ||
kernel.CreateFunctionFromMethod(() => DateTime.UtcNow.ToString("R"), "GetCurrentDateTimeInUtc", "Retrieves the current date time in UTC."), | ||
]); | ||
|
||
OpenAIPromptExecutionSettings settings = new() | ||
{ | ||
ServiceId = "swedencentral", | ||
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() | ||
}; | ||
|
||
var reply = await kernel.InvokePromptAsync("What time is it and what is my eye color and what time is it?", new(settings)); | ||
|
||
Console.WriteLine(reply); | ||
} | ||
|
||
private sealed class AutoFunctionInvocationFilter(ITestOutputHelper output) : IAutoFunctionInvocationFilter | ||
{ | ||
public async Task OnAutoFunctionInvocationAsync(AutoFunctionInvocationContext context, Func<AutoFunctionInvocationContext, Task> next) | ||
{ | ||
var kernel = context.Kernel; | ||
var chatHistory = context.ChatHistory; | ||
var executionSettings = context.ExecutionSettings; | ||
var functionCalls = FunctionCallContent.GetFunctionCalls(context.ChatHistory.Last()); | ||
|
||
if (executionSettings is not null && "swedencentral".Equals(executionSettings.ServiceId, StringComparison.Ordinal)) | ||
{ | ||
bool includesGetEyeColor = functionCalls.Any(fc => fc.FunctionName.Equals("GetEyeColor", StringComparison.Ordinal)); | ||
|
||
// For the "GetEyeColor" function, switch to a different deployment. | ||
// If the function is not present in the collection of function calls, proceed with the request as usual. | ||
if (!includesGetEyeColor) | ||
markwallace-microsoft marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
await next(context); | ||
} | ||
else | ||
{ | ||
output.WriteLine("Switching to use eastus deployment"); | ||
|
||
chatHistory.RemoveAt(chatHistory.Count - 1); | ||
|
||
IChatCompletionService chatCompletionService = kernel.Services.GetRequiredKeyedService<IChatCompletionService>("eastus"); | ||
|
||
OpenAIPromptExecutionSettings settings = new() | ||
{ | ||
ServiceId = "eastus", | ||
FunctionChoiceBehavior = FunctionChoiceBehavior.Auto() | ||
}; | ||
|
||
var chatContent = await chatCompletionService.GetChatMessageContentAsync(chatHistory, settings, context.Kernel); | ||
|
||
context.Result = new FunctionResult(context.Result, chatContent); | ||
context.Terminate = true; | ||
} | ||
} | ||
else | ||
{ | ||
await next(context); | ||
} | ||
} | ||
} | ||
} |
This file contains hidden or 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
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.