From cf968f5eba31855abab79d3f1ae4a6df515a9ea3 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Mon, 6 Jan 2025 10:53:47 +0000 Subject: [PATCH] Fix amazon warnings --- .../BedrockChatCompletionServiceTests.cs | 6 +- .../BedrockTextGenerationServiceTests.cs | 10 +-- ...atCompletionModelExecutionSettingsTests.cs | 18 +++--- ...xtGenerationModelExecutionSettingsTests.cs | 62 +++++++++--------- .../Bedrock/Core/BedrockClientUtilities.cs | 4 +- .../Bedrock/Core/BedrockModelUtilities.cs | 41 ++++++------ .../Clients/BedrockChatCompletionClient.cs | 2 + .../Clients/BedrockTextGenerationClient.cs | 2 + .../Core/Models/AI21Labs/AI21JambaService.cs | 6 +- .../Core/Models/Amazon/AmazonService.cs | 4 +- .../Core/Models/Amazon/TitanRequest.cs | 2 +- .../Core/Models/Anthropic/AnthropicService.cs | 4 +- .../Models/Cohere/CohereCommandRService.cs | 10 +-- .../Bedrock/Core/Models/Meta/MetaService.cs | 4 +- .../Core/Models/Mistral/MistralRequest.cs | 2 +- .../Core/Models/Mistral/MistralService.cs | 4 +- .../Connectors.Amazon.csproj | 2 +- .../IntegrationTests/IntegrationTests.csproj | 2 +- .../Data/VectorStoreRecordPropertyReader.cs | 63 ++++++++----------- .../src/Diagnostics/ActivityExtensions.cs | 4 +- .../Diagnostics/CompilerServicesAttributes.cs | 1 + .../DynamicallyAccessedMembersAttribute.cs | 1 + .../src/Diagnostics/ExperimentalAttribute.cs | 1 + .../src/Diagnostics/ModelDiagnostics.cs | 9 +-- .../src/Diagnostics/NullableAttributes.cs | 3 + .../RequiresDynamicCodeAttribute.cs | 1 + .../RequiresUnreferencedCodeAttribute.cs | 1 + .../UnconditionalSuppressMessageAttribute.cs | 1 + .../src/System/AppContextSwitchHelper.cs | 2 + .../src/System/NonNullCollection.cs | 2 +- .../src/Text/DataUriParser.cs | 13 ++-- .../InternalUtilities/src/Text/SseReader.cs | 2 + .../src/Text/StreamJsonParser.cs | 4 ++ .../src/Type/TypeExtensions.cs | 2 + 34 files changed, 150 insertions(+), 145 deletions(-) diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs index 6c7d045812dc..bfc5b3c593d0 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs @@ -149,14 +149,14 @@ public async Task GetStreamingChatMessageContentsAsyncShouldReturnStreamedChatMe var chatHistory = CreateSampleChatHistory(); // Act - List output = new(); + List output = []; var result = service.GetStreamingChatMessageContentsAsync(chatHistory).ConfigureAwait(true); // Assert int iterations = 0; await foreach (var item in result) { - iterations += 1; + iterations++; Assert.NotNull(item); Assert.NotNull(item.Content); Assert.NotNull(item.Role); @@ -399,7 +399,7 @@ private ConverseResponse CreateConverseResponse(string text, ConversationRole ro Message = new Message { Role = role, - Content = new List { new() { Text = text } } + Content = [new() { Text = text }] } }, Metrics = new ConverseMetrics(), diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockTextGenerationServiceTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockTextGenerationServiceTests.cs index 0148951a144c..5ae3a618be7d 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockTextGenerationServiceTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockTextGenerationServiceTests.cs @@ -150,14 +150,14 @@ public async Task GetTextContentsAsyncShouldReturnTextContentsAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new TitanTextResponse { InputTextTokenCount = 5, - Results = new List - { + Results = + [ new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - } + ] }))), ContentType = "application/json" }); @@ -200,14 +200,14 @@ public async Task GetStreamingTextContentsAsyncShouldReturnStreamedTextContentsA var service = kernel.GetRequiredService(); // Act - List result = new(); + List result = []; var output = service.GetStreamingTextContentsAsync(prompt).ConfigureAwait(true); // Assert int iterations = 0; await foreach (var item in output) { - iterations += 1; + iterations++; Assert.NotNull(item); Assert.NotNull(item.Text); result.Add(item); diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs index c8e8ae949421..375e9ce599d3 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs @@ -82,7 +82,7 @@ public async Task ExecutionSettingsExtensionDataShouldOverridePropertyAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -144,7 +144,7 @@ public async Task TitanExecutionSettingsShouldSetExtensionDataAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -199,7 +199,7 @@ public async Task TitanExecutionSettingsShouldSetPropertiesAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -258,7 +258,7 @@ public async Task ClaudePromptExecutionSettingsExtensionDataSetsProperlyAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -313,7 +313,7 @@ public async Task ClaudePromptExecutionSettingsSetsPropertiesAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -371,7 +371,7 @@ public async Task LlamaGetChatMessageContentsAsyncShouldReturnChatMessageWithPro Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -429,7 +429,7 @@ public async Task CommandRExecutionSettingsShouldSetExtensionDataAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -484,7 +484,7 @@ public async Task CommandRExecutionSettingsShouldSetPropertiesAsync() Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), @@ -544,7 +544,7 @@ public async Task JambaGetChatMessageContentsAsyncShouldReturnChatMessageWithPro Message = new Message { Role = ConversationRole.Assistant, - Content = new List { new() { Text = "I'm doing well." } } + Content = [new() { Text = "I'm doing well." }] } }, Metrics = new ConverseMetrics(), diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs index 0bd0051c38f7..188f3b6bf7b9 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs @@ -15,6 +15,8 @@ using Moq; using Xunit; +#pragma warning disable RCS1261 // Resource can be disposed asynchronously + namespace Microsoft.SemanticKernel.Connectors.Amazon.UnitTests; /// @@ -154,14 +156,14 @@ public async Task TitanExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new TitanTextResponse { InputTextTokenCount = 5, - Results = new List - { + Results = + [ new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - } + ] }))), ContentType = "application/json" }); @@ -224,7 +226,7 @@ public async Task TitanExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.1f, TopP = 0.95f, MaxTokenCount = 256, - StopSequences = new List { "" }, + StopSequences = [""], ModelId = modelId, }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny())) @@ -249,14 +251,14 @@ public async Task TitanExecutionSettingsPropertySetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new TitanTextResponse { InputTextTokenCount = 5, - Results = new List - { + Results = + [ new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - } + ] }))), ContentType = "application/json" }); @@ -350,8 +352,8 @@ public async Task JambaExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JambaResponse.AI21TextResponse { Id = "my-request-id", - Choices = new List - { + Choices = + [ new() { Index = 0, Message = new AI21JambaResponse.Message @@ -361,7 +363,7 @@ public async Task JambaExecutionSettingsExtensionDataSetsProperlyAsync() }, FinishReason = "stop" } - }, + ], Usage = new AI21JambaResponse.JambaUsage { PromptTokens = 10, @@ -441,7 +443,7 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.8f, TopP = 0.95f, MaxTokens = 256, - Stop = new List { "" }, + Stop = [""], NumberOfResponses = 1, FrequencyPenalty = 0.0, PresencePenalty = 0.0, @@ -469,8 +471,8 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JambaResponse.AI21TextResponse { Id = "my-request-id", - Choices = new List - { + Choices = + [ new() { Index = 0, Message = new AI21JambaResponse.Message @@ -480,7 +482,7 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() }, FinishReason = "stop" } - }, + ], Usage = new AI21JambaResponse.JambaUsage { PromptTokens = 10, @@ -588,8 +590,8 @@ public async Task JurassicExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JurassicResponse { Id = 10000000000, - Completions = new List - { + Completions = + [ new() { Data = new AI21JurassicResponse.JurassicData @@ -597,7 +599,7 @@ public async Task JurassicExecutionSettingsExtensionDataSetsProperlyAsync() Text = "Hello! This is a mock AI21 response." } } - } + ] }))) }); var kernel = Kernel.CreateBuilder().AddBedrockTextGenerationService(modelId, mockBedrockApi.Object).Build(); @@ -773,15 +775,15 @@ public async Task CommandExecutionSettingsSetsExtensionDataAsync() { Id = "my-request-id", Prompt = "Write a greeting.", - Generations = new List - { + Generations = + [ new() { Id = "generation-id", Text = "Hello! This is a mock Cohere Command response.", FinishReason = "COMPLETE", IsFinished = true } - } + ] }))), ContentType = "application/json" }); @@ -839,7 +841,7 @@ public async Task CommandExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.8, TopP = 0.95, MaxTokens = 256, - StopSequences = new List { "" }, + StopSequences = [""], ModelId = modelId }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny())) @@ -865,15 +867,15 @@ public async Task CommandExecutionSettingsPropertySetsProperlyAsync() { Id = "my-request-id", Prompt = "Write a greeting.", - Generations = new List - { + Generations = + [ new() { Id = "generation-id", Text = "Hello! This is a mock Cohere Command response.", FinishReason = "COMPLETE", IsFinished = true } - } + ] }))), ContentType = "application/json" }); @@ -957,13 +959,13 @@ public async Task MistralExecutionSettingsSetExtensionDataAsync() { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new MistralResponse { - Outputs = new List - { + Outputs = + [ new() { Text = "Hello! This is a mock Mistral response.", StopReason = "stop_sequence" } - } + ] }))), ContentType = "application/json" }); @@ -1040,13 +1042,13 @@ public async Task MistralExecutionSettingsPropertiesSetAsync() { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new MistralResponse { - Outputs = new List - { + Outputs = + [ new() { Text = "Hello! This is a mock Mistral response.", StopReason = "stop_sequence" } - } + ] }))), ContentType = "application/json" }); diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockClientUtilities.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockClientUtilities.cs index cd69136b2f3c..1f3f37fcfccd 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockClientUtilities.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockClientUtilities.cs @@ -21,12 +21,12 @@ internal sealed class BedrockClientUtilities /// The ActivityStatusCode for the Semantic Kernel internal static ActivityStatusCode ConvertHttpStatusCodeToActivityStatusCode(HttpStatusCode httpStatusCode) { - if ((int)httpStatusCode >= 200 && (int)httpStatusCode < 300) + if ((int)httpStatusCode is >= 200 and < 300) { // 2xx status codes represent success return ActivityStatusCode.Ok; } - if ((int)httpStatusCode >= 400 && (int)httpStatusCode < 600) + if ((int)httpStatusCode is >= 400 and < 600) { // 4xx and 5xx status codes represent errors return ActivityStatusCode.Error; diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs index 3490d3a6b1e2..77ddda9976da 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs @@ -22,17 +22,11 @@ internal static class BedrockModelUtilities /// Thrown if invalid role. internal static ConversationRole MapAuthorRoleToConversationRole(AuthorRole role) { - if (role == AuthorRole.User) - { - return ConversationRole.User; - } - - if (role == AuthorRole.Assistant) - { - return ConversationRole.Assistant; - } - - throw new ArgumentOutOfRangeException($"Invalid role: {role}"); + return role == AuthorRole.User + ? ConversationRole.User + : role == AuthorRole.Assistant + ? ConversationRole.Assistant + : throw new ArgumentOutOfRangeException($"Invalid role: {role}"); } /// @@ -58,19 +52,20 @@ internal static List BuildMessageList(ChatHistory chatHistory) { // Check that the text from the latest message in the chat history is not empty. Verify.NotNullOrEmpty(chatHistory); +#pragma warning disable IDE0056 // Use index operator string? text = chatHistory[chatHistory.Count - 1].Content; - if (string.IsNullOrWhiteSpace(text)) - { - throw new ArgumentException("Last message in chat history was null or whitespace."); - } - return chatHistory - .Where(m => m.Role != AuthorRole.System) - .Select(m => new Message - { - Role = MapAuthorRoleToConversationRole(m.Role), - Content = new List { new() { Text = m.Content } } - }) - .ToList(); +#pragma warning restore IDE0056 // Use index operator + + return string.IsNullOrWhiteSpace(text) + ? throw new ArgumentException("Last message in chat history was null or whitespace.") + : chatHistory + .Where(m => m.Role != AuthorRole.System) + .Select(m => new Message + { + Role = MapAuthorRoleToConversationRole(m.Role), + Content = [new() { Text = m.Content }] + }) + .ToList(); } /// diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs index b258c3b696a6..be2913c68dc1 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs @@ -14,6 +14,8 @@ using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Diagnostics; +#pragma warning disable IDE0305 // Simplify collection initialization + namespace Microsoft.SemanticKernel.Connectors.Amazon.Core; /// diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs index b659cb81bf74..528403b2e4a1 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs @@ -15,6 +15,8 @@ using Microsoft.Extensions.Logging.Abstractions; using Microsoft.SemanticKernel.Diagnostics; +#pragma warning disable RCS1261 /// Resource can be disposed asynchronously + namespace Microsoft.SemanticKernel.Connectors.Amazon.Core; /// diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/AI21Labs/AI21JambaService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/AI21Labs/AI21JambaService.cs index 110782a2c8ad..4196189992af 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/AI21Labs/AI21JambaService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/AI21Labs/AI21JambaService.cs @@ -20,14 +20,14 @@ internal sealed class AI21JambaService : IBedrockTextGenerationService, IBedrock public object GetInvokeModelRequestBody(string modelId, string prompt, PromptExecutionSettings? executionSettings) { var settings = AmazonJambaExecutionSettings.FromExecutionSettings(executionSettings); - List messages = new() - { + List messages = + [ new AI21JambaRequest.AI21TextGenerationRequest.JambaMessage() { Role = "user", Content = prompt } - }; + ]; // Get the prompt execution settings from ExtensionData dictionary of PromptExecutionSettings or AmazonJambaTextExecutionSettings specific parameters. var requestBody = new AI21JambaRequest.AI21TextGenerationRequest() diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/AmazonService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/AmazonService.cs index 17a32450ed24..d11c6491fafd 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/AmazonService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/AmazonService.cs @@ -78,7 +78,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List() + AdditionalModelResponseFieldPaths = [] }; return converseRequest; @@ -119,7 +119,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List() + AdditionalModelResponseFieldPaths = [] }; return converseRequest; diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/TitanRequest.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/TitanRequest.cs index 8faff37a8497..1583fb7d3eab 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/TitanRequest.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Amazon/TitanRequest.cs @@ -57,6 +57,6 @@ internal sealed class AmazonTitanTextGenerationConfig /// [JsonPropertyName("stopSequences")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public IList? StopSequences { get; set; } = new List(); + public IList? StopSequences { get; set; } = []; } } diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Anthropic/AnthropicService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Anthropic/AnthropicService.cs index d28d86b3cd2c..e0ac686edb01 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Anthropic/AnthropicService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Anthropic/AnthropicService.cs @@ -111,7 +111,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = additionalModelRequestFields, - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, // Set if needed ToolConfig = null // Set if needed }; @@ -194,7 +194,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = additionalModelRequestFields, - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, // Set if needed ToolConfig = null // Set if needed }; diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Cohere/CohereCommandRService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Cohere/CohereCommandRService.cs index 433cdc1417f4..86ab3ec66fe4 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Cohere/CohereCommandRService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Cohere/CohereCommandRService.cs @@ -24,14 +24,14 @@ public object GetInvokeModelRequestBody(string modelId, string prompt, PromptExe var chatHistory = BedrockModelUtilities.GetExtensionDataValue>(executionSettings?.ExtensionData, "chat_history") ?? exec.ChatHistory; if (chatHistory == null || chatHistory.Count == 0) { - chatHistory = new List - { + chatHistory = + [ new() { Role = "USER", Message = prompt } - }; + ]; } var requestBody = new CommandRRequest.CommandRTextGenerationRequest() { @@ -131,7 +131,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = additionalModelRequestFields, - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, ToolConfig = null }; @@ -210,7 +210,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = additionalModelRequestFields, - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, ToolConfig = null }; diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Meta/MetaService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Meta/MetaService.cs index 0b6e0ba6d355..d9cdf84bf87c 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Meta/MetaService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Meta/MetaService.cs @@ -66,7 +66,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, ToolConfig = null }; @@ -110,7 +110,7 @@ public ConverseStreamRequest GetConverseStreamRequest( System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List(), + AdditionalModelResponseFieldPaths = [], GuardrailConfig = null, ToolConfig = null }; diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralRequest.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralRequest.cs index 3e5905803422..08affadd9c3a 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralRequest.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralRequest.cs @@ -30,7 +30,7 @@ internal sealed class MistralTextGenerationRequest /// [JsonPropertyName("stop")] [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] - public IList? StopSequences { get; set; } = new List(); + public IList? StopSequences { get; set; } = []; /// /// Controls the randomness of predictions made by the model. diff --git a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralService.cs b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralService.cs index eee8076b5165..daf9b1cef3d7 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralService.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Models/Mistral/MistralService.cs @@ -76,7 +76,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List() + AdditionalModelResponseFieldPaths = [] }; return converseRequest; } @@ -121,7 +121,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = new List() + AdditionalModelResponseFieldPaths = [] }; return converseRequest; } diff --git a/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj b/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj index d80ad909e216..3aa2650a4622 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj +++ b/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj @@ -6,7 +6,7 @@ $(AssemblyName) net8.0;netstandard2.0 alpha - $(NoWarn);SKEXP0001;SKEXP0070 + $(NoWarn);SKEXP0001;SKEXP0070;IDE0010;IDE0017;IDE0021;IDE0022;IDE0024;IDE0046 diff --git a/dotnet/src/IntegrationTests/IntegrationTests.csproj b/dotnet/src/IntegrationTests/IntegrationTests.csproj index e24215b583d6..fb9b160835c2 100644 --- a/dotnet/src/IntegrationTests/IntegrationTests.csproj +++ b/dotnet/src/IntegrationTests/IntegrationTests.csproj @@ -5,7 +5,7 @@ net8.0 true false - $(NoWarn);CA2007,CA1861,VSTHRD111,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0080,SKEXP0110,OPENAI001 + $(NoWarn);IDE0021;IDE0022;IDE0017;CA2007;CA1861;VSTHRD111;SKEXP0001;SKEXP0010;SKEXP0020;SKEXP0040;SKEXP0050;SKEXP0060;SKEXP0070;SKEXP0080;SKEXP0110;OPENAI001 b7762d10-e29b-4bb1-8b74-b6d69a667dd4 diff --git a/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs b/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs index 48287af8b963..42f0fe018e2e 100644 --- a/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs +++ b/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs @@ -8,6 +8,8 @@ using System.Text.Json; using System.Text.Json.Serialization; +#pragma warning disable IDE0046 // Convert to conditional expression + namespace Microsoft.Extensions.VectorData; /// @@ -118,11 +120,8 @@ public VectorStoreRecordPropertyReader( this._parameterlessConstructorInfo = new Lazy(() => { - var constructor = dataModelType.GetConstructor(Type.EmptyTypes); - if (constructor == null) - { - throw new ArgumentException($"Type {dataModelType.FullName} must have a parameterless constructor."); - } + var constructor = dataModelType.GetConstructor(Type.EmptyTypes) + ?? throw new ArgumentException($"Type {dataModelType.FullName} must have a parameterless constructor."); return constructor; }); @@ -173,7 +172,9 @@ public VectorStoreRecordPropertyReader( } /// Gets the record definition of the current storage model. +#pragma warning disable RCS1085 // Use auto-implemented property public VectorStoreRecordDefinition RecordDefinition => this._vectorStoreRecordDefinition; +#pragma warning restore RCS1085 // Use auto-implemented property /// Gets the list of properties from the record definition. public IReadOnlyList Properties => this._vectorStoreRecordDefinition.Properties; @@ -393,13 +394,11 @@ private static (List KeyProperties, List 1) - { - throw new ArgumentException($"Multiple vector properties found on type {typeName} or the provided {nameof(VectorStoreRecordDefinition)} while only one is supported."); - } - - return (keyProperties, dataProperties, vectorProperties); + return !supportsMultipleVectors && vectorProperties.Count > 1 + ? throw new ArgumentException($"Multiple vector properties found on type {typeName} or the provided {nameof(VectorStoreRecordDefinition)} while only one is supported.") + : ((List KeyProperties, List DataProperties, List VectorProperties))(keyProperties, dataProperties, vectorProperties); } /// @@ -411,9 +410,9 @@ private static (List KeyProperties, ListThe categorized properties. private static (List KeyProperties, List DataProperties, List VectorProperties) FindPropertiesInfo([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type) { - List keyProperties = new(); - List dataProperties = new(); - List vectorProperties = new(); + List keyProperties = []; + List dataProperties = []; + List vectorProperties = []; foreach (var property in type.GetProperties()) { @@ -449,42 +448,33 @@ private static (List KeyProperties, List DataPropert /// The categorized properties. public static (List KeyProperties, List DataProperties, List VectorProperties) FindPropertiesInfo([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type, VectorStoreRecordDefinition vectorStoreRecordDefinition) { - List keyProperties = new(); - List dataProperties = new(); - List vectorProperties = new(); + List keyProperties = []; + List dataProperties = []; + List vectorProperties = []; foreach (VectorStoreRecordProperty property in vectorStoreRecordDefinition.Properties) { // Key. if (property is VectorStoreRecordKeyProperty keyPropertyInfo) { - var keyProperty = type.GetProperty(keyPropertyInfo.DataModelPropertyName); - if (keyProperty == null) - { - throw new ArgumentException($"Key property '{keyPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); - } + var keyProperty = type.GetProperty(keyPropertyInfo.DataModelPropertyName) + ?? throw new ArgumentException($"Key property '{keyPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); keyProperties.Add(keyProperty); } // Data. else if (property is VectorStoreRecordDataProperty dataPropertyInfo) { - var dataProperty = type.GetProperty(dataPropertyInfo.DataModelPropertyName); - if (dataProperty == null) - { - throw new ArgumentException($"Data property '{dataPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); - } + var dataProperty = type.GetProperty(dataPropertyInfo.DataModelPropertyName) + ?? throw new ArgumentException($"Data property '{dataPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); dataProperties.Add(dataProperty); } // Vector. else if (property is VectorStoreRecordVectorProperty vectorPropertyInfo) { - var vectorProperty = type.GetProperty(vectorPropertyInfo.DataModelPropertyName); - if (vectorProperty == null) - { - throw new ArgumentException($"Vector property '{vectorPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); - } + var vectorProperty = type.GetProperty(vectorPropertyInfo.DataModelPropertyName) + ?? throw new ArgumentException($"Vector property '{vectorPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); vectorProperties.Add(vectorProperty); } @@ -635,11 +625,8 @@ private static string GetJsonPropertyName(VectorStoreRecordProperty property, [D } } - if (options?.PropertyNamingPolicy is not null) - { - return options.PropertyNamingPolicy.ConvertName(property.DataModelPropertyName); - } - - return property.DataModelPropertyName; + return options?.PropertyNamingPolicy is not null + ? options.PropertyNamingPolicy.ConvertName(property.DataModelPropertyName) + : property.DataModelPropertyName; } } diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs b/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs index d5b36387b305..cfac3d8aad75 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs @@ -24,7 +24,7 @@ public static Activity SetTags(this Activity activity, ReadOnlySpan { - if (c.Metadata?.TryGetValue("FinishReason", out var finishReason) == true && !string.IsNullOrEmpty(finishReason as string)) - { - return finishReason; - } - - return "N/A"; + return c.Metadata?.TryGetValue("FinishReason", out var finishReason) == true && !string.IsNullOrEmpty(finishReason as string) + ? finishReason + : "N/A"; }); if (finishReasons.Any()) diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs index 91d716132ced..f01498a7a28a 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs @@ -7,6 +7,9 @@ // This was copied from https://github.com/dotnet/runtime/blob/39b9607807f29e48cae4652cd74735182b31182e/src/libraries/System.Private.CoreLib/src/System/Diagnostics/CodeAnalysis/NullableAttributes.cs // and updated to have the scope of the attributes be internal. +#pragma warning disable RCS1251 //Remove unnecessary braces +#pragma warning disable IDE0290 // Using directive is unnecessary. + #if !NETCOREAPP namespace System.Diagnostics.CodeAnalysis; diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs index aca550799b86..bfa8f7727167 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs @@ -1,4 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. +#pragma warning disable IDE0290 // Use primary constructor #if !NET7_0_OR_GREATER namespace System.Diagnostics.CodeAnalysis; diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs index e4a6e9da7255..f4dac450d352 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs @@ -1,4 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. +#pragma warning disable IDE0290 // Use primary constructor #if !NET5_0_OR_GREATER namespace System.Diagnostics.CodeAnalysis; diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs b/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs index 810040dde7fc..f42b85e322c9 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs @@ -1,4 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. +#pragma warning disable IDE0290 // Use primary constructor #if !NET8_0_OR_GREATER namespace System.Diagnostics.CodeAnalysis; diff --git a/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs b/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs index c58a497c0a6b..a142b6e37eb0 100644 --- a/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs +++ b/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs @@ -3,6 +3,8 @@ using System; using System.Diagnostics.CodeAnalysis; +#pragma warning disable IDE0046 // Convert to conditional expression + namespace Microsoft.SemanticKernel; /// diff --git a/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs b/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs index 94785e17c762..31a50d51e07d 100644 --- a/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs +++ b/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs @@ -31,7 +31,7 @@ internal sealed class NonNullCollection : IList, IReadOnlyList public NonNullCollection(IEnumerable items) { Verify.NotNull(items); - this._items = new(items); + this._items = [.. items]; } /// diff --git a/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs b/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs index 41887a4cbe79..4043cbfa5593 100644 --- a/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs +++ b/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs @@ -19,11 +19,11 @@ internal static class DataUriParser { private const string Scheme = "data:"; - private static readonly char[] s_base64Chars = { + private static readonly char[] s_base64Chars = [ 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/' - }; + ]; /// /// Extension method to test whether the value is a base64 string /// @@ -36,9 +36,8 @@ private static bool IsBase64String(string? value) // If it is not you can return false. Quite effective // Further, if it meets the above criteria, then test for spaces. // If it contains spaces, it is not base64 - if (value is null - || value.Length == 0 - || value.Length % 4 != 0 + if (string.IsNullOrEmpty(value) + || value!.Length % 4 != 0 || value.Contains(' ') || value.Contains('\t') || value.Contains('\r') @@ -88,8 +87,10 @@ internal static DataUri Parse(string? dataUri) throw new UriFormatException("Invalid data uri format. The data URI must contain a comma separating the metadata and the data."); } +#pragma warning disable IDE0057 // Use range operator string metadata = dataUri.Substring(currentIndex, dataIndex - currentIndex); model.Data = dataUri.Substring(dataIndex + 1); +#pragma warning restore IDE0057 // Use range operator // Split the metadata into components var metadataParts = metadata.Split(';'); @@ -157,7 +158,7 @@ internal sealed class DataUri /// /// The optional parameters of the data. /// - internal Dictionary Parameters { get; set; } = new(); + internal Dictionary Parameters { get; set; } = []; /// /// The optional format of the data. Most common is "base64". diff --git a/dotnet/src/InternalUtilities/src/Text/SseReader.cs b/dotnet/src/InternalUtilities/src/Text/SseReader.cs index 2298f9b72a07..b46718878bb7 100644 --- a/dotnet/src/InternalUtilities/src/Text/SseReader.cs +++ b/dotnet/src/InternalUtilities/src/Text/SseReader.cs @@ -154,7 +154,9 @@ private bool TryParseLine(string lineText, out SseLine line) ReadOnlySpan lineSpan = lineText.AsSpan(); int colonIndex = lineSpan.IndexOf(':'); +#pragma warning disable IDE0057 // Use range operator ReadOnlySpan fieldValue = colonIndex >= 0 ? lineSpan.Slice(colonIndex + 1) : string.Empty.AsSpan(); +#pragma warning restore IDE0057 // Use range operator bool hasSpace = fieldValue.Length > 0 && fieldValue[0] == ' '; line = new SseLine(lineText, colonIndex, hasSpace, this._lastEventName); diff --git a/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs b/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs index 26ed0480649a..efdec5cac6ab 100644 --- a/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs +++ b/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs @@ -113,8 +113,10 @@ private bool ProcessLineUntilCompleteJson(string line) int nextIndex = i + 1; if (nextIndex < line.Length) { +#pragma warning disable IDE0057 // Use range operator this._lastLine = line.Substring(nextIndex); this.AppendLine(line.Substring(0, nextIndex)); +#pragma warning restore IDE0057 // Use range operator } else { @@ -146,7 +148,9 @@ private void AppendLine(string line) switch (this._jsonBuilder) { case { Length: 0 } when this._startBracketIndex >= 0: +#pragma warning disable IDE0057 // Use range operator this._jsonBuilder.Append(line.Substring(this._startBracketIndex)); +#pragma warning restore IDE0057 // Use range operator break; case { Length: > 0 }: this._jsonBuilder.Append(line); diff --git a/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs b/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs index 90521772d682..ded01a23430d 100644 --- a/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs +++ b/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs @@ -66,7 +66,9 @@ public static string GetFriendlyTypeName(this Type type) { string typeName = type.GetGenericTypeDefinition().Name; // Remove the `1, `2 etc from the type name which indicates the number of generic arguments +#pragma warning disable IDE0057 // Use range operator typeName = typeName.Substring(0, typeName.IndexOf('`', (int)StringComparison.Ordinal)); +#pragma warning restore IDE0057 // Use range operator string genericArgs = string.Join(", ", type.GetGenericArguments().Select(GetFriendlyTypeName)); return $"{typeName}<{genericArgs}>"; }