diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs index 4dfd4c3db346..681b6a869322 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Services/BedrockChatCompletionServiceTests.cs @@ -150,14 +150,14 @@ public async Task GetStreamingChatMessageContentsAsyncShouldReturnStreamedChatMe var chatHistory = CreateSampleChatHistory(); // Act - List output = []; + List output = new(); var result = service.GetStreamingChatMessageContentsAsync(chatHistory).ConfigureAwait(true); // Assert int iterations = 0; await foreach (var item in result) { - iterations++; + iterations += 1; Assert.NotNull(item); Assert.NotNull(item.Content); Assert.NotNull(item.Role); @@ -401,7 +401,7 @@ private ConverseResponse CreateConverseResponse(string text, ConversationRole ro Message = new Message { Role = role, - Content = [new() { Text = text }] + Content = new List { 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 250e09947998..20f1ee5676d0 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 = - [ + Results = new List + { new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - ] + } }))), ContentType = "application/json" }); @@ -201,14 +201,14 @@ public async Task GetStreamingTextContentsAsyncShouldReturnStreamedTextContentsA var service = kernel.GetRequiredService(); // Act - List result = []; + List result = new(); var output = service.GetStreamingTextContentsAsync(prompt).ConfigureAwait(true); // Assert int iterations = 0; await foreach (var item in output) { - iterations++; + iterations += 1; Assert.NotNull(item); Assert.NotNull(item.Text); Assert.NotNull(item.InnerContent); diff --git a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockChatCompletionModelExecutionSettingsTests.cs index 375e9ce599d3..c8e8ae949421 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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() { Text = "I'm doing well." }] + Content = new List { 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 188f3b6bf7b9..0bd0051c38f7 100644 --- a/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs +++ b/dotnet/src/Connectors/Connectors.Amazon.UnitTests/Settings/BedrockTextGenerationModelExecutionSettingsTests.cs @@ -15,8 +15,6 @@ using Moq; using Xunit; -#pragma warning disable RCS1261 // Resource can be disposed asynchronously - namespace Microsoft.SemanticKernel.Connectors.Amazon.UnitTests; /// @@ -156,14 +154,14 @@ public async Task TitanExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new TitanTextResponse { InputTextTokenCount = 5, - Results = - [ + Results = new List + { new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - ] + } }))), ContentType = "application/json" }); @@ -226,7 +224,7 @@ public async Task TitanExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.1f, TopP = 0.95f, MaxTokenCount = 256, - StopSequences = [""], + StopSequences = new List { "" }, ModelId = modelId, }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny())) @@ -251,14 +249,14 @@ public async Task TitanExecutionSettingsPropertySetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new TitanTextResponse { InputTextTokenCount = 5, - Results = - [ + Results = new List + { new() { TokenCount = 10, OutputText = "This is a mock output.", CompletionReason = "stop" } - ] + } }))), ContentType = "application/json" }); @@ -352,8 +350,8 @@ public async Task JambaExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JambaResponse.AI21TextResponse { Id = "my-request-id", - Choices = - [ + Choices = new List + { new() { Index = 0, Message = new AI21JambaResponse.Message @@ -363,7 +361,7 @@ public async Task JambaExecutionSettingsExtensionDataSetsProperlyAsync() }, FinishReason = "stop" } - ], + }, Usage = new AI21JambaResponse.JambaUsage { PromptTokens = 10, @@ -443,7 +441,7 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.8f, TopP = 0.95f, MaxTokens = 256, - Stop = [""], + Stop = new List { "" }, NumberOfResponses = 1, FrequencyPenalty = 0.0, PresencePenalty = 0.0, @@ -471,8 +469,8 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JambaResponse.AI21TextResponse { Id = "my-request-id", - Choices = - [ + Choices = new List + { new() { Index = 0, Message = new AI21JambaResponse.Message @@ -482,7 +480,7 @@ public async Task JambaExecutionSettingsPropertySetsProperlyAsync() }, FinishReason = "stop" } - ], + }, Usage = new AI21JambaResponse.JambaUsage { PromptTokens = 10, @@ -590,8 +588,8 @@ public async Task JurassicExecutionSettingsExtensionDataSetsProperlyAsync() Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new AI21JurassicResponse { Id = 10000000000, - Completions = - [ + Completions = new List + { new() { Data = new AI21JurassicResponse.JurassicData @@ -599,7 +597,7 @@ public async Task JurassicExecutionSettingsExtensionDataSetsProperlyAsync() Text = "Hello! This is a mock AI21 response." } } - ] + } }))) }); var kernel = Kernel.CreateBuilder().AddBedrockTextGenerationService(modelId, mockBedrockApi.Object).Build(); @@ -775,15 +773,15 @@ public async Task CommandExecutionSettingsSetsExtensionDataAsync() { Id = "my-request-id", Prompt = "Write a greeting.", - Generations = - [ + Generations = new List + { new() { Id = "generation-id", Text = "Hello! This is a mock Cohere Command response.", FinishReason = "COMPLETE", IsFinished = true } - ] + } }))), ContentType = "application/json" }); @@ -841,7 +839,7 @@ public async Task CommandExecutionSettingsPropertySetsProperlyAsync() Temperature = 0.8, TopP = 0.95, MaxTokens = 256, - StopSequences = [""], + StopSequences = new List { "" }, ModelId = modelId }; mockBedrockApi.Setup(m => m.DetermineServiceOperationEndpoint(It.IsAny())) @@ -867,15 +865,15 @@ public async Task CommandExecutionSettingsPropertySetsProperlyAsync() { Id = "my-request-id", Prompt = "Write a greeting.", - Generations = - [ + Generations = new List + { new() { Id = "generation-id", Text = "Hello! This is a mock Cohere Command response.", FinishReason = "COMPLETE", IsFinished = true } - ] + } }))), ContentType = "application/json" }); @@ -959,13 +957,13 @@ public async Task MistralExecutionSettingsSetExtensionDataAsync() { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new MistralResponse { - Outputs = - [ + Outputs = new List + { new() { Text = "Hello! This is a mock Mistral response.", StopReason = "stop_sequence" } - ] + } }))), ContentType = "application/json" }); @@ -1042,13 +1040,13 @@ public async Task MistralExecutionSettingsPropertiesSetAsync() { Body = new MemoryStream(Encoding.UTF8.GetBytes(JsonSerializer.Serialize(new MistralResponse { - Outputs = - [ + Outputs = new List + { 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 1f3f37fcfccd..cd69136b2f3c 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 is >= 200 and < 300) + if ((int)httpStatusCode >= 200 && (int)httpStatusCode < 300) { // 2xx status codes represent success return ActivityStatusCode.Ok; } - if ((int)httpStatusCode is >= 400 and < 600) + if ((int)httpStatusCode >= 400 && (int)httpStatusCode < 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 77ddda9976da..3490d3a6b1e2 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/BedrockModelUtilities.cs @@ -22,11 +22,17 @@ internal static class BedrockModelUtilities /// Thrown if invalid role. internal static ConversationRole MapAuthorRoleToConversationRole(AuthorRole role) { - return role == AuthorRole.User - ? ConversationRole.User - : role == AuthorRole.Assistant - ? ConversationRole.Assistant - : throw new ArgumentOutOfRangeException($"Invalid role: {role}"); + if (role == AuthorRole.User) + { + return ConversationRole.User; + } + + if (role == AuthorRole.Assistant) + { + return ConversationRole.Assistant; + } + + throw new ArgumentOutOfRangeException($"Invalid role: {role}"); } /// @@ -52,20 +58,19 @@ 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; -#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(); + 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(); } /// 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 e6e85df1be6b..a50b221fc4ca 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockChatCompletionClient.cs @@ -14,8 +14,6 @@ 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 1328edab0a8c..98ed2aebc1c2 100644 --- a/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs +++ b/dotnet/src/Connectors/Connectors.Amazon/Bedrock/Core/Clients/BedrockTextGenerationClient.cs @@ -15,8 +15,6 @@ 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 cc834d14e3af..17e80c89fdb6 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 = - [ + List messages = new() + { 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 42206871b1e9..cd1d82a255dc 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 @@ -77,7 +77,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = [] + AdditionalModelResponseFieldPaths = new List() }; return converseRequest; @@ -118,7 +118,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = [] + AdditionalModelResponseFieldPaths = new List() }; 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 1583fb7d3eab..8faff37a8497 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; } = []; + public IList? StopSequences { get; set; } = new List(); } } 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 73fd43e9bfa2..274fcb6a332b 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 = [], + AdditionalModelResponseFieldPaths = new List(), 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 = [], + AdditionalModelResponseFieldPaths = new List(), 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 9d373697ffb1..3dd2aaa4b074 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 = - [ + chatHistory = new List + { 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 = [], + AdditionalModelResponseFieldPaths = new List(), GuardrailConfig = null, ToolConfig = null }; @@ -210,7 +210,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = additionalModelRequestFields, - AdditionalModelResponseFieldPaths = [], + AdditionalModelResponseFieldPaths = new List(), 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 28f0eeb349d8..8aba3b0e9153 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 = [], + AdditionalModelResponseFieldPaths = new List(), GuardrailConfig = null, ToolConfig = null }; @@ -110,7 +110,7 @@ public ConverseStreamRequest GetConverseStreamRequest( System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = [], + AdditionalModelResponseFieldPaths = new List(), 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 08affadd9c3a..3e5905803422 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; } = []; + public IList? StopSequences { get; set; } = new List(); /// /// 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 14a14f83219f..60aca758e78e 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 @@ -77,7 +77,7 @@ public ConverseRequest GetConverseRequest(string modelId, ChatHistory chatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = [] + AdditionalModelResponseFieldPaths = new List() }; return converseRequest; } @@ -122,7 +122,7 @@ public ConverseStreamRequest GetConverseStreamRequest(string modelId, ChatHistor System = systemMessages, InferenceConfig = inferenceConfig, AdditionalModelRequestFields = new Document(), - AdditionalModelResponseFieldPaths = [] + AdditionalModelResponseFieldPaths = new List() }; return converseRequest; } diff --git a/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj b/dotnet/src/Connectors/Connectors.Amazon/Connectors.Amazon.csproj index 3aa2650a4622..d80ad909e216 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;IDE0010;IDE0017;IDE0021;IDE0022;IDE0024;IDE0046 + $(NoWarn);SKEXP0001;SKEXP0070 diff --git a/dotnet/src/IntegrationTests/IntegrationTests.csproj b/dotnet/src/IntegrationTests/IntegrationTests.csproj index fb9b160835c2..e24215b583d6 100644 --- a/dotnet/src/IntegrationTests/IntegrationTests.csproj +++ b/dotnet/src/IntegrationTests/IntegrationTests.csproj @@ -5,7 +5,7 @@ net8.0 true false - $(NoWarn);IDE0021;IDE0022;IDE0017;CA2007;CA1861;VSTHRD111;SKEXP0001;SKEXP0010;SKEXP0020;SKEXP0040;SKEXP0050;SKEXP0060;SKEXP0070;SKEXP0080;SKEXP0110;OPENAI001 + $(NoWarn);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 42f0fe018e2e..48287af8b963 100644 --- a/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs +++ b/dotnet/src/InternalUtilities/src/Data/VectorStoreRecordPropertyReader.cs @@ -8,8 +8,6 @@ using System.Text.Json; using System.Text.Json.Serialization; -#pragma warning disable IDE0046 // Convert to conditional expression - namespace Microsoft.Extensions.VectorData; /// @@ -120,8 +118,11 @@ public VectorStoreRecordPropertyReader( this._parameterlessConstructorInfo = new Lazy(() => { - var constructor = dataModelType.GetConstructor(Type.EmptyTypes) - ?? throw new ArgumentException($"Type {dataModelType.FullName} must have a parameterless constructor."); + var constructor = dataModelType.GetConstructor(Type.EmptyTypes); + if (constructor == null) + { + throw new ArgumentException($"Type {dataModelType.FullName} must have a parameterless constructor."); + } return constructor; }); @@ -172,9 +173,7 @@ 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; @@ -394,11 +393,13 @@ 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.") - : ((List KeyProperties, List DataProperties, List VectorProperties))(keyProperties, dataProperties, vectorProperties); + if (!supportsMultipleVectors && vectorProperties.Count > 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); } /// @@ -410,9 +411,9 @@ private static (List KeyProperties, ListThe categorized properties. private static (List KeyProperties, List DataProperties, List VectorProperties) FindPropertiesInfo([DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicProperties)] Type type) { - List keyProperties = []; - List dataProperties = []; - List vectorProperties = []; + List keyProperties = new(); + List dataProperties = new(); + List vectorProperties = new(); foreach (var property in type.GetProperties()) { @@ -448,33 +449,42 @@ 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 = []; - List dataProperties = []; - List vectorProperties = []; + List keyProperties = new(); + List dataProperties = new(); + List vectorProperties = new(); foreach (VectorStoreRecordProperty property in vectorStoreRecordDefinition.Properties) { // Key. if (property is VectorStoreRecordKeyProperty keyPropertyInfo) { - var keyProperty = type.GetProperty(keyPropertyInfo.DataModelPropertyName) - ?? throw new ArgumentException($"Key property '{keyPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); + var keyProperty = type.GetProperty(keyPropertyInfo.DataModelPropertyName); + if (keyProperty == null) + { + 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) - ?? throw new ArgumentException($"Data property '{dataPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); + var dataProperty = type.GetProperty(dataPropertyInfo.DataModelPropertyName); + if (dataProperty == null) + { + 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) - ?? throw new ArgumentException($"Vector property '{vectorPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); + var vectorProperty = type.GetProperty(vectorPropertyInfo.DataModelPropertyName); + if (vectorProperty == null) + { + throw new ArgumentException($"Vector property '{vectorPropertyInfo.DataModelPropertyName}' not found on type {type.FullName}."); + } vectorProperties.Add(vectorProperty); } @@ -625,8 +635,11 @@ private static string GetJsonPropertyName(VectorStoreRecordProperty property, [D } } - return options?.PropertyNamingPolicy is not null - ? options.PropertyNamingPolicy.ConvertName(property.DataModelPropertyName) - : property.DataModelPropertyName; + if (options?.PropertyNamingPolicy is not null) + { + return options.PropertyNamingPolicy.ConvertName(property.DataModelPropertyName); + } + + return property.DataModelPropertyName; } } diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs b/dotnet/src/InternalUtilities/src/Diagnostics/ActivityExtensions.cs index cfac3d8aad75..d5b36387b305 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 { - return c.Metadata?.TryGetValue("FinishReason", out var finishReason) == true && !string.IsNullOrEmpty(finishReason as string) - ? finishReason - : "N/A"; + if (c.Metadata?.TryGetValue("FinishReason", out var finishReason) == true && !string.IsNullOrEmpty(finishReason as string)) + { + return finishReason; + } + + return "N/A"; }); if (finishReasons.Any()) diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs index f01498a7a28a..91d716132ced 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs @@ -7,9 +7,6 @@ // 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 bfa8f7727167..aca550799b86 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresDynamicCodeAttribute.cs @@ -1,5 +1,4 @@ // 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 f4dac450d352..e4a6e9da7255 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/RequiresUnreferencedCodeAttribute.cs @@ -1,5 +1,4 @@ // 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 f42b85e322c9..810040dde7fc 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/UnconditionalSuppressMessageAttribute.cs @@ -1,5 +1,4 @@ // 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 a142b6e37eb0..c58a497c0a6b 100644 --- a/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs +++ b/dotnet/src/InternalUtilities/src/System/AppContextSwitchHelper.cs @@ -3,8 +3,6 @@ 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 31a50d51e07d..94785e17c762 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 = [.. items]; + this._items = new(items); } /// diff --git a/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs b/dotnet/src/InternalUtilities/src/Text/DataUriParser.cs index 4043cbfa5593..41887a4cbe79 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,8 +36,9 @@ 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 (string.IsNullOrEmpty(value) - || value!.Length % 4 != 0 + if (value is null + || value.Length == 0 + || value.Length % 4 != 0 || value.Contains(' ') || value.Contains('\t') || value.Contains('\r') @@ -87,10 +88,8 @@ 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(';'); @@ -158,7 +157,7 @@ internal sealed class DataUri /// /// The optional parameters of the data. /// - internal Dictionary Parameters { get; set; } = []; + internal Dictionary Parameters { get; set; } = new(); /// /// 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 b46718878bb7..2298f9b72a07 100644 --- a/dotnet/src/InternalUtilities/src/Text/SseReader.cs +++ b/dotnet/src/InternalUtilities/src/Text/SseReader.cs @@ -154,9 +154,7 @@ 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 efdec5cac6ab..26ed0480649a 100644 --- a/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs +++ b/dotnet/src/InternalUtilities/src/Text/StreamJsonParser.cs @@ -113,10 +113,8 @@ 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 { @@ -148,9 +146,7 @@ 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 ded01a23430d..90521772d682 100644 --- a/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs +++ b/dotnet/src/InternalUtilities/src/Type/TypeExtensions.cs @@ -66,9 +66,7 @@ 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}>"; }