-
Notifications
You must be signed in to change notification settings - Fork 4k
.Net: Hybrid model orchestration sample #10503
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
SergeyMenshykh
merged 10 commits into
microsoft:main
from
SergeyMenshykh:hybrid-ai-model-sample
Feb 12, 2025
Merged
Changes from 6 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
d7b906a
add sample for fallback chat client
SergeyMenshykh 76dad58
Merge branch 'main' into hybrid-ai-model-sample
SergeyMenshykh 82a1f32
fix formatting issue
SergeyMenshykh 871bff9
Merge branch 'hybrid-ai-model-sample' of https://github.com/SergeyMen…
SergeyMenshykh 4dcb9ec
fix nuget package issues
SergeyMenshykh 2f49f86
fix badly formatted XML comment
SergeyMenshykh d759e2f
address pr review comments
SergeyMenshykh 27612a5
Merge branch 'main' into hybrid-ai-model-sample
SergeyMenshykh be7d09a
reference latest version of the Microsoft.Extensions.AI.OpenAI nuget …
SergeyMenshykh 02c860c
Merge branch 'main' into hybrid-ai-model-sample
SergeyMenshykh 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
264 changes: 264 additions & 0 deletions
264
dotnet/samples/Concepts/ChatCompletion/Hybrid/HybridCompletion_Fallback.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,264 @@ | ||
// Copyright (c) Microsoft. All rights reserved. | ||
|
||
using System.ClientModel; | ||
using System.ClientModel.Primitives; | ||
using System.ComponentModel; | ||
using System.Net; | ||
using System.Runtime.CompilerServices; | ||
using Azure.AI.OpenAI; | ||
using Azure.Identity; | ||
using Microsoft.Extensions.AI; | ||
using Microsoft.SemanticKernel; | ||
|
||
namespace ChatCompletion; | ||
|
||
/// <summary> | ||
/// This example demonstrates how an AI application can use code to attempt inference with the first available chat client in the list, falling back to the next client if the previous one fails. | ||
/// The <see cref="FallbackChatClient"/> class handles all the fallback complexities, abstracting them away from the application code. | ||
/// Since the <see cref="FallbackChatClient"/> class implements the <see cref="IChatClient"/> interface, the chat client used for inference the application can be easily replaced with the <see cref="FallbackChatClient"/>. | ||
/// </summary> | ||
/// <remarks> | ||
/// The <see cref="FallbackChatClient"/> class is useful when an application utilizes multiple models and needs to switch between them based on the situation. | ||
/// For example, the application may use a cloud-based model by default and seamlessly fall back to a local model when the cloud model is unavailable (e.g., in offline mode), and vice versa. | ||
/// Additionally, the application can enhance resilience by employing several cloud models, falling back to the next one if the previous model fails. | ||
/// </remarks> | ||
public class HybridCompletion_Fallback(ITestOutputHelper output) : BaseTest(output) | ||
SergeyMenshykh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
/// <summary> | ||
/// This example demonstrates how to perform completion using the <see cref="FallbackChatClient"/>, which falls back to an available model when the primary model is unavailable. | ||
/// </summary> | ||
[Fact] | ||
public async Task FallbackToAvailableModelAsync() | ||
{ | ||
// Create an unavailable chat client that fails with 503 Service Unavailable HTTP status code | ||
IChatClient unavailableChatClient = CreateUnavailableOpenAIChatClient(); | ||
|
||
// Create a cloud available chat client | ||
IChatClient availableChatClient = CreateAzureOpenAIChatClient(); | ||
|
||
// Create a fallback chat client that will fallback to the available chat client when unavailable chat client fails | ||
IChatClient fallbackChatClient = new FallbackChatClient([unavailableChatClient, availableChatClient]); | ||
|
||
ChatOptions chatOptions = new() { Tools = [AIFunctionFactory.Create(GetWeather, new AIFunctionFactoryCreateOptions { Name = "GetWeather" })] }; | ||
|
||
var result = await fallbackChatClient.CompleteAsync("Do I need an umbrella?", chatOptions); | ||
|
||
Output.WriteLine(result); | ||
|
||
[Description("Gets the weather")] | ||
string GetWeather() => "It's sunny"; | ||
} | ||
|
||
/// <summary> | ||
/// This example demonstrates how to perform streaming completion using the <see cref="FallbackChatClient"/>, which falls back to an available model when the primary model is unavailable. | ||
/// </summary> | ||
[Fact] | ||
public async Task FallbackToAvailableModelStreamingAsync() | ||
{ | ||
// Create an unavailable chat client that fails with 503 Service Unavailable HTTP status code | ||
IChatClient unavailableChatClient = CreateUnavailableOpenAIChatClient(); | ||
|
||
// Create a cloud available chat client | ||
IChatClient availableChatClient = CreateAzureOpenAIChatClient(); | ||
|
||
// Create a fallback chat client that will fallback to the available chat client when unavailable chat client fails | ||
IChatClient fallbackChatClient = new FallbackChatClient([unavailableChatClient, availableChatClient]); | ||
|
||
ChatOptions chatOptions = new() { Tools = [AIFunctionFactory.Create(GetWeather, new AIFunctionFactoryCreateOptions { Name = "GetWeather" })] }; | ||
|
||
var result = fallbackChatClient.CompleteStreamingAsync("Do I need an umbrella?", chatOptions); | ||
|
||
await foreach (var update in result) | ||
{ | ||
Output.WriteLine(update); | ||
} | ||
|
||
[Description("Gets the weather")] | ||
string GetWeather() => "It's sunny"; | ||
} | ||
|
||
private static IChatClient CreateUnavailableOpenAIChatClient() | ||
{ | ||
AzureOpenAIClientOptions options = new() | ||
{ | ||
Transport = new HttpClientPipelineTransport( | ||
new HttpClient | ||
( | ||
new StubHandler(new HttpClientHandler(), async (response) => { response.StatusCode = System.Net.HttpStatusCode.ServiceUnavailable; }) | ||
) | ||
) | ||
}; | ||
|
||
IChatClient openAiClient = new AzureOpenAIClient(new Uri(TestConfiguration.AzureOpenAI.Endpoint), new AzureCliCredential(), options).AsChatClient(TestConfiguration.AzureOpenAI.ChatDeploymentName); | ||
|
||
return new ChatClientBuilder(openAiClient) | ||
.UseFunctionInvocation() | ||
.Build(); | ||
} | ||
|
||
private static IChatClient CreateAzureOpenAIChatClient() | ||
{ | ||
IChatClient chatClient = new AzureOpenAIClient(new Uri(TestConfiguration.AzureOpenAI.Endpoint), new AzureCliCredential()).AsChatClient(TestConfiguration.AzureOpenAI.ChatDeploymentName); | ||
|
||
return new ChatClientBuilder(chatClient) | ||
.UseFunctionInvocation() | ||
.Build(); | ||
} | ||
|
||
protected sealed class StubHandler(HttpMessageHandler innerHandler, Func<HttpResponseMessage, Task> handler) : DelegatingHandler(innerHandler) | ||
{ | ||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) | ||
{ | ||
var result = await base.SendAsync(request, cancellationToken); | ||
|
||
await handler(result); | ||
|
||
return result; | ||
} | ||
} | ||
} | ||
|
||
/// <summary> | ||
/// Represents a chat client that performs inference using the first available chat client in the list, falling back to the next one if the previous client fails. | ||
/// </summary> | ||
internal sealed class FallbackChatClient : IChatClient | ||
SergeyMenshykh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
private readonly IEnumerable<IChatClient> _chatClients; | ||
private static readonly List<HttpStatusCode> s_defaultFallbackStatusCodes = new() | ||
{ | ||
HttpStatusCode.InternalServerError, | ||
HttpStatusCode.NotImplemented, | ||
HttpStatusCode.BadGateway, | ||
HttpStatusCode.ServiceUnavailable, | ||
HttpStatusCode.GatewayTimeout | ||
}; | ||
|
||
/// <summary> | ||
/// Initializes a new instance of the <see cref="FallbackChatClient"/> class. | ||
/// </summary> | ||
/// <param name="chatClients">The chat clients to fallback to.</param> | ||
public FallbackChatClient(IEnumerable<IChatClient> chatClients) | ||
{ | ||
this._chatClients = chatClients?.Any() == true ? chatClients : throw new ArgumentException("At least one chat client must be provided.", nameof(chatClients)); | ||
} | ||
|
||
/// <summary> | ||
/// Gets or sets the HTTP status codes that will trigger the fallback to the next chat client. | ||
/// </summary> | ||
public List<HttpStatusCode>? FallbackStatusCodes { get; set; } | ||
|
||
/// <inheritdoc/> | ||
public ChatClientMetadata Metadata => new(); | ||
|
||
/// <inheritdoc/> | ||
public async Task<Microsoft.Extensions.AI.ChatCompletion> CompleteAsync(IList<ChatMessage> chatMessages, ChatOptions? options = null, CancellationToken cancellationToken = default) | ||
{ | ||
for (int i = 0; i < this._chatClients.Count(); i++) | ||
SergeyMenshykh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
var chatClient = this._chatClients.ElementAt(i); | ||
|
||
try | ||
{ | ||
return await chatClient.CompleteAsync(chatMessages, options, cancellationToken).ConfigureAwait(false); | ||
} | ||
catch (Exception ex) | ||
{ | ||
if (this.ShouldFallbackToNextClient(ex, i, this._chatClients.Count())) | ||
SergeyMenshykh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{ | ||
continue; | ||
} | ||
|
||
throw; | ||
} | ||
} | ||
|
||
// If all clients fail, throw an exception or return a default value | ||
throw new InvalidOperationException("Neither of the chat clients could complete the inference."); | ||
} | ||
|
||
/// <inheritdoc/> | ||
public async IAsyncEnumerable<StreamingChatCompletionUpdate> CompleteStreamingAsync(IList<ChatMessage> chatMessages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
{ | ||
for (int i = 0; i < this._chatClients.Count(); i++) | ||
{ | ||
var chatClient = this._chatClients.ElementAt(i); | ||
|
||
IAsyncEnumerable<StreamingChatCompletionUpdate> completionStream = chatClient.CompleteStreamingAsync(chatMessages, options, cancellationToken); | ||
|
||
ConfiguredCancelableAsyncEnumerable<StreamingChatCompletionUpdate>.Enumerator enumerator = completionStream.ConfigureAwait(false).GetAsyncEnumerator(); | ||
|
||
try | ||
{ | ||
try | ||
{ | ||
// Move to the first update to reveal any exceptions. | ||
if (!await enumerator.MoveNextAsync()) | ||
{ | ||
yield break; | ||
} | ||
} | ||
catch (Exception ex) | ||
{ | ||
if (this.ShouldFallbackToNextClient(ex, i, this._chatClients.Count())) | ||
{ | ||
continue; | ||
} | ||
|
||
throw; | ||
} | ||
|
||
// Yield the first update. | ||
yield return enumerator.Current; | ||
|
||
// Yield the rest of the updates. | ||
while (await enumerator.MoveNextAsync()) | ||
{ | ||
yield return enumerator.Current; | ||
} | ||
|
||
// The stream has ended so break the while loop. | ||
break; | ||
} | ||
finally | ||
{ | ||
await enumerator.DisposeAsync(); | ||
} | ||
} | ||
} | ||
|
||
private bool ShouldFallbackToNextClient(Exception ex, int clientIndex, int numberOfClients) | ||
{ | ||
// If the exception is thrown by the last client then don't fallback. | ||
if (clientIndex == numberOfClients - 1) | ||
{ | ||
return false; | ||
} | ||
|
||
HttpStatusCode? statusCode = ex switch | ||
{ | ||
HttpOperationException operationException => operationException.StatusCode, | ||
HttpRequestException httpRequestException => httpRequestException.StatusCode, | ||
ClientResultException clientResultException => (HttpStatusCode?)clientResultException.Status, | ||
_ => throw new InvalidOperationException($"Unsupported exception type: {ex.GetType()}."), | ||
}; | ||
|
||
if (statusCode is null) | ||
{ | ||
throw new InvalidOperationException("The exception does not contain an HTTP status code."); | ||
} | ||
|
||
return (this.FallbackStatusCodes ?? s_defaultFallbackStatusCodes).Contains(statusCode!.Value); | ||
} | ||
|
||
/// <inheritdoc/> | ||
public void Dispose() | ||
{ | ||
// We don't own the chat clients so we don't dispose them. | ||
} | ||
|
||
/// <inheritdoc/> | ||
public object? GetService(Type serviceType, object? serviceKey = null) | ||
{ | ||
return null; | ||
} | ||
} |
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.