-
Notifications
You must be signed in to change notification settings - Fork 4.7k
.Net: Copy OpenAITextToImageService related code to AzureOpenAI project #7077
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 1 commit into
microsoft:feature-connectors-openai
from
SergeyMenshykh:migrate-azure-text-to-image-service-1
Jul 3, 2024
Merged
Changes from all commits
Commits
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
107 changes: 107 additions & 0 deletions
107
...onnectors/Connectors.AzureOpenAI.UnitTests/Services/AzureOpenAITextToImageServiceTests.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,107 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.IO; | ||
| using System.Net.Http; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.SemanticKernel.Connectors.AzureOpenAI; | ||
| using Microsoft.SemanticKernel.Services; | ||
| using Moq; | ||
| using OpenAI; | ||
|
|
||
| namespace SemanticKernel.Connectors.AzureOpenAI.UnitTests.Services; | ||
|
|
||
| /// <summary> | ||
| /// Unit tests for <see cref="AzureOpenAITextToImageServiceTests"/> class. | ||
| /// </summary> | ||
| public sealed class AzureOpenAITextToImageServiceTests : IDisposable | ||
| { | ||
| private readonly HttpMessageHandlerStub _messageHandlerStub; | ||
| private readonly HttpClient _httpClient; | ||
| private readonly Mock<ILoggerFactory> _mockLoggerFactory; | ||
|
|
||
| public AzureOpenAITextToImageServiceTests() | ||
| { | ||
| this._messageHandlerStub = new() | ||
| { | ||
| ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) | ||
| { | ||
| Content = new StringContent(File.ReadAllText("./TestData/text-to-image-response.txt")) | ||
| } | ||
| }; | ||
| this._httpClient = new HttpClient(this._messageHandlerStub, false); | ||
| this._mockLoggerFactory = new Mock<ILoggerFactory>(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void ConstructorWorksCorrectly() | ||
| { | ||
| // Arrange & Act | ||
| var sut = new AzureOpenAITextToImageServiceTests("model", "api-key", "organization"); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(sut); | ||
| Assert.Equal("organization", sut.Attributes[ClientCore.OrganizationKey]); | ||
| Assert.Equal("model", sut.Attributes[AIServiceExtensions.ModelIdKey]); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void OpenAIClientConstructorWorksCorrectly() | ||
| { | ||
| // Arrange | ||
| var sut = new AzureOpenAITextToImageServiceTests("model", new OpenAIClient("apikey")); | ||
|
|
||
| // Assert | ||
| Assert.NotNull(sut); | ||
| Assert.Equal("model", sut.Attributes[AIServiceExtensions.ModelIdKey]); | ||
| } | ||
|
|
||
| [Theory] | ||
| [InlineData(256, 256, "dall-e-2")] | ||
| [InlineData(512, 512, "dall-e-2")] | ||
| [InlineData(1024, 1024, "dall-e-2")] | ||
| [InlineData(1024, 1024, "dall-e-3")] | ||
| [InlineData(1024, 1792, "dall-e-3")] | ||
| [InlineData(1792, 1024, "dall-e-3")] | ||
| [InlineData(123, 321, "custom-model-1")] | ||
| [InlineData(179, 124, "custom-model-2")] | ||
| public async Task GenerateImageWorksCorrectlyAsync(int width, int height, string modelId) | ||
| { | ||
| // Arrange | ||
| var sut = new AzureOpenAITextToImageServiceTests(modelId, "api-key", httpClient: this._httpClient); | ||
| Assert.Equal(modelId, sut.Attributes["ModelId"]); | ||
|
|
||
| // Act | ||
| var result = await sut.GenerateImageAsync("description", width, height); | ||
|
|
||
| // Assert | ||
| Assert.Equal("https://image-url/", result); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task GenerateImageDoesLogActionAsync() | ||
| { | ||
| // Assert | ||
| var modelId = "dall-e-2"; | ||
| var logger = new Mock<ILogger<AzureOpenAITextToImageServiceTests>>(); | ||
| logger.Setup(l => l.IsEnabled(It.IsAny<LogLevel>())).Returns(true); | ||
|
|
||
| this._mockLoggerFactory.Setup(x => x.CreateLogger(It.IsAny<string>())).Returns(logger.Object); | ||
|
|
||
| // Arrange | ||
| var sut = new AzureOpenAITextToImageServiceTests(modelId, "apiKey", httpClient: this._httpClient, loggerFactory: this._mockLoggerFactory.Object); | ||
|
|
||
| // Act | ||
| await sut.GenerateImageAsync("description", 256, 256); | ||
|
|
||
| // Assert | ||
| logger.VerifyLog(LogLevel.Information, $"Action: {nameof(AzureOpenAITextToImageServiceTests.GenerateImageAsync)}. OpenAI Model ID: {modelId}.", Times.Once()); | ||
| } | ||
|
|
||
| public void Dispose() | ||
| { | ||
| this._httpClient.Dispose(); | ||
| this._messageHandlerStub.Dispose(); | ||
| } | ||
| } |
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
44 changes: 44 additions & 0 deletions
44
dotnet/src/Connectors/Connectors.AzureOpenAI/Core/ClientCore.TextToImage.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,44 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.ClientModel; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using OpenAI.Images; | ||
|
|
||
| namespace Microsoft.SemanticKernel.Connectors.AzureOpenAI; | ||
|
|
||
| /// <summary> | ||
| /// Base class for AI clients that provides common functionality for interacting with OpenAI services. | ||
| /// </summary> | ||
| internal partial class ClientCore | ||
| { | ||
| /// <summary> | ||
| /// Generates an image with the provided configuration. | ||
| /// </summary> | ||
| /// <param name="prompt">Prompt to generate the image</param> | ||
| /// <param name="width">Width of the image</param> | ||
| /// <param name="height">Height of the image</param> | ||
| /// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests. The default is <see cref="CancellationToken.None"/>.</param> | ||
| /// <returns>Url of the generated image</returns> | ||
| internal async Task<string> GenerateImageAsync( | ||
| string prompt, | ||
| int width, | ||
| int height, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| Verify.NotNullOrWhiteSpace(prompt); | ||
|
|
||
| var size = new GeneratedImageSize(width, height); | ||
|
|
||
| var imageOptions = new ImageGenerationOptions() | ||
| { | ||
| Size = size, | ||
| ResponseFormat = GeneratedImageFormat.Uri | ||
| }; | ||
|
|
||
| ClientResult<GeneratedImage> response = await RunRequestAsync(() => this.Client.GetImageClient(this.ModelId).GenerateImageAsync(prompt, imageOptions, cancellationToken)).ConfigureAwait(false); | ||
| var generatedImage = response.Value; | ||
|
|
||
| return generatedImage.ImageUri?.ToString() ?? throw new KernelException("The generated image is not in url format"); | ||
| } | ||
| } |
66 changes: 66 additions & 0 deletions
66
dotnet/src/Connectors/Connectors.AzureOpenAI/Services/AzureOpenAITextToImageService.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,66 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Diagnostics.CodeAnalysis; | ||
| using System.Net.Http; | ||
| using System.Threading; | ||
| using System.Threading.Tasks; | ||
| using Microsoft.Extensions.Logging; | ||
| using Microsoft.SemanticKernel.TextToImage; | ||
| using OpenAI; | ||
|
|
||
| namespace Microsoft.SemanticKernel.Connectors.AzureOpenAI; | ||
|
|
||
| /// <summary> | ||
| /// OpenAI text to image service. | ||
| /// </summary> | ||
| [Experimental("SKEXP0010")] | ||
| public class AzureOpenAITextToImageService : ITextToImageService | ||
| { | ||
| private readonly ClientCore _client; | ||
|
|
||
| /// <inheritdoc/> | ||
| public IReadOnlyDictionary<string, object?> Attributes => this._client.Attributes; | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="AzureOpenAITextToImageService"/> class. | ||
| /// </summary> | ||
| /// <param name="modelId">The model to use for image generation.</param> | ||
| /// <param name="apiKey">OpenAI API key, see https://platform.openai.com/account/api-keys</param> | ||
| /// <param name="organizationId">OpenAI organization id. This is usually optional unless your account belongs to multiple organizations.</param> | ||
| /// <param name="endpoint">Non-default endpoint for the OpenAI API.</param> | ||
| /// <param name="httpClient">Custom <see cref="HttpClient"/> for HTTP requests.</param> | ||
| /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param> | ||
| public AzureOpenAITextToImageService( | ||
| string modelId, | ||
| string? apiKey = null, | ||
| string? organizationId = null, | ||
| Uri? endpoint = null, | ||
| HttpClient? httpClient = null, | ||
| ILoggerFactory? loggerFactory = null) | ||
| { | ||
| this._client = new(modelId, apiKey, organizationId, endpoint, httpClient, loggerFactory?.CreateLogger(this.GetType())); | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Initializes a new instance of the <see cref="AzureOpenAITextToImageService"/> class. | ||
| /// </summary> | ||
| /// <param name="modelId">Model name</param> | ||
| /// <param name="openAIClient">Custom <see cref="OpenAIClient"/> for HTTP requests.</param> | ||
| /// <param name="loggerFactory">The <see cref="ILoggerFactory"/> to use for logging. If null, no logging will be performed.</param> | ||
| public AzureOpenAITextToImageService( | ||
| string modelId, | ||
| OpenAIClient openAIClient, | ||
| ILoggerFactory? loggerFactory = null) | ||
| { | ||
| this._client = new(modelId, openAIClient, loggerFactory?.CreateLogger(typeof(OpenAITextEmbeddingGenerationService))); | ||
| } | ||
|
|
||
| /// <inheritdoc/> | ||
| public Task<string> GenerateImageAsync(string description, int width, int height, Kernel? kernel = null, CancellationToken cancellationToken = default) | ||
| { | ||
| this._client.LogActionDetails(); | ||
| return this._client.GenerateImageAsync(description, width, height, cancellationToken); | ||
| } | ||
| } |
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
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.