diff --git a/src/helpers/GenerateDocs/Program.cs b/src/helpers/GenerateDocs/Program.cs index b78f5f77..463c67c6 100644 --- a/src/helpers/GenerateDocs/Program.cs +++ b/src/helpers/GenerateDocs/Program.cs @@ -10,7 +10,7 @@ Path.Combine(solutionDirectory, "docs", "index.md")); Console.WriteLine($"Generating samples from {sampleDirectory}..."); -foreach (var path in Directory.EnumerateFiles(sampleDirectory, "*.cs", SearchOption.AllDirectories)) +foreach (var path in Directory.EnumerateFiles(sampleDirectory, "Examples.*.cs", SearchOption.AllDirectories)) { var code = await File.ReadAllTextAsync(path); @@ -21,7 +21,7 @@ var lines = code.Split('\n')[1..^2]; code = string.Join('\n', lines.Select(x => x.Length > 8 ? x[8..] : string.Empty)); - var newPath = Path.Combine(newDir, $"{Path.GetExtension(Path.GetFileNameWithoutExtension(path)).TrimStart('.')}.md"); + var newPath = Path.Combine(newDir, $"{Path.GetFileNameWithoutExtension(path).Replace("Examples.", string.Empty)}.md"); await File.WriteAllTextAsync(newPath, $@"```csharp {code} ```"); diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListAssistantsWithPagination.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListAssistantsWithPagination.cs new file mode 100644 index 00000000..64b51a94 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListAssistantsWithPagination.cs @@ -0,0 +1,23 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task ListAssistantsWithPagination() + { + using var api = GetAuthenticatedClient(); + + int count = 0; + + ListAssistantsResponse response = await api.Assistants.ListAssistantsAsync(); + foreach (AssistantObject assistant in response.Data) + { + Console.WriteLine($"[{count,3}] {assistant.Id} {assistant.CreatedAt:s} {assistant.Name}"); + + count++; + + //_ = await api.Assistants.DeleteAssistantAsync(assistant.Id); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListFiles.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListFiles.cs new file mode 100644 index 00000000..9454e2d8 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.ListFiles.cs @@ -0,0 +1,23 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task ListFiles() + { + using var api = GetAuthenticatedClient(); + + int count = 0; + + ListFilesResponse files = await api.Files.ListFilesAsync(purpose: CreateFileRequestPurpose.Assistants.ToValueString()); + foreach (OpenAIFile file in files.Data) + { + Console.WriteLine($"[{count,3}] {file.Id} {file.CreatedAt:s} {file.Filename}"); + + count++; + + //_ = await api.Files.DeleteFileAsync(file.Id); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.RetrievalAugmentedGeneration.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.RetrievalAugmentedGeneration.cs new file mode 100644 index 00000000..bc2cdf90 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Assistants.RetrievalAugmentedGeneration.cs @@ -0,0 +1,158 @@ +using System.Text; + +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task RetrievalAugmentedGeneration() + { + using var api = GetAuthenticatedClient(); + + // First, let's contrive a document we'll use retrieval with and upload it. + string document = /* language=json */ + """ + { + "description": "This document contains the sale history data for Contoso products.", + "sales": [ + { + "month": "January", + "by_product": { + "113043": 15, + "113045": 12, + "113049": 2 + } + }, + { + "month": "February", + "by_product": { + "113045": 22 + } + }, + { + "month": "March", + "by_product": { + "113045": 16, + "113055": 5 + } + } + ] + } + """; + + OpenAIFile salesFile = await api.Files.CreateFileAsync( + file: Encoding.UTF8.GetBytes(document), + filename: "monthly_sales.json", + purpose: CreateFileRequestPurpose.Assistants); + + AssistantObject assistant = await api.Assistants.CreateAssistantAsync( + model: CreateAssistantRequestModel.Gpt4o, + name: "Example: Contoso sales RAG", + instructions: "You are an assistant that looks up sales data and helps visualize the information based" + + " on user queries. When asked to generate a graph, chart, or other visualization, use" + + " the code interpreter tool to do so.", + tools: + [ + new AssistantToolsFileSearch(), + new AssistantToolsCode(), + ], + toolResources: new CreateAssistantRequestToolResources + { + FileSearch = new CreateAssistantRequestToolResourcesFileSearch + { + VectorStores = + [ + new CreateAssistantRequestToolResourcesFileSearchVectorStore + { + FileIds = [salesFile.Id], + } + ], + } + }); + + // Now we'll create a thread with a user query about the data already associated with the assistant, then run it + RunObject threadRun = await api.Assistants.CreateThreadAndRunAsync( + assistantId: assistant.Id, + thread: new CreateThreadRequest + { + Messages = new List + { + new() + { + Role = CreateMessageRequestRole.User, + Content = "How well did product 113045 sell in February? Graph its trend over time.", + }, + }, + }); + + // Check back to see when the run is done + do + { + await Task.Delay(TimeSpan.FromSeconds(1)); + + threadRun = await api.Assistants.GetRunAsync( + threadId: threadRun.ThreadId, + runId: threadRun.Id); + } while (threadRun.Status is RunObjectStatus.Queued or RunObjectStatus.InProgress); + + // Finally, we'll print out the full history for the thread that includes the augmented generation + // TODO: IAsyncEnumerable pagination + ListMessagesResponse messages + = await api.Assistants.ListMessagesAsync( + threadId: threadRun.ThreadId); // ListOrder.OldestFirst + + foreach (MessageObject message in messages.Data) + { + Console.Write($"[{message.Role.ToString().ToUpper()}]: "); + foreach (OneOf< + MessageContentImageFileObject, + MessageContentImageUrlObject, + MessageContentTextObject, + MessageContentRefusalObject> contentItem in message.Content) + { + if (contentItem.IsValue3) + { + Console.WriteLine($"{contentItem.Value3.Text.Value}"); + + if (contentItem.Value3.Text.Annotations.Count > 0) + { + Console.WriteLine(); + } + + // Include annotations, if any. + foreach (OneOf< + MessageContentTextAnnotationsFileCitationObject, + MessageContentTextAnnotationsFilePathObject> annotation in contentItem.Value3.Text.Annotations) + { + if (annotation.IsValue1 && !string.IsNullOrEmpty(annotation.Value1.FileCitation.FileId)) + { + Console.WriteLine($"* File citation, file ID: {annotation.Value1.FileCitation.FileId}"); + } + if (annotation.IsValue2 && !string.IsNullOrEmpty(annotation.Value2.FilePath.FileId)) + { + Console.WriteLine($"* File output, new file ID: {annotation.Value2.FilePath.FileId}"); + } + } + } + if (contentItem.IsValue1) + { + OpenAIFile imageInfo = await api.Files.RetrieveFileAsync(contentItem.Value1.ImageFile.FileId); + byte[] imageBytes = await api.Files.DownloadFileAsync(contentItem.Value1.ImageFile.FileId); + + FileInfo fileInfo = new($"{imageInfo.Filename}.png"); + + await File.WriteAllBytesAsync(fileInfo.FullName, imageBytes); + + Console.WriteLine($""); + } + } + Console.WriteLine(); + } + + // Optionally, delete any persistent resources you no longer need. + _ = await api.Assistants.DeleteThreadAsync(threadRun.ThreadId); + _ = await api.Assistants.DeleteAssistantAsync(assistant.Id); + _ = await api.Files.DeleteFileAsync(salesFile.Id); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTextToSpeech.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTextToSpeech.cs new file mode 100644 index 00000000..5d650028 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTextToSpeech.cs @@ -0,0 +1,26 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleTextToSpeech() + { + using var api = GetAuthenticatedClient(); + + byte[] bytes = await api.Audio.CreateSpeechAsync( + model: CreateSpeechRequestModel.Tts1, + input: "Overwatering is a common issue for those taking care of houseplants. To prevent it, it is" + + " crucial to allow the soil to dry out between waterings. Instead of watering on a fixed schedule," + + " consider using a moisture meter to accurately gauge the soil’s wetness. Should the soil retain" + + " moisture, it is wise to postpone watering for a couple more days. When in doubt, it is often safer" + + " to water sparingly and maintain a less-is-more approach.", + voice: CreateSpeechRequestVoice.Alloy); + + FileInfo fileInfo = new($"{Guid.NewGuid()}.mp3"); + + await File.WriteAllBytesAsync(fileInfo.FullName, bytes); + + Console.WriteLine($"Audio available at:\n{new Uri(fileInfo.FullName).AbsoluteUri}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranscription.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranscription.cs new file mode 100644 index 00000000..177f6e5d --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranscription.cs @@ -0,0 +1,18 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleTranscription() + { + using var api = GetAuthenticatedClient(); + + OneOf response = await api.Audio.CreateTranscriptionAsync( + file: H.Resources.audio_houseplant_care_mp3.AsBytes(), + filename: H.Resources.audio_houseplant_care_mp3.FileName, + model: CreateTranscriptionRequestModel.Whisper1); + + Console.WriteLine($"{response.Value1?.Text}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranslation.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranslation.cs new file mode 100644 index 00000000..79fc934c --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.SimpleTranslation.cs @@ -0,0 +1,18 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleTranslation() + { + using var api = GetAuthenticatedClient(); + + OneOf response = await api.Audio.CreateTranslationAsync( + file: H.Resources.audio_french_wav.AsBytes(), + filename: H.Resources.audio_french_wav.FileName, + model: CreateTranslationRequestModel.Whisper1); + + Console.WriteLine($"{response.Value1?.Text}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.VerboseTranscription.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.VerboseTranscription.cs new file mode 100644 index 00000000..8828f328 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Audio.VerboseTranscription.cs @@ -0,0 +1,41 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + // TODO: Does not work yet + public async Task VerboseTranscription() + { + using var api = GetAuthenticatedClient(); + + OneOf response = await api.Audio.CreateTranscriptionAsync( + file: H.Resources.audio_houseplant_care_mp3.AsBytes(), + filename: H.Resources.audio_houseplant_care_mp3.FileName, + model: CreateTranscriptionRequestModel.Whisper1, + responseFormat: CreateTranscriptionRequestResponseFormat.VerboseJson, + timestampGranularities: [ + CreateTranscriptionRequestTimestampGranularitie.Word, + CreateTranscriptionRequestTimestampGranularitie.Segment + ]); + + response.Value2.Should().NotBeNull(); + + Console.WriteLine("Transcription:"); + Console.WriteLine($"{response.Value2!.Text}"); + + Console.WriteLine(); + Console.WriteLine($"Words:"); + foreach (TranscriptionWord word in response.Value2.Words ?? []) + { + Console.WriteLine($" {word.Word,15} : {word.Start * 1000,5:0} - {word.End * 1000,5:0}"); + } + + Console.WriteLine(); + Console.WriteLine($"Segments:"); + foreach (TranscriptionSegment segment in response.Value2.Segments ?? []) + { + Console.WriteLine($" {segment.Text,90} : {segment.Start * 1000,5:0} - {segment.End * 1000,5:0}"); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.ChatWithVision.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.ChatWithVision.cs new file mode 100644 index 00000000..4bc75e7e --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.ChatWithVision.cs @@ -0,0 +1,21 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task ChatWithVision() + { + using var api = GetAuthenticatedClient(); + + CreateChatCompletionResponse response = await api.Chat.CreateChatCompletionAsync( + messages: [ + "Please describe the following image.", + H.Resources.images_dog_and_cat_png.AsBytes().AsUserMessage(mimeType: "image/png"), + ], + model: CreateChatCompletionRequestModel.Gpt4o); + + Console.WriteLine("[ASSISTANT]:"); + Console.WriteLine($"{response.Choices[0].Message.Content}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChat.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChat.cs new file mode 100644 index 00000000..92a5cebe --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChat.cs @@ -0,0 +1,18 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleChat() + { + using var api = GetAuthenticatedClient(); + + CreateChatCompletionResponse response = await api.Chat.CreateChatCompletionAsync( + messages: ["Say 'this is a test.'"], + model: CreateChatCompletionRequestModel.Gpt4o); + + Console.WriteLine("[ASSISTANT]:"); + Console.WriteLine($"{response.Choices[0].Message.Content}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChatStreaming.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChatStreaming.cs new file mode 100644 index 00000000..41302054 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Chat.SimpleChatStreaming.cs @@ -0,0 +1,21 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleChatStreaming() + { + using var api = GetAuthenticatedClient(); + + IAsyncEnumerable enumerable = api.Chat.CreateChatCompletionAsStreamAsync( + messages: ["Say 'this is a test.'"], + model: CreateChatCompletionRequestModel.Gpt4o); + + Console.WriteLine("[ASSISTANT]:"); + await foreach (CreateChatCompletionStreamResponse chatUpdate in enumerable) + { + Console.Write(chatUpdate.Choices[0].Delta.Content); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.AlpacaArtAssessor.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.AlpacaArtAssessor.cs similarity index 86% rename from src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.AlpacaArtAssessor.cs rename to src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.AlpacaArtAssessor.cs index 4df8a880..d0208c4e 100644 --- a/src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.AlpacaArtAssessor.cs +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.AlpacaArtAssessor.cs @@ -1,16 +1,12 @@ -using NUnit.Framework; +namespace OpenAI.IntegrationTests.Examples; -namespace OpenAI.Examples.Miscellaneous; - -public partial class CombinationExamples +public partial class Examples { [Test] [Explicit] public async Task AlpacaArtAssessor() { - using var api = new OpenAiApi(apiKey: - Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? - throw new AssertInconclusiveException("OPENAI_API_KEY environment variable is not found.")); + using var api = GetAuthenticatedClient(); // First, we create an image using dall-e-3: ImagesResponse imageResult = await api.Images.CreateImageAsync( diff --git a/src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.CuriousCreatureCreator.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.CuriousCreatureCreator.cs similarity index 92% rename from src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.CuriousCreatureCreator.cs rename to src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.CuriousCreatureCreator.cs index 9c164575..1afcce75 100644 --- a/src/tests/OpenAI.IntegrationTests/Examples/CombinationExamples.CuriousCreatureCreator.cs +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Combination.CuriousCreatureCreator.cs @@ -1,16 +1,12 @@ -using NUnit.Framework; +namespace OpenAI.IntegrationTests.Examples; -namespace OpenAI.Examples.Miscellaneous; - -public partial class CombinationExamples +public partial class Examples { [Test] [Explicit] public async Task CuriousCreatureCreator() { - using var api = new OpenAiApi(apiKey: - Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? - throw new AssertInconclusiveException("OPENAI_API_KEY environment variable is not found.")); + using var api = GetAuthenticatedClient(); // First, we'll use gpt-4o to have a creative helper imagine a twist on a household pet CreateChatCompletionResponse creativeWriterResult = await api.Chat.CreateChatCompletionAsync( diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.EmbeddingWithOptions.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.EmbeddingWithOptions.cs new file mode 100644 index 00000000..07013fcb --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.EmbeddingWithOptions.cs @@ -0,0 +1,26 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task EmbeddingWithOptions() + { + using var api = GetAuthenticatedClient(); + + CreateEmbeddingResponse embedding = await api.Embeddings.CreateEmbeddingAsync( + input: "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," + + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" + + " attractions. We highly recommend this hotel.", + model: CreateEmbeddingRequestModel.TextEmbedding3Small, + dimensions: 512); + IList vector = embedding.Data[0].Embedding1; + + Console.WriteLine($"Dimension: {vector.Count}"); + Console.WriteLine("Floats: "); + for (int i = 0; i < vector.Count; i++) + { + Console.WriteLine($" [{i,3}] = {vector[i]}"); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.MultipleEmbeddings.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.MultipleEmbeddings.cs new file mode 100644 index 00000000..46e4c1b1 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.MultipleEmbeddings.cs @@ -0,0 +1,35 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task MultipleEmbeddings() + { + using var api = GetAuthenticatedClient(); + + string category = "Luxury"; + string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," + + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" + + " attractions. We highly recommend this hotel."; + List inputs = [category, description]; + + CreateEmbeddingResponse response = await api.Embeddings.CreateEmbeddingAsync( + input: inputs, + model: CreateEmbeddingRequestModel.TextEmbedding3Small); + + foreach (Embedding embedding in response.Data) + { + IList vector = embedding.Embedding1; + + Console.WriteLine($"Dimension: {vector.Count}"); + Console.WriteLine("Floats: "); + for (int i = 0; i < vector.Count; i++) + { + Console.WriteLine($" [{i,4}] = {vector[i]}"); + } + + Console.WriteLine(); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.SimpleEmbedding.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.SimpleEmbedding.cs new file mode 100644 index 00000000..b80c8842 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Embeddings.SimpleEmbedding.cs @@ -0,0 +1,25 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleEmbedding() + { + using var api = GetAuthenticatedClient(); + + CreateEmbeddingResponse embedding = await api.Embeddings.CreateEmbeddingAsync( + input: "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," + + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" + + " attractions. We highly recommend this hotel.", + model: CreateEmbeddingRequestModel.TextEmbedding3Small); + IList vector = embedding.Data[0].Embedding1; + + Console.WriteLine($"Dimension: {vector.Count}"); + Console.WriteLine("Floats: "); + for (int i = 0; i < vector.Count; i++) + { + Console.WriteLine($" [{i,4}] = {vector[i]}"); + } + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageEdit.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageEdit.cs new file mode 100644 index 00000000..a4842a48 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageEdit.cs @@ -0,0 +1,40 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleImageEdit() + { + using var api = GetAuthenticatedClient(); + + FileInfo originalFileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(originalFileInfo.FullName, H.Resources.images_flower_vase_png.AsBytes()); + + Console.WriteLine($"Original Image available at:\n{new Uri(originalFileInfo.FullName).AbsoluteUri}"); + + FileInfo maskFileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(maskFileInfo.FullName, H.Resources.images_flower_vase_mask_png.AsBytes()); + + Console.WriteLine($"Mask available at:\n{new Uri(maskFileInfo.FullName).AbsoluteUri}"); + + ImagesResponse image = await api.Images.CreateImageEditAsync( + image: H.Resources.images_flower_vase_png.AsBytes(), + imagename: H.Resources.images_flower_vase_png.FileName, + prompt: "A vase full of beautiful flowers.", + mask: H.Resources.images_flower_vase_mask_png.AsBytes(), + maskname: H.Resources.images_flower_vase_mask_png.FileName, + model: CreateImageEditRequestModel.DallE2, + size: CreateImageEditRequestSize.x512x512, + responseFormat: CreateImageEditRequestResponseFormat.B64Json); + byte[] bytes = image.Data[0].Bytes; + + FileInfo fileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(fileInfo.FullName, bytes); + + Console.WriteLine($"Image available at:\n{new Uri(fileInfo.FullName).AbsoluteUri}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageGeneration.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageGeneration.cs new file mode 100644 index 00000000..ea6e8604 --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageGeneration.cs @@ -0,0 +1,32 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleImageGeneration() + { + using var api = GetAuthenticatedClient(); + + ImagesResponse image = await api.Images.CreateImageAsync( + prompt: "The concept for a living room that blends Scandinavian simplicity with Japanese minimalism for" + + " a serene and cozy atmosphere. It's a space that invites relaxation and mindfulness, with natural light" + + " and fresh air. Using neutral tones, including colors like white, beige, gray, and black, that create a" + + " sense of harmony. Featuring sleek wood furniture with clean lines and subtle curves to add warmth and" + + " elegance. Plants and flowers in ceramic pots adding color and life to a space. They can serve as focal" + + " points, creating a connection with nature. Soft textiles and cushions in organic fabrics adding comfort" + + " and softness to a space. They can serve as accents, adding contrast and texture.", + model: CreateImageRequestModel.DallE3, + quality: CreateImageRequestQuality.Hd, + size: CreateImageRequestSize.x1792x1024, + style: CreateImageRequestStyle.Vivid, + responseFormat: CreateImageRequestResponseFormat.B64Json); + byte[] bytes = image.Data[0].Bytes; + + FileInfo fileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(fileInfo.FullName, bytes); + + Console.WriteLine($"Image available at:\n{new Uri(fileInfo.FullName).AbsoluteUri}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageVariation.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageVariation.cs new file mode 100644 index 00000000..6853651d --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.Images.SimpleImageVariation.cs @@ -0,0 +1,31 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + [Test] + [Explicit] + public async Task SimpleImageVariation() + { + using var api = GetAuthenticatedClient(); + + FileInfo originalFileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(originalFileInfo.FullName, H.Resources.images_dog_and_cat_png.AsBytes()); + + Console.WriteLine($"Original Image available at:\n{new Uri(originalFileInfo.FullName).AbsoluteUri}"); + + ImagesResponse image = await api.Images.CreateImageVariationAsync( + image: H.Resources.images_dog_and_cat_png.AsBytes(), + imagename: H.Resources.images_dog_and_cat_png.FileName, + model: CreateImageVariationRequestModel.DallE2, + size: CreateImageVariationRequestSize.x256x256, + responseFormat: CreateImageVariationRequestResponseFormat.B64Json); + byte[] bytes = image.Data[0].Bytes; + + FileInfo fileInfo = new($"{Guid.NewGuid()}.png"); + + await File.WriteAllBytesAsync(fileInfo.FullName, bytes); + + Console.WriteLine($"Image available at:\n{new Uri(fileInfo.FullName).AbsoluteUri}"); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Examples/Examples.cs b/src/tests/OpenAI.IntegrationTests/Examples/Examples.cs new file mode 100644 index 00000000..d13b780e --- /dev/null +++ b/src/tests/OpenAI.IntegrationTests/Examples/Examples.cs @@ -0,0 +1,11 @@ +namespace OpenAI.IntegrationTests.Examples; + +public partial class Examples +{ + public static OpenAiApi GetAuthenticatedClient() + { + return new OpenAiApi(apiKey: + Environment.GetEnvironmentVariable("OPENAI_API_KEY") ?? + throw new AssertInconclusiveException("OPENAI_API_KEY environment variable is not found.")); + } +} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGeneration.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGeneration.cs deleted file mode 100644 index b6f16f8c..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGeneration.cs +++ /dev/null @@ -1,155 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using OpenAI.Files; -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.IO; -using System.Threading; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public void Example01_RetrievalAugmentedGeneration() - { - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - FileClient fileClient = openAIClient.GetFileClient(); - AssistantClient assistantClient = openAIClient.GetAssistantClient(); - - // First, let's contrive a document we'll use retrieval with and upload it. - using Stream document = BinaryData.FromString(""" - { - "description": "This document contains the sale history data for Contoso products.", - "sales": [ - { - "month": "January", - "by_product": { - "113043": 15, - "113045": 12, - "113049": 2 - } - }, - { - "month": "February", - "by_product": { - "113045": 22 - } - }, - { - "month": "March", - "by_product": { - "113045": 16, - "113055": 5 - } - } - ] - } - """).ToStream(); - - OpenAIFileInfo salesFile = fileClient.UploadFile( - document, - "monthly_sales.json", - FileUploadPurpose.Assistants); - - // Now, we'll create a client intended to help with that data - AssistantCreationOptions assistantOptions = new() - { - Name = "Example: Contoso sales RAG", - Instructions = - "You are an assistant that looks up sales data and helps visualize the information based" - + " on user queries. When asked to generate a graph, chart, or other visualization, use" - + " the code interpreter tool to do so.", - Tools = - { - new FileSearchToolDefinition(), - new CodeInterpreterToolDefinition(), - }, - ToolResources = new() - { - FileSearch = new() - { - NewVectorStores = - { - new VectorStoreCreationHelper([salesFile.Id]), - } - } - }, - }; - - Assistant assistant = assistantClient.CreateAssistant("gpt-4o", assistantOptions); - - // Now we'll create a thread with a user query about the data already associated with the assistant, then run it - ThreadCreationOptions threadOptions = new() - { - InitialMessages = - { - new ThreadInitializationMessage(new List() - { - MessageContent.FromText("How well did product 113045 sell in February? Graph its trend over time."), - }), - }, - }; - - ThreadRun threadRun = assistantClient.CreateThreadAndRun(assistant.Id, threadOptions); - - // Check back to see when the run is done - do - { - Thread.Sleep(TimeSpan.FromSeconds(1)); - threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id); - } while (!threadRun.Status.IsTerminal); - - // Finally, we'll print out the full history for the thread that includes the augmented generation - PageableCollection messages - = assistantClient.GetMessages(threadRun.ThreadId, ListOrder.OldestFirst); - - foreach (ThreadMessage message in messages) - { - Console.Write($"[{message.Role.ToString().ToUpper()}]: "); - foreach (MessageContent contentItem in message.Content) - { - if (!string.IsNullOrEmpty(contentItem.Text)) - { - Console.WriteLine($"{contentItem.Text}"); - - if (contentItem.TextAnnotations.Count > 0) - { - Console.WriteLine(); - } - - // Include annotations, if any. - foreach (TextAnnotation annotation in contentItem.TextAnnotations) - { - if (!string.IsNullOrEmpty(annotation.InputFileId)) - { - Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}"); - } - if (!string.IsNullOrEmpty(annotation.OutputFileId)) - { - Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}"); - } - } - } - if (!string.IsNullOrEmpty(contentItem.ImageFileId)) - { - OpenAIFileInfo imageInfo = fileClient.GetFile(contentItem.ImageFileId); - BinaryData imageBytes = fileClient.DownloadFile(contentItem.ImageFileId); - using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png"); - imageBytes.ToStream().CopyTo(stream); - - Console.WriteLine($""); - } - } - Console.WriteLine(); - } - - // Optionally, delete any persistent resources you no longer need. - _ = assistantClient.DeleteThread(threadRun.ThreadId); - _ = assistantClient.DeleteAssistant(assistant); - _ = fileClient.DeleteFile(salesFile); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs deleted file mode 100644 index 68767bd1..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example01_RetrievalAugmentedGenerationAsync.cs +++ /dev/null @@ -1,156 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using OpenAI.Files; -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.IO; -using System.Threading; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public async Task Example01_RetrievalAugmentedGenerationAsync() - { - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - FileClient fileClient = openAIClient.GetFileClient(); - AssistantClient assistantClient = openAIClient.GetAssistantClient(); - - // First, let's contrive a document we'll use retrieval with and upload it. - using Stream document = BinaryData.FromString(""" - { - "description": "This document contains the sale history data for Contoso products.", - "sales": [ - { - "month": "January", - "by_product": { - "113043": 15, - "113045": 12, - "113049": 2 - } - }, - { - "month": "February", - "by_product": { - "113045": 22 - } - }, - { - "month": "March", - "by_product": { - "113045": 16, - "113055": 5 - } - } - ] - } - """).ToStream(); - - OpenAIFileInfo salesFile = await fileClient.UploadFileAsync( - document, - "monthly_sales.json", - FileUploadPurpose.Assistants); - - // Now, we'll create a client intended to help with that data - AssistantCreationOptions assistantOptions = new() - { - Name = "Example: Contoso sales RAG", - Instructions = - "You are an assistant that looks up sales data and helps visualize the information based" - + " on user queries. When asked to generate a graph, chart, or other visualization, use" - + " the code interpreter tool to do so.", - Tools = - { - new FileSearchToolDefinition(), - new CodeInterpreterToolDefinition(), - }, - ToolResources = new() - { - FileSearch = new() - { - NewVectorStores = - { - new VectorStoreCreationHelper([salesFile.Id]), - } - } - }, - }; - - Assistant assistant = await assistantClient.CreateAssistantAsync("gpt-4o", assistantOptions); - - // Now we'll create a thread with a user query about the data already associated with the assistant, then run it - ThreadCreationOptions threadOptions = new() - { - InitialMessages = - { - new ThreadInitializationMessage(new List() - { - MessageContent.FromText("How well did product 113045 sell in February? Graph its trend over time."), - }), - }, - }; - - ThreadRun threadRun = await assistantClient.CreateThreadAndRunAsync(assistant.Id, threadOptions); - - // Check back to see when the run is done - do - { - Thread.Sleep(TimeSpan.FromSeconds(1)); - threadRun = assistantClient.GetRun(threadRun.ThreadId, threadRun.Id); - } while (!threadRun.Status.IsTerminal); - - // Finally, we'll print out the full history for the thread that includes the augmented generation - AsyncPageableCollection messages - = assistantClient.GetMessagesAsync(threadRun.ThreadId, ListOrder.OldestFirst); - - await foreach (ThreadMessage message in messages) - { - Console.Write($"[{message.Role.ToString().ToUpper()}]: "); - foreach (MessageContent contentItem in message.Content) - { - if (!string.IsNullOrEmpty(contentItem.Text)) - { - Console.WriteLine($"{contentItem.Text}"); - - if (contentItem.TextAnnotations.Count > 0) - { - Console.WriteLine(); - } - - // Include annotations, if any. - foreach (TextAnnotation annotation in contentItem.TextAnnotations) - { - if (!string.IsNullOrEmpty(annotation.InputFileId)) - { - Console.WriteLine($"* File citation, file ID: {annotation.InputFileId}"); - } - if (!string.IsNullOrEmpty(annotation.OutputFileId)) - { - Console.WriteLine($"* File output, new file ID: {annotation.OutputFileId}"); - } - } - } - if (!string.IsNullOrEmpty(contentItem.ImageFileId)) - { - OpenAIFileInfo imageInfo = await fileClient.GetFileAsync(contentItem.ImageFileId); - BinaryData imageBytes = await fileClient.DownloadFileAsync(contentItem.ImageFileId); - using FileStream stream = File.OpenWrite($"{imageInfo.Filename}.png"); - imageBytes.ToStream().CopyTo(stream); - - Console.WriteLine($""); - } - } - Console.WriteLine(); - } - - // Optionally, delete any persistent resources you no longer need. - _ = await assistantClient.DeleteThreadAsync(threadRun.ThreadId); - _ = await assistantClient.DeleteAssistantAsync(assistant); - _ = await fileClient.DeleteFileAsync(salesFile); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example02_FunctionCalling.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example02_FunctionCalling.cs deleted file mode 100644 index f3e3f464..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example02_FunctionCalling.cs +++ /dev/null @@ -1,193 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.Text.Json; -using System.Threading; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public void Example02_FunctionCalling() - { - #region - string GetCurrentLocation() - { - // Call a location API here. - return "San Francisco"; - } - - const string GetCurrentLocationFunctionName = "get_current_location"; - - FunctionToolDefinition getLocationTool = new() - { - FunctionName = GetCurrentLocationFunctionName, - Description = "Get the user's current location" - }; - - string GetCurrentWeather(string location, string unit = "celsius") - { - // Call a weather API here. - return $"31 {unit}"; - } - - const string GetCurrentWeatherFunctionName = "get_current_weather"; - - FunctionToolDefinition getWeatherTool = new() - { - FunctionName = GetCurrentWeatherFunctionName, - Description = "Get the current weather in a given location", - Parameters = BinaryData.FromString(""" - { - "type": "object", - "properties": { - "location": { - "type": "string", - "description": "The city and state, e.g. Boston, MA" - }, - "unit": { - "type": "string", - "enum": [ "celsius", "fahrenheit" ], - "description": "The temperature unit to use. Infer this from the specified location." - } - }, - "required": [ "location" ] - } - """), - }; - #endregion - - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - AssistantClient client = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - #region - // Create an assistant that can call the function tools. - AssistantCreationOptions assistantOptions = new() - { - Name = "Example: Function Calling", - Instructions = - "Don't make assumptions about what values to plug into functions." - + " Ask for clarification if a user request is ambiguous.", - Tools = { getLocationTool, getWeatherTool }, - }; - - Assistant assistant = client.CreateAssistant("gpt-4-turbo", assistantOptions); - #endregion - - #region - // Create a thread with an initial user message and run it. - ThreadCreationOptions threadOptions = new() - { - InitialMessages = { new ThreadInitializationMessage(["What's the weather like today?"]), }, - }; - - ThreadRun run = client.CreateThreadAndRun(assistant.Id, threadOptions); - #endregion - - #region - // Poll the run until it is no longer queued or in progress. - while (!run.Status.IsTerminal) - { - Thread.Sleep(TimeSpan.FromSeconds(1)); - run = client.GetRun(run.ThreadId, run.Id); - - // If the run requires action, resolve them. - if (run.Status == RunStatus.RequiresAction) - { - List toolOutputs = []; - - foreach (RequiredAction action in run.RequiredActions) - { - switch (action.FunctionName) - { - case GetCurrentLocationFunctionName: - { - string toolResult = GetCurrentLocation(); - toolOutputs.Add(new ToolOutput(action.ToolCallId, toolResult)); - break; - } - - case GetCurrentWeatherFunctionName: - { - // The arguments that the model wants to use to call the function are specified as a - // stringified JSON object based on the schema defined in the tool definition. Note that - // the model may hallucinate arguments too. Consequently, it is important to do the - // appropriate parsing and validation before calling the function. - using JsonDocument argumentsJson = JsonDocument.Parse(action.FunctionArguments); - bool hasLocation = argumentsJson.RootElement.TryGetProperty("location", out JsonElement location); - bool hasUnit = argumentsJson.RootElement.TryGetProperty("unit", out JsonElement unit); - - if (!hasLocation) - { - throw new ArgumentNullException(nameof(location), "The location argument is required."); - } - - string toolResult = hasUnit - ? GetCurrentWeather(location.GetString(), unit.GetString()) - : GetCurrentWeather(location.GetString()); - toolOutputs.Add(new ToolOutput(action.ToolCallId, toolResult)); - break; - } - - default: - { - // Handle other or unexpected calls. - throw new NotImplementedException(); - } - } - } - - // Submit the tool outputs to the assistant, which returns the run to the queued state. - run = client.SubmitToolOutputsToRun(run.ThreadId, run.Id, toolOutputs); - } - } - #endregion - - #region - // With the run complete, list the messages and display their content - if (run.Status == RunStatus.Completed) - { - PageableCollection messages - = client.GetMessages(run.ThreadId, resultOrder: ListOrder.OldestFirst); - - foreach (ThreadMessage message in messages) - { - Console.WriteLine($"[{message.Role.ToString().ToUpper()}]: "); - foreach (MessageContent contentItem in message.Content) - { - Console.WriteLine($"{contentItem.Text}"); - - if (contentItem.ImageFileId is not null) - { - Console.WriteLine($" {contentItem.ImageFileId}"); - } - - // Include annotations, if any. - if (contentItem.TextAnnotations.Count > 0) - { - Console.WriteLine(); - foreach (TextAnnotation annotation in contentItem.TextAnnotations) - { - Console.WriteLine($"* File ID used by file_search: {annotation.InputFileId}"); - Console.WriteLine($"* file_search quote from file: {annotation.InputQuote}"); - Console.WriteLine($"* File ID created by code_interpreter: {annotation.OutputFileId}"); - Console.WriteLine($"* Text to replace: {annotation.TextToReplace}"); - Console.WriteLine($"* Message content index range: {annotation.StartIndex}-{annotation.EndIndex}"); - } - } - - } - Console.WriteLine(); - } - } - else - { - throw new NotImplementedException(run.Status.ToString()); - } - #endregion - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPagination.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPagination.cs deleted file mode 100644 index 1c49470c..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPagination.cs +++ /dev/null @@ -1,27 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using System; -using System.ClientModel; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public void Example03_ListAssistantsWithPagination() - { - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - AssistantClient client = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - int count = 0; - - PageableCollection assistants = client.GetAssistants(); - foreach (Assistant assistant in assistants) - { - Console.WriteLine($"[{count,3}] {assistant.Id} {assistant.CreatedAt:s} {assistant.Name}"); - - count++; - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPaginationAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPaginationAsync.cs deleted file mode 100644 index 145dcfea..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example03_ListAssistantsWithPaginationAsync.cs +++ /dev/null @@ -1,28 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using System; -using System.ClientModel; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public async Task Example03_ListAssistantsWithPaginationAsync() - { - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - AssistantClient client = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - int count = 0; - - AsyncPageableCollection assistants = client.GetAssistantsAsync(); - await foreach (Assistant assistant in assistants) - { - Console.WriteLine($"[{count,3}] {assistant.Id} {assistant.CreatedAt:s} {assistant.Name}"); - - count++; - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example05_AssistantsWithVision.cs b/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example05_AssistantsWithVision.cs deleted file mode 100644 index 61edd89a..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Assistants/Example05_AssistantsWithVision.cs +++ /dev/null @@ -1,71 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using OpenAI.Files; -using System; -using System.ClientModel; - -namespace OpenAI.Examples; - -public partial class AssistantExamples -{ - [Test] - public void Example05_AssistantsWithVision() - { - // Assistants is a beta API and subject to change; acknowledge its experimental status by suppressing the matching warning. -#pragma warning disable OPENAI001 - OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - FileClient fileClient = openAIClient.GetFileClient(); - AssistantClient assistantClient = openAIClient.GetAssistantClient(); - - OpenAIFileInfo pictureOfAppleFile = fileClient.UploadFile( - "picture-of-apple.jpg", - FileUploadPurpose.Vision); - Uri linkToPictureOfOrange = new("https://platform.openai.com/fictitious-files/picture-of-orange.png"); - - Assistant assistant = assistantClient.CreateAssistant( - "gpt-4o", - new AssistantCreationOptions() - { - Instructions = "When asked a question, attempt to answer very concisely. " - + "Prefer one-sentence answers whenever feasible." - }); - - AssistantThread thread = assistantClient.CreateThread(new ThreadCreationOptions() - { - InitialMessages = - { - new ThreadInitializationMessage( - [ - "Hello, assistant! Please compare these two images for me:", - MessageContent.FromImageFileId(pictureOfAppleFile.Id), - MessageContent.FromImageUrl(linkToPictureOfOrange), - ]), - } - }); - - ResultCollection streamingUpdates = assistantClient.CreateRunStreaming( - thread, - assistant, - new RunCreationOptions() - { - AdditionalInstructions = "When possible, try to sneak in puns if you're asked to compare things.", - }); - - foreach (StreamingUpdate streamingUpdate in streamingUpdates) - { - if (streamingUpdate.UpdateKind == StreamingUpdateReason.RunCreated) - { - Console.WriteLine($"--- Run started! ---"); - } - if (streamingUpdate is MessageContentUpdate contentUpdate) - { - Console.Write(contentUpdate.Text); - } - } - - // Delete temporary resources, if desired - _ = fileClient.DeleteFile(pictureOfAppleFile); - _ = assistantClient.DeleteThread(thread); - _ = assistantClient.DeleteAssistant(assistant); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeech.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeech.cs deleted file mode 100644 index 79b8ac12..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeech.cs +++ /dev/null @@ -1,26 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public void Example01_SimpleTextToSpeech() - { - AudioClient client = new("tts-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string input = "Overwatering is a common issue for those taking care of houseplants. To prevent it, it is" - + " crucial to allow the soil to dry out between waterings. Instead of watering on a fixed schedule," - + " consider using a moisture meter to accurately gauge the soil’s wetness. Should the soil retain" - + " moisture, it is wise to postpone watering for a couple more days. When in doubt, it is often safer" - + " to water sparingly and maintain a less-is-more approach."; - - BinaryData speech = client.GenerateSpeechFromText(input, GeneratedSpeechVoice.Alloy); - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.mp3"); - speech.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeechAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeechAsync.cs deleted file mode 100644 index ae8432eb..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example01_SimpleTextToSpeechAsync.cs +++ /dev/null @@ -1,27 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public async Task Example01_SimpleTextToSpeechAsync() - { - AudioClient client = new("tts-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string input = "Overwatering is a common issue for those taking care of houseplants. To prevent it, it is" - + " crucial to allow the soil to dry out between waterings. Instead of watering on a fixed schedule," - + " consider using a moisture meter to accurately gauge the soil’s wetness. Should the soil retain" - + " moisture, it is wise to postpone watering for a couple more days. When in doubt, it is often safer" - + " to water sparingly and maintain a less-is-more approach."; - - BinaryData speech = await client.GenerateSpeechFromTextAsync(input, GeneratedSpeechVoice.Alloy); - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.mp3"); - speech.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscription.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscription.cs deleted file mode 100644 index d5596adc..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscription.cs +++ /dev/null @@ -1,21 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public void Example02_SimpleTranscription() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_houseplant_care.mp3"); - - AudioTranscription transcription = client.TranscribeAudio(audioFilePath); - - Console.WriteLine($"{transcription.Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscriptionAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscriptionAsync.cs deleted file mode 100644 index 8c46d947..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example02_SimpleTranscriptionAsync.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public async Task Example02_SimpleTranscriptionAsync() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_houseplant_care.mp3"); - - AudioTranscription transcription = await client.TranscribeAudioAsync(audioFilePath); - - Console.WriteLine($"{transcription.Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTranscription.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTranscription.cs deleted file mode 100644 index 14e796c8..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTranscription.cs +++ /dev/null @@ -1,42 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public void Example03_VerboseTranscription() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_houseplant_care.mp3"); - - AudioTranscriptionOptions options = new() - { - ResponseFormat = AudioTranscriptionFormat.Verbose, - Granularities = AudioTimestampGranularities.Word | AudioTimestampGranularities.Segment, - }; - - AudioTranscription transcription = client.TranscribeAudio(audioFilePath, options); - - Console.WriteLine("Transcription:"); - Console.WriteLine($"{transcription.Text}"); - - Console.WriteLine(); - Console.WriteLine($"Words:"); - foreach (TranscribedWord word in transcription.Words) - { - Console.WriteLine($" {word.Word,15} : {word.Start.TotalMilliseconds,5:0} - {word.End.TotalMilliseconds,5:0}"); - } - - Console.WriteLine(); - Console.WriteLine($"Segments:"); - foreach (TranscribedSegment segment in transcription.Segments) - { - Console.WriteLine($" {segment.Text,90} : {segment.Start.TotalMilliseconds,5:0} - {segment.End.TotalMilliseconds,5:0}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTrascriptionAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTrascriptionAsync.cs deleted file mode 100644 index 570b8252..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example03_VerboseTrascriptionAsync.cs +++ /dev/null @@ -1,43 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public async Task Example03_VerboseTranscriptionAsync() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_houseplant_care.mp3"); - - AudioTranscriptionOptions options = new() - { - ResponseFormat = AudioTranscriptionFormat.Verbose, - Granularities = AudioTimestampGranularities.Word | AudioTimestampGranularities.Segment, - }; - - AudioTranscription transcription = await client.TranscribeAudioAsync(audioFilePath, options); - - Console.WriteLine("Transcription:"); - Console.WriteLine($"{transcription.Text}"); - - Console.WriteLine(); - Console.WriteLine($"Words:"); - foreach (TranscribedWord word in transcription.Words) - { - Console.WriteLine($" {word.Word,15} : {word.Start.TotalMilliseconds,5:0} - {word.End.TotalMilliseconds,5:0}"); - } - - Console.WriteLine(); - Console.WriteLine($"Segments:"); - foreach (TranscribedSegment segment in transcription.Segments) - { - Console.WriteLine($" {segment.Text,90} : {segment.Start.TotalMilliseconds,5:0} - {segment.End.TotalMilliseconds,5:0}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslation.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslation.cs deleted file mode 100644 index fa6fdebf..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslation.cs +++ /dev/null @@ -1,21 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public void Example04_SimpleTranslation() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_french.wav"); - - AudioTranslation translation = client.TranslateAudio(audioFilePath); - - Console.WriteLine($"{translation.Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslationAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslationAsync.cs deleted file mode 100644 index 5578258d..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Audio/Example04_SimpleTranslationAsync.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class AudioExamples -{ - [Test] - public async Task Example04_SimpleTranslationAsync() - { - AudioClient client = new("whisper-1", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string audioFilePath = Path.Combine("Assets", "audio_french.wav"); - - AudioTranslation translation = await client.TranslateAudioAsync(audioFilePath); - - Console.WriteLine($"{translation.Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChat.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChat.cs deleted file mode 100644 index c964f85a..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChat.cs +++ /dev/null @@ -1,22 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public void Example01_SimpleChat() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - ChatCompletion chatCompletion = client.CompleteChat( - [ - new UserChatMessage("Say 'this is a test.'"), - ]); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{chatCompletion.Content[0].Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChatAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChatAsync.cs deleted file mode 100644 index 94343b88..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example01_SimpleChatAsync.cs +++ /dev/null @@ -1,23 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public async Task Example01_SimpleChatAsync() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - ChatCompletion chatCompletion = await client.CompleteChatAsync( - [ - new UserChatMessage("Say 'this is a test.'"), - ]); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{chatCompletion.Content[0].Text}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreaming.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreaming.cs deleted file mode 100644 index 9e62dfec..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreaming.cs +++ /dev/null @@ -1,30 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.ClientModel; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public void Example02_SimpleChatStreaming() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - ResultCollection chatUpdates - = client.CompleteChatStreaming( - [ - new UserChatMessage("Say 'this is a test.'"), - ]); - - Console.WriteLine($"[ASSISTANT]:"); - foreach (StreamingChatCompletionUpdate chatUpdate in chatUpdates) - { - foreach (ChatMessageContentPart contentPart in chatUpdate.ContentUpdate) - { - Console.Write(contentPart.Text); - } - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreamingAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreamingAsync.cs deleted file mode 100644 index 9ca24a18..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example02_SimpleChatStreamingAsync.cs +++ /dev/null @@ -1,31 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.ClientModel; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public async Task Example02_SimpleChatStreamingAsync() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - AsyncResultCollection asyncChatUpdates - = client.CompleteChatStreamingAsync( - [ - new UserChatMessage("Say 'this is a test.'"), - ]); - - Console.WriteLine($"[ASSISTANT]:"); - await foreach (StreamingChatCompletionUpdate chatUpdate in asyncChatUpdates) - { - foreach (ChatMessageContentPart contentPart in chatUpdate.ContentUpdate) - { - Console.Write(contentPart.Text); - } - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example04_FunctionCallingStreaming.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example04_FunctionCallingStreaming.cs deleted file mode 100644 index e0e799d8..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example04_FunctionCallingStreaming.cs +++ /dev/null @@ -1,202 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.ClientModel; -using System.Collections.Generic; -using System.Text; -using System.Text.Json; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - // See Example03_FunctionCalling.cs for the tool and function definitions. - - [Test] - public void Example04_FunctionCallingStreaming() - { - ChatClient client = new("gpt-4-turbo", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - #region - List messages = [ - new UserChatMessage("What's the weather like today?"), - ]; - - ChatCompletionOptions options = new() - { - Tools = { getCurrentLocationTool, getCurrentWeatherTool }, - }; - #endregion - - #region - bool requiresAction; - - do - { - requiresAction = false; - Dictionary indexToToolCallId = []; - Dictionary indexToFunctionName = []; - Dictionary indexToFunctionArguments = []; - StringBuilder contentBuilder = new(); - ResultCollection chatUpdates - = client.CompleteChatStreaming(messages, options); - - foreach (StreamingChatCompletionUpdate chatUpdate in chatUpdates) - { - // Accumulate the text content as new updates arrive. - foreach (ChatMessageContentPart contentPart in chatUpdate.ContentUpdate) - { - contentBuilder.Append(contentPart.Text); - } - - // Build the tool calls as new updates arrive. - foreach (StreamingChatToolCallUpdate toolCallUpdate in chatUpdate.ToolCallUpdates) - { - // Keep track of which tool call ID belongs to this update index. - if (toolCallUpdate.Id is not null) - { - indexToToolCallId[toolCallUpdate.Index] = toolCallUpdate.Id; - } - - // Keep track of which function name belongs to this update index. - if (toolCallUpdate.FunctionName is not null) - { - indexToFunctionName[toolCallUpdate.Index] = toolCallUpdate.FunctionName; - } - - // Keep track of which function arguments belong to this update index, - // and accumulate the arguments string as new updates arrive. - if (toolCallUpdate.FunctionArgumentsUpdate is not null) - { - StringBuilder argumentsBuilder - = indexToFunctionArguments.TryGetValue(toolCallUpdate.Index, out StringBuilder existingBuilder) - ? existingBuilder - : new StringBuilder(); - argumentsBuilder.Append(toolCallUpdate.FunctionArgumentsUpdate); - indexToFunctionArguments[toolCallUpdate.Index] = argumentsBuilder; - } - } - - switch (chatUpdate.FinishReason) - { - case ChatFinishReason.Stop: - { - // Add the assistant message to the conversation history. - messages.Add(new AssistantChatMessage(contentBuilder.ToString())); - break; - } - - case ChatFinishReason.ToolCalls: - { - // First, collect the accumulated function arguments into complete tool calls to be processed - List toolCalls = []; - foreach ((int index, string toolCallId) in indexToToolCallId) - { - ChatToolCall toolCall = ChatToolCall.CreateFunctionToolCall( - toolCallId, - indexToFunctionName[index], - indexToFunctionArguments[index].ToString()); - - toolCalls.Add(toolCall); - } - - // Next, add the assistant message with tool calls to the conversation history. - string content = contentBuilder.Length > 0 ? contentBuilder.ToString() : null; - messages.Add(new AssistantChatMessage(toolCalls, content)); - - // Then, add a new tool message for each tool call to be resolved. - foreach (ChatToolCall toolCall in toolCalls) - { - switch (toolCall.FunctionName) - { - case nameof(GetCurrentLocation): - { - string toolResult = GetCurrentLocation(); - messages.Add(new ToolChatMessage(toolCall.Id, toolResult)); - break; - } - - case nameof(GetCurrentWeather): - { - // The arguments that the model wants to use to call the function are specified as a - // stringified JSON object based on the schema defined in the tool definition. Note that - // the model may hallucinate arguments too. Consequently, it is important to do the - // appropriate parsing and validation before calling the function. - using JsonDocument argumentsJson = JsonDocument.Parse(toolCall.FunctionArguments); - bool hasLocation = argumentsJson.RootElement.TryGetProperty("location", out JsonElement location); - bool hasUnit = argumentsJson.RootElement.TryGetProperty("unit", out JsonElement unit); - - if (!hasLocation) - { - throw new ArgumentNullException(nameof(location), "The location argument is required."); - } - - string toolResult = hasUnit - ? GetCurrentWeather(location.GetString(), unit.GetString()) - : GetCurrentWeather(location.GetString()); - messages.Add(new ToolChatMessage(toolCall.Id, toolResult)); - break; - } - - default: - { - // Handle other unexpected calls. - throw new NotImplementedException(); - } - } - } - - requiresAction = true; - break; - } - - case ChatFinishReason.Length: - throw new NotImplementedException("Incomplete model output due to MaxTokens parameter or token limit exceeded."); - - case ChatFinishReason.ContentFilter: - throw new NotImplementedException("Omitted content due to a content filter flag."); - - case ChatFinishReason.FunctionCall: - throw new NotImplementedException("Deprecated in favor of tool calls."); - - case null: - break; - } - } - } while (requiresAction); - #endregion - - #region - foreach (ChatMessage requestMessage in messages) - { - switch (requestMessage) - { - case SystemChatMessage systemMessage: - Console.WriteLine($"[SYSTEM]:"); - Console.WriteLine($"{systemMessage.Content[0].Text}"); - Console.WriteLine(); - break; - - case UserChatMessage userMessage: - Console.WriteLine($"[USER]:"); - Console.WriteLine($"{userMessage.Content[0].Text}"); - Console.WriteLine(); - break; - - case AssistantChatMessage assistantMessage when assistantMessage.Content.Count > 0: - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{assistantMessage.Content[0].Text}"); - Console.WriteLine(); - break; - - case ToolChatMessage: - // Do not print any tool messages; let the assistant summarize the tool results instead. - break; - - default: - break; - } - } - #endregion - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVision.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVision.cs deleted file mode 100644 index dbe8543e..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVision.cs +++ /dev/null @@ -1,31 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.Collections.Generic; -using System.IO; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public void Example05_ChatWithVision() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_dog_and_cat.png"); - using Stream imageStream = File.OpenRead(imageFilePath); - BinaryData imageBytes = BinaryData.FromStream(imageStream); - - List messages = [ - new UserChatMessage( - ChatMessageContentPart.CreateTextMessageContentPart("Please describe the following image."), - ChatMessageContentPart.CreateImageMessageContentPart(imageBytes, "image/png")) - ]; - - ChatCompletion chatCompletion = client.CompleteChat(messages); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{chatCompletion.Content[0].Text}"); - } -} \ No newline at end of file diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVisionAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVisionAsync.cs deleted file mode 100644 index c8f4c05c..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example05_ChatWithVisionAsync.cs +++ /dev/null @@ -1,32 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.Collections.Generic; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public async Task Example05_ChatWithVisionAsync() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_dog_and_cat.png"); - using Stream imageStream = File.OpenRead(imageFilePath); - BinaryData imageBytes = BinaryData.FromStream(imageStream); - - List messages = [ - new UserChatMessage( - ChatMessageContentPart.CreateTextMessageContentPart("Please describe the following image."), - ChatMessageContentPart.CreateImageMessageContentPart(imageBytes, "image/png")) - ]; - - ChatCompletion chatCompletion = await client.CompleteChatAsync(messages); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{chatCompletion.Content[0].Text}"); - } -} \ No newline at end of file diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocol.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocol.cs deleted file mode 100644 index 6ee96ae3..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocol.cs +++ /dev/null @@ -1,42 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.ClientModel; -using System.Text.Json; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public void Example06_SimpleChatProtocol() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - BinaryData input = BinaryData.FromString(""" - { - "model": "gpt-4o", - "messages": [ - { - "role": "user", - "content": "How does AI work? Explain it in simple terms." - } - ] - } - """); - - using BinaryContent content = BinaryContent.Create(input); - ClientResult result = client.CompleteChat(content); - BinaryData output = result.GetRawResponse().Content; - - using JsonDocument outputAsJson = JsonDocument.Parse(output.ToString()); - string message = outputAsJson.RootElement - .GetProperty("choices")[0] - .GetProperty("message") - .GetProperty("content") - .GetString(); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{message}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocolAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocolAsync.cs deleted file mode 100644 index 743b49f2..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Chat/Example06_SimpleChatProtocolAsync.cs +++ /dev/null @@ -1,43 +0,0 @@ -using NUnit.Framework; -using OpenAI.Chat; -using System; -using System.ClientModel; -using System.Text.Json; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ChatExamples -{ - [Test] - public async Task Example06_SimpleChatProtocolAsync() - { - ChatClient client = new("gpt-4o", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - BinaryData input = BinaryData.FromString(""" - { - "model": "gpt-4o", - "messages": [ - { - "role": "user", - "content": "How does AI work? Explain it in simple terms." - } - ] - } - """); - - using BinaryContent content = BinaryContent.Create(input); - ClientResult result = await client.CompleteChatAsync(content); - BinaryData output = result.GetRawResponse().Content; - - using JsonDocument outputAsJson = JsonDocument.Parse(output.ToString()); - string message = outputAsJson.RootElement - .GetProperty("choices")[0] - .GetProperty("message") - .GetProperty("content") - .GetString(); - - Console.WriteLine($"[ASSISTANT]:"); - Console.WriteLine($"{message}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/ClientExamples.cs b/src/tests/OpenAI.IntegrationTests/Extended/ClientExamples.cs deleted file mode 100644 index 798d9ef3..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/ClientExamples.cs +++ /dev/null @@ -1,49 +0,0 @@ -using NUnit.Framework; -using OpenAI.Assistants; -using OpenAI.Audio; -using OpenAI.Chat; -using OpenAI.Embeddings; -using OpenAI.Files; -using OpenAI.Images; -using System; - -namespace OpenAI.Examples.Miscellaneous; - -public partial class ClientExamples -{ - [Test] - public void CreateChatClient() - { - ChatClient client = new("gpt-3.5-turbo", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - } - - [Test] - public void CreateEmbeddingClient() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - } - - [Test] - public void CreateImageClient() - { - ImageClient client = new("dall-e-3", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - } - - [Test] - public void CreateMultipleAudioClients() - { - OpenAIClient client = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - AudioClient ttsClient = client.GetAudioClient("tts-1"); - AudioClient whisperClient = client.GetAudioClient("whisper-1"); - } - - [Test] - public void CreateAssistantAndFileClients() - { - OpenAIClient openAIClient = new(Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - FileClient fileClient = openAIClient.GetFileClient(); -#pragma warning disable OPENAI001 - AssistantClient assistantClient = openAIClient.GetAssistantClient(); -#pragma warning restore OPENAI001 - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/CombinationExamples.cs b/src/tests/OpenAI.IntegrationTests/Extended/CombinationExamples.cs deleted file mode 100644 index 31d5ef4c..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/CombinationExamples.cs +++ /dev/null @@ -1,150 +0,0 @@ -using NUnit.Framework; -using OpenAI.Audio; -using OpenAI.Chat; -using OpenAI.Images; -using System; -using System.ClientModel; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples.Miscellaneous; - -public partial class CombinationExamples -{ - [Test] - public void AlpacaArtAssessor() - { - // First, we create an image using dall-e-3: - ImageClient imageClient = new("dall-e-3"); - ClientResult imageResult = imageClient.GenerateImage( - "a majestic alpaca on a mountain ridge, backed by an expansive blue sky accented with sparse clouds", - new() - { - Style = GeneratedImageStyle.Vivid, - Quality = GeneratedImageQuality.High, - Size = GeneratedImageSize.W1792xH1024, - }); - GeneratedImage imageGeneration = imageResult.Value; - Console.WriteLine($"Majestic alpaca available at:\n{imageGeneration.ImageUri.AbsoluteUri}"); - - // Now, we'll ask a cranky art critic to evaluate the image using gpt-4-vision-preview: - ChatClient chatClient = new("gpt-4-vision-preview"); - ChatCompletion chatCompletion = chatClient.CompleteChat( - [ - new SystemChatMessage("Assume the role of a cranky art critic. When asked to describe or " - + "evaluate imagery, focus on criticizing elements of subject, composition, and other details."), - new UserChatMessage( - ChatMessageContentPart.CreateTextMessageContentPart("describe the following image in a few sentences"), - ChatMessageContentPart.CreateImageMessageContentPart(imageGeneration.ImageUri)), - ], - new ChatCompletionOptions() - { - MaxTokens = 2048, - } - ); - - string chatResponseText = chatCompletion.Content[0].Text; - Console.WriteLine($"Art critique of majestic alpaca:\n{chatResponseText}"); - - // Finally, we'll get some text-to-speech for that critical evaluation using tts-1-hd: - AudioClient audioClient = new("tts-1-hd"); - ClientResult ttsResult = audioClient.GenerateSpeechFromText( - text: chatResponseText, - GeneratedSpeechVoice.Fable, - new SpeechGenerationOptions() - { - Speed = 0.9f, - ResponseFormat = GeneratedSpeechFormat.Opus, - }); - FileInfo ttsFileInfo = new($"{chatCompletion.Id}.opus"); - using (FileStream ttsFileStream = ttsFileInfo.Create()) - using (BinaryWriter ttsFileWriter = new(ttsFileStream)) - { - ttsFileWriter.Write(ttsResult.Value); - } - Console.WriteLine($"Alpaca evaluation audio available at:\n{new Uri(ttsFileInfo.FullName).AbsoluteUri}"); - } - - [Test] - public async Task CuriousCreatureCreator() - { - // First, we'll use gpt-4 to have a creative helper imagine a twist on a household pet - ChatClient creativeWriterClient = new("gpt-4"); - ClientResult creativeWriterResult = creativeWriterClient.CompleteChat( - [ - new SystemChatMessage("You're a creative helper that specializes in brainstorming designs for concepts that fuse ordinary, mundane items with a fantastical touch. In particular, you can provide good one-paragraph descriptions of concept images."), - new UserChatMessage("Imagine a household pet. Now add in a subtle touch of magic or 'different'. What do you imagine? Provide a one-paragraph description of a picture of this new creature, focusing on the details of the imagery such that it'd be suitable for creating a picture."), - ], - new ChatCompletionOptions() - { - MaxTokens = 2048, - }); - string description = creativeWriterResult.Value.Content[0].Text; - Console.WriteLine($"Creative helper's creature description:\n{description}"); - - // Asynchronously, in parallel to the next steps, we'll get the creative description in the voice of Onyx - AudioClient ttsClient = new("tts-1-hd"); - Task> imageDescriptionAudioTask = ttsClient.GenerateSpeechFromTextAsync( - description, - GeneratedSpeechVoice.Onyx, - new SpeechGenerationOptions() - { - Speed = 1.1f, - ResponseFormat = GeneratedSpeechFormat.Opus, - }); - _ = Task.Run(async () => - { - ClientResult audioResult = await imageDescriptionAudioTask; - FileInfo audioFileInfo = new FileInfo($"{creativeWriterResult.Value.Id}-description.opus"); - using FileStream fileStream = audioFileInfo.Create(); - using BinaryWriter fileWriter = new(fileStream); - fileWriter.Write(audioResult.Value); - Console.WriteLine($"Spoken description available at:\n{new Uri(audioFileInfo.FullName).AbsoluteUri}"); - }); - - // Meanwhile, we'll use dall-e-3 to generate a rendition of our LLM artist's vision - ImageClient imageGenerationClient = new("dall-e-3"); - ClientResult imageGenerationResult = await imageGenerationClient.GenerateImageAsync( - description, - new ImageGenerationOptions() - { - Size = GeneratedImageSize.W1792xH1024, - Quality = GeneratedImageQuality.High, - }); - Uri imageLocation = imageGenerationResult.Value.ImageUri; - Console.WriteLine($"Creature image available at:\n{imageLocation.AbsoluteUri}"); - - // Now, we'll use gpt-4-vision-preview to get a hopelessly taken assessment from a usually exigent art connoisseur - ChatClient imageCriticClient = new("gpt-4-vision-preview"); - ClientResult criticalAppraisalResult = await imageCriticClient.CompleteChatAsync( - [ - new SystemChatMessage("Assume the role of an art critic. Although usually cranky and occasionally even referred to as a 'curmudgeon', you're somehow entirely smitten with the subject presented to you and, despite your best efforts, can't help but lavish praise when you're asked to appraise a provided image."), - new UserChatMessage( - ChatMessageContentPart.CreateTextMessageContentPart("Evaluate this image for me. What is it, and what do you think of it?"), - ChatMessageContentPart.CreateImageMessageContentPart(imageLocation)), - ], - new ChatCompletionOptions() - { - MaxTokens = 2048, - }); - string appraisal = criticalAppraisalResult.Value.Content[0].Text; - Console.WriteLine($"Critic's appraisal:\n{appraisal}"); - - // Finally, we'll get that art expert's laudations in the voice of Fable - ClientResult appraisalAudioResult = await ttsClient.GenerateSpeechFromTextAsync( - appraisal, - GeneratedSpeechVoice.Fable, - new SpeechGenerationOptions() - { - Speed = 0.9f, - ResponseFormat = GeneratedSpeechFormat.Opus, - }); - FileInfo criticAudioFileInfo = new($"{criticalAppraisalResult.Value.Id}-appraisal.opus"); - using (FileStream criticStream = criticAudioFileInfo.Create()) - using (BinaryWriter criticFileWriter = new(criticStream)) - { - criticFileWriter.Write(appraisalAudioResult.Value); - } - Console.WriteLine($"Critical appraisal available at:\n{new Uri(criticAudioFileInfo.FullName).AbsoluteUri}"); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbedding.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbedding.cs deleted file mode 100644 index 0eaacb7c..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbedding.cs +++ /dev/null @@ -1,28 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public void Example01_SimpleEmbedding() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - - Embedding embedding = client.GenerateEmbedding(description); - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbeddingAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbeddingAsync.cs deleted file mode 100644 index 0a81b587..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example01_SimpleEmbeddingAsync.cs +++ /dev/null @@ -1,29 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public async Task Example01_SimpleEmbeddingAsync() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - - Embedding embedding = await client.GenerateEmbeddingAsync(description); - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptions.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptions.cs deleted file mode 100644 index 16e744f2..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptions.cs +++ /dev/null @@ -1,30 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public void Example02_EmbeddingWithOptions() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - - EmbeddingGenerationOptions options = new() { Dimensions = 512 }; - - Embedding embedding = client.GenerateEmbedding(description, options); - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,3}] = {vector.Span[i]}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptionsAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptionsAsync.cs deleted file mode 100644 index bbb12cb7..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example02_EmbeddingWithOptionsAsync.cs +++ /dev/null @@ -1,31 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public async Task Example02_EmbeddingWithOptionsAsync() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - - EmbeddingGenerationOptions options = new() { Dimensions = 512 }; - - Embedding embedding = await client.GenerateEmbeddingAsync(description, options); - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,3}] = {vector.Span[i]}"); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddings.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddings.cs deleted file mode 100644 index a85dd200..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddings.cs +++ /dev/null @@ -1,37 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; -using System.Collections.Generic; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public void Example03_MultipleEmbeddings() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string category = "Luxury"; - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - List inputs = [category, description]; - - EmbeddingCollection collection = client.GenerateEmbeddings(inputs); - - foreach (Embedding embedding in collection) - { - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); - } - - Console.WriteLine(); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddingsAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddingsAsync.cs deleted file mode 100644 index 6f82d2d5..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Embeddings/Example03_MultipleEmbeddingsAsync.cs +++ /dev/null @@ -1,38 +0,0 @@ -using NUnit.Framework; -using OpenAI.Embeddings; -using System; -using System.Collections.Generic; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class EmbeddingExamples -{ - [Test] - public async Task Example03_MultipleEmbeddingsAsync() - { - EmbeddingClient client = new("text-embedding-3-small", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string category = "Luxury"; - string description = "Best hotel in town if you like luxury hotels. They have an amazing infinity pool, a spa," - + " and a really helpful concierge. The location is perfect -- right downtown, close to all the tourist" - + " attractions. We highly recommend this hotel."; - List inputs = [category, description]; - - EmbeddingCollection collection = await client.GenerateEmbeddingsAsync(inputs); - - foreach (Embedding embedding in collection) - { - ReadOnlyMemory vector = embedding.Vector; - - Console.WriteLine($"Dimension: {vector.Length}"); - Console.WriteLine($"Floats: "); - for (int i = 0; i < vector.Length; i++) - { - Console.WriteLine($" [{i,4}] = {vector.Span[i]}"); - } - - Console.WriteLine(); - } - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGeneration.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGeneration.cs deleted file mode 100644 index f194348a..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGeneration.cs +++ /dev/null @@ -1,37 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public void Example01_SimpleImageGeneration() - { - ImageClient client = new("dall-e-3", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string prompt = "The concept for a living room that blends Scandinavian simplicity with Japanese minimalism for" - + " a serene and cozy atmosphere. It's a space that invites relaxation and mindfulness, with natural light" - + " and fresh air. Using neutral tones, including colors like white, beige, gray, and black, that create a" - + " sense of harmony. Featuring sleek wood furniture with clean lines and subtle curves to add warmth and" - + " elegance. Plants and flowers in ceramic pots adding color and life to a space. They can serve as focal" - + " points, creating a connection with nature. Soft textiles and cushions in organic fabrics adding comfort" - + " and softness to a space. They can serve as accents, adding contrast and texture."; - - ImageGenerationOptions options = new() - { - Quality = GeneratedImageQuality.High, - Size = GeneratedImageSize.W1792xH1024, - Style = GeneratedImageStyle.Vivid, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage image = client.GenerateImage(prompt, options); - BinaryData bytes = image.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - bytes.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGenerationAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGenerationAsync.cs deleted file mode 100644 index 20487d3a..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example01_SimpleImageGenerationAsync.cs +++ /dev/null @@ -1,38 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public async Task Example01_SimpleImageGenerationAsync() - { - ImageClient client = new("dall-e-3", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string prompt = "The concept for a living room that blends Scandinavian simplicity with Japanese minimalism for" - + " a serene and cozy atmosphere. It's a space that invites relaxation and mindfulness, with natural light" - + " and fresh air. Using neutral tones, including colors like white, beige, gray, and black, that create a" - + " sense of harmony. Featuring sleek wood furniture with clean lines and subtle curves to add warmth and" - + " elegance. Plants and flowers in ceramic pots adding color and life to a space. They can serve as focal" - + " points, creating a connection with nature. Soft textiles and cushions in organic fabrics adding comfort" - + " and softness to a space. They can serve as accents, adding contrast and texture."; - - ImageGenerationOptions options = new() - { - Quality = GeneratedImageQuality.High, - Size = GeneratedImageSize.W1792xH1024, - Style = GeneratedImageStyle.Vivid, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage image = await client.GenerateImageAsync(prompt, options); - BinaryData bytes = image.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - bytes.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEdit.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEdit.cs deleted file mode 100644 index 155f9b5f..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEdit.cs +++ /dev/null @@ -1,31 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public void Example02_SimpleImageEdit() - { - ImageClient client = new("dall-e-2", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_flower_vase.png"); - string prompt = "A vase full of beautiful flowers."; - string maskFilePath = Path.Combine("Assets", "images_flower_vase_mask.png"); - - ImageEditOptions options = new() - { - Size = GeneratedImageSize.W512xH512, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage edit = client.GenerateImageEdit(imageFilePath, prompt, maskFilePath, options); - BinaryData bytes = edit.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - bytes.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEditAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEditAsync.cs deleted file mode 100644 index f6d36434..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example02_SimpleImageEditAsync.cs +++ /dev/null @@ -1,32 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public async Task Example02_SimpleImageEditAsync() - { - ImageClient client = new("dall-e-2", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_flower_vase.png"); - string prompt = "A vase full of beautiful flowers."; - string maskFilePath = Path.Combine("Assets", "images_flower_vase_mask.png"); - - ImageEditOptions options = new() - { - Size = GeneratedImageSize.W512xH512, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage edit = await client.GenerateImageEditAsync(imageFilePath, prompt, maskFilePath, options); - BinaryData bytes = edit.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - await bytes.ToStream().CopyToAsync(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariation.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariation.cs deleted file mode 100644 index 04bd3a39..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariation.cs +++ /dev/null @@ -1,29 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public void Example03_SimpleImageVariation() - { - ImageClient client = new("dall-e-2", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_dog_and_cat.png"); - - ImageVariationOptions options = new() - { - Size = GeneratedImageSize.W256xH256, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage variation = client.GenerateImageVariation(imageFilePath, options); - BinaryData bytes = variation.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - bytes.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariationAsync.cs b/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariationAsync.cs deleted file mode 100644 index 50c90a24..00000000 --- a/src/tests/OpenAI.IntegrationTests/Extended/Images/Example03_SimpleImageVariationAsync.cs +++ /dev/null @@ -1,30 +0,0 @@ -using NUnit.Framework; -using OpenAI.Images; -using System; -using System.IO; -using System.Threading.Tasks; - -namespace OpenAI.Examples; - -public partial class ImageExamples -{ - [Test] - public async Task Example03_SimpleImageVariationAsync() - { - ImageClient client = new("dall-e-2", Environment.GetEnvironmentVariable("OPENAI_API_KEY")); - - string imageFilePath = Path.Combine("Assets", "images_dog_and_cat.png"); - - ImageVariationOptions options = new() - { - Size = GeneratedImageSize.W256xH256, - ResponseFormat = GeneratedImageFormat.Bytes - }; - - GeneratedImage variation = await client.GenerateImageVariationAsync(imageFilePath, options); - BinaryData bytes = variation.ImageBytes; - - using FileStream stream = File.OpenWrite($"{Guid.NewGuid()}.png"); - bytes.ToStream().CopyTo(stream); - } -} diff --git a/src/tests/OpenAI.IntegrationTests/OpenAI.IntegrationTests.csproj b/src/tests/OpenAI.IntegrationTests/OpenAI.IntegrationTests.csproj index 1f54ea6d..0bbde0aa 100644 --- a/src/tests/OpenAI.IntegrationTests/OpenAI.IntegrationTests.csproj +++ b/src/tests/OpenAI.IntegrationTests/OpenAI.IntegrationTests.csproj @@ -9,6 +9,10 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + @@ -20,6 +24,7 @@ + diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assets/audio_french.wav b/src/tests/OpenAI.IntegrationTests/Resources/audio_french.wav similarity index 100% rename from src/tests/OpenAI.IntegrationTests/Extended/Assets/audio_french.wav rename to src/tests/OpenAI.IntegrationTests/Resources/audio_french.wav diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assets/audio_houseplant_care.mp3 b/src/tests/OpenAI.IntegrationTests/Resources/audio_houseplant_care.mp3 similarity index 100% rename from src/tests/OpenAI.IntegrationTests/Extended/Assets/audio_houseplant_care.mp3 rename to src/tests/OpenAI.IntegrationTests/Resources/audio_houseplant_care.mp3 diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assets/images_dog_and_cat.png b/src/tests/OpenAI.IntegrationTests/Resources/images_dog_and_cat.png similarity index 100% rename from src/tests/OpenAI.IntegrationTests/Extended/Assets/images_dog_and_cat.png rename to src/tests/OpenAI.IntegrationTests/Resources/images_dog_and_cat.png diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assets/images_flower_vase.png b/src/tests/OpenAI.IntegrationTests/Resources/images_flower_vase.png similarity index 100% rename from src/tests/OpenAI.IntegrationTests/Extended/Assets/images_flower_vase.png rename to src/tests/OpenAI.IntegrationTests/Resources/images_flower_vase.png diff --git a/src/tests/OpenAI.IntegrationTests/Extended/Assets/images_flower_vase_mask.png b/src/tests/OpenAI.IntegrationTests/Resources/images_flower_vase_mask.png similarity index 100% rename from src/tests/OpenAI.IntegrationTests/Extended/Assets/images_flower_vase_mask.png rename to src/tests/OpenAI.IntegrationTests/Resources/images_flower_vase_mask.png diff --git a/src/tests/OpenAI.IntegrationTests/Tools/VariousTypesTools.cs b/src/tests/OpenAI.IntegrationTests/Tools/VariousTypesTools.cs index 67ee13bb..bf2e479b 100755 --- a/src/tests/OpenAI.IntegrationTests/Tools/VariousTypesTools.cs +++ b/src/tests/OpenAI.IntegrationTests/Tools/VariousTypesTools.cs @@ -1,5 +1,4 @@ -using System; -using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; +using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; namespace OpenAI.IntegrationTests; diff --git a/src/tests/OpenAI.IntegrationTests/Tools/WeatherStrictTools.cs b/src/tests/OpenAI.IntegrationTests/Tools/WeatherStrictTools.cs index 94dd0266..5c727b29 100755 --- a/src/tests/OpenAI.IntegrationTests/Tools/WeatherStrictTools.cs +++ b/src/tests/OpenAI.IntegrationTests/Tools/WeatherStrictTools.cs @@ -1,6 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; -using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; +using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; namespace OpenAI.IntegrationTests; diff --git a/src/tests/OpenAI.IntegrationTests/Tools/WeatherTools.cs b/src/tests/OpenAI.IntegrationTests/Tools/WeatherTools.cs index 3ac69a25..cd7ffb72 100755 --- a/src/tests/OpenAI.IntegrationTests/Tools/WeatherTools.cs +++ b/src/tests/OpenAI.IntegrationTests/Tools/WeatherTools.cs @@ -1,6 +1,4 @@ -using System.Threading; -using System.Threading.Tasks; -using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; +using DescriptionAttribute = System.ComponentModel.DescriptionAttribute; namespace OpenAI.IntegrationTests;