-
Notifications
You must be signed in to change notification settings - Fork 281
Added embedding API to C# SDK #581
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
phanindraraja
wants to merge
9
commits into
microsoft:main
Choose a base branch
from
phanindraraja:user/rchava/embedding-support
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
9 commits
Select commit
Hold shift + click to select a range
010cdd5
Added embedding API to SDK
ce4ed01
Added embedding tests
cb20fd8
tests fix
99a7027
Updated documentation
e0dc1c3
Update sdk/cs/test/FoundryLocal.Tests/EmbeddingClientTests.cs
phanindraraja e9d887d
Added more null checks in tests
b29d663
fixed copilot comments
e2366ab
Updated tests with new int4 embedding model results
ed20218
Updated documentation
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
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
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
50 changes: 50 additions & 0 deletions
50
sdk/cs/docs/api/microsoft.ai.foundry.local.openaiembeddingclient.md
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,50 @@ | ||
| # OpenAIEmbeddingClient | ||
|
|
||
| Namespace: Microsoft.AI.Foundry.Local | ||
|
|
||
| Embedding Client that uses the OpenAI API. | ||
| Implemented using Betalgo.Ranul.OpenAI SDK types. | ||
|
|
||
| ```csharp | ||
| public class OpenAIEmbeddingClient | ||
| ``` | ||
|
|
||
| Inheritance [Object](https://docs.microsoft.com/en-us/dotnet/api/system.object) → [OpenAIEmbeddingClient](./microsoft.ai.foundry.local.openaiembeddingclient.md)<br> | ||
| Attributes [NullableContextAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.nullablecontextattribute), [NullableAttribute](https://docs.microsoft.com/en-us/dotnet/api/system.runtime.compilerservices.nullableattribute) | ||
|
|
||
| ## Properties | ||
|
|
||
| ### **Settings** | ||
|
|
||
| Settings to use for embedding requests using this client. | ||
|
|
||
| ```csharp | ||
| public EmbeddingSettings Settings { get; } | ||
| ``` | ||
|
|
||
| #### Property Value | ||
|
|
||
| EmbeddingSettings<br> | ||
|
|
||
| ## Methods | ||
|
|
||
| ### **GenerateEmbeddingAsync(String, Nullable<CancellationToken>)** | ||
|
|
||
| Generate embeddings for the given input text. | ||
|
|
||
| ```csharp | ||
| public Task<EmbeddingCreateResponse> GenerateEmbeddingAsync(string input, Nullable<CancellationToken> ct) | ||
| ``` | ||
|
|
||
| #### Parameters | ||
|
|
||
| `input` [String](https://docs.microsoft.com/en-us/dotnet/api/system.string)<br> | ||
| The text to generate embeddings for. | ||
|
|
||
| `ct` [Nullable<CancellationToken>](https://docs.microsoft.com/en-us/dotnet/api/system.nullable-1)<br> | ||
| Optional cancellation token. | ||
|
|
||
| #### Returns | ||
|
|
||
| [Task<EmbeddingCreateResponse>](https://docs.microsoft.com/en-us/dotnet/api/system.threading.tasks.task-1)<br> | ||
| Embedding response containing the embedding vector. |
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
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
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,81 @@ | ||
| // -------------------------------------------------------------------------------------------------------------------- | ||
| // <copyright company="Microsoft"> | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
| // </copyright> | ||
| // -------------------------------------------------------------------------------------------------------------------- | ||
|
|
||
| namespace Microsoft.AI.Foundry.Local; | ||
|
|
||
| using Betalgo.Ranul.OpenAI.ObjectModels.ResponseModels; | ||
|
|
||
| using Microsoft.AI.Foundry.Local.Detail; | ||
| using Microsoft.AI.Foundry.Local.OpenAI; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| /// <summary> | ||
| /// Embedding Client that uses the OpenAI API. | ||
| /// Implemented using Betalgo.Ranul.OpenAI SDK types. | ||
| /// </summary> | ||
| public class OpenAIEmbeddingClient | ||
| { | ||
| private readonly string _modelId; | ||
|
|
||
| private readonly ICoreInterop _coreInterop = FoundryLocalManager.Instance.CoreInterop; | ||
| private readonly ILogger _logger = FoundryLocalManager.Instance.Logger; | ||
|
|
||
| internal OpenAIEmbeddingClient(string modelId) | ||
| { | ||
| _modelId = modelId; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Settings that are supported by Foundry Local for embeddings. | ||
| /// </summary> | ||
| public record EmbeddingSettings | ||
| { | ||
| /// <summary> | ||
| /// The number of dimensions the resulting output embeddings should have. | ||
| /// Only supported by some models. | ||
| /// </summary> | ||
| public int? Dimensions { get; set; } | ||
|
|
||
| /// <summary> | ||
| /// The format to return the embeddings in. Can be either "float" or "base64". | ||
| /// </summary> | ||
| public string? EncodingFormat { get; set; } | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Settings to use for embedding requests using this client. | ||
| /// </summary> | ||
| public EmbeddingSettings Settings { get; } = new(); | ||
|
|
||
| /// <summary> | ||
| /// Generate embeddings for the given input text. | ||
| /// </summary> | ||
| /// <param name="input">The text to generate embeddings for.</param> | ||
| /// <param name="ct">Optional cancellation token.</param> | ||
| /// <returns>Embedding response containing the embedding vector.</returns> | ||
| public async Task<EmbeddingCreateResponse> GenerateEmbeddingAsync(string input, | ||
| CancellationToken? ct = null) | ||
| { | ||
phanindraraja marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| return await Utils.CallWithExceptionHandling( | ||
| () => GenerateEmbeddingImplAsync(input, ct), | ||
| "Error during embedding generation.", _logger).ConfigureAwait(false); | ||
phanindraraja marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| private async Task<EmbeddingCreateResponse> GenerateEmbeddingImplAsync(string input, | ||
| CancellationToken? ct) | ||
| { | ||
| var embeddingRequest = EmbeddingCreateRequestExtended.FromUserInput(_modelId, input, Settings); | ||
| var embeddingRequestJson = embeddingRequest.ToJson(); | ||
|
|
||
| var request = new CoreInteropRequest { Params = new() { { "OpenAICreateRequest", embeddingRequestJson } } }; | ||
| var response = await _coreInterop.ExecuteCommandAsync("embeddings", request, | ||
| ct ?? CancellationToken.None).ConfigureAwait(false); | ||
|
|
||
| var embeddingResponse = response.ToEmbeddingResponse(_logger); | ||
|
|
||
| return embeddingResponse; | ||
| } | ||
| } | ||
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,81 @@ | ||
| // -------------------------------------------------------------------------------------------------------------------- | ||
| // <copyright company="Microsoft"> | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
| // </copyright> | ||
| // -------------------------------------------------------------------------------------------------------------------- | ||
|
|
||
| namespace Microsoft.AI.Foundry.Local.OpenAI; | ||
|
|
||
| using System.Text.Json; | ||
| using System.Text.Json.Serialization; | ||
|
|
||
| using Betalgo.Ranul.OpenAI.ObjectModels.ResponseModels; | ||
|
|
||
| using Microsoft.AI.Foundry.Local.Detail; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| // https://platform.openai.com/docs/api-reference/embeddings/create | ||
| internal record EmbeddingCreateRequestExtended | ||
| { | ||
| [JsonPropertyName("input")] | ||
| public string? Input { get; set; } | ||
|
|
||
| [JsonPropertyName("model")] | ||
| public string? Model { get; set; } | ||
|
|
||
| [JsonPropertyName("dimensions")] | ||
| public int? Dimensions { get; set; } | ||
|
|
||
| [JsonPropertyName("encoding_format")] | ||
| public string? EncodingFormat { get; set; } | ||
|
|
||
| internal static EmbeddingCreateRequestExtended FromUserInput(string modelId, | ||
| string input, | ||
| OpenAIEmbeddingClient.EmbeddingSettings settings) | ||
| { | ||
| return new EmbeddingCreateRequestExtended | ||
| { | ||
| Model = modelId, | ||
| Input = input, | ||
| Dimensions = settings.Dimensions, | ||
| EncodingFormat = settings.EncodingFormat | ||
| }; | ||
| } | ||
| } | ||
|
|
||
| internal static class EmbeddingRequestResponseExtensions | ||
| { | ||
| internal static string ToJson(this EmbeddingCreateRequestExtended request) | ||
| { | ||
| return JsonSerializer.Serialize(request, JsonSerializationContext.Default.EmbeddingCreateRequestExtended); | ||
| } | ||
|
|
||
| internal static EmbeddingCreateResponse ToEmbeddingResponse(this ICoreInterop.Response response, ILogger logger) | ||
| { | ||
| if (response.Error != null) | ||
| { | ||
| logger.LogError("Error from embeddings: {Error}", response.Error); | ||
| throw new FoundryLocalException($"Error from embeddings command: {response.Error}"); | ||
| } | ||
|
|
||
| if (string.IsNullOrWhiteSpace(response.Data)) | ||
| { | ||
| logger.LogError("Embeddings command returned no data"); | ||
| throw new FoundryLocalException("Embeddings command returned null or empty response data"); | ||
| } | ||
|
|
||
| return response.Data.ToEmbeddingResponse(logger); | ||
| } | ||
|
|
||
| internal static EmbeddingCreateResponse ToEmbeddingResponse(this string responseData, ILogger logger) | ||
| { | ||
| var output = JsonSerializer.Deserialize(responseData, JsonSerializationContext.Default.EmbeddingCreateResponse); | ||
| if (output == null) | ||
| { | ||
| logger.LogError("Failed to deserialize EmbeddingCreateResponse (length={Length})", responseData.Length); | ||
| throw new JsonException("Failed to deserialize EmbeddingCreateResponse"); | ||
| } | ||
|
|
||
| return output; | ||
phanindraraja marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| } | ||
| } | ||
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.