-
Notifications
You must be signed in to change notification settings - Fork 840
Add UseEmbeddingGenerationOptions #5594
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
stephentoub
merged 2 commits into
dotnet:main
from
stephentoub:configureembeddingoptions
Nov 1, 2024
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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
75 changes: 75 additions & 0 deletions
75
src/Libraries/Microsoft.Extensions.AI/Embeddings/ConfigureOptionsEmbeddingGenerator.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,75 @@ | ||
| // 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.Runtime.CompilerServices; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Shared.Diagnostics; | ||
|
|
||
| #pragma warning disable SA1629 // Documentation text should end with a period | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary>A delegating embedding generator that updates or replaces the <see cref="EmbeddingGenerationOptions"/> used by the remainder of the pipeline.</summary> | ||
| /// <typeparam name="TInput">Specifies the type of the input passed to the generator.</typeparam> | ||
| /// <typeparam name="TEmbedding">Specifies the type of the embedding instance produced by the generator.</typeparam> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The configuration callback is invoked with the caller-supplied <see cref="EmbeddingGenerationOptions"/> instance. To override the caller-supplied options | ||
| /// with a new instance, the callback may simply return that new instance, for example <c>_ => new EmbeddingGenerationOptions() { Dimensions = 100 }</c>. To provide | ||
| /// a new instance only if the caller-supplied instance is <see langword="null"/>, the callback may conditionally return a new instance, for example | ||
| /// <c>options => options ?? new EmbeddingGenerationOptions() { Dimensions = 100 }</c>. Any changes to the caller-provided options instance will persist on the | ||
| /// original instance, so the callback must take care to only do so when such mutations are acceptable, such as by cloning the original instance | ||
| /// and mutating the clone, for example: | ||
| /// <c> | ||
| /// options => | ||
| /// { | ||
| /// var newOptions = options?.Clone() ?? new(); | ||
| /// newOptions.Dimensions = 100; | ||
| /// return newOptions; | ||
| /// } | ||
| /// </c> | ||
| /// </para> | ||
| /// <para> | ||
| /// The callback may return <see langword="null"/>, in which case a <see langword="null"/> options will be passed to the next generator in the pipeline. | ||
| /// </para> | ||
| /// <para> | ||
| /// The provided implementation of <see cref="IEmbeddingGenerator{TInput, TEmbedding}"/> is thread-safe for concurrent use so long as the employed configuration | ||
| /// callback is also thread-safe for concurrent requests. If callers employ a shared options instance, care should be taken in the | ||
| /// configuration callback, as multiple calls to it may end up running in parallel with the same options instance. | ||
| /// </para> | ||
| /// </remarks> | ||
| public sealed class ConfigureOptionsEmbeddingGenerator<TInput, TEmbedding> : DelegatingEmbeddingGenerator<TInput, TEmbedding> | ||
| where TEmbedding : Embedding | ||
| { | ||
| /// <summary>The callback delegate used to configure options.</summary> | ||
| private readonly Func<EmbeddingGenerationOptions?, EmbeddingGenerationOptions?> _configureOptions; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="ConfigureOptionsEmbeddingGenerator{TInput, TEmbedding}"/> class with the | ||
| /// specified <paramref name="configureOptions"/> callback. | ||
| /// </summary> | ||
| /// <param name="innerGenerator">The inner generator.</param> | ||
| /// <param name="configureOptions"> | ||
| /// The delegate to invoke to configure the <see cref="EmbeddingGenerationOptions"/> instance. It is passed the caller-supplied | ||
| /// <see cref="EmbeddingGenerationOptions"/> instance and should return the configured <see cref="EmbeddingGenerationOptions"/> instance to use. | ||
| /// </param> | ||
| public ConfigureOptionsEmbeddingGenerator( | ||
| IEmbeddingGenerator<TInput, TEmbedding> innerGenerator, | ||
| Func<EmbeddingGenerationOptions?, EmbeddingGenerationOptions?> configureOptions) | ||
| : base(innerGenerator) | ||
| { | ||
| _configureOptions = Throw.IfNull(configureOptions); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public override async Task<GeneratedEmbeddings<TEmbedding>> GenerateAsync( | ||
| IEnumerable<TInput> values, | ||
| EmbeddingGenerationOptions? options = null, | ||
| CancellationToken cancellationToken = default) | ||
| { | ||
| return await base.GenerateAsync(values, _configureOptions(options), cancellationToken).ConfigureAwait(false); | ||
| } | ||
| } |
56 changes: 56 additions & 0 deletions
56
...Microsoft.Extensions.AI/Embeddings/ConfigureOptionsEmbeddingGeneratorBuilderExtensions.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,56 @@ | ||
| // 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 Microsoft.Shared.Diagnostics; | ||
|
|
||
| #pragma warning disable SA1629 // Documentation text should end with a period | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| /// <summary>Provides extensions for configuring <see cref="ConfigureOptionsEmbeddingGenerator{TInput, TEmbedding}"/> instances.</summary> | ||
| public static class ConfigureOptionsEmbeddingGeneratorBuilderExtensions | ||
| { | ||
| /// <summary> | ||
| /// Adds a callback that updates or replaces <see cref="EmbeddingGenerationOptions"/>. This can be used to set default options. | ||
| /// </summary> | ||
| /// <typeparam name="TInput">Specifies the type of the input passed to the generator.</typeparam> | ||
| /// <typeparam name="TEmbedding">Specifies the type of the embedding instance produced by the generator.</typeparam> | ||
| /// <param name="builder">The <see cref="EmbeddingGeneratorBuilder{TInput, TEmbedding}"/>.</param> | ||
| /// <param name="configureOptions"> | ||
| /// The delegate to invoke to configure the <see cref="EmbeddingGenerationOptions"/> instance. It is passed the caller-supplied | ||
| /// <see cref="EmbeddingGenerationOptions"/> instance and should return the configured <see cref="EmbeddingGenerationOptions"/> instance to use. | ||
| /// </param> | ||
| /// <returns>The <paramref name="builder"/>.</returns> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The configuration callback is invoked with the caller-supplied <see cref="EmbeddingGenerationOptions"/> instance. To override the caller-supplied options | ||
| /// with a new instance, the callback may simply return that new instance, for example <c>_ => new EmbeddingGenerationOptions() { Dimensions = 100 }</c>. To provide | ||
| /// a new instance only if the caller-supplied instance is <see langword="null"/>, the callback may conditionally return a new instance, for example | ||
| /// <c>options => options ?? new EmbeddingGenerationOptions() { Dimensions = 100 }</c>. Any changes to the caller-provided options instance will persist on the | ||
| /// original instance, so the callback must take care to only do so when such mutations are acceptable, such as by cloning the original instance | ||
| /// and mutating the clone, for example: | ||
| /// <c> | ||
| /// options => | ||
| /// { | ||
| /// var newOptions = options?.Clone() ?? new(); | ||
| /// newOptions.Dimensions = 100; | ||
| /// return newOptions; | ||
| /// } | ||
| /// </c> | ||
| /// </para> | ||
| /// <para> | ||
| /// The callback may return <see langword="null"/>, in which case a <see langword="null"/> options will be passed to the next generator in the pipeline. | ||
| /// </para> | ||
| /// </remarks> | ||
| public static EmbeddingGeneratorBuilder<TInput, TEmbedding> UseEmbeddingGenerationOptions<TInput, TEmbedding>( | ||
| this EmbeddingGeneratorBuilder<TInput, TEmbedding> builder, | ||
| Func<EmbeddingGenerationOptions?, EmbeddingGenerationOptions?> configureOptions) | ||
| where TEmbedding : Embedding | ||
| { | ||
| _ = Throw.IfNull(builder); | ||
| _ = Throw.IfNull(configureOptions); | ||
|
|
||
| return builder.Use(innerGenerator => new ConfigureOptionsEmbeddingGenerator<TInput, TEmbedding>(innerGenerator, configureOptions)); | ||
| } | ||
| } |
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
58 changes: 58 additions & 0 deletions
58
...aries/Microsoft.Extensions.AI.Tests/Embeddings/ConfigureOptionsEmbeddingGeneratorTests.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,58 @@ | ||
| // 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.Threading; | ||
| using System.Threading.Tasks; | ||
| using Xunit; | ||
|
|
||
| namespace Microsoft.Extensions.AI; | ||
|
|
||
| public class ConfigureOptionsEmbeddingGeneratorTests | ||
| { | ||
| [Fact] | ||
| public void ConfigureOptionsEmbeddingGenerator_InvalidArgs_Throws() | ||
| { | ||
| Assert.Throws<ArgumentNullException>("innerGenerator", () => new ConfigureOptionsEmbeddingGenerator<string, Embedding<float>>(null!, _ => new EmbeddingGenerationOptions())); | ||
| Assert.Throws<ArgumentNullException>("configureOptions", () => new ConfigureOptionsEmbeddingGenerator<string, Embedding<float>>(new TestEmbeddingGenerator(), null!)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void UseEmbeddingGenerationOptions_InvalidArgs_Throws() | ||
| { | ||
| var builder = new EmbeddingGeneratorBuilder<string, Embedding<float>>(); | ||
| Assert.Throws<ArgumentNullException>("configureOptions", () => builder.UseEmbeddingGenerationOptions(null!)); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(false)] | ||
| [InlineData(true)] | ||
| public async Task ConfigureOptions_ReturnedInstancePassedToNextClient(bool nullReturned) | ||
| { | ||
| EmbeddingGenerationOptions providedOptions = new(); | ||
| EmbeddingGenerationOptions? returnedOptions = nullReturned ? null : new(); | ||
| GeneratedEmbeddings<Embedding<float>> expectedEmbeddings = []; | ||
| using CancellationTokenSource cts = new(); | ||
|
|
||
| using IEmbeddingGenerator<string, Embedding<float>> innerGenerator = new TestEmbeddingGenerator | ||
| { | ||
| GenerateAsyncCallback = (inputs, options, cancellationToken) => | ||
| { | ||
| Assert.Same(returnedOptions, options); | ||
| Assert.Equal(cts.Token, cancellationToken); | ||
| return Task.FromResult(expectedEmbeddings); | ||
| } | ||
| }; | ||
|
|
||
| using var generator = new EmbeddingGeneratorBuilder<string, Embedding<float>>() | ||
| .UseEmbeddingGenerationOptions(options => | ||
| { | ||
| Assert.Same(providedOptions, options); | ||
| return returnedOptions; | ||
| }) | ||
| .Use(innerGenerator); | ||
|
|
||
| var embeddings = await generator.GenerateAsync([], providedOptions, cts.Token); | ||
| Assert.Same(expectedEmbeddings, embeddings); | ||
| } | ||
| } |
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.