-
Notifications
You must be signed in to change notification settings - Fork 885
Add extensible chat client routing #7662
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
Open
joshuajyue
wants to merge
17
commits into
dotnet:main
Choose a base branch
from
joshuajyue:routing-behaviors
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
17 commits
Select commit
Hold shift + click to select a range
bd114df
Add extensible chat client routing
joshuajyue 665abe4
Potential fix for pull request finding
joshuajyue f72f3d7
Address routing review feedback
joshuajyue 26d7a5c
Credit semantic-router inspiration
joshuajyue bcff6d3
Handle streaming Current getter failures
joshuajyue acc450e
Avoid context capture in failover routing
joshuajyue d4b3a90
Merge branch 'main' into routing-behaviors
joshuajyue 0abbfd1
Address routing API review feedback
joshuajyue ea929cc
Clarify routing context and attempt reporting
joshuajyue 53f6639
Align routing message and selection semantics
joshuajyue a576773
Simplify ordered failover state
joshuajyue 87d382d
Isolate routing attempt options
joshuajyue 72598e1
Clarify routing identity semantics
joshuajyue 8b79ae4
Address routing review feedback
joshuajyue 938e0b9
Refine routing tests
joshuajyue b8839c1
Merge branch 'main' into routing-behaviors
joshuajyue 78ae023
Add per-attempt routing selections
joshuajyue 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
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
127 changes: 127 additions & 0 deletions
127
src/Libraries/Microsoft.Extensions.AI.Abstractions/ChatRouting/RoutingChatClient.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,127 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Runtime.CompilerServices; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Shared.DiagnosticIds; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary> | ||
| /// Provides a template for an <see cref="IChatClient"/> that selects and invokes another chat client. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Derived classes implement <see cref="SelectClientAsync"/> to supply one selection for each request. The selected | ||
| /// client is invoked once with the selected options, and its response or failure is propagated to the caller. | ||
| /// </remarks> | ||
| [Experimental(DiagnosticIds.Experiments.AIRoutingChat, UrlFormat = DiagnosticIds.UrlFormat)] | ||
| public abstract class RoutingChatClient : IChatClient | ||
| { | ||
| /// <summary>Creates a routing client that selects one client and its options for each request.</summary> | ||
| /// <param name="selector">The callback that produces the selection to invoke.</param> | ||
| /// <returns>A routing client that uses <paramref name="selector"/>.</returns> | ||
| /// <remarks>The selected clients are caller-owned and are not disposed by the returned routing client.</remarks> | ||
| /// <exception cref="ArgumentNullException"><paramref name="selector"/> is <see langword="null"/>.</exception> | ||
| public static RoutingChatClient Create( | ||
| Func<RoutingContext, CancellationToken, ValueTask<RoutingSelection>> selector) | ||
| { | ||
| _ = Throw.IfNull(selector); | ||
|
|
||
| return new CallbackRoutingChatClient(selector); | ||
| } | ||
|
|
||
| /// <summary>Selects the client and complete options to use for the request.</summary> | ||
| /// <param name="context">The request-specific inputs.</param> | ||
| /// <param name="cancellationToken">The cancellation token supplied for the request.</param> | ||
| /// <returns>The selection to invoke.</returns> | ||
| /// <remarks> | ||
| /// The returned <see cref="RoutingSelection.ChatOptions"/> are complete attempt options, not an overlay. | ||
| /// Implementations may clone <see cref="RoutingContext.ChatOptions"/> and adjust the clone for the selected | ||
| /// attempt. Exceptions from this method propagate to the caller. | ||
| /// </remarks> | ||
| protected abstract ValueTask<RoutingSelection> SelectClientAsync( | ||
| RoutingContext context, | ||
| CancellationToken cancellationToken); | ||
|
|
||
| /// <inheritdoc/> | ||
| public virtual async Task<ChatResponse> GetResponseAsync( | ||
| IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default) | ||
| { | ||
| _ = Throw.IfNull(messages); | ||
|
|
||
| var context = new RoutingContext(messages, options); | ||
| RoutingSelection selection = await SelectClientAsync(context, cancellationToken).ConfigureAwait(false) ?? | ||
| throw new InvalidOperationException($"{nameof(SelectClientAsync)} returned null."); | ||
|
|
||
| return await selection.Client.GetResponseAsync( | ||
| context.Messages, | ||
| selection.ChatOptions, | ||
| cancellationToken).ConfigureAwait(false); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public virtual async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync( | ||
| IEnumerable<ChatMessage> messages, ChatOptions? options = null, | ||
| [EnumeratorCancellation] CancellationToken cancellationToken = default) | ||
| { | ||
| _ = Throw.IfNull(messages); | ||
|
|
||
| var context = new RoutingContext(messages, options); | ||
| RoutingSelection selection = await SelectClientAsync(context, cancellationToken).ConfigureAwait(false) ?? | ||
| throw new InvalidOperationException($"{nameof(SelectClientAsync)} returned null."); | ||
|
|
||
| await foreach (ChatResponseUpdate update in | ||
| selection.Client.GetStreamingResponseAsync( | ||
| context.Messages, | ||
| selection.ChatOptions, | ||
| cancellationToken) | ||
| .WithCancellation(cancellationToken) | ||
| .ConfigureAwait(false)) | ||
| { | ||
| yield return update; | ||
| } | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public virtual object? GetService(Type serviceType, object? serviceKey = null) | ||
| { | ||
| _ = Throw.IfNull(serviceType); | ||
|
|
||
| return serviceKey is null && serviceType.IsInstanceOfType(this) ? this : null; | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public void Dispose() | ||
| { | ||
| Dispose(disposing: true); | ||
| GC.SuppressFinalize(this); | ||
| } | ||
|
|
||
| /// <summary>Provides a mechanism for releasing resources owned by the derived instance.</summary> | ||
| /// <param name="disposing"><see langword="true"/> when called from <see cref="Dispose()"/>.</param> | ||
| /// <remarks>The default implementation performs no operation.</remarks> | ||
| protected virtual void Dispose(bool disposing) | ||
| { | ||
| } | ||
|
|
||
| private sealed class CallbackRoutingChatClient : RoutingChatClient | ||
| { | ||
| private readonly Func<RoutingContext, CancellationToken, ValueTask<RoutingSelection>> _selector; | ||
|
|
||
| public CallbackRoutingChatClient( | ||
| Func<RoutingContext, CancellationToken, ValueTask<RoutingSelection>> selector) | ||
| { | ||
| _selector = selector; | ||
| } | ||
|
|
||
| protected override ValueTask<RoutingSelection> SelectClientAsync( | ||
| RoutingContext context, | ||
| CancellationToken cancellationToken) => | ||
| _selector(context, cancellationToken); | ||
| } | ||
| } | ||
49 changes: 49 additions & 0 deletions
49
src/Libraries/Microsoft.Extensions.AI.Abstractions/ChatRouting/RoutingContext.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,49 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.Shared.DiagnosticIds; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary>Provides request-specific inputs to a <see cref="RoutingChatClient"/>.</summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// One context is created for each call to <see cref="IChatClient.GetResponseAsync"/> and for each enumeration | ||
| /// started from the sequence returned by <see cref="IChatClient.GetStreamingResponseAsync"/>. | ||
| /// </para> | ||
| /// <para> | ||
| /// <see cref="ChatOptions"/> is cloned when the context is created and represents the request baseline. Selectors can | ||
| /// clone and modify it to produce complete attempt options through <see cref="RoutingSelection"/>. | ||
| /// </para> | ||
| /// </remarks> | ||
| [Experimental(DiagnosticIds.Experiments.AIRoutingChat, UrlFormat = DiagnosticIds.UrlFormat)] | ||
| public class RoutingContext | ||
| { | ||
| /// <summary>Initializes a new instance of the <see cref="RoutingContext"/> class.</summary> | ||
| /// <param name="messages">The messages to route.</param> | ||
| /// <param name="chatOptions">The options associated with this context.</param> | ||
| public RoutingContext( | ||
| IEnumerable<ChatMessage> messages, | ||
| ChatOptions? chatOptions) | ||
| { | ||
| _ = Throw.IfNull(messages); | ||
|
|
||
| Messages = messages; | ||
| ChatOptions = chatOptions?.Clone(); | ||
| } | ||
|
|
||
| /// <summary>Gets the messages supplied to client selection and the selected client.</summary> | ||
| /// <remarks> | ||
| /// Selection and failover may enumerate this sequence multiple times. Callers should supply a repeatable sequence. | ||
| /// </remarks> | ||
| public IEnumerable<ChatMessage> Messages { get; } | ||
|
|
||
| /// <summary>Gets the request options supplied to client selection.</summary> | ||
| /// <remarks> | ||
| /// This is a clone of the caller's options. Selectors should clone it before applying attempt-specific changes. | ||
| /// </remarks> | ||
| public ChatOptions? ChatOptions { get; } | ||
| } |
35 changes: 35 additions & 0 deletions
35
src/Libraries/Microsoft.Extensions.AI.Abstractions/ChatRouting/RoutingSelection.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,35 @@ | ||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using System; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using Microsoft.Shared.DiagnosticIds; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary>Represents the client and complete options selected for one routing attempt.</summary> | ||
| /// <remarks> | ||
| /// The exact <see cref="Client"/> instance represents the routing identity. <see cref="ChatOptions"/> are ephemeral | ||
| /// attempt data and do not participate in that identity. The selected client may further transform the options. | ||
| /// </remarks> | ||
| [Experimental(DiagnosticIds.Experiments.AIRoutingChat, UrlFormat = DiagnosticIds.UrlFormat)] | ||
| public sealed class RoutingSelection | ||
| { | ||
| /// <summary>Initializes a new instance of the <see cref="RoutingSelection"/> class.</summary> | ||
| /// <param name="client">The client selected for the attempt.</param> | ||
| /// <param name="chatOptions">The complete options selected for the attempt, or <see langword="null"/>.</param> | ||
| /// <exception cref="ArgumentNullException"><paramref name="client"/> is <see langword="null"/>.</exception> | ||
| public RoutingSelection(IChatClient client, ChatOptions? chatOptions) | ||
| { | ||
| Client = Throw.IfNull(client); | ||
| ChatOptions = chatOptions?.Clone(); | ||
| } | ||
|
|
||
| /// <summary>Gets the client selected for the attempt.</summary> | ||
| public IChatClient Client { get; } | ||
|
|
||
| /// <summary>Gets the complete options selected for the attempt.</summary> | ||
| /// <remarks>This is a clone of the options supplied to the constructor.</remarks> | ||
| public ChatOptions? ChatOptions { get; } | ||
| } |
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.
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.