From 8d0662e80d0a26c51f38162ea3c7b27f037d0d8b Mon Sep 17 00:00:00 2001 From: Stephen Toub Date: Thu, 11 Apr 2024 10:43:57 -0400 Subject: [PATCH] .Net: Use C# 11/12 features throughout repo (#4387) ~~Fixes https://github.com/microsoft/semantic-kernel/issues/4295. For now this is done using a package reference to the latest C# toolset. Once we drop use of the .NET 6/7 SDKs in CI, this reference can be removed.~~ The changes to upgrade projects to LangVersion 12 was done separately. This PR now rolls out use of C# 12 features. --- dotnet/Directory.Packages.props | 5 - .../samples/CreateChatGptPlugin/.editorconfig | 3 +- .../CreateChatGptPlugin/Solution/Program.cs | 2 +- .../samples/DocumentationExamples/BaseTest.cs | 2 +- .../ConfiguringPrompts.cs | 9 +- .../CreatingFunctions.cs | 2 +- .../FunctionsWithinPrompts.cs | 20 +- .../samples/DocumentationExamples/Planner.cs | 2 +- .../SerializingPrompts.cs | 20 +- .../DocumentationExamples/Templates.cs | 14 +- dotnet/samples/HomeAutomation/Program.cs | 2 +- .../Example16_CustomLLM.cs | 6 +- .../Example20_HuggingFace.cs | 2 +- .../Example21_OpenAIPlugins.cs | 14 +- .../Example22_OpenAIPlugin_AzureKeyVault.cs | 12 +- .../Example24_OpenApiPlugin_Jira.cs | 15 +- .../Example25_ReadOnlyMemoryStore.cs | 4 +- .../Example35_GrpcPlugins.cs | 8 +- .../Example37_CompletionIdentity.cs | 5 +- .../Example40_DIContainer.cs | 12 +- .../Example55_TextChunker.cs | 2 +- ...ateMethodFunctionsWithMultipleArguments.cs | 6 +- .../Example58_ConfigureExecutionSettings.cs | 28 +-- .../Example59_OpenAIFunctionCalling.cs | 6 +- .../Example61_MultipleLLMs.cs | 2 +- ...xample66_FunctionCallingStepwisePlanner.cs | 5 +- .../Example68_GPTVision.cs | 6 +- .../KernelSyntaxExamples/Example70_Agents.cs | 2 +- .../Example71_AgentDelegation.cs | 2 +- .../Example72_AgentCollaboration.cs | 4 +- .../Example73_AgentAuthoring.cs | 2 +- .../Example74_FlowOrchestrator.cs | 8 +- .../Example75_AgentTools.cs | 4 +- .../KernelSyntaxExamples/Example76_Filters.cs | 2 +- .../Example79_ChatCompletionAgent.cs | 6 +- ...Example80_FunctionCallingPlannerWithRAG.cs | 5 +- .../Example83_ApiManifest.cs | 22 +-- .../Example84_AzureAISearchPlugin.cs | 4 +- .../Example87_ChatHistorySerialization.cs | 20 +- .../Example97_GeminiVision.cs | 12 +- .../Example98_GeminiFunctionCalling.cs | 8 +- .../Step4_Dependency_Injection.cs | 9 +- .../Getting_Started/Step8_Pipelining.cs | 2 +- .../ComplexParamsDictionaryPlugin.cs | 18 +- .../RepoUtils/EnumerableExtensions.cs | 2 +- .../RepoUtils/RepoFiles.cs | 2 +- .../TelemetryExample/RepoUtils/RepoFiles.cs | 2 +- .../AzureAISearchMemoryStoreTests.cs | 22 +-- .../Core/Gemini/GeminiRequestTests.cs | 12 +- .../GeminiPromptExecutionSettingsTests.cs | 6 +- .../GeminiPluginCollectionExtensions.cs | 2 +- .../Core/Gemini/Models/GeminiRequest.cs | 16 +- .../Core/Gemini/Models/GeminiTool.cs | 2 +- .../Core/GoogleAI/GoogleAIEmbeddingRequest.cs | 6 +- .../GeminiToolCallBehavior.cs | 9 +- .../GoogleAIGeminiChatCompletionService.cs | 2 +- .../GoogleAITextEmbeddingGenerationService.cs | 2 +- .../VertexAIGeminiChatCompletionService.cs | 2 +- .../VertexAITextEmbeddingGenerationService.cs | 2 +- .../HuggingFaceEmbeddingGenerationTests.cs | 12 +- .../HuggingFaceTextGenerationTests.cs | 2 +- .../Client/TextEmbeddingRequest.cs | 2 +- .../Services/HuggingFaceImageToTextService.cs | 2 +- ...ggingFaceTextEmbeddingGenerationService.cs | 2 +- .../HuggingFaceTextGenerationService.cs | 2 +- .../AzureAISearchMemoryStore.cs | 12 +- .../ChromaMemoryStore.cs | 10 +- .../Http/ApiSchema/ChromaEmbeddingsModel.cs | 6 +- .../Http/ApiSchema/ChromaQueryResultModel.cs | 8 +- .../Connectors.Memory.DuckDB/Database.cs | 9 +- .../DuckDBMemoryStore.cs | 4 +- .../KustoMemoryStore.cs | 12 +- .../MilvusMemoryStore.cs | 32 +-- .../Http/ApiSchema/DeleteRequest.cs | 4 +- .../Http/ApiSchema/UpsertRequest.cs | 2 +- .../Model/IndexMetadataConfig.cs | 6 +- .../Model/PodType.cs | 10 +- .../PineconeClient.cs | 12 +- .../PineconeDocument.cs | 2 +- .../PineconeMemoryStore.cs | 22 +-- .../PineconeUtils.cs | 2 +- .../Http/ApiSchema/CreateCollectionRequest.cs | 12 +- .../Http/ApiSchema/DeleteVectorsRequest.cs | 2 +- .../Http/ApiSchema/GetVectorsRequest.cs | 2 +- .../Http/ApiSchema/GetVectorsResponse.cs | 2 +- .../Http/ApiSchema/ListCollectionsResponse.cs | 2 +- .../Http/ApiSchema/SearchVectorsRequest.cs | 2 +- .../Http/ApiSchema/SearchVectorsResponse.cs | 2 +- .../Http/ApiSchema/UpsertVectorRequest.cs | 6 +- .../QdrantMemoryStore.cs | 24 +-- .../RedisMemoryStore.cs | 6 +- .../SqliteMemoryStore.cs | 2 +- .../Http/ApiSchema/BatchRequest.cs | 4 +- .../ApiSchema/CreateClassSchemaRequest.cs | 16 +- .../Http/ApiSchema/CreateGraphRequest.cs | 2 +- .../WeaviateMemoryStore.cs | 17 +- .../BertOnnxTextEmbeddingGenerationService.cs | 2 +- .../AzureSdk/AddHeaderRequestPolicy.cs | 12 +- .../AzureSdk/AzureOpenAITextToAudioClient.cs | 4 +- .../AzureSdk/ChatHistoryExtensions.cs | 2 +- .../Connectors.OpenAI/AzureSdk/ClientCore.cs | 6 +- .../AzureSdk/OpenAIChatMessageContent.cs | 5 +- .../AzureSdk/OpenAIFunction.cs | 4 +- .../AzureSdk/OpenAIFunctionToolCall.cs | 8 +- .../OpenAIPluginCollectionExtensions.cs | 2 +- .../AzureSdk/OpenAITextToAudioClient.cs | 4 +- ...zureOpenAIChatCompletionWithDataService.cs | 11 +- .../ChatWithDataResponse.cs | 11 +- .../OpenAITextToImageClientCore.cs | 4 +- .../Files/OpenAIFileService.cs | 2 +- .../AzureOpenAITextToImageService.cs | 7 +- .../TextToImage/OpenAITextToImageService.cs | 2 +- .../TextToImage/TextToImageResponse.cs | 2 +- .../Memory/DuckDB/DuckDBMemoryStoreTests.cs | 4 +- .../Memory/MongoDB/MongoDBMemoryStoreTests.cs | 15 +- .../PineconeMemoryBuilderExtensionsTests.cs | 2 +- .../Pinecone/PineconeMemoryStoreTests.cs | 9 +- .../QdrantMemoryBuilderExtensionsTests.cs | 2 +- .../Memory/Qdrant/QdrantMemoryStoreTests2.cs | 14 +- .../Memory/Qdrant/QdrantMemoryStoreTests3.cs | 27 ++- .../Memory/Redis/RedisMemoryStoreTests.cs | 28 +-- .../Memory/Sqlite/SqliteMemoryStoreTests.cs | 6 +- .../RequestFailedExceptionExtensionsTests.cs | 2 +- .../AzureOpenAIChatCompletionServiceTests.cs | 8 +- .../OpenAIChatCompletionServiceTests.cs | 174 +++++++++-------- .../KernelFunctionMetadataExtensionsTests.cs | 26 +-- .../FunctionCalling/OpenAIFunctionTests.cs | 8 +- .../OpenAIPromptExecutionSettingsTests.cs | 24 +-- .../AzureOpenAITextToImageTests.cs | 20 +- .../ChatCompletionAgentTests.cs | 11 +- .../Extensions/KernelExtensionTests.cs | 2 +- .../Integration/RunHarness.cs | 12 +- .../Integration/ThreadHarness.cs | 12 +- .../src/Experimental/Agents/AgentBuilder.cs | 4 +- dotnet/src/Experimental/Agents/AgentPlugin.cs | 2 +- .../OpenAIRestExtensions.Messages.cs | 3 +- .../src/Experimental/Agents/Internal/Agent.cs | 16 +- .../Agents/Models/AssistantModel.cs | 6 +- .../Agents/Models/OpenAIListModel.cs | 2 +- .../Agents/Models/OpenAIParameters.cs | 2 +- .../Agents/Models/ThreadMessageModel.cs | 8 +- .../Experimental/Agents/Models/ThreadModel.cs | 2 +- .../Agents/Models/ThreadRunModel.cs | 6 +- .../Agents/Models/ThreadRunStepModel.cs | 3 +- .../CollectEmailPlugin.cs | 3 +- .../FlowExtensionsTests.cs | 6 +- .../Execution/ChatHistorySerializer.cs | 5 +- .../Orchestration.Flow/Execution/Constants.cs | 4 +- .../Execution/ExecutionState.cs | 8 +- .../Execution/FlowExecutor.cs | 6 +- .../Execution/FlowStatusProvider.cs | 4 +- .../Execution/ReActEngine.cs | 12 +- .../Orchestration.Flow/FlowOrchestrator.cs | 2 +- .../FlowOrchestratorConfig.cs | 6 +- .../Orchestration.Flow/FlowSerializer.cs | 10 +- .../Orchestration.Flow/Model/Flow.cs | 2 +- .../Orchestration.Flow/Model/FlowStep.cs | 14 +- .../Helpers/KernelFunctionHelpersTests.cs | 10 +- .../Helpers/KernelSystemHelpersTests.cs | 10 +- .../HandlebarsPromptTemplate.cs | 2 +- .../HandlebarsPromptTemplateOptions.cs | 4 +- .../Extensions/GrpcKernelExtensions.cs | 5 +- .../Extensions/GrpcOperationExtensions.cs | 39 ---- .../Functions.Grpc/GrpcOperationRunner.cs | 47 ++--- .../Functions.Grpc/Model/GrpcOperation.cs | 21 ++ .../Model/GrpcOperationDataContractType.cs | 2 +- .../Protobuf/ProtoDocumentParser.cs | 13 +- .../Extensions/ApiManifestKernelExtensions.cs | 2 +- .../Functions.OpenApi/DocumentLoader.cs | 8 +- .../OpenApiFunctionExecutionParameters.cs | 2 +- .../Extensions/OpenApiKernelExtensions.cs | 4 +- .../Extensions/RestApiOperationExtensions.cs | 8 +- .../OpenApi/OpenApiDocumentParser.cs | 8 +- .../RestApiOperationRunner.cs | 6 +- .../GrpcOperationExtensionsTests.cs | 14 +- .../Grpc/GrpcRunnerTests.cs | 69 ++++--- .../TestPlugins/ResourcePluginsProvider.cs | 7 +- .../RestApiOperationExtensionsTests.cs | 27 ++- .../OpenApi/HttpMessageHandlerStub.cs | 18 +- .../OpenApi/OpenApiDocumentParserV20Tests.cs | 2 +- .../OpenApi/OpenApiDocumentParserV30Tests.cs | 2 +- .../OpenApi/OpenApiDocumentParserV31Tests.cs | 2 +- .../OpenApi/RestApiOperationRunnerTests.cs | 184 +++++++++--------- .../OpenApi/RestApiOperationTests.cs | 14 +- .../TestPlugins/ResourcePluginsProvider.cs | 7 +- .../TestResponses/ResourceResponseProvider.cs | 5 +- .../Functions.Yaml/KernelFunctionYaml.cs | 2 +- .../Gemini/GeminiChatCompletionTests.cs | 24 +-- .../Gemini/GeminiFunctionCallingTests.cs | 6 +- .../Memory/Chroma/ChromaMemoryStoreTests.cs | 6 +- .../Memory/Milvus/MilvusMemoryStoreTests.cs | 24 +-- .../Connectors/Memory/MongoDB/DataHelper.cs | 6 +- .../Memory/MongoDB/MongoDBMemoryStoreTests.cs | 11 +- .../Postgres/PostgresMemoryStoreTests.cs | 28 ++- .../Connectors/OpenAI/ChatHistoryTests.cs | 4 +- .../OpenAI/OpenAICompletionTests.cs | 21 +- .../OpenAI/OpenAITextEmbeddingTests.cs | 5 +- .../Connectors/OpenAI/OpenAIToolsTests.cs | 4 +- .../Weaviate/WeaviateMemoryStoreTests.cs | 6 +- .../KernelFunctionExtensionsTests.cs | 11 +- .../Handlebars/HandlebarsPlannerTests.cs | 4 +- .../FunctionCallingStepwisePlannerTests.cs | 10 +- .../IntegrationTests/Plugins/PluginTests.cs | 122 ++++++------ dotnet/src/IntegrationTests/RedirectOutput.cs | 12 +- .../TestSettings/AzureOpenAIConfiguration.cs | 30 +-- .../TestSettings/OpenAIConfiguration.cs | 18 +- dotnet/src/IntegrationTests/XunitLogger.cs | 9 +- ...OnlyFunctionCollectionPlannerExtensions.cs | 2 +- .../planning/PlannerOptions.cs | 4 +- .../Schema/JsonSchemaFunctionParameters.cs | 4 +- .../planning/Schema/JsonSchemaFunctionView.cs | 2 +- .../planning/SemanticMemoryConfig.cs | 2 +- .../src/Diagnostics/NullableAttributes.cs | 4 +- .../src/Diagnostics/Verify.cs | 18 +- .../src/Http/HttpResponseStream.cs | 12 +- .../JsonSchemaMapper.ReflectionHelpers.cs | 2 +- .../src/Schema/JsonSchemaMapper.cs | 36 ++-- .../Polyfills/NullabilityInfoContext.cs | 6 +- .../src/System/NonNullCollection.cs | 2 +- .../InternalUtilities/src/Text/SseReader.cs | 12 +- .../test/HttpMessageHandlerStub.cs | 6 +- .../test/MultipleHttpMessageHandlerStub.cs | 12 +- .../Planning/PlanTests.cs | 2 +- .../Sequential/SequentialPlanParserTests.cs | 2 +- .../Planners.Core/Action/ActionPlanner.cs | 2 +- .../Planners.Core/Stepwise/StepwisePlanner.cs | 2 +- .../Handlebars/HandlebarsPlannerTests.cs | 35 ++-- .../KernelParameterMetadataExtensionsTests.cs | 12 +- .../KernelParameterMetadataExtensions.cs | 4 +- .../Handlebars/HandlebarsPlanner.cs | 6 +- .../Models/HandlebarsParameterTypeMetadata.cs | 2 +- .../Planners.OpenAI/Utils/EmbeddedResource.cs | 8 +- .../Extensions/WordprocessingDocumentEx.cs | 26 +-- .../Plugins.Memory/Collections/MinHeap.cs | 2 +- .../Plugins/Plugins.MsGraph/CalendarPlugin.cs | 2 +- .../Client/MsGraphClientLoggingHandler.cs | 6 +- .../Connectors/Client/MsGraphConfiguration.cs | 3 +- .../Connectors/MicrosoftToDoConnector.cs | 4 +- .../Plugins/Plugins.MsGraph/EmailPlugin.cs | 2 +- .../Plugins.MsGraph/Models/CalendarEvent.cs | 3 +- .../Plugins/Plugins.MsGraph/TaskListPlugin.cs | 10 +- .../Memory/VolatileMemoryStoreTests.cs | 6 +- .../MsGraph/CalendarPluginTests.cs | 12 +- .../OrganizationHierarchyPluginTests.cs | 2 +- .../Web/WebSearchEngineSkillTests.cs | 4 +- .../Plugins/Plugins.Web/Bing/BingConnector.cs | 10 +- .../Plugins.Web/Google/GoogleConnector.cs | 4 +- .../AI/ChatCompletion/ChatHistory.cs | 4 +- .../ChatMessageContentItemCollection.cs | 2 +- .../AI/ChatCompletion/ChatPromptParser.cs | 4 +- .../EmbeddingGenerationServiceExtensions.cs | 2 +- .../AI/PromptNode.cs | 4 +- .../AI/XmlPromptParser.cs | 2 +- .../Contents/ChatMessageContent.cs | 2 +- .../Functions/KernelFunction.cs | 4 +- .../Functions/KernelFunctionMetadata.cs | 2 +- .../Functions/KernelPlugin.cs | 8 +- .../Functions/KernelPluginCollection.cs | 3 +- .../Functions/KernelPluginExtensions.cs | 2 +- .../src/SemanticKernel.Abstractions/Kernel.cs | 10 +- .../Memory/NullMemory.cs | 2 +- .../PromptTemplate/PromptTemplateConfig.cs | 6 +- .../Contents/StreamingMethodContent.cs | 3 +- .../Functions/KernelFunctionFactory.cs | 2 +- .../Functions/KernelFunctionFromMethod.cs | 12 +- .../SemanticKernel.Core/KernelExtensions.cs | 4 +- .../TemplateEngine/Blocks/CodeBlock.cs | 45 +++-- .../TemplateEngine/Blocks/NamedArgBlock.cs | 4 +- .../TemplateEngine/CodeTokenizer.cs | 11 +- .../TemplateEngine/TemplateTokenizer.cs | 4 +- .../SemanticKernel.Core/Text/TextChunker.cs | 12 +- .../Events/FunctionInvokedEventArgsTests.cs | 4 +- .../Functions/KernelArgumentsTests.cs | 2 +- .../Functions/KernelBuilderTests.cs | 8 +- .../KernelFunctionExtensionsTests.cs | 18 +- .../KernelFunctionFromMethodTests1.cs | 60 +++--- .../KernelFunctionFromMethodTests2.cs | 10 +- .../KernelFunctionFromPromptTests.cs | 19 +- .../Functions/KernelFunctionMetadataTests.cs | 4 +- .../Functions/KernelParameterMetadataTests.cs | 8 +- .../Functions/KernelPluginCollectionTests.cs | 4 +- .../KernelReturnParameterMetadataTests.cs | 12 +- .../Functions/MultipleModelTests.cs | 81 ++++---- .../OrderedAIServiceSelectorTests.cs | 20 +- .../HttpMessageHandlerStub.cs | 6 +- .../KernelExtensionsTests.cs | 16 +- .../Memory/MemoryRecordTests.cs | 110 ++++++----- .../Prompt/XmlPromptParserTests.cs | 2 +- .../AggregatorPromptTemplateFactoryTests.cs | 18 +- .../KernelPromptTemplateTests.cs | 10 +- .../PromptTemplateConfigTests.cs | 34 ++-- .../TemplateEngine/Blocks/CodeBlockTests.cs | 76 ++++---- .../Blocks/NamedArgBlockTests.cs | 2 +- .../TemplateEngine/Blocks/VarBlockTests.cs | 2 +- .../TemplateEngine/CodeTokenizerTests.cs | 6 +- .../Text/TextChunkerTests.cs | 166 ++++++++-------- .../Utilities/HttpClientExtensionsTests.cs | 8 +- .../Utilities/HttpContentExtensionsTests.cs | 10 +- .../Utilities/InternalTypeConverterTests.cs | 3 +- 299 files changed, 1622 insertions(+), 1790 deletions(-) delete mode 100644 dotnet/src/Functions/Functions.Grpc/Extensions/GrpcOperationExtensions.cs diff --git a/dotnet/Directory.Packages.props b/dotnet/Directory.Packages.props index b6e3a9abab06..5701aa34f162 100644 --- a/dotnet/Directory.Packages.props +++ b/dotnet/Directory.Packages.props @@ -86,11 +86,6 @@ - - - all - runtime; build; native; contentfiles; analyzers; buildtransitive - all diff --git a/dotnet/samples/CreateChatGptPlugin/.editorconfig b/dotnet/samples/CreateChatGptPlugin/.editorconfig index 39b98ac3a778..0a2d6e80e502 100644 --- a/dotnet/samples/CreateChatGptPlugin/.editorconfig +++ b/dotnet/samples/CreateChatGptPlugin/.editorconfig @@ -1,2 +1,3 @@ [*.cs] -dotnet_diagnostic.CA1016.severity = none \ No newline at end of file +dotnet_diagnostic.CA1016.severity = none +dotnet_diagnostic.CA2007.severity = none \ No newline at end of file diff --git a/dotnet/samples/CreateChatGptPlugin/Solution/Program.cs b/dotnet/samples/CreateChatGptPlugin/Solution/Program.cs index 33500fbd7178..3ff433d6cd8e 100644 --- a/dotnet/samples/CreateChatGptPlugin/Solution/Program.cs +++ b/dotnet/samples/CreateChatGptPlugin/Solution/Program.cs @@ -19,7 +19,7 @@ await kernel.ImportPluginFromOpenApiAsync("MathPlugin", new Uri("http://localhost:7071/swagger.json")).ConfigureAwait(false); // Create chat history -ChatHistory history = new(); +ChatHistory history = []; // Get chat completion service var chatCompletionService = kernel.GetRequiredService(); diff --git a/dotnet/samples/DocumentationExamples/BaseTest.cs b/dotnet/samples/DocumentationExamples/BaseTest.cs index 4017d80066b5..738f065c70b7 100644 --- a/dotnet/samples/DocumentationExamples/BaseTest.cs +++ b/dotnet/samples/DocumentationExamples/BaseTest.cs @@ -10,7 +10,7 @@ public abstract class BaseTest { protected ITestOutputHelper Output { get; } - protected List SimulatedInputText = new(); + protected List SimulatedInputText = []; protected int SimulatedInputTextIndex = 0; protected BaseTest(ITestOutputHelper output) diff --git a/dotnet/samples/DocumentationExamples/ConfiguringPrompts.cs b/dotnet/samples/DocumentationExamples/ConfiguringPrompts.cs index 8802210f9d6e..bce40826e44b 100644 --- a/dotnet/samples/DocumentationExamples/ConfiguringPrompts.cs +++ b/dotnet/samples/DocumentationExamples/ConfiguringPrompts.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.SemanticKernel; @@ -50,11 +49,11 @@ public async Task RunAsync() User: {{$request}} Assistant: ", TemplateFormat = "semantic-kernel", - InputVariables = new List() - { + InputVariables = + [ new() { Name = "history", Description = "The history of the conversation.", IsRequired = false, Default = "" }, new() { Name = "request", Description = "The user's request.", IsRequired = true } - }, + ], ExecutionSettings = { { @@ -88,7 +87,7 @@ public async Task RunAsync() // // Create chat history and choices - ChatHistory history = new(); + ChatHistory history = []; // Start the chat loop Write("User > "); diff --git a/dotnet/samples/DocumentationExamples/CreatingFunctions.cs b/dotnet/samples/DocumentationExamples/CreatingFunctions.cs index 80f002404178..d18324f2c281 100644 --- a/dotnet/samples/DocumentationExamples/CreatingFunctions.cs +++ b/dotnet/samples/DocumentationExamples/CreatingFunctions.cs @@ -48,7 +48,7 @@ public async Task RunAsync() // // Create chat history - ChatHistory history = new(); + ChatHistory history = []; // diff --git a/dotnet/samples/DocumentationExamples/FunctionsWithinPrompts.cs b/dotnet/samples/DocumentationExamples/FunctionsWithinPrompts.cs index e2fb161176d1..3a9c04f01cd0 100644 --- a/dotnet/samples/DocumentationExamples/FunctionsWithinPrompts.cs +++ b/dotnet/samples/DocumentationExamples/FunctionsWithinPrompts.cs @@ -41,24 +41,22 @@ public async Task RunAsync() Kernel kernel = builder.Build(); // - List choices = new() { "ContinueConversation", "EndConversation" }; + List choices = ["ContinueConversation", "EndConversation"]; // Create few-shot examples - List fewShotExamples = new() - { - new ChatHistory() - { + List fewShotExamples = + [ + [ new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation") - }, - new ChatHistory() - { + ], + [ new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "EndConversation") - } - }; + ] + ]; // Create handlebars template for intent // @@ -97,7 +95,7 @@ public async Task RunAsync() // // Create chat history - ChatHistory history = new(); + ChatHistory history = []; // Start the chat loop while (true) diff --git a/dotnet/samples/DocumentationExamples/Planner.cs b/dotnet/samples/DocumentationExamples/Planner.cs index 53fc6f8a9cc5..f9875db60028 100644 --- a/dotnet/samples/DocumentationExamples/Planner.cs +++ b/dotnet/samples/DocumentationExamples/Planner.cs @@ -45,7 +45,7 @@ public async Task RunAsync() var chatCompletionService = kernel.GetRequiredService(); // Create chat history - ChatHistory history = new(); + ChatHistory history = []; // Start the conversation Write("User > "); diff --git a/dotnet/samples/DocumentationExamples/SerializingPrompts.cs b/dotnet/samples/DocumentationExamples/SerializingPrompts.cs index 8d309e0ebabe..26f97df03826 100644 --- a/dotnet/samples/DocumentationExamples/SerializingPrompts.cs +++ b/dotnet/samples/DocumentationExamples/SerializingPrompts.cs @@ -52,27 +52,25 @@ await reader.ReadToEndAsync(), ); // Create choices - List choices = new() { "ContinueConversation", "EndConversation" }; + List choices = ["ContinueConversation", "EndConversation"]; // Create few-shot examples - List fewShotExamples = new() - { - new ChatHistory() - { + List fewShotExamples = + [ + [ new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation") - }, - new ChatHistory() - { + ], + [ new ChatMessageContent(AuthorRole.User, "Can you send the full update to the marketing team?"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "EndConversation") - } - }; + ] + ]; // Create chat history - ChatHistory history = new(); + ChatHistory history = []; // Start the chat loop Write("User > "); diff --git a/dotnet/samples/DocumentationExamples/Templates.cs b/dotnet/samples/DocumentationExamples/Templates.cs index e75f6de98213..7b7cc2d679d0 100644 --- a/dotnet/samples/DocumentationExamples/Templates.cs +++ b/dotnet/samples/DocumentationExamples/Templates.cs @@ -44,23 +44,21 @@ public async Task RunAsync() Assistant: "); // Create choices - List choices = new() { "ContinueConversation", "EndConversation" }; + List choices = ["ContinueConversation", "EndConversation"]; // Create few-shot examples List fewShotExamples = [ - new ChatHistory() - { + [ new ChatMessageContent(AuthorRole.User, "Can you send a very quick approval to the marketing team?"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "ContinueConversation") - }, - new ChatHistory() - { + ], + [ new ChatMessageContent(AuthorRole.User, "Thanks, I'm done for now"), new ChatMessageContent(AuthorRole.System, "Intent:"), new ChatMessageContent(AuthorRole.Assistant, "EndConversation") - } + ] ]; // Create handlebars template for intent @@ -89,7 +87,7 @@ public async Task RunAsync() new HandlebarsPromptTemplateFactory() ); - ChatHistory history = new(); + ChatHistory history = []; // Start the chat loop while (true) diff --git a/dotnet/samples/HomeAutomation/Program.cs b/dotnet/samples/HomeAutomation/Program.cs index be62d8d5b392..e55279405ceb 100644 --- a/dotnet/samples/HomeAutomation/Program.cs +++ b/dotnet/samples/HomeAutomation/Program.cs @@ -75,7 +75,7 @@ internal static async Task Main(string[] args) builder.Services.AddKeyedTransient("HomeAutomationKernel", (sp, key) => { // Create a collection of plugins that the kernel will use - KernelPluginCollection pluginCollection = new(); + KernelPluginCollection pluginCollection = []; pluginCollection.AddFromObject(sp.GetRequiredService()); pluginCollection.AddFromObject(sp.GetRequiredService()); pluginCollection.AddFromObject(sp.GetRequiredKeyedService("OfficeLight"), "OfficeLight"); diff --git a/dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs b/dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs index 7cb61dd0b9b8..af88e841c96f 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs @@ -111,10 +111,10 @@ public async IAsyncEnumerable GetStreamingTextContentsAsyn public Task> GetTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default) { - return Task.FromResult>(new List - { + return Task.FromResult>( + [ new(LLMResultText) - }); + ]); } } diff --git a/dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs b/dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs index c5c4a11bb23f..4841f2c61347 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs @@ -50,7 +50,7 @@ public async Task RunInferenceApiEmbeddingAsync() var embeddingGenerator = kernel.GetRequiredService(); // Generate embeddings for each chunk. - var embeddings = await embeddingGenerator.GenerateEmbeddingsAsync(new[] { "John: Hello, how are you?\nRoger: Hey, I'm Roger!" }); + var embeddings = await embeddingGenerator.GenerateEmbeddingsAsync(["John: Hello, how are you?\nRoger: Hey, I'm Roger!"]); this.WriteLine($"Generated {embeddings.Count} embeddings for the provided text"); } diff --git a/dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs b/dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs index 5f0c7a1d68ab..19828a7128f8 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs @@ -44,12 +44,14 @@ public async Task CallKlarnaAsync() var plugin = await kernel.ImportPluginFromOpenAIAsync("Klarna", new Uri("https://www.klarna.com/.well-known/ai-plugin.json")); - var arguments = new KernelArguments(); - arguments["q"] = "Laptop"; // Category or product that needs to be searched for. - arguments["size"] = "3"; // Number of products to return - arguments["budget"] = "200"; // Maximum price of the matching product in local currency - arguments["countryCode"] = "US";// ISO 3166 country code with 2 characters based on the user location. - // Currently, only US, GB, DE, SE and DK are supported. + var arguments = new KernelArguments + { + ["q"] = "Laptop", // Category or product that needs to be searched for. + ["size"] = "3", // Number of products to return + ["budget"] = "200", // Maximum price of the matching product in local currency + ["countryCode"] = "US" // ISO 3166 country code with 2 characters based on the user location. + }; + // Currently, only US, GB, DE, SE and DK are supported. var functionResult = await kernel.InvokeAsync(plugin["productsUsingGET"], arguments); diff --git a/dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs b/dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs index 14e914a9e260..370dae279ff6 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs @@ -105,9 +105,11 @@ private async Task AddSecretToAzureKeyVaultAsync(Kernel kernel, KernelPlugin plu private static async Task GetSecretFromAzureKeyVaultWithRetryAsync(Kernel kernel, KernelPlugin plugin) { // Add arguments for required parameters, arguments for optional ones can be skipped. - var arguments = new KernelArguments(); - arguments["secret-name"] = SecretName; - arguments["api-version"] = "7.0"; + var arguments = new KernelArguments + { + ["secret-name"] = SecretName, + ["api-version"] = "7.0" + }; // Run var functionResult = await kernel.InvokeAsync(plugin["GetSecret"], arguments); @@ -139,8 +141,8 @@ internal sealed class OpenAIAuthenticationProvider /// A dictionary containing credentials for each authentication scheme. public OpenAIAuthenticationProvider(Dictionary>? oAuthValues = null, Dictionary? credentials = null) { - this._oAuthValues = oAuthValues ?? new(); - this._credentials = credentials ?? new(); + this._oAuthValues = oAuthValues ?? []; + this._credentials = credentials ?? []; } /// diff --git a/dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs b/dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs index c484d040722c..94891e401c44 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs @@ -85,12 +85,13 @@ public async Task RunAsync() ); } - var arguments = new KernelArguments(); - - // GetIssue Function - // Set Properties for the Get Issue operation in the openAPI.swagger.json - // Make sure the issue exists in your Jira instance or it will return a 404 - arguments["issueKey"] = "TEST-1"; + var arguments = new KernelArguments + { + // GetIssue Function + // Set Properties for the Get Issue operation in the openAPI.swagger.json + // Make sure the issue exists in your Jira instance or it will return a 404 + ["issueKey"] = "TEST-1" + }; // Run operation via the semantic kernel var result = await kernel.InvokeAsync(jiraFunctions["GetIssue"], arguments); @@ -102,7 +103,7 @@ public async Task RunAsync() // AddComment Function arguments["issueKey"] = "TEST-2"; - arguments[RestApiOperation.PayloadArgumentName] = "{\"body\": \"Here is a rad comment\"}"; + arguments[RestApiOperation.PayloadArgumentName] = """{"body": "Here is a rad comment"}"""; // Run operation via the semantic kernel result = await kernel.InvokeAsync(jiraFunctions["AddComment"], arguments); diff --git a/dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs b/dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs index 9c54af7e751c..6d356f671d2b 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs @@ -29,7 +29,7 @@ public async Task RunAsync() { var store = new ReadOnlyMemoryStore(s_jsonVectorEntries); - var embedding = new ReadOnlyMemory(new float[] { 22, 4, 6 }); + var embedding = new ReadOnlyMemory([22, 4, 6]); WriteLine("Reading data from custom read-only memory store"); var memoryRecord = await store.GetAsync("collection", "key3"); @@ -136,7 +136,7 @@ public IAsyncEnumerable GetCollectionsAsync(CancellationToken cancellati throw new Exception($"Embedding vector size {embedding.Length} does not match expected size of {this._vectorSize}"); } - List<(MemoryRecord Record, double Score)> embeddings = new(); + List<(MemoryRecord Record, double Score)> embeddings = []; foreach (var item in this._memoryRecords) { diff --git a/dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs b/dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs index f9d8ed41d710..3fcea0ab328a 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs @@ -22,9 +22,11 @@ public async Task RunAsync() var plugin = kernel.ImportPluginFromGrpcFile("", ""); // Add arguments for required parameters, arguments for optional ones can be skipped. - var arguments = new KernelArguments(); - arguments["address"] = ""; - arguments["payload"] = ""; + var arguments = new KernelArguments + { + ["address"] = "", + ["payload"] = "" + }; // Run var result = await kernel.InvokeAsync(plugin[""], arguments); diff --git a/dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs b/dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs index 984562e67a0e..dc02cc8d7591 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs @@ -72,11 +72,10 @@ public async Task StreamingIdentityAsync(bool withName) private static ChatHistory CreateHistory(bool withName) { return - new ChatHistory() - { + [ new ChatMessageContent(AuthorRole.System, "Write one paragraph in response to the user that rhymes") { AuthorName = withName ? "Echo" : null }, new ChatMessageContent(AuthorRole.User, "Why is AI awesome") { AuthorName = withName ? "Ralph" : null }, - }; + ]; } private void ValidateMessages(ChatHistory chatHistory, bool expectName) diff --git a/dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs b/dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs index 15e4f120f5b5..483a1dd1739f 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs @@ -39,16 +39,10 @@ public async Task RunAsync() /// /// Class that uses/references Kernel. /// - private sealed class KernelClient + private sealed class KernelClient(Kernel kernel, ILoggerFactory loggerFactory) { - private readonly Kernel _kernel; - private readonly ILogger _logger; - - public KernelClient(Kernel kernel, ILoggerFactory loggerFactory) - { - this._kernel = kernel; - this._logger = loggerFactory.CreateLogger(nameof(KernelClient)); - } + private readonly Kernel _kernel = kernel; + private readonly ILogger _logger = loggerFactory.CreateLogger(nameof(KernelClient)); public async Task SummarizeAsync(string ask) { diff --git a/dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs b/dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs index fa5f50363403..f01ab224fb00 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs @@ -167,7 +167,7 @@ public DeepDevTokenCounter() public int Count(string input) { - var tokens = this._tokenizer.Encode(input, new HashSet()); + var tokens = this._tokenizer.Encode(input, []); return tokens.Count; } } diff --git a/dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs b/dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs index 9e7eeaa4b125..2109700f40ba 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs @@ -44,8 +44,10 @@ public async Task RunAsync() modelId: modelId); Kernel kernel = builder.Build(); - var arguments = new KernelArguments(); - arguments["word2"] = " Potter"; + var arguments = new KernelArguments + { + ["word2"] = " Potter" + }; // Load native plugin into the kernel function collection, sharing its functions with prompt templates // Functions loaded here are available as "text.*" diff --git a/dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs b/dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs index d9338f91be85..397997ceffff 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs @@ -57,19 +57,21 @@ public async Task RunAsync() // Load prompt template configuration including the execution settings from a JSON payload // Create the prompt functions using the prompt template and the configuration (loaded in the previous step) // Invoke the prompt function using the implicitly set execution settings - string configPayload = @"{ - ""schema"": 1, - ""name"": ""HelloAI"", - ""description"": ""Say hello to an AI"", - ""type"": ""completion"", - ""completion"": { - ""max_tokens"": 256, - ""temperature"": 0.5, - ""top_p"": 0.0, - ""presence_penalty"": 0.0, - ""frequency_penalty"": 0.0 - } - }"; + string configPayload = """ + { + "schema": 1, + "name": "HelloAI", + "description": "Say hello to an AI", + "type": "completion", + "completion": { + "max_tokens": 256, + "temperature": 0.5, + "top_p": 0.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0 + } + } + """; var promptConfig = JsonSerializer.Deserialize(configPayload)!; promptConfig.Template = prompt; var func = kernel.CreateFunctionFromPrompt(promptConfig); diff --git a/dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs b/dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs index 3c874fe9e053..227e4215905a 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs @@ -33,8 +33,8 @@ public async Task RunAsync() Kernel kernel = builder.Build(); // Add a plugin with some helper functions we want to allow the model to utilize. - kernel.ImportPluginFromFunctions("HelperFunctions", new[] - { + kernel.ImportPluginFromFunctions("HelperFunctions", + [ kernel.CreateFunctionFromMethod(() => DateTime.UtcNow.ToString("R"), "GetCurrentUtcTime", "Retrieves the current time in UTC."), kernel.CreateFunctionFromMethod((string cityName) => cityName switch @@ -48,7 +48,7 @@ public async Task RunAsync() "Tel Aviv" => "80 and sunny", _ => "31 and snowing", }, "Get_Weather_For_City", "Gets the current weather for the specified city"), - }); + ]); WriteLine("======== Example 1: Use automated function calling with a non-streaming prompt ========"); { diff --git a/dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs b/dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs index 29a434c90878..c0446051f892 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs @@ -40,7 +40,7 @@ private async Task RunByServiceIdAsync(Kernel kernel, string serviceId) var prompt = "Hello AI, what can you do for me?"; - KernelArguments arguments = new(); + KernelArguments arguments = []; arguments.ExecutionSettings = new Dictionary() { { serviceId, new PromptExecutionSettings() } diff --git a/dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs b/dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs index e6135ed5fc91..0ae6bd59ef21 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs @@ -14,11 +14,12 @@ public class Example66_FunctionCallingStepwisePlanner : BaseTest [Fact] public async Task RunAsync() { - string[] questions = { + string[] questions = + [ "What is the current hour number, plus 5?", "What is 387 minus 22? Email the solution to John and Mary.", "Write a limerick, translate it to Spanish, and send it to Jane", - }; + ]; var kernel = InitializeKernel(); diff --git a/dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs b/dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs index 8011f79b570d..3cc99f1a2b47 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs @@ -25,11 +25,11 @@ public async Task RunAsync() var chatHistory = new ChatHistory("You are a friendly assistant."); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection - { + chatHistory.AddUserMessage( + [ new TextContent("What’s in this image?"), new ImageContent(new Uri(ImageUri)) - }); + ]); var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory); diff --git a/dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs b/dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs index 72674d0a5e63..ebcf294ae498 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs @@ -86,7 +86,7 @@ public Task RunWithPromptFunctionsAsync() functionName: "spellChecker", description: "Correct the spelling for the user input."); - var plugin = KernelPluginFactory.CreateFromFunctions("spelling", "Spelling functions", new[] { function }); + var plugin = KernelPluginFactory.CreateFromFunctions("spelling", "Spelling functions", [function]); // Call the common chat-loop return ChatAsync( diff --git a/dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs b/dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs index a95d3d7af7ee..49896a3063f0 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs @@ -24,7 +24,7 @@ public class Example71_AgentDelegation : BaseTest private const string OpenAIFunctionEnabledModel = "gpt-3.5-turbo-1106"; // Track agents for clean-up - private static readonly List s_agents = new(); + private static readonly List s_agents = []; /// /// Show how to combine coordinate multiple agents. diff --git a/dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs b/dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs index 56ef2c3c0b7b..36b9e9839565 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs @@ -27,7 +27,7 @@ public class Example72_AgentCollaboration : BaseTest private const bool UseOpenAI = false; // Track agents for clean-up - private static readonly List s_agents = new(); + private static readonly List s_agents = []; /// /// Show how two agents are able to collaborate as agents on a single thread. @@ -131,7 +131,7 @@ await CreateAgentBuilder() .BuildAsync()); } - private async static Task CreateArtDirectorAsync() + private static async Task CreateArtDirectorAsync() { return Track( diff --git a/dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs b/dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs index 004a3ef373fd..d16c12b4948f 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs @@ -21,7 +21,7 @@ public class Example73_AgentAuthoring : BaseTest private const string OpenAIFunctionEnabledModel = "gpt-4-1106-preview"; // Track agents for clean-up - private static readonly List s_agents = new(); + private static readonly List s_agents = []; [Fact(Skip = "This test take more than 2 minutes to execute")] public async Task RunAgentAsync() diff --git a/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs b/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs index 76e051bb58bb..8eef73bc707b 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs @@ -88,14 +88,14 @@ await FlowStatusProvider.ConnectAsync(new VolatileMemoryStore()), WriteLine("Answer: " + result.Metadata!["answer"]); WriteLine("Assistant: " + result.GetValue>()!.Single()); - string[] userInputs = new[] - { + string[] userInputs = + [ "my email is bad*email&address", "my email is sample@xyz.com", "yes", // confirm to add another email address "I also want to notify foo@bar.com", "no I don't need notify any more address", // end of collect emails - }; + ]; foreach (var t in userInputs) { @@ -170,7 +170,7 @@ public ChatPlugin(Kernel kernel) this._chatRequestSettings = new OpenAIPromptExecutionSettings { MaxTokens = this.MaxTokens, - StopSequences = new List() { "Observation:" }, + StopSequences = ["Observation:"], Temperature = 0 }; } diff --git a/dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs b/dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs index 7f514069ee4b..4efa3abe3f18 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs @@ -36,7 +36,7 @@ public sealed class Example75_AgentTools : BaseTest private const bool ForceOpenAI = true; // Track agents for clean-up - private readonly List _agents = new(); + private readonly List _agents = []; /// /// Show how to utilize code_interpreter tool. @@ -133,7 +133,7 @@ private async Task ChatAsync( string[]? fileIds = null; if (fileId != null) { - fileIds = new string[] { fileId }; + fileIds = [fileId]; } foreach (var question in questions) diff --git a/dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs b/dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs index 2fbbfcbf53df..63a3bd92f4c1 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs @@ -35,7 +35,7 @@ public async Task FunctionAndPromptFiltersAsync() kernel.PromptFilters.Add(new FirstPromptFilter(this.Output)); var function = kernel.CreateFunctionFromPrompt("What is Seattle", functionName: "MyFunction"); - kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: new[] { function })); + kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: [function])); var result = await kernel.InvokeAsync(kernel.Plugins["MyPlugin"]["MyFunction"]); WriteLine(result); diff --git a/dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs b/dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs index 4cf7a3d8aa41..e6cceb65ac00 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs @@ -45,7 +45,7 @@ public async Task ChatWithAgentAsync() ); var prompt = PrintPrompt("I need help with my investment portfolio. Please guide me."); - PrintConversation(await agent.InvokeAsync(new[] { new ChatMessageContent(AuthorRole.User, prompt) })); + PrintConversation(await agent.InvokeAsync([new ChatMessageContent(AuthorRole.User, prompt)])); } /// @@ -92,7 +92,7 @@ public async Task TurnBasedAgentsChatAsync() settings ); - var chat = new TurnBasedChat(new[] { fitnessTrainer, stressManagementExpert }, (chatHistory, replies, turn) => + var chat = new TurnBasedChat([fitnessTrainer, stressManagementExpert], (chatHistory, replies, turn) => turn >= 10 || // Limit the number of turns to 10 replies.Any( message => message.Role == AuthorRole.Assistant && @@ -134,7 +134,7 @@ public async Task> SendMessageAsync(string mes var chat = new ChatHistory(); chat.AddUserMessage(message); - IReadOnlyList result = new List(); + IReadOnlyList result; var turn = 0; diff --git a/dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs b/dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs index b2b300d0005b..996ab9f3efd8 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs @@ -14,12 +14,13 @@ public class Example80_FunctionCallingPlannerWithRAG : BaseTest [Fact] public async Task RunAsync() { - string[] questions = { + string[] questions = + [ "When should I use the name Bob?", "When should I use the name Tom?", "When should I use the name Alice?", "When should I use the name Harry?", - }; + ]; var kernel = InitializeKernel(); diff --git a/dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs b/dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs index a8afd171ea86..e54157d9294d 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs @@ -24,21 +24,21 @@ public Example83_ApiManifest(ITestOutputHelper output) : base(output) { } - public static readonly IEnumerable s_parameters = new List - { + public static readonly IEnumerable s_parameters = + [ // function names are sanitized operationIds from the OpenAPI document - new object[] { "MessagesPlugin", "meListMessages", new KernelArguments { { "_top", "1" } }, "MessagesPlugin" }, - new object[] { "DriveItemPlugin", "driverootGetChildrenContent", new KernelArguments { { "driveItem-Id", "test.txt" } }, "DriveItemPlugin", "MessagesPlugin" }, - new object[] { "ContactsPlugin", "meListContacts", new KernelArguments() { { "_count", "true" } }, "ContactsPlugin", "MessagesPlugin" }, - new object[] { "CalendarPlugin", "mecalendarListEvents", new KernelArguments() { { "_top", "1" } }, "CalendarPlugin", "MessagesPlugin"}, + ["MessagesPlugin", "meListMessages", new KernelArguments { { "_top", "1" } }, "MessagesPlugin"], + ["DriveItemPlugin", "driverootGetChildrenContent", new KernelArguments { { "driveItem-Id", "test.txt" } }, "DriveItemPlugin", "MessagesPlugin"], + ["ContactsPlugin", "meListContacts", new KernelArguments() { { "_count", "true" } }, "ContactsPlugin", "MessagesPlugin"], + ["CalendarPlugin", "mecalendarListEvents", new KernelArguments() { { "_top", "1" } }, "CalendarPlugin", "MessagesPlugin"], -#region Multiple API dependencies (multiple auth requirements) scenario within the same plugin + #region Multiple API dependencies (multiple auth requirements) scenario within the same plugin // Graph API uses MSAL - new object[] { "AstronomyPlugin", "meListMessages", new KernelArguments { { "_top", "1" } }, "AstronomyPlugin" }, + ["AstronomyPlugin", "meListMessages", new KernelArguments { { "_top", "1" } }, "AstronomyPlugin"], // Astronomy API uses API key authentication - new object[] { "AstronomyPlugin", "apod", new KernelArguments { { "_date", "2022-02-02" } }, "AstronomyPlugin" }, -#endregion - }; + ["AstronomyPlugin", "apod", new KernelArguments { { "_date", "2022-02-02" } }, "AstronomyPlugin"], + #endregion + ]; [Theory, MemberData(nameof(s_parameters))] public async Task RunSampleWithPlannerAsync(string pluginToTest, string functionToTest, KernelArguments? arguments, params string[] pluginsToLoad) diff --git a/dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs b/dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs index ae81e4ec5694..0c03cda84ccd 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs @@ -120,7 +120,7 @@ private interface IAzureAISearchService /// private sealed class AzureAISearchService : IAzureAISearchService { - private readonly List _defaultVectorFields = new() { "vector" }; + private readonly List _defaultVectorFields = ["vector"]; private readonly SearchIndexClient _indexClient; @@ -150,7 +150,7 @@ public AzureAISearchService(SearchIndexClient indexClient) // Perform search request Response> response = await searchClient.SearchAsync(searchOptions, cancellationToken); - List results = new(); + List results = []; // Collect search results await foreach (SearchResult result in response.Value.GetResultsAsync()) diff --git a/dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs b/dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs index 12831d4eed69..c09034c19318 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs @@ -26,17 +26,17 @@ public void SerializeChatHistoryWithSKContentTypes() var data = new[] { 1, 2, 3 }; var message = new ChatMessageContent(AuthorRole.User, "Describe the factors contributing to climate change."); - message.Items = new ChatMessageContentItemCollection - { + message.Items = + [ new TextContent("Discuss the potential long-term consequences for the Earth's ecosystem as well."), new ImageContent(new Uri("https://fake-random-test-host:123")), new BinaryContent(new BinaryData(data)), - #pragma warning disable SKEXP0001 +#pragma warning disable SKEXP0001 new AudioContent(new BinaryData(data)) - #pragma warning restore SKEXP0001 - }; +#pragma warning restore SKEXP0001 + ]; - var chatHistory = new ChatHistory(new[] { message }); + var chatHistory = new ChatHistory([message]); var chatHistoryJson = JsonSerializer.Serialize(chatHistory, s_options); @@ -65,13 +65,13 @@ public void SerializeChatHistoryWithSKContentTypes() public void SerializeChatWithHistoryWithCustomContentType() { var message = new ChatMessageContent(AuthorRole.User, "Describe the factors contributing to climate change."); - message.Items = new ChatMessageContentItemCollection - { + message.Items = + [ new TextContent("Discuss the potential long-term consequences for the Earth's ecosystem as well."), new CustomContent("Some custom content"), - }; + ]; - var chatHistory = new ChatHistory(new[] { message }); + var chatHistory = new ChatHistory([message]); // The custom resolver should be used to serialize and deserialize the chat history with custom . var options = new JsonSerializerOptions diff --git a/dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs b/dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs index eead9e734e65..bcb2c128d6a4 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs @@ -40,13 +40,13 @@ public async Task GoogleAIAsync() using var binaryReader = new BinaryReader(stream); var bytes = binaryReader.ReadBytes((int)stream.Length); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection - { + chatHistory.AddUserMessage( + [ new TextContent("What’s in this image?"), // Google AI Gemini API requires the image to be in base64 format, doesn't support URI // You have to always provide the mimeType for the image new ImageContent(bytes) { MimeType = "image/jpeg" }, - }); + ]); var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory); @@ -108,8 +108,8 @@ public async Task VertexAIAsync() using var binaryReader = new BinaryReader(stream); var bytes = binaryReader.ReadBytes((int)stream.Length); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection - { + chatHistory.AddUserMessage( + [ new TextContent("What’s in this image?"), // Vertex AI Gemini API supports both base64 and URI format // You have to always provide the mimeType for the image @@ -118,7 +118,7 @@ public async Task VertexAIAsync() // The bucket that stores the file must be in the same Google Cloud project that's sending the request. // new ImageContent(new Uri("gs://generativeai-downloads/images/scones.jpg"), // metadata: new Dictionary { { "mimeType", "image/jpeg" } }) - }); + ]); var reply = await chatCompletionService.GetChatMessageContentAsync(chatHistory); diff --git a/dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs b/dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs index fb4d9de7c1de..ed6c06d35ab5 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs +++ b/dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs @@ -89,8 +89,8 @@ public async Task VertexAIAsync() private async Task RunSampleAsync(Kernel kernel) { // Add a plugin with some helper functions we want to allow the model to utilize. - kernel.ImportPluginFromFunctions("HelperFunctions", new[] - { + kernel.ImportPluginFromFunctions("HelperFunctions", + [ kernel.CreateFunctionFromMethod(() => DateTime.UtcNow.ToString("R"), "GetCurrentUtcTime", "Retrieves the current time in UTC."), kernel.CreateFunctionFromMethod((string cityName) => cityName switch @@ -104,7 +104,7 @@ private async Task RunSampleAsync(Kernel kernel) "Tel Aviv" => "80 and sunny", _ => "31 and snowing", }, "Get_Weather_For_City", "Gets the current weather for the specified city"), - }); + ]); WriteLine("======== Example 1: Use automated function calling with a non-streaming prompt ========"); { @@ -156,7 +156,7 @@ private async Task RunSampleAsync(Kernel kernel) // Add parameters to arguments if (toolCall.Arguments is not null) { - arguments = new KernelArguments(); + arguments = []; foreach (var parameter in toolCall.Arguments) { arguments[parameter.Key] = parameter.Value?.ToString(); diff --git a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step4_Dependency_Injection.cs b/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step4_Dependency_Injection.cs index 084eb6b98a5e..bd0122d83520 100644 --- a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step4_Dependency_Injection.cs +++ b/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step4_Dependency_Injection.cs @@ -56,14 +56,9 @@ private ServiceProvider BuildServiceProvider() /// /// A plugin that returns the current time. /// - public class TimeInformation + public class TimeInformation(ILoggerFactory loggerFactory) { - private readonly ILogger _logger; - - public TimeInformation(ILoggerFactory loggerFactory) - { - this._logger = loggerFactory.CreateLogger(typeof(TimeInformation)); - } + private readonly ILogger _logger = loggerFactory.CreateLogger(typeof(TimeInformation)); [KernelFunction] [Description("Retrieves the current time in UTC.")] diff --git a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step8_Pipelining.cs b/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step8_Pipelining.cs index 51b1e6377be3..d0499af1fb1a 100644 --- a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step8_Pipelining.cs +++ b/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step8_Pipelining.cs @@ -40,7 +40,7 @@ public async Task RunAsync() KernelFunction humanize = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig() { Template = "Spell out this number in English: {{$number}}", - InputVariables = new() { new() { Name = "number" } }, + InputVariables = [new() { Name = "number" }], }); KernelFunction pipeline = KernelFunctionCombinators.Pipe(new[] { parseInt32, multiplyByN, truncate, humanize }, "pipeline"); diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs b/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs index 838b11d336a5..afb7d0a5cf55 100644 --- a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs +++ b/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs @@ -18,14 +18,14 @@ public sealed class ComplexParamsDictionaryPlugin { public const string PluginName = nameof(ComplexParamsDictionaryPlugin); - private readonly List _dictionary = new() - { + private readonly List _dictionary = + [ new DictionaryEntry("apple", "a round fruit with red, green, or yellow skin and a white flesh"), new DictionaryEntry("book", "a set of printed or written pages bound together along one edge"), new DictionaryEntry("cat", "a small furry animal with whiskers and a long tail that is often kept as a pet"), new DictionaryEntry("dog", "a domesticated animal with four legs, a tail, and a keen sense of smell that is often used for hunting or companionship"), new DictionaryEntry("elephant", "a large gray mammal with a long trunk, tusks, and ears that lives in Africa and Asia") - }; + ]; [KernelFunction, Description("Gets a random word from a dictionary of common words and their definitions.")] public DictionaryEntry GetRandomEntry() @@ -62,16 +62,10 @@ public string GetDefinition([Description("Word to get definition for.")] string /// It's possible to choose any format (e.g. XML, JSON, YAML) to represent your object. /// [TypeConverter(typeof(DictionaryEntryConverter))] -public sealed class DictionaryEntry +public sealed class DictionaryEntry(string word, string definition) { - public string Word { get; set; } = string.Empty; - public string Definition { get; set; } = string.Empty; - - public DictionaryEntry(string word, string definition) - { - this.Word = word; - this.Definition = definition; - } + public string Word { get; set; } = word; + public string Definition { get; set; } = definition; } /// diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs b/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs index a685f494b896..238f270b3cf9 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs +++ b/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs @@ -35,7 +35,7 @@ public static IEnumerable> ChunkByAggregate( yield return chunk; } - chunk = new List() { current }; + chunk = [current]; aggregate = aggregator(seed, current); index = 1; } diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs b/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs index 176cc998fb86..4361c37d25a0 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs +++ b/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs @@ -16,7 +16,7 @@ public static string SamplePluginsPath() const string Parent = "samples"; const string Folder = "plugins"; - bool SearchPath(string pathToFind, out string result, int maxAttempts = 10) + static bool SearchPath(string pathToFind, out string result, int maxAttempts = 10) { var currDir = Path.GetFullPath(Assembly.GetExecutingAssembly().Location); bool found; diff --git a/dotnet/samples/TelemetryExample/RepoUtils/RepoFiles.cs b/dotnet/samples/TelemetryExample/RepoUtils/RepoFiles.cs index 0c7d595b1bad..11e00f29805a 100644 --- a/dotnet/samples/TelemetryExample/RepoUtils/RepoFiles.cs +++ b/dotnet/samples/TelemetryExample/RepoUtils/RepoFiles.cs @@ -14,7 +14,7 @@ public static string SamplePluginsPath() const string Parent = "samples"; const string Folder = "plugins"; - bool SearchPath(string pathToFind, out string result, int maxAttempts = 10) + static bool SearchPath(string pathToFind, out string result, int maxAttempts = 10) { var currDir = Path.GetFullPath(Assembly.GetExecutingAssembly().Location); bool found; diff --git a/dotnet/src/Connectors/Connectors.AzureAISearch.UnitTests/AzureAISearchMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.AzureAISearch.UnitTests/AzureAISearchMemoryStoreTests.cs index 5ebab857b3d8..0ebda1fc706e 100644 --- a/dotnet/src/Connectors/Connectors.AzureAISearch.UnitTests/AzureAISearchMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.AzureAISearch.UnitTests/AzureAISearchMemoryStoreTests.cs @@ -41,13 +41,13 @@ public AzureAISearchMemoryStoreTests() public async Task GetCollectionsReturnsIndexNamesAsync() { // Arrange - Page page = Page.FromValues(new[] - { + Page page = Page.FromValues( + [ new SearchIndex("index-1"), new SearchIndex("index-2"), - }, null, Mock.Of()); + ], null, Mock.Of()); - var pageable = AsyncPageable.FromPages(new[] { page }); + var pageable = AsyncPageable.FromPages([page]); this._mockSearchIndexClient .Setup(x => x.GetIndexesAsync(It.IsAny())) @@ -95,13 +95,13 @@ public async Task GetCollectionsOnErrorThrowsHttpOperationExceptionAsync() public async Task DoesCollectionExistReturnsValidResultAsync(string collectionName, bool expectedResult) { // Arrange - Page page = Page.FromValues(new[] - { + Page page = Page.FromValues( + [ new SearchIndex("index-1"), new SearchIndex("index-2"), - }, null, Mock.Of()); + ], null, Mock.Of()); - var pageable = AsyncPageable.FromPages(new[] { page }); + var pageable = AsyncPageable.FromPages([page]); this._mockSearchIndexClient .Setup(x => x.GetIndexesAsync(It.IsAny())) @@ -166,7 +166,7 @@ public async Task UpsertReturnsValidRecordKeyAsync() { // Arrange var indexingResult = SearchModelFactory.IndexingResult("record-id", null, true, 200); - var results = SearchModelFactory.IndexDocumentsResult(new[] { indexingResult }); + var results = SearchModelFactory.IndexDocumentsResult([indexingResult]); this._mockSearchClient .Setup(x => x.IndexDocumentsAsync( @@ -206,7 +206,7 @@ public async Task UpsertOnNotFoundErrorCreatesIndexAsync() { // Arrange var indexingResult = SearchModelFactory.IndexingResult("record-id", null, true, 200); - var results = SearchModelFactory.IndexDocumentsResult(new[] { indexingResult }); + var results = SearchModelFactory.IndexDocumentsResult([indexingResult]); this._mockSearchClient .SetupSequence(x => x.IndexDocumentsAsync( @@ -336,7 +336,7 @@ public async Task RemoveBatchCallsDeleteDocumentsMethodAsync() { // Arrange var indexingResult = SearchModelFactory.IndexingResult("record-id", null, true, 200); - var results = SearchModelFactory.IndexDocumentsResult(new[] { indexingResult }); + var results = SearchModelFactory.IndexDocumentsResult([indexingResult]); this._mockSearchClient .Setup(x => x.DeleteDocumentsAsync( diff --git a/dotnet/src/Connectors/Connectors.Google.UnitTests/Core/Gemini/GeminiRequestTests.cs b/dotnet/src/Connectors/Connectors.Google.UnitTests/Core/Gemini/GeminiRequestTests.cs index f25492274cd7..d2af4f17ba97 100644 --- a/dotnet/src/Connectors/Connectors.Google.UnitTests/Core/Gemini/GeminiRequestTests.cs +++ b/dotnet/src/Connectors/Connectors.Google.UnitTests/Core/Gemini/GeminiRequestTests.cs @@ -43,10 +43,10 @@ public void FromPromptItReturnsGeminiRequestWithSafetySettings() var prompt = "prompt-example"; var executionSettings = new GeminiPromptExecutionSettings { - SafetySettings = new List - { + SafetySettings = + [ new(GeminiSafetyCategory.Derogatory, GeminiSafetyThreshold.BlockNone) - } + ] }; // Act @@ -107,10 +107,10 @@ public void FromChatHistoryItReturnsGeminiRequestWithSafetySettings() chatHistory.AddUserMessage("user-message2"); var executionSettings = new GeminiPromptExecutionSettings { - SafetySettings = new List - { + SafetySettings = + [ new(GeminiSafetyCategory.Derogatory, GeminiSafetyThreshold.BlockNone) - } + ] }; // Act diff --git a/dotnet/src/Connectors/Connectors.Google.UnitTests/GeminiPromptExecutionSettingsTests.cs b/dotnet/src/Connectors/Connectors.Google.UnitTests/GeminiPromptExecutionSettingsTests.cs index e23e9b3a3066..dd589fe739bb 100644 --- a/dotnet/src/Connectors/Connectors.Google.UnitTests/GeminiPromptExecutionSettingsTests.cs +++ b/dotnet/src/Connectors/Connectors.Google.UnitTests/GeminiPromptExecutionSettingsTests.cs @@ -41,10 +41,10 @@ public void ItUsesExistingGeminiExecutionSettings() CandidateCount = 3, StopSequences = new[] { "foo", "bar" }, MaxTokens = 128, - SafetySettings = new List() - { + SafetySettings = + [ new(GeminiSafetyCategory.Harassment, GeminiSafetyThreshold.BlockOnlyHigh) - } + ] }; // Act diff --git a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/GeminiPluginCollectionExtensions.cs b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/GeminiPluginCollectionExtensions.cs index c480f76b9207..029bc5f536b7 100644 --- a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/GeminiPluginCollectionExtensions.cs +++ b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/GeminiPluginCollectionExtensions.cs @@ -31,7 +31,7 @@ public static bool TryGetFunctionAndArguments( arguments = null; if (functionToolCall.Arguments is not null) { - arguments = new KernelArguments(); + arguments = []; foreach (var parameter in functionToolCall.Arguments) { arguments[parameter.Key] = parameter.Value?.ToString(); diff --git a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiRequest.cs b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiRequest.cs index eba6f7fe2925..def81d9a7083 100644 --- a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiRequest.cs +++ b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiRequest.cs @@ -29,7 +29,7 @@ internal sealed class GeminiRequest public void AddFunction(GeminiFunction function) { // NOTE: Currently Gemini only supports one tool i.e. function calling. - this.Tools ??= new List(); + this.Tools ??= []; if (this.Tools.Count == 0) { this.Tools.Add(new GeminiTool()); @@ -74,19 +74,19 @@ private static GeminiRequest CreateGeminiRequest(string prompt) { GeminiRequest obj = new() { - Contents = new List - { + Contents = + [ new() { - Parts = new List - { + Parts = + [ new() { Text = prompt } - } + ] } - } + ] }; return obj; } @@ -119,7 +119,7 @@ public void AddChatMessage(ChatMessageContent message) private static List CreateGeminiParts(ChatMessageContent content) { - List parts = new(); + List parts = []; switch (content) { case GeminiChatMessageContent { CalledToolResult: not null } contentWithCalledTool: diff --git a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiTool.cs b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiTool.cs index 55853c8f7591..093fa1201476 100644 --- a/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiTool.cs +++ b/dotnet/src/Connectors/Connectors.Google/Core/Gemini/Models/GeminiTool.cs @@ -23,7 +23,7 @@ internal sealed class GeminiTool /// a [FunctionResponse][content.part.function_response] with the [content.role] "function" generation context for the next model turn. /// [JsonPropertyName("functionDeclarations")] - public IList Functions { get; set; } = new List(); + public IList Functions { get; set; } = []; /// /// Structured representation of a function declaration as defined by the OpenAPI 3.03 specification. diff --git a/dotnet/src/Connectors/Connectors.Google/Core/GoogleAI/GoogleAIEmbeddingRequest.cs b/dotnet/src/Connectors/Connectors.Google/Core/GoogleAI/GoogleAIEmbeddingRequest.cs index 4849e7bc5901..a9f5316c9934 100644 --- a/dotnet/src/Connectors/Connectors.Google/Core/GoogleAI/GoogleAIEmbeddingRequest.cs +++ b/dotnet/src/Connectors/Connectors.Google/Core/GoogleAI/GoogleAIEmbeddingRequest.cs @@ -18,13 +18,13 @@ internal sealed class GoogleAIEmbeddingRequest Model = $"models/{modelId}", Content = new() { - Parts = new List - { + Parts = + [ new() { Text = text } - } + ] } }).ToList() }; diff --git a/dotnet/src/Connectors/Connectors.Google/GeminiToolCallBehavior.cs b/dotnet/src/Connectors/Connectors.Google/GeminiToolCallBehavior.cs index 104bf342386b..c7f8ae6e9611 100644 --- a/dotnet/src/Connectors/Connectors.Google/GeminiToolCallBehavior.cs +++ b/dotnet/src/Connectors/Connectors.Google/GeminiToolCallBehavior.cs @@ -176,14 +176,9 @@ static string GetDescription(KernelParameterMetadata param) /// /// Represents a that provides a specified list of functions to the model. /// - internal sealed class EnabledFunctions : GeminiToolCallBehavior + internal sealed class EnabledFunctions(IEnumerable functions, bool autoInvoke) : GeminiToolCallBehavior(autoInvoke) { - private readonly GeminiFunction[] _functions; - - public EnabledFunctions(IEnumerable functions, bool autoInvoke) : base(autoInvoke) - { - this._functions = functions.ToArray(); - } + private readonly GeminiFunction[] _functions = functions.ToArray(); public override string ToString() => $"{nameof(EnabledFunctions)}(autoInvoke:{this.MaximumAutoInvokeAttempts != 0}): " + diff --git a/dotnet/src/Connectors/Connectors.Google/Services/GoogleAIGeminiChatCompletionService.cs b/dotnet/src/Connectors/Connectors.Google/Services/GoogleAIGeminiChatCompletionService.cs index de8e01a1aa6e..ca7d62f80ebb 100644 --- a/dotnet/src/Connectors/Connectors.Google/Services/GoogleAIGeminiChatCompletionService.cs +++ b/dotnet/src/Connectors/Connectors.Google/Services/GoogleAIGeminiChatCompletionService.cs @@ -17,7 +17,7 @@ namespace Microsoft.SemanticKernel.Connectors.Google; /// public sealed class GoogleAIGeminiChatCompletionService : IChatCompletionService { - private readonly Dictionary _attributesInternal = new(); + private readonly Dictionary _attributesInternal = []; private readonly GeminiChatCompletionClient _chatCompletionClient; /// diff --git a/dotnet/src/Connectors/Connectors.Google/Services/GoogleAITextEmbeddingGenerationService.cs b/dotnet/src/Connectors/Connectors.Google/Services/GoogleAITextEmbeddingGenerationService.cs index b5692a91a665..afda71c9f297 100644 --- a/dotnet/src/Connectors/Connectors.Google/Services/GoogleAITextEmbeddingGenerationService.cs +++ b/dotnet/src/Connectors/Connectors.Google/Services/GoogleAITextEmbeddingGenerationService.cs @@ -18,7 +18,7 @@ namespace Microsoft.SemanticKernel.Connectors.Google; /// public sealed class GoogleAITextEmbeddingGenerationService : ITextEmbeddingGenerationService { - private readonly Dictionary _attributesInternal = new(); + private readonly Dictionary _attributesInternal = []; private readonly GoogleAIEmbeddingClient _embeddingClient; /// diff --git a/dotnet/src/Connectors/Connectors.Google/Services/VertexAIGeminiChatCompletionService.cs b/dotnet/src/Connectors/Connectors.Google/Services/VertexAIGeminiChatCompletionService.cs index 1a830de49147..640134288afe 100644 --- a/dotnet/src/Connectors/Connectors.Google/Services/VertexAIGeminiChatCompletionService.cs +++ b/dotnet/src/Connectors/Connectors.Google/Services/VertexAIGeminiChatCompletionService.cs @@ -18,7 +18,7 @@ namespace Microsoft.SemanticKernel.Connectors.Google; /// public sealed class VertexAIGeminiChatCompletionService : IChatCompletionService { - private readonly Dictionary _attributesInternal = new(); + private readonly Dictionary _attributesInternal = []; private readonly GeminiChatCompletionClient _chatCompletionClient; /// diff --git a/dotnet/src/Connectors/Connectors.Google/Services/VertexAITextEmbeddingGenerationService.cs b/dotnet/src/Connectors/Connectors.Google/Services/VertexAITextEmbeddingGenerationService.cs index 267fe7b1e3b7..c4d7c4108513 100644 --- a/dotnet/src/Connectors/Connectors.Google/Services/VertexAITextEmbeddingGenerationService.cs +++ b/dotnet/src/Connectors/Connectors.Google/Services/VertexAITextEmbeddingGenerationService.cs @@ -18,7 +18,7 @@ namespace Microsoft.SemanticKernel.Connectors.Google; /// public sealed class VertexAITextEmbeddingGenerationService : ITextEmbeddingGenerationService { - private readonly Dictionary _attributesInternal = new(); + private readonly Dictionary _attributesInternal = []; private readonly VertexAIEmbeddingClient _embeddingClient; /// diff --git a/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceEmbeddingGenerationTests.cs b/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceEmbeddingGenerationTests.cs index 65bc835bb27c..82c3482904ea 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceEmbeddingGenerationTests.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceEmbeddingGenerationTests.cs @@ -35,7 +35,7 @@ public async Task SpecifiedModelShouldBeUsedAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", new Uri("https://fake-random-test-host/fake-path"), httpClient: this._httpClient); //Act - await sut.GenerateEmbeddingsAsync(new List()); + await sut.GenerateEmbeddingsAsync([]); //Assert Assert.EndsWith("/fake-model", this._messageHandlerStub.RequestUri?.AbsoluteUri, StringComparison.OrdinalIgnoreCase); @@ -48,7 +48,7 @@ public async Task UserAgentHeaderShouldBeUsedAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", new Uri("https://fake-random-test-host/fake-path"), httpClient: this._httpClient); //Act - await sut.GenerateEmbeddingsAsync(new List()); + await sut.GenerateEmbeddingsAsync([]); //Assert Assert.True(this._messageHandlerStub.RequestHeaders?.Contains("User-Agent")); @@ -66,7 +66,7 @@ public async Task ProvidedEndpointShouldBeUsedAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", new Uri("https://fake-random-test-host/fake-path"), httpClient: this._httpClient); //Act - await sut.GenerateEmbeddingsAsync(new List()); + await sut.GenerateEmbeddingsAsync([]); //Assert Assert.StartsWith("https://fake-random-test-host/fake-path", this._messageHandlerStub.RequestUri?.AbsoluteUri, StringComparison.OrdinalIgnoreCase); @@ -81,7 +81,7 @@ public async Task HttpClientBaseAddressShouldBeUsedAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", httpClient: this._httpClient); //Act - await sut.GenerateEmbeddingsAsync(new List()); + await sut.GenerateEmbeddingsAsync([]); //Assert Assert.StartsWith("https://fake-random-test-host/fake-path", this._messageHandlerStub.RequestUri?.AbsoluteUri, StringComparison.OrdinalIgnoreCase); @@ -94,7 +94,7 @@ public async Task ModelUrlShouldBeBuiltSuccessfullyAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", endpoint: new Uri("https://fake-random-test-host/fake-path"), httpClient: this._httpClient); //Act - await sut.GenerateEmbeddingsAsync(new List()); + await sut.GenerateEmbeddingsAsync([]); //Assert Assert.Equal("https://fake-random-test-host/fake-path/pipeline/feature-extraction/fake-model", this._messageHandlerStub.RequestUri?.AbsoluteUri); @@ -124,7 +124,7 @@ public async Task ShouldHandleServiceResponseAsync() var sut = new HuggingFaceTextEmbeddingGenerationService("fake-model", new Uri("https://fake-random-test-host/fake-path"), httpClient: this._httpClient); //Act - var embeddings = await sut.GenerateEmbeddingsAsync(new List() { "something" }); + var embeddings = await sut.GenerateEmbeddingsAsync(["something"]); //Assert diff --git a/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceTextGenerationTests.cs b/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceTextGenerationTests.cs index 3284551e628c..5347a61eea0d 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceTextGenerationTests.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace.UnitTests/Services/HuggingFaceTextGenerationTests.cs @@ -233,7 +233,7 @@ public async Task GetStreamingTextContentsShouldHaveModelIdDefinedAsync() await foreach (var textContent in sut.GetStreamingTextContentsAsync("Any prompt")) { lastTextContent = textContent; - }; + } // Assert Assert.NotNull(lastTextContent!.ModelId); diff --git a/dotnet/src/Connectors/Connectors.HuggingFace/Client/TextEmbeddingRequest.cs b/dotnet/src/Connectors/Connectors.HuggingFace/Client/TextEmbeddingRequest.cs index b5aa7a4d7a76..0e14185864ee 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace/Client/TextEmbeddingRequest.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace/Client/TextEmbeddingRequest.cs @@ -14,5 +14,5 @@ internal sealed class TextEmbeddingRequest /// Data to embed. /// [JsonPropertyName("inputs")] - public IList Inputs { get; set; } = new List(); + public IList Inputs { get; set; } = []; } diff --git a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceImageToTextService.cs b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceImageToTextService.cs index ea03eae74125..d2c5d62d9d9c 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceImageToTextService.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceImageToTextService.cs @@ -18,7 +18,7 @@ namespace Microsoft.SemanticKernel.Connectors.HuggingFace; /// public sealed class HuggingFaceImageToTextService : IImageToTextService { - private readonly Dictionary _attributesInternal = new(); + private readonly Dictionary _attributesInternal = []; private readonly HuggingFaceClient _client; /// diff --git a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextEmbeddingGenerationService.cs b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextEmbeddingGenerationService.cs index 7b2946ce44f9..f00fda4488a2 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextEmbeddingGenerationService.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextEmbeddingGenerationService.cs @@ -18,7 +18,7 @@ namespace Microsoft.SemanticKernel.Connectors.HuggingFace; /// public sealed class HuggingFaceTextEmbeddingGenerationService : ITextEmbeddingGenerationService { - private Dictionary AttributesInternal { get; } = new(); + private Dictionary AttributesInternal { get; } = []; private HuggingFaceClient Client { get; } /// diff --git a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextGenerationService.cs b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextGenerationService.cs index bd32a44f7a46..6d15391fe4ff 100644 --- a/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextGenerationService.cs +++ b/dotnet/src/Connectors/Connectors.HuggingFace/Services/HuggingFaceTextGenerationService.cs @@ -19,7 +19,7 @@ namespace Microsoft.SemanticKernel.Connectors.HuggingFace; /// public sealed class HuggingFaceTextGenerationService : ITextGenerationService { - private Dictionary AttributesInternal { get; } = new(); + private Dictionary AttributesInternal { get; } = []; private HuggingFaceClient Client { get; } /// diff --git a/dotnet/src/Connectors/Connectors.Memory.AzureAISearch/AzureAISearchMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.AzureAISearch/AzureAISearchMemoryStore.cs index 52e0fa06df37..2df5f9ecf61e 100644 --- a/dotnet/src/Connectors/Connectors.Memory.AzureAISearch/AzureAISearchMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.AzureAISearch/AzureAISearchMemoryStore.cs @@ -227,7 +227,7 @@ public async IAsyncEnumerable GetBatchAsync( /// public async Task RemoveAsync(string collectionName, string key, CancellationToken cancellationToken = default) { - await this.RemoveBatchAsync(collectionName, new[] { key }, cancellationToken).ConfigureAwait(false); + await this.RemoveBatchAsync(collectionName, [key], cancellationToken).ConfigureAwait(false); } /// @@ -286,8 +286,8 @@ private Task> CreateIndexAsync( var newIndex = new SearchIndex(indexName) { - Fields = new List - { + Fields = + [ new SimpleField(AzureAISearchMemoryRecord.IdField, SearchFieldDataType.String) { IsKey = true }, new VectorSearchField(AzureAISearchMemoryRecord.EmbeddingField, embeddingSize, ProfileName), new(AzureAISearchMemoryRecord.TextField, SearchFieldDataType.String) { IsFilterable = true, IsFacetable = true }, @@ -295,7 +295,7 @@ private Task> CreateIndexAsync( new SimpleField(AzureAISearchMemoryRecord.AdditionalMetadataField, SearchFieldDataType.String) { IsFilterable = true, IsFacetable = true }, new SimpleField(AzureAISearchMemoryRecord.ExternalSourceNameField, SearchFieldDataType.String) { IsFilterable = true, IsFacetable = true }, new SimpleField(AzureAISearchMemoryRecord.IsReferenceField, SearchFieldDataType.Boolean) { IsFilterable = true, IsFacetable = true }, - }, + ], VectorSearch = new VectorSearch { Algorithms = @@ -378,7 +378,7 @@ Task> UpsertCode() /// Value to normalize /// The name of the argument used with . /// Normalized name - private string NormalizeIndexName(string indexName, [CallerArgumentExpression("indexName")] string? parameterName = null) + private string NormalizeIndexName(string indexName, [CallerArgumentExpression(nameof(indexName))] string? parameterName = null) { if (indexName.Length > 128) { @@ -466,7 +466,7 @@ private static double ScoreToCosineSimilarity(double score) { // Azure AI Search score formula. The min value is 0.333 for cosine similarity -1. score = Math.Max(score, 1.0 / 3); - return 2 - 1 / score; + return 2 - (1 / score); } private static double CosineSimilarityToScore(double similarity) diff --git a/dotnet/src/Connectors/Connectors.Memory.Chroma/ChromaMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Chroma/ChromaMemoryStore.cs index 6dec81adbaec..528430d90f6a 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Chroma/ChromaMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Chroma/ChromaMemoryStore.cs @@ -90,7 +90,7 @@ public async Task DoesCollectionExistAsync(string collectionName, Cancella /// public async Task GetAsync(string collectionName, string key, bool withEmbedding = false, CancellationToken cancellationToken = default) { - return await this.GetBatchAsync(collectionName, new[] { key }, withEmbedding, cancellationToken) + return await this.GetBatchAsync(collectionName, [key], withEmbedding, cancellationToken) .FirstOrDefaultAsync(cancellationToken) .ConfigureAwait(false); } @@ -166,7 +166,7 @@ public IAsyncEnumerable GetCollectionsAsync(CancellationToken cancellati /// public async Task RemoveAsync(string collectionName, string key, CancellationToken cancellationToken = default) { - await this.RemoveBatchAsync(collectionName, new[] { key }, cancellationToken).ConfigureAwait(false); + await this.RemoveBatchAsync(collectionName, [key], cancellationToken).ConfigureAwait(false); } /// @@ -184,7 +184,7 @@ public async Task UpsertAsync(string collectionName, MemoryRecord record { Verify.NotNullOrWhiteSpace(collectionName); - var key = await this.UpsertBatchAsync(collectionName, new[] { record }, cancellationToken) + var key = await this.UpsertBatchAsync(collectionName, [record], cancellationToken) .FirstOrDefaultAsync(cancellationToken) .ConfigureAwait(false); @@ -228,7 +228,7 @@ public async IAsyncEnumerable UpsertBatchAsync(string collectionName, IE private readonly ILogger _logger; private readonly IChromaClient _chromaClient; - private readonly List _defaultEmbeddingIncludeTypes = new() { IncludeMetadatas }; + private readonly List _defaultEmbeddingIncludeTypes = [IncludeMetadatas]; private async Task GetCollectionOrThrowAsync(string collectionName, CancellationToken cancellationToken) { @@ -265,7 +265,7 @@ private string[] GetEmbeddingIncludeTypes(bool withEmbeddings = false, bool with includeList.Add(IncludeDistances); } - return includeList.ToArray(); + return [.. includeList]; } private MemoryRecord GetMemoryRecordFromEmbeddingsModel(ChromaEmbeddingsModel embeddingsModel, int recordIndex) diff --git a/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaEmbeddingsModel.cs b/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaEmbeddingsModel.cs index 16232e8e5ed7..ea53cb9cd03f 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaEmbeddingsModel.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaEmbeddingsModel.cs @@ -14,17 +14,17 @@ public class ChromaEmbeddingsModel /// Embedding identifiers. /// [JsonPropertyName("ids")] - public List Ids { get; set; } = new(); + public List Ids { get; set; } = []; /// /// Embedding vectors. /// [JsonPropertyName("embeddings")] - public List Embeddings { get; set; } = new(); + public List Embeddings { get; set; } = []; /// /// Embedding metadatas. /// [JsonPropertyName("metadatas")] - public List> Metadatas { get; set; } = new(); + public List> Metadatas { get; set; } = []; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaQueryResultModel.cs b/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaQueryResultModel.cs index bdbf8d6b7906..fddebeb8b063 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaQueryResultModel.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Chroma/Http/ApiSchema/ChromaQueryResultModel.cs @@ -14,23 +14,23 @@ public class ChromaQueryResultModel /// List of embedding identifiers. /// [JsonPropertyName("ids")] - public List> Ids { get; set; } = new(); + public List> Ids { get; set; } = []; /// /// List of embedding vectors. /// [JsonPropertyName("embeddings")] - public List> Embeddings { get; set; } = new(); + public List> Embeddings { get; set; } = []; /// /// List of embedding metadatas. /// [JsonPropertyName("metadatas")] - public List>> Metadatas { get; set; } = new(); + public List>> Metadatas { get; set; } = []; /// /// List of embedding distances. /// [JsonPropertyName("distances")] - public List> Distances { get; set; } = new(); + public List> Distances { get; set; } = []; } diff --git a/dotnet/src/Connectors/Connectors.Memory.DuckDB/Database.cs b/dotnet/src/Connectors/Connectors.Memory.DuckDB/Database.cs index f06a979d55c2..38cde0c95918 100644 --- a/dotnet/src/Connectors/Connectors.Memory.DuckDB/Database.cs +++ b/dotnet/src/Connectors/Connectors.Memory.DuckDB/Database.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Collections.Generic; using System.Globalization; using System.Linq; @@ -63,7 +62,7 @@ public async Task CreateCollectionAsync(DuckDBConnection conn, string collection private static string EncodeFloatArrayToString(float[]? data) { - var dataArrayString = $"[{string.Join(", ", (data ?? Array.Empty()).Select(n => n.ToString("F10", CultureInfo.InvariantCulture)))}]"; + var dataArrayString = $"[{string.Join(", ", (data ?? []).Select(n => n.ToString("F10", CultureInfo.InvariantCulture)))}]"; return dataArrayString; } @@ -72,7 +71,7 @@ public async Task UpdateOrInsertAsync(DuckDBConnection conn, string collectionName, string key, string? metadata, float[]? embedding, string? timestamp, CancellationToken cancellationToken = default) { await this.DeleteAsync(conn, collectionName, key, cancellationToken).ConfigureAwait(true); - var embeddingArrayString = EncodeFloatArrayToString(embedding ?? Array.Empty()); + var embeddingArrayString = EncodeFloatArrayToString(embedding ?? []); using var cmd = conn.CreateCommand(); cmd.CommandText = $"INSERT INTO {TableName} VALUES(${nameof(collectionName)}, ${nameof(key)}, ${nameof(metadata)}, {embeddingArrayString}, ${nameof(timestamp)})"; cmd.Parameters.Add(new DuckDBParameter(nameof(collectionName), collectionName)); @@ -136,7 +135,7 @@ ORDER BY score DESC } string metadata = dataReader.GetFieldValue("metadata"); - float[] embeddingFromSearch = (dataReader.GetFieldValue>("embedding").ToArray()); + float[] embeddingFromSearch = [.. dataReader.GetFieldValue>("embedding")]; string timestamp = dataReader.GetFieldValue("timestamp"); float score = dataReader.GetFieldValue("score"); @@ -168,7 +167,7 @@ ORDER BY score DESC if (await dataReader.ReadAsync(cancellationToken).ConfigureAwait(false)) { string metadata = dataReader.GetFieldValue("metadata"); - float[] embeddingFromSearch = (dataReader.GetFieldValue>("embedding").ToArray()); + float[] embeddingFromSearch = [.. dataReader.GetFieldValue>("embedding")]; string timestamp = dataReader.GetFieldValue("timestamp"); return new DatabaseEntry diff --git a/dotnet/src/Connectors/Connectors.Memory.DuckDB/DuckDBMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.DuckDB/DuckDBMemoryStore.cs index de669a350702..8c1d5610c615 100644 --- a/dotnet/src/Connectors/Connectors.Memory.DuckDB/DuckDBMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.DuckDB/DuckDBMemoryStore.cs @@ -147,13 +147,13 @@ public async Task RemoveBatchAsync(string collectionName, IEnumerable ke yield break; } - List<(MemoryRecord Record, double Score)> embeddings = new(); + List<(MemoryRecord Record, double Score)> embeddings = []; await foreach (var dbEntry in this._dbConnector.GetNearestMatchesAsync(this._dbConnection, collectionName, embedding.ToArray(), limit, minRelevanceScore, cancellationToken).ConfigureAwait(false)) { var entry = MemoryRecord.FromJsonMetadata( json: dbEntry.MetadataString, - withEmbeddings ? dbEntry.Embedding : Array.Empty(), + withEmbeddings ? dbEntry.Embedding : [], dbEntry.Key, ParseTimestamp(dbEntry.Timestamp)); embeddings.Add(new(entry, dbEntry.Score)); diff --git a/dotnet/src/Connectors/Connectors.Memory.Kusto/KustoMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Kusto/KustoMemoryStore.cs index 731095ea430b..36012a45cf12 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Kusto/KustoMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Kusto/KustoMemoryStore.cs @@ -93,7 +93,7 @@ public async Task DoesCollectionExistAsync(string collectionName, Cancella /// public async Task GetAsync(string collectionName, string key, bool withEmbedding = false, CancellationToken cancellationToken = default) { - var result = this.GetBatchAsync(collectionName, new[] { key }, withEmbedding, cancellationToken); + var result = this.GetBatchAsync(collectionName, [key], withEmbedding, cancellationToken); return await result.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } @@ -226,7 +226,7 @@ public async IAsyncEnumerable GetCollectionsAsync([EnumeratorCancellatio /// public Task RemoveAsync(string collectionName, string key, CancellationToken cancellationToken = default) - => this.RemoveBatchAsync(collectionName, new[] { key }, cancellationToken); + => this.RemoveBatchAsync(collectionName, [key], cancellationToken); /// public async Task RemoveBatchAsync(string collectionName, IEnumerable keys, CancellationToken cancellationToken = default) @@ -246,7 +246,7 @@ public async Task RemoveBatchAsync(string collectionName, IEnumerable ke /// public async Task UpsertAsync(string collectionName, MemoryRecord record, CancellationToken cancellationToken = default) { - var result = this.UpsertBatchAsync(collectionName, new[] { record }, cancellationToken); + var result = this.UpsertBatchAsync(collectionName, [record], cancellationToken); return await result.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false) ?? string.Empty; } @@ -340,13 +340,13 @@ protected virtual void Dispose(bool disposing) private static readonly ColumnSchema s_embeddingColumn = new("Embedding", typeof(object).FullName); private static readonly ColumnSchema s_timestampColumn = new("Timestamp", typeof(DateTime).FullName); - private static readonly ColumnSchema[] s_collectionColumns = new ColumnSchema[] - { + private static readonly ColumnSchema[] s_collectionColumns = + [ s_keyColumn, s_metadataColumn, s_embeddingColumn, s_timestampColumn - }; + ]; /// /// Converts collection name to Kusto table name. diff --git a/dotnet/src/Connectors/Connectors.Memory.Milvus/MilvusMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Milvus/MilvusMemoryStore.cs index 24f5f62adf38..1b91daa51e96 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Milvus/MilvusMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Milvus/MilvusMemoryStore.cs @@ -251,10 +251,10 @@ public async Task UpsertAsync(string collectionName, MemoryRecord record var metadata = record.Metadata; - List fieldData = new() - { + List fieldData = + [ FieldData.Create(IdFieldName, new[] { metadata.Id }), - FieldData.CreateFloatVector(EmbeddingFieldName, new[] { record.Embedding }), + FieldData.CreateFloatVector(EmbeddingFieldName, [record.Embedding]), FieldData.Create(IsReferenceFieldName, new[] { metadata.IsReference }, isDynamic: true), FieldData.Create(ExternalSourceNameFieldName, new[] { metadata.ExternalSourceName }, isDynamic: true), @@ -263,7 +263,7 @@ public async Task UpsertAsync(string collectionName, MemoryRecord record FieldData.Create(AdditionalMetadataFieldName, new[] { metadata.AdditionalMetadata }, isDynamic: true), FieldData.Create(KeyFieldName, new[] { record.Key }, isDynamic: true), FieldData.Create(TimestampFieldName, new[] { record.Timestamp?.ToString(CultureInfo.InvariantCulture) ?? string.Empty }, isDynamic: true) - }; + ]; MutationResult result = await collection.UpsertAsync(fieldData, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -278,15 +278,15 @@ public async IAsyncEnumerable UpsertBatchAsync( { StringBuilder idString = new(); - List isReferenceData = new(); - List externalSourceNameData = new(); - List idData = new(); - List descriptionData = new(); - List textData = new(); - List additionalMetadataData = new(); - List> embeddingData = new(); - List keyData = new(); - List timestampData = new(); + List isReferenceData = []; + List externalSourceNameData = []; + List idData = []; + List descriptionData = []; + List textData = []; + List additionalMetadataData = []; + List> embeddingData = []; + List keyData = []; + List timestampData = []; foreach (MemoryRecord record in records) { @@ -313,7 +313,7 @@ public async IAsyncEnumerable UpsertBatchAsync( MilvusCollection collection = this.Client.GetCollection(collectionName); FieldData[] fieldData = - { + [ FieldData.Create(IdFieldName, idData), FieldData.CreateFloatVector(EmbeddingFieldName, embeddingData), @@ -324,7 +324,7 @@ public async IAsyncEnumerable UpsertBatchAsync( FieldData.Create(AdditionalMetadataFieldName, additionalMetadataData, isDynamic: true), FieldData.Create(KeyFieldName, keyData, isDynamic: true), FieldData.Create(TimestampFieldName, timestampData, isDynamic: true) - }; + ]; MutationResult result = await collection.UpsertAsync(fieldData, cancellationToken: cancellationToken).ConfigureAwait(false); @@ -341,7 +341,7 @@ public async IAsyncEnumerable UpsertBatchAsync( bool withEmbedding = false, CancellationToken cancellationToken = default) { - await foreach (MemoryRecord record in this.GetBatchAsync(collectionName, new[] { key }, withEmbedding, cancellationToken).ConfigureAwait(false)) + await foreach (MemoryRecord record in this.GetBatchAsync(collectionName, [key], withEmbedding, cancellationToken).ConfigureAwait(false)) { return record; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/DeleteRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/DeleteRequest.cs index f97bc27c9657..1a743adce367 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/DeleteRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/DeleteRequest.cs @@ -134,12 +134,12 @@ public override string ToString() private DeleteRequest(IEnumerable? ids) { - this.Ids = ids ?? new List(); + this.Ids = ids ?? []; } private DeleteRequest(bool clear) { - this.Ids = new List(); + this.Ids = []; this.DeleteAll = clear; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/UpsertRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/UpsertRequest.cs index ae9c04e3d3d2..bd6322c4bf94 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/UpsertRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Http/ApiSchema/UpsertRequest.cs @@ -56,7 +56,7 @@ public HttpRequestMessage Build() [JsonConstructor] private UpsertRequest() { - this.Vectors = new List(); + this.Vectors = []; } #endregion diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/IndexMetadataConfig.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/IndexMetadataConfig.cs index e454625c544d..8b5849dfc1cf 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/IndexMetadataConfig.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/IndexMetadataConfig.cs @@ -66,8 +66,8 @@ public MetadataIndexConfig(List indexed) /// /// /// - public static MetadataIndexConfig Default => new(new List(new List - { + public static MetadataIndexConfig Default => new(new List( + [ "document_Id", "source", "source_Id", @@ -75,5 +75,5 @@ public MetadataIndexConfig(List indexed) "type", "tags", "created_at" - })); + ])); } diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/PodType.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/PodType.cs index 5821e78c0a81..d340a70df75f 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/PodType.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/Model/PodType.cs @@ -129,15 +129,11 @@ public override PodType Read(ref Utf8JsonReader reader, Type typeToConvert, Json public override void Write(Utf8JsonWriter writer, PodType value, JsonSerializerOptions options) { - EnumMemberAttribute? enumMemberAttr = value.GetType().GetMember(value.ToString())[0].GetCustomAttribute(typeof(EnumMemberAttribute)) as EnumMemberAttribute; - - if (enumMemberAttr != null) - { - writer.WriteStringValue(enumMemberAttr.Value); - } - else + if (value.GetType().GetMember(value.ToString())[0].GetCustomAttribute(typeof(EnumMemberAttribute)) is not EnumMemberAttribute enumMemberAttr) { throw new JsonException($"Unable to find EnumMember attribute for PodType '{value}'."); } + + writer.WriteStringValue(enumMemberAttr.Value); } } diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeClient.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeClient.cs index 456dad2e0dd0..effd43c5130d 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeClient.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeClient.cs @@ -154,7 +154,7 @@ public PineconeClient(string pineconeEnvironment, string apiKey, ILoggerFactory? { this._logger.LogDebug("Searching top {0} nearest vectors with threshold {1}", topK, threshold); - List<(PineconeDocument document, float score)> documents = new(); + List<(PineconeDocument document, float score)> documents = []; Query query = Query.Create(topK) .WithVector(vector) @@ -185,8 +185,8 @@ public PineconeClient(string pineconeEnvironment, string apiKey, ILoggerFactory? yield break; } - // sort documents by score, and order by descending - documents = documents.OrderByDescending(x => x.score).ToList(); + // sort documents descending by score + documents.Sort((x, y) => y.score.CompareTo(x.score)); foreach ((PineconeDocument document, float score) in documents) { @@ -556,12 +556,8 @@ private async Task GetIndexHostAsync(string indexName, CancellationToken this._logger.LogDebug("Getting index host from Pinecone."); - PineconeIndex? pineconeIndex = await this.DescribeIndexAsync(indexName, cancellationToken).ConfigureAwait(false); - - if (pineconeIndex == null) - { + PineconeIndex pineconeIndex = await this.DescribeIndexAsync(indexName, cancellationToken).ConfigureAwait(false) ?? throw new KernelException("Index not found in Pinecone. Create index to perform operations with vectors."); - } if (string.IsNullOrWhiteSpace(pineconeIndex.Status.Host)) { diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeDocument.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeDocument.cs index f743b84062cd..f3bd7faec7e9 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeDocument.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeDocument.cs @@ -99,7 +99,7 @@ public PineconeDocument( { this.Id = id ?? Guid.NewGuid().ToString(); this.Values = values; - this.Metadata = metadata ?? new Dictionary(); + this.Metadata = metadata ?? []; this.SparseValues = sparseValues; this.Score = score; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeMemoryStore.cs index 0aaf832d03f0..2209223f72bc 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeMemoryStore.cs @@ -114,7 +114,7 @@ public async Task UpsertToNamespaceAsync(string indexName, string indexN Task request = operationType switch { - OperationType.Upsert => this._pineconeClient.UpsertAsync(indexName, new[] { vectorData }, indexNamespace, cancellationToken), + OperationType.Upsert => this._pineconeClient.UpsertAsync(indexName, [vectorData], indexNamespace, cancellationToken), OperationType.Update => this._pineconeClient.UpdateAsync(indexName, vectorData, indexNamespace, cancellationToken), OperationType.Skip => Task.CompletedTask, _ => Task.CompletedTask @@ -155,8 +155,8 @@ public async IAsyncEnumerable UpsertBatchToNamespaceAsync( IEnumerable records, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - List upsertDocuments = new(); - List updateDocuments = new(); + List upsertDocuments = []; + List updateDocuments = []; foreach (MemoryRecord? record in records) { @@ -184,7 +184,7 @@ public async IAsyncEnumerable UpsertBatchToNamespaceAsync( } } - List tasks = new(); + List tasks = []; if (upsertDocuments.Count > 0) { @@ -199,7 +199,7 @@ public async IAsyncEnumerable UpsertBatchToNamespaceAsync( tasks.AddRange(updates); } - PineconeDocument[] vectorData = upsertDocuments.Concat(updateDocuments).ToArray(); + PineconeDocument[] vectorData = [.. upsertDocuments, .. updateDocuments]; try { @@ -243,7 +243,7 @@ public async IAsyncEnumerable UpsertBatchToNamespaceAsync( { await foreach (PineconeDocument? record in this._pineconeClient.FetchVectorsAsync( indexName, - new[] { key }, + [key], indexNamespace, withEmbedding, cancellationToken).ConfigureAwait(false)) @@ -314,7 +314,7 @@ public async IAsyncEnumerable GetBatchFromNamespaceAsync( bool withEmbedding = false, [EnumeratorCancellation] CancellationToken cancellationToken = default) { - await foreach (MemoryRecord? record in this.GetWithDocumentIdBatchAsync(indexName, new[] { documentId }, limit, indexNamespace, withEmbedding, cancellationToken).ConfigureAwait(false)) + await foreach (MemoryRecord? record in this.GetWithDocumentIdBatchAsync(indexName, [documentId], limit, indexNamespace, withEmbedding, cancellationToken).ConfigureAwait(false)) { yield return record; } @@ -397,10 +397,10 @@ public async Task RemoveFromNamespaceAsync(string indexName, string indexNamespa { try { - await this._pineconeClient.DeleteAsync(indexName, new[] - { + await this._pineconeClient.DeleteAsync(indexName, + [ key - }, + ], indexNamespace, cancellationToken: cancellationToken).ConfigureAwait(false); } @@ -668,7 +668,7 @@ public async Task ClearNamespaceAsync(string indexName, string indexNamespace, C PineconeDocument vectorData = record.ToPineconeDocument(); - PineconeDocument? existingRecord = await this._pineconeClient.FetchVectorsAsync(indexName, new[] { key }, indexNamespace, false, cancellationToken) + PineconeDocument? existingRecord = await this._pineconeClient.FetchVectorsAsync(indexName, [key], indexNamespace, false, cancellationToken) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); if (existingRecord is null) diff --git a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeUtils.cs b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeUtils.cs index c8d3abb5d8f7..c13182948863 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeUtils.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Pinecone/PineconeUtils.cs @@ -183,7 +183,7 @@ private static int GetMetadataSize(Dictionary metadata) /// public static Dictionary ConvertFilterToPineconeFilter(Dictionary filter) { - Dictionary pineconeFilter = new(); + Dictionary pineconeFilter = []; foreach (KeyValuePair entry in filter) { diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/CreateCollectionRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/CreateCollectionRequest.cs index ae724f176af3..34137649288f 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/CreateCollectionRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/CreateCollectionRequest.cs @@ -32,10 +32,10 @@ public HttpRequestMessage Build() payload: this); } - internal sealed class VectorSettings + internal sealed class VectorSettings(int vectorSize, QdrantDistanceType distanceType) { [JsonPropertyName("size")] - public int? Size { get; set; } + public int? Size { get; set; } = vectorSize; [JsonPropertyName("distance")] public string? DistanceAsString @@ -44,13 +44,7 @@ public string? DistanceAsString } [JsonIgnore] - private QdrantDistanceType DistanceType { get; set; } - - public VectorSettings(int vectorSize, QdrantDistanceType distanceType) - { - this.Size = vectorSize; - this.DistanceType = distanceType; - } + private QdrantDistanceType DistanceType { get; set; } = distanceType; private static string DistanceTypeToString(QdrantDistanceType x) { diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/DeleteVectorsRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/DeleteVectorsRequest.cs index 712db7750fa1..a611606ffa02 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/DeleteVectorsRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/DeleteVectorsRequest.cs @@ -46,7 +46,7 @@ public HttpRequestMessage Build() private DeleteVectorsRequest(string collectionName) { - this.Ids = new List(); + this.Ids = []; this._collectionName = collectionName; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsRequest.cs index 9ed68b78f85c..bcb99aaf9763 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsRequest.cs @@ -25,7 +25,7 @@ internal sealed class GetVectorsRequest /// Array of vector IDs to retrieve /// [JsonPropertyName("ids")] - public IEnumerable PointIds { get; set; } = new List(); + public IEnumerable PointIds { get; set; } = []; /// /// Select which payload to return with the response. Default: All diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsResponse.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsResponse.cs index da23a88e1124..d154adcda9d7 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsResponse.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/GetVectorsResponse.cs @@ -35,6 +35,6 @@ public Record(string id, Dictionary? payload, ReadOnlyMemory [JsonPropertyName("result")] - public IEnumerable Result { get; set; } = new List(); + public IEnumerable Result { get; set; } = []; } #pragma warning restore CA1812 // Avoid uninstantiated internal classes diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/ListCollectionsResponse.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/ListCollectionsResponse.cs index 34e28f1153e8..2b6498092c81 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/ListCollectionsResponse.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/ListCollectionsResponse.cs @@ -23,7 +23,7 @@ internal sealed class CollectionDescription /// List of the collection names that the qdrant database contains. /// [JsonPropertyName("collections")] - public IList Collections { get; set; } = new List(); + public IList Collections { get; set; } = []; } /// diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsRequest.cs index 8fbe76352de9..11eac9b3d908 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsRequest.cs @@ -160,7 +160,7 @@ public void Validate() internal Filter() { - this.Conditions = new(); + this.Conditions = []; } internal Filter ValueMustMatch(string key, object value) diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsResponse.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsResponse.cs index 19797b6a9613..4cec00ee35a6 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsResponse.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/SearchVectorsResponse.cs @@ -52,7 +52,7 @@ public SearchVectorsResponse(IEnumerable results) private SearchVectorsResponse() { - this.Results = new List(); + this.Results = []; } #endregion diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/UpsertVectorRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/UpsertVectorRequest.cs index 641a081af116..66a4a6b2fd65 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/UpsertVectorRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/Http/ApiSchema/UpsertVectorRequest.cs @@ -58,9 +58,9 @@ internal sealed class BatchRequest internal BatchRequest() { - this.Ids = new List(); - this.Vectors = new List>(); - this.Payloads = new List>(); + this.Ids = []; + this.Vectors = []; + this.Payloads = []; } } diff --git a/dotnet/src/Connectors/Connectors.Memory.Qdrant/QdrantMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Qdrant/QdrantMemoryStore.cs index cd1627e1c4d9..ca9291e92b0a 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Qdrant/QdrantMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Qdrant/QdrantMemoryStore.cs @@ -95,18 +95,14 @@ public async Task DeleteCollectionAsync(string collectionName, CancellationToken /// public async Task UpsertAsync(string collectionName, MemoryRecord record, CancellationToken cancellationToken = default) { - var vectorData = await this.ConvertFromMemoryRecordAsync(collectionName, record, cancellationToken).ConfigureAwait(false); - - if (vectorData == null) - { + var vectorData = await this.ConvertFromMemoryRecordAsync(collectionName, record, cancellationToken).ConfigureAwait(false) ?? throw new KernelException("Failed to convert memory record to Qdrant vector record"); - } try { await this._qdrantClient.UpsertVectorsAsync( collectionName, - new[] { vectorData }, + [vectorData], cancellationToken).ConfigureAwait(false); } catch (HttpOperationException ex) @@ -192,7 +188,7 @@ public async IAsyncEnumerable GetBatchAsync(string collectionName, try { var vectorDataList = this._qdrantClient - .GetVectorsByIdAsync(collectionName, new[] { pointId }, withEmbedding, cancellationToken); + .GetVectorsByIdAsync(collectionName, [pointId], withEmbedding, cancellationToken); var vectorData = await vectorDataList.FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); @@ -266,7 +262,7 @@ public async Task RemoveWithPointIdAsync(string collectionName, string pointId, { try { - await this._qdrantClient.DeleteVectorsByIdAsync(collectionName, new[] { pointId }, cancellationToken).ConfigureAwait(false); + await this._qdrantClient.DeleteVectorsByIdAsync(collectionName, [pointId], cancellationToken).ConfigureAwait(false); } catch (HttpOperationException ex) { @@ -405,23 +401,17 @@ private async Task ConvertFromMemoryRecordAsync( { // If no matching record can be found, generate an ID for the new record pointId = Guid.NewGuid().ToString(); - existingRecord = await this._qdrantClient.GetVectorsByIdAsync(collectionName, new[] { pointId }, cancellationToken: cancellationToken) + existingRecord = await this._qdrantClient.GetVectorsByIdAsync(collectionName, [pointId], cancellationToken: cancellationToken) .FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false); } while (existingRecord != null); } } - var vectorData = QdrantVectorRecord.FromJsonMetadata( + return QdrantVectorRecord.FromJsonMetadata( pointId: pointId, embedding: record.Embedding, - json: record.GetSerializedMetadata()); - - if (vectorData == null) - { + json: record.GetSerializedMetadata()) ?? throw new KernelException("Failed to convert memory record to Qdrant vector record"); - } - - return vectorData; } #endregion diff --git a/dotnet/src/Connectors/Connectors.Memory.Redis/RedisMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Redis/RedisMemoryStore.cs index 33d2188df310..83c4416c64b8 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Redis/RedisMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Redis/RedisMemoryStore.cs @@ -156,12 +156,12 @@ public async Task UpsertAsync(string collectionName, MemoryRecord record { record.Key = record.Metadata.Id; - await this._database.HashSetAsync(GetRedisKey(collectionName, record.Key), new[] { + await this._database.HashSetAsync(GetRedisKey(collectionName, record.Key), [ new HashEntry("key", record.Key), new HashEntry("metadata", record.GetSerializedMetadata()), new HashEntry("embedding", this.ConvertEmbeddingToBytes(record.Embedding)), new HashEntry("timestamp", ToTimestampLong(record.Timestamp)) - }, flags: CommandFlags.None).ConfigureAwait(false); + ], flags: CommandFlags.None).ConfigureAwait(false); return record.Key; } @@ -336,6 +336,8 @@ private static RedisKey GetRedisKey(string collectionName, string key) private async Task InternalGetAsync(string collectionName, string key, bool withEmbedding, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + HashEntry[] hashEntries = await this._database.HashGetAllAsync(GetRedisKey(collectionName, key), flags: CommandFlags.None).ConfigureAwait(false); if (hashEntries.Length == 0) { return null; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Sqlite/SqliteMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Sqlite/SqliteMemoryStore.cs index 84537cada364..d41948703464 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Sqlite/SqliteMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Sqlite/SqliteMemoryStore.cs @@ -131,7 +131,7 @@ public async Task RemoveBatchAsync(string collectionName, IEnumerable ke } var collectionMemories = new List(); - List<(MemoryRecord Record, double Score)> embeddings = new(); + List<(MemoryRecord Record, double Score)> embeddings = []; await foreach (var record in this.GetAllAsync(collectionName, cancellationToken).ConfigureAwait(false)) { diff --git a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/BatchRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/BatchRequest.cs index ce2f4d9f4aa3..61776fc53926 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/BatchRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/BatchRequest.cs @@ -13,11 +13,11 @@ internal sealed class BatchRequest private BatchRequest(string @class) { this._class = @class; - this.Objects = new(); + this.Objects = []; } // ReSharper disable once UnusedMember.Global - public string[] Fields { get; } = { "ALL" }; + public string[] Fields { get; } = ["ALL"]; // ReSharper disable once MemberCanBePrivate.Global // ReSharper disable once CollectionNeverQueried.Global diff --git a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateClassSchemaRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateClassSchemaRequest.cs index 8513099f7b15..4fc11f41fc37 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateClassSchemaRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateClassSchemaRequest.cs @@ -12,38 +12,38 @@ private CreateClassSchemaRequest(string @class, string description) this.Description = description; this.Vectorizer = "none"; // See: MemoryRecordMetadata, we also store the timestamp - this.Properties = new[] - { + this.Properties = + [ new Property { Name = "sk_timestamp", - DataType = new[] { "date" } + DataType = ["date"] }, new Property { Name = "sk_id", - DataType = new[] { "string" }, + DataType = ["string"], IndexInverted = false }, new Property { Name = "sk_description", - DataType = new[] { "string" }, + DataType = ["string"], IndexInverted = false }, new Property { Name = "sk_text", - DataType = new[] { "string" }, + DataType = ["string"], IndexInverted = false }, new Property { Name = "sk_additional_metadata", - DataType = new[] { "string" }, + DataType = ["string"], IndexInverted = false } - }; + ]; } public string Class { get; set; } diff --git a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateGraphRequest.cs b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateGraphRequest.cs index 6c5afd759ba5..71c31af9a210 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateGraphRequest.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Weaviate/Http/ApiSchema/CreateGraphRequest.cs @@ -27,7 +27,7 @@ public HttpRequestMessage Build() $"distance:{this.Distance}}} " + $"limit:{this.Limit}){{{(this.WithVector ? "_additional{vector}" : string.Empty)} " + "_additional{id distance} sk_timestamp sk_id sk_description sk_text sk_additional_metadata}}}"; - string queryJson = $"{{\"query\":\"{payload}\"}}"; + string queryJson = $$"""{"query":"{{payload}}"}"""; return HttpRequest.CreatePostRequest( "graphql", queryJson); diff --git a/dotnet/src/Connectors/Connectors.Memory.Weaviate/WeaviateMemoryStore.cs b/dotnet/src/Connectors/Connectors.Memory.Weaviate/WeaviateMemoryStore.cs index 4e76651a5f29..2e0c8698e6b0 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Weaviate/WeaviateMemoryStore.cs +++ b/dotnet/src/Connectors/Connectors.Memory.Weaviate/WeaviateMemoryStore.cs @@ -55,7 +55,7 @@ public class WeaviateMemoryStore : IMemoryStore private readonly Uri? _endpoint = null; private readonly string? _apiVersion; private readonly string? _apiKey; - private static readonly string[] s_stringArray = { "vector" }; + private static readonly string[] s_stringArray = ["vector"]; /// /// Initializes a new instance of the class. @@ -200,11 +200,8 @@ public async IAsyncEnumerable GetCollectionsAsync([EnumeratorCancellatio throw; } - GetSchemaResponse? getSchemaResponse = JsonSerializer.Deserialize(responseContent, s_jsonOptionsCache); - if (getSchemaResponse == null) - { + GetSchemaResponse getSchemaResponse = JsonSerializer.Deserialize(responseContent, s_jsonOptionsCache) ?? throw new KernelException("Unable to deserialize list collections response"); - } foreach (GetClassResponse? @class in getSchemaResponse.Classes!) { @@ -242,7 +239,7 @@ public async Task UpsertAsync(string collectionName, MemoryRecord record { Verify.NotNullOrWhiteSpace(collectionName, "Collection name is empty"); - return await this.UpsertBatchAsync(collectionName, new[] { record }, cancellationToken).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false) ?? string.Empty; + return await this.UpsertBatchAsync(collectionName, [record], cancellationToken).FirstOrDefaultAsync(cancellationToken).ConfigureAwait(false) ?? string.Empty; } /// @@ -274,12 +271,8 @@ public async IAsyncEnumerable UpsertBatchAsync(string collectionName, IE throw; } - BatchResponse[]? result = JsonSerializer.Deserialize(responseContent, s_jsonOptionsCache); - - if (result == null) - { + BatchResponse[] result = JsonSerializer.Deserialize(responseContent, s_jsonOptionsCache) ?? throw new KernelException("Unable to deserialize batch response"); - } foreach (BatchResponse batchResponse in result) { @@ -414,7 +407,7 @@ public async Task RemoveBatchAsync(string collectionName, IEnumerable ke WithVector = withEmbeddings }.Build(); - List<(MemoryRecord, double)> result = new(); + List<(MemoryRecord, double)> result = []; try { (_, string responseContent) = await this.ExecuteHttpRequestAsync(request, cancellationToken).ConfigureAwait(false); diff --git a/dotnet/src/Connectors/Connectors.Onnx/BertOnnxTextEmbeddingGenerationService.cs b/dotnet/src/Connectors/Connectors.Onnx/BertOnnxTextEmbeddingGenerationService.cs index e3a2f873e222..4461d0bb704f 100644 --- a/dotnet/src/Connectors/Connectors.Onnx/BertOnnxTextEmbeddingGenerationService.cs +++ b/dotnet/src/Connectors/Connectors.Onnx/BertOnnxTextEmbeddingGenerationService.cs @@ -28,7 +28,7 @@ public sealed class BertOnnxTextEmbeddingGenerationService : ITextEmbeddingGener /// Reusable options instance passed to OnnxSession.Run. private static readonly RunOptions s_runOptions = new(); /// Reusable input name columns passed to OnnxSession.Run. - private static readonly string[] s_inputNames = new[] { "input_ids", "attention_mask", "token_type_ids" }; + private static readonly string[] s_inputNames = ["input_ids", "attention_mask", "token_type_ids"]; /// The ONNX session instance associated with this service. This may be used concurrently. private readonly InferenceSession _onnxSession; diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AddHeaderRequestPolicy.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AddHeaderRequestPolicy.cs index 33f155b9eeec..89ecb3bef22b 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AddHeaderRequestPolicy.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AddHeaderRequestPolicy.cs @@ -8,16 +8,10 @@ namespace Microsoft.SemanticKernel.Connectors.OpenAI; /// /// Helper class to inject headers into Azure SDK HTTP pipeline /// -internal sealed class AddHeaderRequestPolicy : HttpPipelineSynchronousPolicy +internal sealed class AddHeaderRequestPolicy(string headerName, string headerValue) : HttpPipelineSynchronousPolicy { - private readonly string _headerName; - private readonly string _headerValue; - - public AddHeaderRequestPolicy(string headerName, string headerValue) - { - this._headerName = headerName; - this._headerValue = headerValue; - } + private readonly string _headerName = headerName; + private readonly string _headerValue = headerValue; public override void OnSendingRequest(HttpMessage message) { diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AzureOpenAITextToAudioClient.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AzureOpenAITextToAudioClient.cs index f1749e11ab0a..dd02ddd0ebee 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AzureOpenAITextToAudioClient.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/AzureOpenAITextToAudioClient.cs @@ -28,7 +28,7 @@ internal sealed class AzureOpenAITextToAudioClient /// /// Storage for AI service attributes. /// - internal Dictionary Attributes { get; } = new(); + internal Dictionary Attributes { get; } = []; /// /// Creates an instance of the with API key auth. @@ -76,7 +76,7 @@ internal async Task> GetAudioContentsAsync( using var response = await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); var data = await response.Content.ReadAsByteArrayAndTranslateExceptionAsync().ConfigureAwait(false); - return new List { new(data, modelId) }; + return [new(data, modelId)]; } internal void AddAttribute(string key, string? value) diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ChatHistoryExtensions.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ChatHistoryExtensions.cs index e0a151557176..b4466a30af90 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ChatHistoryExtensions.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ChatHistoryExtensions.cs @@ -23,7 +23,7 @@ public static class ChatHistoryExtensions [Experimental("SKEXP0010")] public static async IAsyncEnumerable AddStreamingMessageAsync(this ChatHistory chatHistory, IAsyncEnumerable streamingMessageContents) { - List messageContents = new(); + List messageContents = []; // Stream the response. StringBuilder? contentBuilder = null; diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ClientCore.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ClientCore.cs index 422498b17a30..305d113aecb1 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ClientCore.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/ClientCore.cs @@ -78,7 +78,7 @@ internal ClientCore(ILogger? logger = null) /// /// Storage for AI service attributes. /// - internal Dictionary Attributes { get; } = new(); + internal Dictionary Attributes { get; } = []; /// /// Instance of for metrics. @@ -285,7 +285,7 @@ internal async Task> GetTextContentFromAudioAsync( AudioTranscription responseData = (await RunRequestAsync(() => this.Client.GetAudioTranscriptionAsync(audioOptions, cancellationToken)).ConfigureAwait(false)).Value; - return new List { new(responseData.Text, this.DeploymentOrModelName, metadata: GetResponseMetadata(responseData)) }; + return [new(responseData.Text, this.DeploymentOrModelName, metadata: GetResponseMetadata(responseData))]; } /// @@ -341,7 +341,7 @@ internal async Task> GetChatMessageContentsAsy OpenAIChatMessageContent result = new(resultChoice.Message, this.DeploymentOrModelName, GetChatChoiceMetadata(responseData, resultChoice)); if (result.ToolCalls.Count == 0) { - return new[] { result }; + return [result]; } if (this.Logger.IsEnabled(LogLevel.Debug)) diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIChatMessageContent.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIChatMessageContent.cs index bad2f3ae2a9f..d91f8e45fc40 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIChatMessageContent.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIChatMessageContent.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Collections.Generic; using System.Linq; using Azure.AI.OpenAI; @@ -67,7 +66,7 @@ public IReadOnlyList GetOpenAIFunctionToolCalls() { if (toolCall is ChatCompletionsFunctionToolCall functionToolCall) { - (functionToolCallList ??= new List()).Add(new OpenAIFunctionToolCall(functionToolCall)); + (functionToolCallList ??= []).Add(new OpenAIFunctionToolCall(functionToolCall)); } } @@ -76,7 +75,7 @@ public IReadOnlyList GetOpenAIFunctionToolCalls() return functionToolCallList; } - return Array.Empty(); + return []; } private static IReadOnlyDictionary? CreateMetadataDictionary( diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunction.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunction.cs index f41cbdc9b875..b51faa59c359 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunction.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunction.cs @@ -74,11 +74,11 @@ public sealed class OpenAIFunction /// This is an optimization to avoid serializing the same JSON Schema over and over again /// for this relatively common case. /// - private static readonly BinaryData s_zeroFunctionParametersSchema = new("{\"type\":\"object\",\"required\":[],\"properties\":{}}"); + private static readonly BinaryData s_zeroFunctionParametersSchema = new("""{"type":"object","required":[],"properties":{}}"""); /// /// Cached schema for a descriptionless string. /// - private static readonly KernelJsonSchema s_stringNoDescriptionSchema = KernelJsonSchema.Parse("{\"type\":\"string\"}"); + private static readonly KernelJsonSchema s_stringNoDescriptionSchema = KernelJsonSchema.Parse("""{"type":"string"}"""); /// Initializes the OpenAIFunction. internal OpenAIFunction( diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunctionToolCall.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunctionToolCall.cs index f6ef3b489dfc..af4688e06df1 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunctionToolCall.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIFunctionToolCall.cs @@ -109,7 +109,7 @@ internal static void TrackStreamingToolingUpdate( // we want to keep track of it so we can send back an error. if (update.Id is string id) { - (toolCallIdsByIndex ??= new())[update.ToolCallIndex] = id; + (toolCallIdsByIndex ??= [])[update.ToolCallIndex] = id; } if (update is StreamingFunctionToolCallUpdate ftc) @@ -117,13 +117,13 @@ internal static void TrackStreamingToolingUpdate( // Ensure we're tracking the function's name. if (ftc.Name is string name) { - (functionNamesByIndex ??= new())[ftc.ToolCallIndex] = name; + (functionNamesByIndex ??= [])[ftc.ToolCallIndex] = name; } // Ensure we're tracking the function's arguments. if (ftc.ArgumentsUpdate is string argumentsUpdate) { - if (!(functionArgumentBuildersByIndex ??= new()).TryGetValue(ftc.ToolCallIndex, out StringBuilder? arguments)) + if (!(functionArgumentBuildersByIndex ??= []).TryGetValue(ftc.ToolCallIndex, out StringBuilder? arguments)) { functionArgumentBuildersByIndex[ftc.ToolCallIndex] = arguments = new(); } @@ -144,7 +144,7 @@ internal static ChatCompletionsFunctionToolCall[] ConvertToolCallUpdatesToChatCo ref Dictionary? functionNamesByIndex, ref Dictionary? functionArgumentBuildersByIndex) { - ChatCompletionsFunctionToolCall[] toolCalls = Array.Empty(); + ChatCompletionsFunctionToolCall[] toolCalls = []; if (toolCallIdsByIndex is { Count: > 0 }) { toolCalls = new ChatCompletionsFunctionToolCall[toolCallIdsByIndex.Count]; diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIPluginCollectionExtensions.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIPluginCollectionExtensions.cs index dbb53c10fecf..135b17b83df3 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIPluginCollectionExtensions.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAIPluginCollectionExtensions.cs @@ -45,7 +45,7 @@ public static bool TryGetFunctionAndArguments( arguments = null; if (functionToolCall.Arguments is not null) { - arguments = new KernelArguments(); + arguments = []; foreach (var parameter in functionToolCall.Arguments) { arguments[parameter.Key] = parameter.Value?.ToString(); diff --git a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAITextToAudioClient.cs b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAITextToAudioClient.cs index e683c93de7c8..7f3daaa2d941 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAITextToAudioClient.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/AzureSdk/OpenAITextToAudioClient.cs @@ -27,7 +27,7 @@ internal sealed class OpenAITextToAudioClient /// /// Storage for AI service attributes. /// - internal Dictionary Attributes { get; } = new(); + internal Dictionary Attributes { get; } = []; /// /// Creates an instance of the with API key auth. @@ -68,7 +68,7 @@ internal async Task> GetAudioContentsAsync( using var response = await this.SendRequestAsync(request, cancellationToken).ConfigureAwait(false); var data = await response.Content.ReadAsByteArrayAndTranslateExceptionAsync().ConfigureAwait(false); - return new List { new(data, this._modelId) }; + return [new(data, this._modelId)]; } internal void AddAttribute(string key, string? value) diff --git a/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/AzureOpenAIChatCompletionWithDataService.cs b/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/AzureOpenAIChatCompletionWithDataService.cs index ea3552257987..0a2f86021759 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/AzureOpenAIChatCompletionWithDataService.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/AzureOpenAIChatCompletionWithDataService.cs @@ -89,7 +89,7 @@ public async IAsyncEnumerable GetStreamingTextContentsAsyn private readonly HttpClient _httpClient; private readonly ILogger _logger; - private readonly Dictionary _attributes = new(); + private readonly Dictionary _attributes = []; private void ValidateConfig(AzureOpenAIChatCompletionWithDataConfig config) { Verify.NotNull(config); @@ -245,9 +245,10 @@ private HttpRequestMessage GetRequest( private List GetDataSources() { - return new List - { - new() { + return + [ + new() + { Parameters = new ChatWithDataSourceParameters { Endpoint = this._config.DataSourceEndpoint, @@ -255,7 +256,7 @@ private List GetDataSources() IndexName = this._config.DataSourceIndex } } - }; + ]; } private List GetMessages(ChatHistory chat) diff --git a/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/ChatWithDataResponse.cs b/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/ChatWithDataResponse.cs index 62cb36c2cc5e..3219cd04ea81 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/ChatWithDataResponse.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/ChatCompletionWithData/ChatWithDataResponse.cs @@ -10,7 +10,8 @@ namespace Microsoft.SemanticKernel.Connectors.OpenAI; #pragma warning disable CA1812 // Avoid uninstantiated internal classes [Experimental("SKEXP0010")] -internal sealed class ChatWithDataResponse +[method: JsonConstructor] +internal sealed class ChatWithDataResponse(ChatWithDataUsage usage) { [JsonPropertyName("id")] public string Id { get; set; } = string.Empty; @@ -22,19 +23,13 @@ internal sealed class ChatWithDataResponse public IList Choices { get; set; } = Array.Empty(); [JsonPropertyName("usage")] - public ChatWithDataUsage Usage { get; set; } + public ChatWithDataUsage Usage { get; set; } = usage; [JsonPropertyName("model")] public string Model { get; set; } = string.Empty; [JsonPropertyName("object")] public string Object { get; set; } = string.Empty; - - [JsonConstructor] - public ChatWithDataResponse(ChatWithDataUsage usage) - { - this.Usage = usage; - } } [Experimental("SKEXP0010")] diff --git a/dotnet/src/Connectors/Connectors.OpenAI/CustomClient/OpenAITextToImageClientCore.cs b/dotnet/src/Connectors/Connectors.OpenAI/CustomClient/OpenAITextToImageClientCore.cs index eba4e69239ef..1a01294c4b75 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/CustomClient/OpenAITextToImageClientCore.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/CustomClient/OpenAITextToImageClientCore.cs @@ -33,7 +33,7 @@ internal OpenAITextToImageClientCore(HttpClient? httpClient, ILogger? logger = n /// /// Storage for AI service attributes. /// - internal Dictionary Attributes { get; } = new(); + internal Dictionary Attributes { get; } = []; /// /// Run the HTTP request to generate a list of images @@ -63,7 +63,7 @@ internal void AddAttribute(string key, string? value) { if (!string.IsNullOrEmpty(value)) { - this.Attributes.Add(key, value!); + this.Attributes.Add(key, value); } } diff --git a/dotnet/src/Connectors/Connectors.OpenAI/Files/OpenAIFileService.cs b/dotnet/src/Connectors/Connectors.OpenAI/Files/OpenAIFileService.cs index b8eeeb02bffb..b677c8180cb9 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/Files/OpenAIFileService.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/Files/OpenAIFileService.cs @@ -292,7 +292,7 @@ private string ConvertPurpose(OpenAIFilePurpose purpose) => private class FileInfoList { [JsonPropertyName("data")] - public FileInfo[] Data { get; set; } = Array.Empty(); + public FileInfo[] Data { get; set; } = []; [JsonPropertyName("object")] public string Object { get; set; } = "list"; diff --git a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/AzureOpenAITextToImageService.cs b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/AzureOpenAITextToImageService.cs index 74de8a7b36c8..efa3ffcc87c0 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/AzureOpenAITextToImageService.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/AzureOpenAITextToImageService.cs @@ -26,7 +26,7 @@ public sealed class AzureOpenAITextToImageService : ITextToImageService private readonly OpenAIClient _client; private readonly ILogger _logger; private readonly string _deploymentName; - private readonly Dictionary _attributes = new(); + private readonly Dictionary _attributes = []; /// public IReadOnlyDictionary Attributes => this._attributes; @@ -68,11 +68,8 @@ public AzureOpenAITextToImageService( this._logger = loggerFactory?.CreateLogger(typeof(AzureOpenAITextToImageService)) ?? NullLogger.Instance; - var connectorEndpoint = !string.IsNullOrWhiteSpace(endpoint) ? endpoint! : httpClient?.BaseAddress?.AbsoluteUri; - if (connectorEndpoint is null) - { + var connectorEndpoint = (!string.IsNullOrWhiteSpace(endpoint) ? endpoint! : httpClient?.BaseAddress?.AbsoluteUri) ?? throw new ArgumentException($"The {nameof(httpClient)}.{nameof(HttpClient.BaseAddress)} and {nameof(endpoint)} are both null or empty. Please ensure at least one is provided."); - } this._client = new(new Uri(connectorEndpoint), new AzureKeyCredential(apiKey), diff --git a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/OpenAITextToImageService.cs b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/OpenAITextToImageService.cs index 49cdfbe42db0..08dad90554c8 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/OpenAITextToImageService.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/OpenAITextToImageService.cs @@ -72,7 +72,7 @@ public OpenAITextToImageService( public Task GenerateImageAsync(string description, int width, int height, Kernel? kernel = null, CancellationToken cancellationToken = default) { Verify.NotNull(description); - if (width != height || width != 256 && width != 512 && width != 1024) + if (width != height || (width != 256 && width != 512 && width != 1024)) { throw new ArgumentOutOfRangeException(nameof(width), width, "OpenAI can generate only square images of size 256x256, 512x512, or 1024x1024."); } diff --git a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/TextToImageResponse.cs b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/TextToImageResponse.cs index 4894aad65a04..45d0ae51598d 100644 --- a/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/TextToImageResponse.cs +++ b/dotnet/src/Connectors/Connectors.OpenAI/TextToImage/TextToImageResponse.cs @@ -34,7 +34,7 @@ public sealed class Image /// List of possible images /// [JsonPropertyName("data")] - public IList Images { get; set; } = new List(); + public IList Images { get; set; } = []; /// /// Creation time diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/DuckDB/DuckDBMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/DuckDB/DuckDBMemoryStoreTests.cs index 3cb3c883c409..d7d33ed00001 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/DuckDB/DuckDBMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/DuckDB/DuckDBMemoryStoreTests.cs @@ -129,7 +129,7 @@ public async Task CollectionsCanBeDeletedAsync() // Assert var collections2 = db.GetCollectionsAsync(); - Assert.True(await collections2.CountAsync() == 0); + Assert.Equal(0, await collections2.CountAsync()); } [Fact] @@ -622,7 +622,7 @@ public async Task ItCanBatchRemoveRecordsAsync() IEnumerable records = this.CreateBatchRecords(numRecords); await db.CreateCollectionAsync(collection); - List keys = new(); + List keys = []; // Act await foreach (var key in db.UpsertBatchAsync(collection, records)) diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/MongoDB/MongoDBMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/MongoDB/MongoDBMemoryStoreTests.cs index b484295ce5e2..c8a8229f1685 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/MongoDB/MongoDBMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/MongoDB/MongoDBMemoryStoreTests.cs @@ -177,7 +177,7 @@ public async Task ItCanGetCollectionsAsync() public async Task ItCanGetNearestMatchAsync() { // Arrange - const string ExpectedStage = "{ \"$vectorSearch\" : { \"queryVector\" : [1.0], \"path\" : \"embedding\", \"limit\" : 1, \"numCandidates\" : 10, \"index\" : \"default\" } }"; + const string ExpectedStage = """{ "$vectorSearch" : { "queryVector" : [1.0], "path" : "embedding", "limit" : 1, "numCandidates" : 10, "index" : "default" } }"""; using var memoryStore = new MongoDBMemoryStore(this._mongoClientMock.Object, DatabaseName); var memoryRecord = CreateRecord("id"); @@ -198,7 +198,7 @@ public async Task ItCanGetNearestMatchAsync() public async Task ItCanGetNearestMatchesAsync() { // Arrange - const string ExpectedStage = "{ \"$vectorSearch\" : { \"queryVector\" : [1.0], \"path\" : \"embedding\", \"limit\" : 100, \"numCandidates\" : 1000, \"index\" : \"default\" } }"; + const string ExpectedStage = """{ "$vectorSearch" : { "queryVector" : [1.0], "path" : "embedding", "limit" : 100, "numCandidates" : 1000, "index" : "default" } }"""; using var memoryStore = new MongoDBMemoryStore(this._mongoClientMock.Object, DatabaseName); var (memoryRecords, keys) = CreateRecords(10); @@ -325,17 +325,12 @@ public void ItDisposesClusterOnDispose() #region private ================================================================================ - private sealed class AsyncCursorMock : IAsyncCursor + private sealed class AsyncCursorMock(params T[] items) : IAsyncCursor { - private T[] _items; + private T[] _items = items ?? []; public IEnumerable? Current { get; private set; } - public AsyncCursorMock(params T[] items) - { - this._items = items ?? Array.Empty(); - } - public void Dispose() { } @@ -343,7 +338,7 @@ public void Dispose() public bool MoveNext(CancellationToken cancellationToken = default) { this.Current = this._items; - this._items = Array.Empty(); + this._items = []; return this.Current.Any(); } diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryBuilderExtensionsTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryBuilderExtensionsTests.cs index 00d1a840fffa..d8e5b0ceb8fb 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryBuilderExtensionsTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryBuilderExtensionsTests.cs @@ -31,7 +31,7 @@ public async Task PineconeMemoryStoreShouldBeProperlyInitializedAsync() { // Arrange var embeddingGenerationMock = Mock.Of(); - this._messageHandlerStub.ResponseToReturn.Content = new StringContent("[\"fake-index1\"]", Encoding.UTF8, MediaTypeNames.Application.Json); + this._messageHandlerStub.ResponseToReturn.Content = new StringContent("""["fake-index1"]""", Encoding.UTF8, MediaTypeNames.Application.Json); var builder = new MemoryBuilder(); builder.WithPineconeMemoryStore("fake-environment", "fake-api-key", this._httpClient); diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryStoreTests.cs index d450a72360cf..c06a0784fd5c 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Pinecone/PineconeMemoryStoreTests.cs @@ -178,8 +178,7 @@ public async Task UpsertBatchAsyncProcessesMultipleDocumentsAsync() this._description3, this._embedding3); - List records = new() - { memoryRecord, memoryRecord2, memoryRecord3 }; + List records = [memoryRecord, memoryRecord2, memoryRecord3]; this._mockPineconeClient .Setup>(x => @@ -223,8 +222,8 @@ public async Task TestGetNearestMatchesAsync() // Arrange ReadOnlyMemory embedding = new float[] { 0.1f, 0.2f }; - List<(PineconeDocument, double)> queryResults = new() - { + List<(PineconeDocument, double)> queryResults = + [ new(new() { Id = this._id, @@ -240,7 +239,7 @@ public async Task TestGetNearestMatchesAsync() Metadata = new Dictionary { { "document_Id", "value2" } }, Values = this._embedding2, }, 0.5) - }; + ]; this._mockPineconeClient .Setup>(x => x.GetMostRelevantAsync( diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryBuilderExtensionsTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryBuilderExtensionsTests.cs index f8e9a870c6f7..8d43f12d8983 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryBuilderExtensionsTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryBuilderExtensionsTests.cs @@ -32,7 +32,7 @@ public async Task QdrantMemoryStoreShouldBeProperlyInitializedAsync() var embeddingGenerationMock = Mock.Of(); this._httpClient.BaseAddress = new Uri("https://fake-random-qdrant-host"); - this._messageHandlerStub.ResponseToReturn.Content = new StringContent("{\"result\":{\"collections\":[]}}", Encoding.UTF8, MediaTypeNames.Application.Json); + this._messageHandlerStub.ResponseToReturn.Content = new StringContent("""{"result":{"collections":[]}}""", Encoding.UTF8, MediaTypeNames.Application.Json); var builder = new MemoryBuilder(); builder.WithQdrantMemoryStore(this._httpClient, 123); diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests2.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests2.cs index de6124922f8b..5d16991e6430 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests2.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests2.cs @@ -62,8 +62,8 @@ public async Task GetAsyncCallsDoNotRequestVectorsUnlessSpecifiedAsync() // Act _ = await vectorStore.GetAsync("test_collection", this._id); _ = await vectorStore.GetAsync("test_collection", this._id, true); - _ = await vectorStore.GetBatchAsync("test_collection", new List { this._id2 }).ToListAsync(); - _ = await vectorStore.GetBatchAsync("test_collection", new List { this._id2 }, true).ToListAsync(); + _ = await vectorStore.GetBatchAsync("test_collection", [this._id2]).ToListAsync(); + _ = await vectorStore.GetBatchAsync("test_collection", [this._id2], true).ToListAsync(); _ = await vectorStore.GetWithPointIdAsync("test_collection", guidString); _ = await vectorStore.GetWithPointIdAsync("test_collection", guidString, true); _ = await vectorStore.GetWithPointIdBatchAsync("test_collection", new[] { guidString2 }).ToListAsync(); @@ -206,7 +206,7 @@ public async Task GetBatchAsyncSearchesByMetadataIdReturnsAllResultsIfAllFoundAs var vectorStore = new QdrantMemoryStore(mockQdrantClient.Object, this._mockLogger.Object); // Act - var getBatchResult = await vectorStore.GetBatchAsync("test_collection", new List { this._id, this._id2, this._id3 }, false).ToListAsync(); + var getBatchResult = await vectorStore.GetBatchAsync("test_collection", [this._id, this._id2, this._id3], false).ToListAsync(); // Assert mockQdrantClient.Verify>( @@ -271,7 +271,7 @@ public async Task GetBatchAsyncSearchesByMetadataIdReturnsOnlyNonNullResultsAsyn var vectorStore = new QdrantMemoryStore(mockQdrantClient.Object, this._mockLogger.Object); // Act - var getBatchResult = await vectorStore.GetBatchAsync("test_collection", new List { this._id, this._id2, this._id3 }, false).ToListAsync(); + var getBatchResult = await vectorStore.GetBatchAsync("test_collection", [this._id, this._id2, this._id3], false).ToListAsync(); // Assert mockQdrantClient.Verify>( @@ -310,7 +310,7 @@ public async Task GetBatchAsyncSearchesByMetadataIdReturnsEmptyListIfNoneFoundAs var vectorStore = new QdrantMemoryStore(mockQdrantClient.Object, this._mockLogger.Object); // Act - var getBatchResult = await vectorStore.GetBatchAsync("test_collection", new List { this._id, this._id2, this._id3 }, false).ToListAsync(); + var getBatchResult = await vectorStore.GetBatchAsync("test_collection", [this._id, this._id2, this._id3], false).ToListAsync(); // Assert mockQdrantClient.Verify>( @@ -438,7 +438,7 @@ public async Task GetBatchByQdrantPointIdsReturnsAllResultsIfFoundAsync() var vectorStore = new QdrantMemoryStore(mockQdrantClient.Object, this._mockLogger.Object); // Act - var getBatchResult = await vectorStore.GetWithPointIdBatchAsync("test_collection", new List { key, key2, key3 }, false).ToListAsync(); + var getBatchResult = await vectorStore.GetWithPointIdBatchAsync("test_collection", [key, key2, key3], false).ToListAsync(); // Assert mockQdrantClient.Verify>(x => @@ -472,7 +472,7 @@ public async Task GetBatchByQdrantPointIdsReturnsEmptyEnumerableIfNonFoundAsync( var vectorStore = new QdrantMemoryStore(mockQdrantClient.Object, this._mockLogger.Object); // Act - var getBatchResult = await vectorStore.GetWithPointIdBatchAsync("test_collection", new List { key, key2, key3 }, false).ToListAsync(); + var getBatchResult = await vectorStore.GetWithPointIdBatchAsync("test_collection", [key, key2, key3], false).ToListAsync(); // Assert mockQdrantClient.Verify>(x => diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests3.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests3.cs index caed0eea8e45..f1cff494ff4d 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests3.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Qdrant/QdrantMemoryStoreTests3.cs @@ -250,22 +250,21 @@ public async Task ScoredVectorSupportsIntegerIdsAsync() "}]" + "}"; - using (var httpResponseMessage = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(scoredPointJsonWithIntegerId) }) - { - var mockHttpMessageHandler = new Mock(); - mockHttpMessageHandler.Protected() - .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) - .ReturnsAsync(httpResponseMessage); + using var httpResponseMessage = new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(scoredPointJsonWithIntegerId) }; + + var mockHttpMessageHandler = new Mock(); + mockHttpMessageHandler.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync(httpResponseMessage); - //Act - using var httpClient = new HttpClient(mockHttpMessageHandler.Object); - { - var client = new QdrantVectorDbClient(httpClient, 1536, "https://fake-random-test-host"); - var result = await client.GetVectorByPayloadIdAsync(payloadId, metadataId); + //Act + using var httpClient = new HttpClient(mockHttpMessageHandler.Object); + { + var client = new QdrantVectorDbClient(httpClient, 1536, "https://fake-random-test-host"); + var result = await client.GetVectorByPayloadIdAsync(payloadId, metadataId); - //Assert - Assert.Equal(result!.PointId, expectedId.ToString(CultureInfo.InvariantCulture)); - } + //Assert + Assert.Equal(result!.PointId, expectedId.ToString(CultureInfo.InvariantCulture)); } } } diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Redis/RedisMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Redis/RedisMemoryStoreTests.cs index 9cd81a80f093..53f41384171d 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Redis/RedisMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Redis/RedisMemoryStoreTests.cs @@ -28,7 +28,7 @@ public class RedisMemoryStoreTests public RedisMemoryStoreTests() { this._mockDatabase = new Mock(); - this._collections = new(); + this._collections = []; } [Fact] @@ -94,7 +94,7 @@ public async Task CollectionsCanBeDeletedAsync() // Assert var collections2 = store.GetCollectionsAsync(); - Assert.True(await collections2.CountAsync() == 0); + Assert.Equal(0, await collections2.CountAsync()); } [Fact] @@ -678,7 +678,7 @@ public async Task ItCanBatchRemoveRecordsAsync() }); await store.CreateCollectionAsync(collection); - List keys = new(); + List keys = []; // Act await foreach (var key in store.UpsertBatchAsync(collection, records)) @@ -771,7 +771,7 @@ private void MockCreateIndex(string collection, Action? callback = null) .ReturnsAsync(RedisResult.Create("OK", ResultType.SimpleString)) .Callback(() => { - this._collections.TryAdd(collection, new()); + this._collections.TryAdd(collection, []); this._mockDatabase .Setup>(x => x.ExecuteAsync( @@ -843,7 +843,7 @@ private void MockHashSet(string collection, MemoryRecord record, Action? callbac ) .Callback(() => { - (this._collections[collection] ??= new()).Add(record); + (this._collections[collection] ??= []).Add(record); this._mockDatabase .Setup>(x => x.HashGetAllAsync(It.Is(x => x == redisKey), It.IsAny())) @@ -870,11 +870,11 @@ private void MockKeyDelete(string collection, string key, Action? callback = nul .ReturnsAsync(true) .Callback(() => { - (this._collections[collection] ??= new()).RemoveAll(x => x.Key == key); + (this._collections[collection] ??= []).RemoveAll(x => x.Key == key); this._mockDatabase .Setup>(x => x.HashGetAllAsync(It.Is(x => x == redisKey), It.IsAny())) - .ReturnsAsync(Array.Empty()); + .ReturnsAsync([]); callback?.Invoke(); }); @@ -892,13 +892,13 @@ private void MockKeyDelete(string collection, IEnumerable keys, Action? .ReturnsAsync(redisKeys.Length) .Callback(() => { - (this._collections[collection] ??= new()).RemoveAll(x => keys.Contains(x.Key)); + (this._collections[collection] ??= []).RemoveAll(x => keys.Contains(x.Key)); foreach (var redisKey in redisKeys) { this._mockDatabase .Setup>(x => x.HashGetAllAsync(It.Is(x => x == redisKey), It.IsAny())) - .ReturnsAsync(Array.Empty()); + .ReturnsAsync([]); } callback?.Invoke(); @@ -907,9 +907,9 @@ private void MockKeyDelete(string collection, IEnumerable keys, Action? private void MockSearch(string collection, ReadOnlyMemory compareEmbedding, int topN, double threshold, bool returnStringVectorScore = false) { - List<(MemoryRecord Record, double Score)> embeddings = new(); + List<(MemoryRecord Record, double Score)> embeddings = []; - List records = this._collections.TryGetValue(collection, out var value) ? value : new(); + List records = this._collections.TryGetValue(collection, out var value) ? value : []; foreach (var record in records) { @@ -924,8 +924,10 @@ private void MockSearch(string collection, ReadOnlyMemory compareEmbeddin string redisKey = $"{collection}"; - var redisResults = new List(); - redisResults.Add(RedisResult.Create(embeddings.Count)); + var redisResults = new List + { + RedisResult.Create(embeddings.Count) + }; foreach (var item in embeddings) { diff --git a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Sqlite/SqliteMemoryStoreTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Sqlite/SqliteMemoryStoreTests.cs index 7b68c41e4050..e91a1794d2a8 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/Memory/Sqlite/SqliteMemoryStoreTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/Memory/Sqlite/SqliteMemoryStoreTests.cs @@ -28,7 +28,7 @@ public SqliteMemoryStoreTests() File.Delete(DatabaseFile); } - using (var stream = File.Create(DatabaseFile)) { } + File.Create(DatabaseFile).Dispose(); } public void Dispose() @@ -150,7 +150,7 @@ public async Task CollectionsCanBeDeletedAsync() // Assert var collections2 = db.GetCollectionsAsync(); - Assert.True(await collections2.CountAsync() == 0); + Assert.Equal(0, await collections2.CountAsync()); } [Fact] @@ -649,7 +649,7 @@ public async Task ItCanBatchRemoveRecordsAsync() IEnumerable records = this.CreateBatchRecords(numRecords); await db.CreateCollectionAsync(collection); - List keys = new(); + List keys = []; // Act await foreach (var key in db.UpsertBatchAsync(collection, records)) diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/AzureSdk/RequestFailedExceptionExtensionsTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/AzureSdk/RequestFailedExceptionExtensionsTests.cs index 4267c57435db..21da96b13e9c 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/AzureSdk/RequestFailedExceptionExtensionsTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/AzureSdk/RequestFailedExceptionExtensionsTests.cs @@ -58,7 +58,7 @@ private sealed class FakeResponse(string responseContent, int status) : Response { private readonly string _responseContent = responseContent; private readonly int _status = status; - private readonly IEnumerable _headers = new List(); + private readonly IEnumerable _headers = []; public override BinaryData Content => BinaryData.FromString(this._responseContent); public override int Status => this._status; diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/AzureOpenAIChatCompletionServiceTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/AzureOpenAIChatCompletionServiceTests.cs index 9a0cca6adf1b..856490cd3823 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/AzureOpenAIChatCompletionServiceTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/AzureOpenAIChatCompletionServiceTests.cs @@ -166,7 +166,7 @@ public async Task GetChatMessageContentsHandlesSettingsCorrectlyAsync() var chatHistory = new ChatHistory(); chatHistory.AddUserMessage("User Message"); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection { new ImageContent(new Uri("https://image")), new TextContent("User Message") }); + chatHistory.AddUserMessage([new ImageContent(new Uri("https://image")), new TextContent("User Message")]); chatHistory.AddSystemMessage("System Message"); chatHistory.AddAssistantMessage("Assistant Message"); @@ -660,11 +660,11 @@ public async Task GetChatMessageContentsWithChatMessageContentItemCollectionAndS var chatHistory = new ChatHistory(); chatHistory.AddUserMessage(Prompt); chatHistory.AddAssistantMessage(AssistantMessage); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection() - { + chatHistory.AddUserMessage( + [ new TextContent(CollectionItemPrompt), new ImageContent(new Uri("https://image")) - }); + ]); // Act var result = await service.GetChatMessageContentsAsync(chatHistory, settings); diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/OpenAIChatCompletionServiceTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/OpenAIChatCompletionServiceTests.cs index 5c192ebdd922..f78b5b918b9c 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/OpenAIChatCompletionServiceTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/ChatCompletion/OpenAIChatCompletionServiceTests.cs @@ -92,7 +92,7 @@ public async Task ItCreatesCorrectFunctionToolCallsWhenUsingAutoAsync() { Content = new StringContent(ChatCompletionResponse) }; // Act - await chatCompletion.GetChatMessageContentsAsync(new ChatHistory(), this._executionSettings); + await chatCompletion.GetChatMessageContentsAsync([], this._executionSettings); // Assert var actualRequestContent = Encoding.UTF8.GetString(this._messageHandlerStub.RequestContent!); @@ -113,7 +113,7 @@ public async Task ItCreatesCorrectFunctionToolCallsWhenUsingNowAsync() this._executionSettings.ToolCallBehavior = ToolCallBehavior.RequireFunction(this._timepluginNow); // Act - await chatCompletion.GetChatMessageContentsAsync(new ChatHistory(), this._executionSettings); + await chatCompletion.GetChatMessageContentsAsync([], this._executionSettings); // Assert var actualRequestContent = Encoding.UTF8.GetString(this._messageHandlerStub.RequestContent!); @@ -133,7 +133,7 @@ public async Task ItCreatesNoFunctionsWhenUsingNoneAsync() this._executionSettings.ToolCallBehavior = null; // Act - await chatCompletion.GetChatMessageContentsAsync(new ChatHistory(), this._executionSettings); + await chatCompletion.GetChatMessageContentsAsync([], this._executionSettings); // Assert var actualRequestContent = Encoding.UTF8.GetString(this._messageHandlerStub.RequestContent!); @@ -288,11 +288,11 @@ public async Task GetChatMessageContentsWithChatMessageContentItemCollectionAndS var chatHistory = new ChatHistory(); chatHistory.AddUserMessage(Prompt); chatHistory.AddAssistantMessage(AssistantMessage); - chatHistory.AddUserMessage(new ChatMessageContentItemCollection() - { + chatHistory.AddUserMessage( + [ new TextContent(CollectionItemPrompt), new ImageContent(new Uri("https://image")) - }); + ]); // Act await chatCompletion.GetChatMessageContentsAsync(chatHistory, settings); @@ -329,91 +329,95 @@ public void Dispose() this._messageHandlerStub.Dispose(); } - private const string ChatCompletionResponse = @"{ - ""id"": ""chatcmpl-8IlRBQU929ym1EqAY2J4T7GGkW5Om"", - ""object"": ""chat.completion"", - ""created"": 1699482945, - ""model"": ""gpt-3.5-turbo"", - ""choices"": [ - { - ""index"": 0, - ""message"": { - ""role"": ""assistant"", - ""content"": null, - ""function_call"": { - ""name"": ""TimePlugin_Date"", - ""arguments"": ""{}"" - } - }, - ""finish_reason"": ""stop"" - } - ], - ""usage"": { - ""prompt_tokens"": 52, - ""completion_tokens"": 1, - ""total_tokens"": 53 - } -}"; - private const string AzureChatCompletionResponse = @"{ - ""id"": ""chatcmpl-8S914omCBNQ0KU1NFtxmupZpzKWv2"", - ""object"": ""chat.completion"", - ""created"": 1701718534, - ""model"": ""gpt-3.5-turbo"", - ""prompt_filter_results"": [ + private const string ChatCompletionResponse = """ { - ""prompt_index"": 0, - ""content_filter_results"": { - ""hate"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""self_harm"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""sexual"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""violence"": { - ""filtered"": false, - ""severity"": ""safe"" + "id": "chatcmpl-8IlRBQU929ym1EqAY2J4T7GGkW5Om", + "object": "chat.completion", + "created": 1699482945, + "model": "gpt-3.5-turbo", + "choices": [ + { + "index": 0, + "message": { + "role": "assistant", + "content": null, + "function_call": { + "name": "TimePlugin_Date", + "arguments": "{}" } + }, + "finish_reason": "stop" } + ], + "usage": { + "prompt_tokens": 52, + "completion_tokens": 1, + "total_tokens": 53 + } } - ], - ""choices"": [ + """; + private const string AzureChatCompletionResponse = """ { - ""index"": 0, - ""finish_reason"": ""stop"", - ""message"": { - ""role"": ""assistant"", - ""content"": ""Hello! How can I help you today? Please provide me with a question or topic you would like information on."" - }, - ""content_filter_results"": { - ""hate"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""self_harm"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""sexual"": { - ""filtered"": false, - ""severity"": ""safe"" - }, - ""violence"": { - ""filtered"": false, - ""severity"": ""safe"" + "id": "chatcmpl-8S914omCBNQ0KU1NFtxmupZpzKWv2", + "object": "chat.completion", + "created": 1701718534, + "model": "gpt-3.5-turbo", + "prompt_filter_results": [ + { + "prompt_index": 0, + "content_filter_results": { + "hate": { + "filtered": false, + "severity": "safe" + }, + "self_harm": { + "filtered": false, + "severity": "safe" + }, + "sexual": { + "filtered": false, + "severity": "safe" + }, + "violence": { + "filtered": false, + "severity": "safe" + } + } + } + ], + "choices": [ + { + "index": 0, + "finish_reason": "stop", + "message": { + "role": "assistant", + "content": "Hello! How can I help you today? Please provide me with a question or topic you would like information on." + }, + "content_filter_results": { + "hate": { + "filtered": false, + "severity": "safe" + }, + "self_harm": { + "filtered": false, + "severity": "safe" + }, + "sexual": { + "filtered": false, + "severity": "safe" + }, + "violence": { + "filtered": false, + "severity": "safe" + } + } } + ], + "usage": { + "prompt_tokens": 23, + "completion_tokens": 23, + "total_tokens": 46 } } - ], - ""usage"": { - ""prompt_tokens"": 23, - ""completion_tokens"": 23, - ""total_tokens"": 46 - } -}"; + """; } diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/KernelFunctionMetadataExtensionsTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/KernelFunctionMetadataExtensionsTests.cs index 9f609814d941..8cf6288d8a19 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/KernelFunctionMetadataExtensionsTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/KernelFunctionMetadataExtensionsTests.cs @@ -24,7 +24,7 @@ public void ItCanConvertToOpenAIFunctionNoParameters() ReturnParameter = new KernelReturnParameterMetadata { Description = "retDesc", - Schema = KernelJsonSchema.Parse("{\"type\": \"object\" }"), + Schema = KernelJsonSchema.Parse("""{"type": "object" }"""), } }; @@ -39,7 +39,7 @@ public void ItCanConvertToOpenAIFunctionNoParameters() Assert.NotNull(result.ReturnParameter); Assert.Equal("retDesc", result.ReturnParameter.Description); - Assert.Equivalent(KernelJsonSchema.Parse("{\"type\": \"object\" }"), result.ReturnParameter.Schema); + Assert.Equivalent(KernelJsonSchema.Parse("""{"type": "object" }"""), result.ReturnParameter.Schema); Assert.Null(result.ReturnParameter.ParameterType); } @@ -54,7 +54,7 @@ public void ItCanConvertToOpenAIFunctionNoPluginName() ReturnParameter = new KernelReturnParameterMetadata { Description = "retDesc", - Schema = KernelJsonSchema.Parse("{\"type\": \"object\" }"), + Schema = KernelJsonSchema.Parse("""{"type": "object" }"""), } }; @@ -69,7 +69,7 @@ public void ItCanConvertToOpenAIFunctionNoPluginName() Assert.NotNull(result.ReturnParameter); Assert.Equal("retDesc", result.ReturnParameter.Description); - Assert.Equivalent(KernelJsonSchema.Parse("{\"type\": \"object\" }"), result.ReturnParameter.Schema); + Assert.Equivalent(KernelJsonSchema.Parse("""{"type": "object" }"""), result.ReturnParameter.Schema); Assert.Null(result.ReturnParameter.ParameterType); } @@ -85,7 +85,7 @@ public void ItCanConvertToOpenAIFunctionWithParameter(bool withSchema) DefaultValue = "1", ParameterType = typeof(int), IsRequired = false, - Schema = withSchema ? KernelJsonSchema.Parse("{\"type\":\"integer\"}") : null, + Schema = withSchema ? KernelJsonSchema.Parse("""{"type":"integer"}""") : null, }; var sut = new KernelFunctionMetadata("foo") @@ -96,7 +96,7 @@ public void ItCanConvertToOpenAIFunctionWithParameter(bool withSchema) ReturnParameter = new KernelReturnParameterMetadata { Description = "retDesc", - Schema = KernelJsonSchema.Parse("{\"type\": \"object\" }"), + Schema = KernelJsonSchema.Parse("""{"type": "object" }"""), } }; @@ -113,7 +113,7 @@ public void ItCanConvertToOpenAIFunctionWithParameter(bool withSchema) Assert.NotNull(result.ReturnParameter); Assert.Equal("retDesc", result.ReturnParameter.Description); - Assert.Equivalent(KernelJsonSchema.Parse("{\"type\": \"object\" }"), result.ReturnParameter.Schema); + Assert.Equivalent(KernelJsonSchema.Parse("""{"type": "object" }"""), result.ReturnParameter.Schema); Assert.Null(result.ReturnParameter.ParameterType); } @@ -131,7 +131,7 @@ public void ItCanConvertToOpenAIFunctionWithParameterNoType() ReturnParameter = new KernelReturnParameterMetadata { Description = "retDesc", - Schema = KernelJsonSchema.Parse("{\"type\": \"object\" }"), + Schema = KernelJsonSchema.Parse("""{"type": "object" }"""), } }; @@ -146,7 +146,7 @@ public void ItCanConvertToOpenAIFunctionWithParameterNoType() Assert.NotNull(result.ReturnParameter); Assert.Equal("retDesc", result.ReturnParameter.Description); - Assert.Equivalent(KernelJsonSchema.Parse("{\"type\": \"object\" }"), result.ReturnParameter.Schema); + Assert.Equivalent(KernelJsonSchema.Parse("""{"type": "object" }"""), result.ReturnParameter.Schema); Assert.Null(result.ReturnParameter.ParameterType); } @@ -196,7 +196,7 @@ public void ItCanCreateValidOpenAIFunctionManualForPlugin() // Assert Assert.NotNull(result); Assert.Equal( - "{\"type\":\"object\",\"required\":[\"parameter1\",\"parameter2\",\"parameter3\"],\"properties\":{\"parameter1\":{\"type\":\"string\",\"description\":\"String parameter\"},\"parameter2\":{\"enum\":[\"Value1\",\"Value2\"],\"description\":\"Enum parameter\"},\"parameter3\":{\"type\":\"string\",\"format\":\"date-time\",\"description\":\"DateTime parameter\"}}}", + """{"type":"object","required":["parameter1","parameter2","parameter3"],"properties":{"parameter1":{"type":"string","description":"String parameter"},"parameter2":{"enum":["Value1","Value2"],"description":"Enum parameter"},"parameter3":{"type":"string","format":"date-time","description":"DateTime parameter"}}}""", result.Parameters.ToString() ); } @@ -213,13 +213,13 @@ public void ItCanCreateValidOpenAIFunctionManualForPrompt() { Name = "parameter1", Description = "String parameter", - JsonSchema = "{\"type\":\"string\",\"description\":\"String parameter\"}" + JsonSchema = """{"type":"string","description":"String parameter"}""" }); promptTemplateConfig.InputVariables.Add(new InputVariable { Name = "parameter2", Description = "Enum parameter", - JsonSchema = "{\"enum\":[\"Value1\",\"Value2\"],\"description\":\"Enum parameter\"}" + JsonSchema = """{"enum":["Value1","Value2"],"description":"Enum parameter"}""" }); var function = KernelFunctionFactory.CreateFromPrompt(promptTemplateConfig); var functionMetadata = function.Metadata; @@ -231,7 +231,7 @@ public void ItCanCreateValidOpenAIFunctionManualForPrompt() // Assert Assert.NotNull(result); Assert.Equal( - "{\"type\":\"object\",\"required\":[\"parameter1\",\"parameter2\"],\"properties\":{\"parameter1\":{\"type\":\"string\",\"description\":\"String parameter\"},\"parameter2\":{\"enum\":[\"Value1\",\"Value2\"],\"description\":\"Enum parameter\"}}}", + """{"type":"object","required":["parameter1","parameter2"],"properties":{"parameter1":{"type":"string","description":"String parameter"},"parameter2":{"enum":["Value1","Value2"],"description":"Enum parameter"}}}""", result.Parameters.ToString() ); } diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/OpenAIFunctionTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/OpenAIFunctionTests.cs index ea763440c43e..518e0cd0097e 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/OpenAIFunctionTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/FunctionCalling/OpenAIFunctionTests.cs @@ -92,7 +92,7 @@ public void ItCanConvertToFunctionDefinitionWithPluginName() [Fact] public void ItCanConvertToFunctionDefinitionsWithParameterTypesAndReturnParameterType() { - string expectedParameterSchema = "{ \"type\": \"object\", \"required\": [\"param1\", \"param2\"], \"properties\": { \"param1\": { \"type\": \"string\", \"description\": \"String param 1\" }, \"param2\": { \"type\": \"integer\", \"description\": \"Int param 2\" } } } "; + string expectedParameterSchema = """{ "type": "object", "required": ["param1", "param2"], "properties": { "param1": { "type": "string", "description": "String param 1" }, "param2": { "type": "integer", "description": "Int param 2" } } } """; KernelPlugin plugin = KernelPluginFactory.CreateFromFunctions("Tests", new[] { @@ -118,7 +118,7 @@ public void ItCanConvertToFunctionDefinitionsWithParameterTypesAndReturnParamete [Fact] public void ItCanConvertToFunctionDefinitionsWithParameterTypesAndNoReturnParameterType() { - string expectedParameterSchema = "{ \"type\": \"object\", \"required\": [\"param1\", \"param2\"], \"properties\": { \"param1\": { \"type\": \"string\", \"description\": \"String param 1\" }, \"param2\": { \"type\": \"integer\", \"description\": \"Int param 2\" } } } "; + string expectedParameterSchema = """{ "type": "object", "required": ["param1", "param2"], "properties": { "param1": { "type": "string", "description": "String param 1" }, "param2": { "type": "integer", "description": "Int param 2" } } } """; KernelPlugin plugin = KernelPluginFactory.CreateFromFunctions("Tests", new[] { @@ -154,7 +154,7 @@ public void ItCanConvertToFunctionDefinitionsWithNoParameterTypes() Assert.NotNull(pd.properties); Assert.Single(pd.properties); Assert.Equal( - JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"string\" }")), + JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"string" }""")), JsonSerializer.Serialize(pd.properties.First().Value.RootElement)); } @@ -174,7 +174,7 @@ public void ItCanConvertToFunctionDefinitionsWithNoParameterTypesButWithDescript Assert.NotNull(pd.properties); Assert.Single(pd.properties); Assert.Equal( - JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"string\", \"description\":\"something neat\" }")), + JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"string", "description":"something neat" }""")), JsonSerializer.Serialize(pd.properties.First().Value.RootElement)); } diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/OpenAIPromptExecutionSettingsTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/OpenAIPromptExecutionSettingsTests.cs index 2160f9babf44..a136fa155fa8 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/OpenAIPromptExecutionSettingsTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/OpenAIPromptExecutionSettingsTests.cs @@ -139,17 +139,19 @@ public void ItCreatesOpenAIExecutionSettingsFromExtraPropertiesAsStrings() public void ItCreatesOpenAIExecutionSettingsFromJsonSnakeCase() { // Arrange - var json = @"{ - ""temperature"": 0.7, - ""top_p"": 0.7, - ""frequency_penalty"": 0.7, - ""presence_penalty"": 0.7, - ""results_per_prompt"": 2, - ""stop_sequences"": [ ""foo"", ""bar"" ], - ""chat_system_prompt"": ""chat system prompt"", - ""token_selection_biases"": { ""1"": 2, ""3"": 4 }, - ""max_tokens"": 128 -}"; + var json = """ + { + "temperature": 0.7, + "top_p": 0.7, + "frequency_penalty": 0.7, + "presence_penalty": 0.7, + "results_per_prompt": 2, + "stop_sequences": [ "foo", "bar" ], + "chat_system_prompt": "chat system prompt", + "token_selection_biases": { "1": 2, "3": 4 }, + "max_tokens": 128 + } + """; var actualSettings = JsonSerializer.Deserialize(json); // Act diff --git a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/TextToImage/AzureOpenAITextToImageTests.cs b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/TextToImage/AzureOpenAITextToImageTests.cs index ab7163826a64..3ce95b1b5dd2 100644 --- a/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/TextToImage/AzureOpenAITextToImageTests.cs +++ b/dotnet/src/Connectors/Connectors.UnitTests/OpenAI/TextToImage/AzureOpenAITextToImageTests.cs @@ -84,15 +84,17 @@ public async Task ItValidatesTheModelIdAsync(int width, int height, Type? expect using var httpClient = new HttpClient(messageHandlerStub, false); messageHandlerStub.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) { - Content = new StringContent(@"{ - ""created"": 1702575371, - ""data"": [ - { - ""revised_prompt"": ""A photo capturing the diversity of the Earth's landscapes."", - ""url"": ""https://dalleprodsec.blob.core.windows.net/private/images/0f20c621-7eb0-449d-87fd-8dd2a3a15fbe/generated_00.png?se=2023-12-15T17%3A36%3A25Z&sig=jd2%2Fa8jOM9NmclrUbOLdRgAxcFDFPezOpG%2BSF82d7zM%3D&ske=2023-12-20T10%3A10%3A28Z&skoid=e52d5ed7-0657-4f62-bc12-7e5dbb260a96&sks=b&skt=2023-12-13T10%3A10%3A28Z&sktid=33e01921-4d64-4f8c-a055-5bdaffd5e33d&skv=2020-10-02&sp=r&spr=https&sr=b&sv=2020-10-02"" - } - ] - }", Encoding.UTF8, "application/json") + Content = new StringContent(""" + { + "created": 1702575371, + "data": [ + { + "revised_prompt": "A photo capturing the diversity of the Earth's landscapes.", + "url": "https://dalleprodsec.blob.core.windows.net/private/images/0f20c621-7eb0-449d-87fd-8dd2a3a15fbe/generated_00.png?se=2023-12-15T17%3A36%3A25Z&sig=jd2%2Fa8jOM9NmclrUbOLdRgAxcFDFPezOpG%2BSF82d7zM%3D&ske=2023-12-20T10%3A10%3A28Z&skoid=e52d5ed7-0657-4f62-bc12-7e5dbb260a96&sks=b&skt=2023-12-13T10%3A10%3A28Z&sktid=33e01921-4d64-4f8c-a055-5bdaffd5e33d&skv=2020-10-02&sp=r&spr=https&sr=b&sv=2020-10-02" + } + ] + } + """, Encoding.UTF8, "application/json") }; var textToImageCompletion = new AzureOpenAITextToImageService(deploymentName: "gpt-35-turbo", modelId: "gpt-3.5-turbo", endpoint: "https://az.com", apiKey: "NOKEY", httpClient: httpClient); diff --git a/dotnet/src/Experimental/Agents.UnitTests/ChatCompletionAgentTests.cs b/dotnet/src/Experimental/Agents.UnitTests/ChatCompletionAgentTests.cs index a7ca53e57cb6..e08d1c9b4415 100644 --- a/dotnet/src/Experimental/Agents.UnitTests/ChatCompletionAgentTests.cs +++ b/dotnet/src/Experimental/Agents.UnitTests/ChatCompletionAgentTests.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -32,7 +31,7 @@ public async Task ItShouldResolveChatCompletionServiceFromKernelAsync() var agent = new ChatCompletionAgent(this._kernelBuilder.Build(), "fake-instructions"); // Act - var result = await agent.InvokeAsync(new List()); + var result = await agent.InvokeAsync([]); // Assert mockChatCompletionService.Verify(x => @@ -55,7 +54,7 @@ public async Task ItShouldAddSystemInstructionsAndMessagesToChatHistoryAsync() var agent = new ChatCompletionAgent(this._kernelBuilder.Build(), "fake-instructions"); // Act - var result = await agent.InvokeAsync(new List() { new(AuthorRole.User, "fake-user-message") }); + var result = await agent.InvokeAsync([new(AuthorRole.User, "fake-user-message")]); // Assert mockChatCompletionService.Verify( @@ -76,17 +75,17 @@ public async Task ItShouldReturnChatCompletionServiceMessagesAsync() var mockChatCompletionService = new Mock(); mockChatCompletionService .Setup(ccs => ccs.GetChatMessageContentsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync(new List { + .ReturnsAsync([ new(AuthorRole.Assistant, "fake-assistant-message-1"), new(AuthorRole.Assistant, "fake-assistant-message-2") - }); + ]); this._kernelBuilder.Services.AddSingleton(mockChatCompletionService.Object); var agent = new ChatCompletionAgent(this._kernelBuilder.Build(), "fake-instructions"); // Act - var result = await agent.InvokeAsync(new List()); + var result = await agent.InvokeAsync([]); // Assert Assert.Equal(2, result.Count); diff --git a/dotnet/src/Experimental/Agents.UnitTests/Extensions/KernelExtensionTests.cs b/dotnet/src/Experimental/Agents.UnitTests/Extensions/KernelExtensionTests.cs index c117be28577a..fc900c13f932 100644 --- a/dotnet/src/Experimental/Agents.UnitTests/Extensions/KernelExtensionTests.cs +++ b/dotnet/src/Experimental/Agents.UnitTests/Extensions/KernelExtensionTests.cs @@ -20,7 +20,7 @@ public static void InvokeTwoPartTool() var function = KernelFunctionFactory.CreateFromMethod(() => { }, functionName: "Bogus"); var kernel = new Kernel(); - kernel.ImportPluginFromFunctions("Fake", new[] { function }); + kernel.ImportPluginFromFunctions("Fake", [function]); //Act var tool = kernel.GetAssistantTool(TwoPartToolName); diff --git a/dotnet/src/Experimental/Agents.UnitTests/Integration/RunHarness.cs b/dotnet/src/Experimental/Agents.UnitTests/Integration/RunHarness.cs index bd901a472c21..0326b059f821 100644 --- a/dotnet/src/Experimental/Agents.UnitTests/Integration/RunHarness.cs +++ b/dotnet/src/Experimental/Agents.UnitTests/Integration/RunHarness.cs @@ -23,7 +23,7 @@ namespace SemanticKernel.Experimental.Agents.UnitTests.Integration; /// [Trait("Category", "Integration Tests")] [Trait("Feature", "Agent")] -public sealed class RunHarness +public sealed class RunHarness(ITestOutputHelper output) { #if DISABLEHOST private const string SkipReason = "Harness only for local/dev environment"; @@ -31,15 +31,7 @@ public sealed class RunHarness private const string SkipReason = null; #endif - private readonly ITestOutputHelper _output; - - /// - /// Test constructor. - /// - public RunHarness(ITestOutputHelper output) - { - this._output = output; - } + private readonly ITestOutputHelper _output = output; /// /// Verify creation of run. diff --git a/dotnet/src/Experimental/Agents.UnitTests/Integration/ThreadHarness.cs b/dotnet/src/Experimental/Agents.UnitTests/Integration/ThreadHarness.cs index 24824402859b..888ddc831afd 100644 --- a/dotnet/src/Experimental/Agents.UnitTests/Integration/ThreadHarness.cs +++ b/dotnet/src/Experimental/Agents.UnitTests/Integration/ThreadHarness.cs @@ -19,7 +19,7 @@ namespace SemanticKernel.Experimental.Agents.UnitTests.Integration; /// [Trait("Category", "Integration Tests")] [Trait("Feature", "Agent")] -public sealed class ThreadHarness +public sealed class ThreadHarness(ITestOutputHelper output) { #if DISABLEHOST private const string SkipReason = "Harness only for local/dev environment"; @@ -27,15 +27,7 @@ public sealed class ThreadHarness private const string SkipReason = null; #endif - private readonly ITestOutputHelper _output; - - /// - /// Test constructor. - /// - public ThreadHarness(ITestOutputHelper output) - { - this._output = output; - } + private readonly ITestOutputHelper _output = output; /// /// Verify creation and retrieval of thread. diff --git a/dotnet/src/Experimental/Agents/AgentBuilder.cs b/dotnet/src/Experimental/Agents/AgentBuilder.cs index 96159a57f911..fe1a0a473aa8 100644 --- a/dotnet/src/Experimental/Agents/AgentBuilder.cs +++ b/dotnet/src/Experimental/Agents/AgentBuilder.cs @@ -36,9 +36,9 @@ public partial class AgentBuilder public AgentBuilder() { this._model = new AssistantModel(); - this._plugins = new KernelPluginCollection(); + this._plugins = []; this._tools = new HashSet(StringComparer.OrdinalIgnoreCase); - this._fileIds = new List(); + this._fileIds = []; } /// diff --git a/dotnet/src/Experimental/Agents/AgentPlugin.cs b/dotnet/src/Experimental/Agents/AgentPlugin.cs index b11deeccab6c..1c8d4acc9859 100644 --- a/dotnet/src/Experimental/Agents/AgentPlugin.cs +++ b/dotnet/src/Experimental/Agents/AgentPlugin.cs @@ -41,7 +41,7 @@ public async Task InvokeAsync(string input, CancellationToken cancellati /// The agent response public async Task InvokeAsync(string input, KernelArguments? arguments, CancellationToken cancellationToken = default) { - arguments ??= new KernelArguments(); + arguments ??= []; arguments["input"] = input; diff --git a/dotnet/src/Experimental/Agents/Extensions/OpenAIRestExtensions.Messages.cs b/dotnet/src/Experimental/Agents/Extensions/OpenAIRestExtensions.Messages.cs index 88b5908978b5..ee73eb991226 100644 --- a/dotnet/src/Experimental/Agents/Extensions/OpenAIRestExtensions.Messages.cs +++ b/dotnet/src/Experimental/Agents/Extensions/OpenAIRestExtensions.Messages.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Collections.Generic; using System.Linq; using System.Threading; @@ -36,7 +35,7 @@ public static Task CreateUserTextMessageAsync( new { role = AuthorRole.User.Label, - file_ids = fileIds?.ToArray() ?? Array.Empty(), + file_ids = fileIds?.ToArray() ?? [], content }; diff --git a/dotnet/src/Experimental/Agents/Internal/Agent.cs b/dotnet/src/Experimental/Agents/Internal/Agent.cs index 6ab144a86d73..67e3fac786e6 100644 --- a/dotnet/src/Experimental/Agents/Internal/Agent.cs +++ b/dotnet/src/Experimental/Agents/Internal/Agent.cs @@ -278,24 +278,18 @@ private void ThrowIfDeleted() } } - private sealed class AgentPluginImpl : AgentPlugin + private sealed class AgentPluginImpl(Agent agent, KernelFunction functionAsk) : + AgentPlugin(s_removeInvalidCharsRegex.Replace(agent.Name ?? agent.Id, string.Empty), + agent.Description ?? agent.Instructions) { - public KernelFunction FunctionAsk { get; } + public KernelFunction FunctionAsk { get; } = functionAsk; - internal override Agent Agent { get; } + internal override Agent Agent { get; } = agent; public override int FunctionCount => 1; private static readonly string s_functionName = nameof(Agent.AskAsync).Substring(0, nameof(AgentPluginImpl.Agent.AskAsync).Length - 5); - public AgentPluginImpl(Agent agent, KernelFunction functionAsk) - : base(s_removeInvalidCharsRegex.Replace(agent.Name ?? agent.Id, string.Empty), - agent.Description ?? agent.Instructions) - { - this.Agent = agent; - this.FunctionAsk = functionAsk; - } - public override IEnumerator GetEnumerator() { yield return this.FunctionAsk; diff --git a/dotnet/src/Experimental/Agents/Models/AssistantModel.cs b/dotnet/src/Experimental/Agents/Models/AssistantModel.cs index b7320433dcca..8fb57b65d418 100644 --- a/dotnet/src/Experimental/Agents/Models/AssistantModel.cs +++ b/dotnet/src/Experimental/Agents/Models/AssistantModel.cs @@ -62,14 +62,14 @@ internal sealed record AssistantModel /// There can be a maximum of 128 tools per assistant. /// [JsonPropertyName("tools")] - public List Tools { get; init; } = new List(); + public List Tools { get; init; } = []; /// /// A list of file IDs attached to this assistant. /// There can be a maximum of 20 files attached to the assistant. /// [JsonPropertyName("file_ids")] - public List FileIds { get; init; } = new List(); + public List FileIds { get; init; } = []; /// /// Set of 16 key-value pairs that can be attached to an object. @@ -79,7 +79,7 @@ internal sealed record AssistantModel /// maximum of 512 characters long. /// [JsonPropertyName("metadata")] - public Dictionary Metadata { get; init; } = new Dictionary(); + public Dictionary Metadata { get; init; } = []; /// /// Assistant file model. diff --git a/dotnet/src/Experimental/Agents/Models/OpenAIListModel.cs b/dotnet/src/Experimental/Agents/Models/OpenAIListModel.cs index 1425bb3543d2..199286fd3717 100644 --- a/dotnet/src/Experimental/Agents/Models/OpenAIListModel.cs +++ b/dotnet/src/Experimental/Agents/Models/OpenAIListModel.cs @@ -15,7 +15,7 @@ internal abstract class OpenAIListModel /// List of steps. /// [JsonPropertyName("data")] - public List Data { get; set; } = new List(); + public List Data { get; set; } = []; /// /// The identifier of the first data record. diff --git a/dotnet/src/Experimental/Agents/Models/OpenAIParameters.cs b/dotnet/src/Experimental/Agents/Models/OpenAIParameters.cs index f87f3aec84c1..69ac459e4c5b 100644 --- a/dotnet/src/Experimental/Agents/Models/OpenAIParameters.cs +++ b/dotnet/src/Experimental/Agents/Models/OpenAIParameters.cs @@ -26,7 +26,7 @@ internal sealed class OpenAIParameters /// Set of parameters. /// [JsonPropertyName("properties")] - public Dictionary Properties { get; set; } = new(); + public Dictionary Properties { get; set; } = []; /// /// Set of parameters. diff --git a/dotnet/src/Experimental/Agents/Models/ThreadMessageModel.cs b/dotnet/src/Experimental/Agents/Models/ThreadMessageModel.cs index 25156680370f..cde59d5caaf0 100644 --- a/dotnet/src/Experimental/Agents/Models/ThreadMessageModel.cs +++ b/dotnet/src/Experimental/Agents/Models/ThreadMessageModel.cs @@ -48,13 +48,13 @@ internal sealed class ThreadMessageModel /// The content of the message in array of text and/or images. /// [JsonPropertyName("content")] - public List Content { get; set; } = new List(); + public List Content { get; set; } = []; /// /// A list of file IDs that the agent should use. /// [JsonPropertyName("file_ids")] - public List FileIds { get; set; } = new List(); + public List FileIds { get; set; } = []; /// /// If applicable, the ID of the assistant that authored this message. @@ -75,7 +75,7 @@ internal sealed class ThreadMessageModel /// characters long and values can be a maximum of 512 characters long. /// [JsonPropertyName("metadata")] - public Dictionary Metadata { get; set; } = new Dictionary(); + public Dictionary Metadata { get; set; } = []; /// /// Representa contents within a message. @@ -128,7 +128,7 @@ public sealed class TextContentModel /// Any annotations on the text. /// [JsonPropertyName("annotations")] - public List Annotations { get; set; } = new List(); + public List Annotations { get; set; } = []; } public sealed class TextAnnotationModel diff --git a/dotnet/src/Experimental/Agents/Models/ThreadModel.cs b/dotnet/src/Experimental/Agents/Models/ThreadModel.cs index 85570cb76d36..0fa72520a527 100644 --- a/dotnet/src/Experimental/Agents/Models/ThreadModel.cs +++ b/dotnet/src/Experimental/Agents/Models/ThreadModel.cs @@ -30,5 +30,5 @@ internal sealed class ThreadModel /// characters long and values can be a maximum of 512 characters long. /// [JsonPropertyName("metadata")] - public Dictionary Metadata { get; set; } = new Dictionary(); + public Dictionary Metadata { get; set; } = []; } diff --git a/dotnet/src/Experimental/Agents/Models/ThreadRunModel.cs b/dotnet/src/Experimental/Agents/Models/ThreadRunModel.cs index fcb17a61321a..45cf1606cdd0 100644 --- a/dotnet/src/Experimental/Agents/Models/ThreadRunModel.cs +++ b/dotnet/src/Experimental/Agents/Models/ThreadRunModel.cs @@ -94,13 +94,13 @@ internal sealed class ThreadRunModel /// The list of tools that the assistant used for this run. /// [JsonPropertyName("tools")] - public List Tools { get; set; } = new List(); + public List Tools { get; set; } = []; /// /// The list of File IDs the assistant used for this run. /// [JsonPropertyName("file_ids")] - public List FileIds { get; set; } = new List(); + public List FileIds { get; set; } = []; /// /// Set of 16 key-value pairs that can be attached to an object. @@ -109,7 +109,7 @@ internal sealed class ThreadRunModel /// characters long and values can be a maximum of 512 characters long. /// [JsonPropertyName("metadata")] - public Dictionary Metadata { get; set; } = new Dictionary(); + public Dictionary Metadata { get; set; } = []; /// /// Run error information. diff --git a/dotnet/src/Experimental/Agents/Models/ThreadRunStepModel.cs b/dotnet/src/Experimental/Agents/Models/ThreadRunStepModel.cs index 5c1b67b384f6..aa647c75e7ea 100644 --- a/dotnet/src/Experimental/Agents/Models/ThreadRunStepModel.cs +++ b/dotnet/src/Experimental/Agents/Models/ThreadRunStepModel.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. #pragma warning disable CA1812 -using System; using System.Text.Json.Serialization; namespace Microsoft.SemanticKernel.Experimental.Agents.Models; @@ -125,7 +124,7 @@ public sealed class StepDetailsModel /// Details of tool calls. /// [JsonPropertyName("tool_calls")] - public ToolCallsDetailsModel[] ToolCalls { get; set; } = Array.Empty(); + public ToolCallsDetailsModel[] ToolCalls { get; set; } = []; } /// diff --git a/dotnet/src/Experimental/Orchestration.Flow.IntegrationTests/CollectEmailPlugin.cs b/dotnet/src/Experimental/Orchestration.Flow.IntegrationTests/CollectEmailPlugin.cs index 9fee46ea2bd7..499541429ab4 100644 --- a/dotnet/src/Experimental/Orchestration.Flow.IntegrationTests/CollectEmailPlugin.cs +++ b/dotnet/src/Experimental/Orchestration.Flow.IntegrationTests/CollectEmailPlugin.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.ComponentModel; using System.Text.RegularExpressions; using System.Threading.Tasks; @@ -37,7 +36,7 @@ public CollectEmailPlugin(Kernel kernel) this._chatRequestSettings = new OpenAIPromptExecutionSettings { MaxTokens = this.MaxTokens, - StopSequences = new List() { "Observation:" }, + StopSequences = ["Observation:"], Temperature = 0 }; } diff --git a/dotnet/src/Experimental/Orchestration.Flow.UnitTests/FlowExtensionsTests.cs b/dotnet/src/Experimental/Orchestration.Flow.UnitTests/FlowExtensionsTests.cs index 85f4bd62ac15..f793ae002457 100644 --- a/dotnet/src/Experimental/Orchestration.Flow.UnitTests/FlowExtensionsTests.cs +++ b/dotnet/src/Experimental/Orchestration.Flow.UnitTests/FlowExtensionsTests.cs @@ -27,7 +27,7 @@ public async Task TestBuildReferenceStepAsync() flow2.AddStep(step5); // Act - var catalog = new InMemoryFlowCatalog(new List { flow1, flow2 }); + var catalog = new InMemoryFlowCatalog([flow1, flow2]); var flow1InCatalog = await catalog.GetFlowAsync("flow1"); Assert.NotNull(flow1InCatalog); @@ -54,7 +54,7 @@ public void TestBuildNonExistReferenceStep() flow2.AddStep(step5); // Act and assert - Assert.Throws(() => new InMemoryFlowCatalog(new List { flow1, flow2 })); + Assert.Throws(() => new InMemoryFlowCatalog([flow1, flow2])); } private static Microsoft.SemanticKernel.Experimental.Orchestration.Flow CreateFlowWithReferenceStep(string referenceFlowName) @@ -82,7 +82,7 @@ private static Microsoft.SemanticKernel.Experimental.Orchestration.Flow CreateFl private sealed class InMemoryFlowCatalog : IFlowCatalog { - private readonly Dictionary _flows = new(); + private readonly Dictionary _flows = []; internal InMemoryFlowCatalog() { diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/ChatHistorySerializer.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/ChatHistorySerializer.cs index c22eae855e2b..4ea1a75e3f2b 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/ChatHistorySerializer.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/ChatHistorySerializer.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Linq; using System.Text.Json; using Microsoft.SemanticKernel.ChatCompletion; @@ -16,8 +15,8 @@ internal static class ChatHistorySerializer return null; } - var messages = JsonSerializer.Deserialize(input) ?? Array.Empty(); - ChatHistory history = new(); + var messages = JsonSerializer.Deserialize(input) ?? []; + ChatHistory history = []; foreach (var message in messages) { history.AddMessage(new AuthorRole(message.Role!), message.Content!); diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/Constants.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/Constants.cs index c2c987de315c..ff069bf5dcec 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/Constants.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/Constants.cs @@ -29,7 +29,7 @@ internal static class ActionVariableNames /// /// All reserved variable names /// - public static readonly string[] All = new[] { ChatHistory, ChatInput }; + public static readonly string[] All = [ChatHistory, ChatInput]; } internal static class ChatPluginVariables @@ -62,6 +62,6 @@ internal static class ChatPluginVariables /// /// The variables that change the default flow /// - public static readonly string[] ControlVariables = new[] { PromptInputName, ExitLoopName, ContinueLoopName, StopFlowName }; + public static readonly string[] ControlVariables = [PromptInputName, ExitLoopName, ContinueLoopName, StopFlowName]; } } diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/ExecutionState.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/ExecutionState.cs index 4632d7b6fe1a..4d73ae8e431f 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/ExecutionState.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/ExecutionState.cs @@ -17,12 +17,12 @@ public sealed class ExecutionState /// /// Execution state described by variables. /// - public Dictionary Variables { get; set; } = new Dictionary(); + public Dictionary Variables { get; set; } = []; /// /// Execution state of each step /// - public Dictionary StepStates { get; set; } = new Dictionary(); + public Dictionary StepStates { get; set; } = []; /// /// Step execution state @@ -42,7 +42,7 @@ public class StepExecutionState /// /// The output variables provided by the step /// - public Dictionary> Output { get; set; } = new Dictionary>(); + public Dictionary> Output { get; set; } = []; /// /// Add or update variable for the step @@ -54,7 +54,7 @@ public void AddOrUpdateVariable(int executionIndex, string key, string value) { if (!this.Output.TryGetValue(key, out List? output)) { - this.Output[key] = output = new(); + this.Output[key] = output = []; } if (output!.Count <= executionIndex) diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowExecutor.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowExecutor.cs index a53fac6c5d97..216a91ae16c8 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowExecutor.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowExecutor.cs @@ -162,7 +162,7 @@ public async Task ExecuteFlowAsync(Flow flow, string sessionId, // populate persisted state arguments ExecutionState executionState = await this._flowStatusProvider.GetExecutionStateAsync(sessionId).ConfigureAwait(false); - List outputs = new(); + List outputs = []; while (executionState.CurrentStepIndex < sortedSteps.Count) { @@ -508,7 +508,7 @@ private void ValidateStep(FlowStep step, KernelArguments context) } else { - chatHistory = new ChatHistory(); + chatHistory = []; } var scratchPad = this.CreateRepeatOrStartStepScratchPad(chatHistory); @@ -654,7 +654,7 @@ private async Task ExecuteStepAsync(FlowStep step, string sessio var chatHistory = await this._flowStatusProvider.GetChatHistoryAsync(sessionId, stepId).ConfigureAwait(false); if (chatHistory is null) { - chatHistory = new ChatHistory(); + chatHistory = []; } else { diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowStatusProvider.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowStatusProvider.cs index 74e0b2527ced..5113fc409944 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowStatusProvider.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/FlowStatusProvider.cs @@ -125,7 +125,7 @@ public async Task> GetReActStepsAsync(string sessionId, string s { try { - return JsonSerializer.Deserialize>(text) ?? new List(); + return JsonSerializer.Deserialize>(text) ?? []; } catch { @@ -134,7 +134,7 @@ public async Task> GetReActStepsAsync(string sessionId, string s } } - return new List(); + return []; } /// diff --git a/dotnet/src/Experimental/Orchestration.Flow/Execution/ReActEngine.cs b/dotnet/src/Experimental/Orchestration.Flow/Execution/ReActEngine.cs index 6409ab0144d1..b10f1f2b551c 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Execution/ReActEngine.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Execution/ReActEngine.cs @@ -173,7 +173,7 @@ internal ReActEngine(Kernel systemKernel, ILogger logger, FlowOrchestratorConfig internal async Task InvokeActionAsync(ReActStep actionStep, string chatInput, ChatHistory chatHistory, Kernel kernel, KernelArguments contextVariables) { - var variables = actionStep.ActionVariables ?? new Dictionary(); + var variables = actionStep.ActionVariables ?? []; variables[Constants.ActionVariableNames.ChatInput] = chatInput; variables[Constants.ActionVariableNames.ChatHistory] = ChatHistorySerializer.Serialize(chatHistory); @@ -274,7 +274,7 @@ private string CreateScratchPad(List stepsTaken) { // ignore the built-in context variables var variablesToPrint = s.ActionVariables?.Where(v => !Constants.ActionVariableNames.All.Contains(v.Key)).ToDictionary(_ => _.Key, _ => _.Value); - scratchPadLines.Insert(insertPoint, $"{Action} {{\"action\": \"{s.Action}\",\"action_variables\": {JsonSerializer.Serialize(variablesToPrint)}}}"); + scratchPadLines.Insert(insertPoint, $$"""{{Action}} {"action": "{{s.Action}}","action_variables": {{JsonSerializer.Serialize(variablesToPrint)}}}"""); } if (i != 0) @@ -370,8 +370,8 @@ private IEnumerable GetAvailableFunctions(Kernel kernel) { var functionViews = kernel.Plugins.GetFunctionsMetadata(); - var excludedPlugins = this._config.ExcludedPlugins ?? new HashSet(); - var excludedFunctions = this._config.ExcludedFunctions ?? new HashSet(); + var excludedPlugins = this._config.ExcludedPlugins ?? []; + var excludedFunctions = this._config.ExcludedFunctions ?? []; var availableFunctions = functionViews @@ -390,14 +390,14 @@ private static KernelFunctionMetadata GetStopAndPromptUserFunction() { Description = "The message to be shown to the user.", ParameterType = typeof(string), - Schema = KernelJsonSchema.Parse("{\"type\":\"string\"}"), + Schema = KernelJsonSchema.Parse("""{"type":"string"}"""), }; return new KernelFunctionMetadata(Constants.StopAndPromptFunctionName) { PluginName = "_REACT_ENGINE_", Description = "Terminate the session, only used when previous attempts failed with FATAL error and need notify user", - Parameters = new[] { promptParameter } + Parameters = [promptParameter] }; } diff --git a/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestrator.cs b/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestrator.cs index 32cbaa7c0c72..d86c1681b96e 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestrator.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestrator.cs @@ -43,7 +43,7 @@ public FlowOrchestrator( this._kernelBuilder = kernelBuilder; this._flowStatusProvider = flowStatusProvider; - this._globalPluginCollection = globalPluginCollection ?? new Dictionary(); + this._globalPluginCollection = globalPluginCollection ?? []; this._flowValidator = validator ?? new FlowValidator(); this._config = config; } diff --git a/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestratorConfig.cs b/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestratorConfig.cs index 171756034cce..0c4aaaeb3002 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestratorConfig.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/FlowOrchestratorConfig.cs @@ -13,12 +13,12 @@ public sealed class FlowOrchestratorConfig /// /// A list of plugins to exclude from the plan creation request. /// - public HashSet ExcludedPlugins { get; } = new(); + public HashSet ExcludedPlugins { get; } = []; /// /// A list of functions to exclude from the plan creation request. /// - public HashSet ExcludedFunctions { get; } = new(); + public HashSet ExcludedFunctions { get; } = []; /// /// The maximum number of tokens to allow in a plan. @@ -59,7 +59,7 @@ public sealed class FlowOrchestratorConfig /// /// Optional. The allowed AI service id for the React engine. /// - public HashSet AIServiceIds { get; set; } = new(); + public HashSet AIServiceIds { get; set; } = []; /// /// Optional. The AI request settings for the ReAct engine. diff --git a/dotnet/src/Experimental/Orchestration.Flow/FlowSerializer.cs b/dotnet/src/Experimental/Orchestration.Flow/FlowSerializer.cs index d36a725034a6..1b7aa89345a8 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/FlowSerializer.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/FlowSerializer.cs @@ -89,11 +89,11 @@ private class FlowStepModel { public string Goal { get; set; } = string.Empty; - public List Requires { get; set; } = new(); + public List Requires { get; set; } = []; - public List Provides { get; set; } = new(); + public List Provides { get; set; } = []; - public List Passthrough { get; set; } = new(); + public List Passthrough { get; set; } = []; public CompletionType CompletionType { get; set; } = CompletionType.Once; @@ -101,7 +101,7 @@ private class FlowStepModel public string? TransitionMessage { get; set; } - public List Plugins { get; set; } = new(); + public List Plugins { get; set; } = []; public string? FlowName { get; set; } } @@ -110,6 +110,6 @@ private class FlowModel : FlowStepModel { public string Name { get; set; } = string.Empty; - public List Steps { get; set; } = new(); + public List Steps { get; set; } = []; } } diff --git a/dotnet/src/Experimental/Orchestration.Flow/Model/Flow.cs b/dotnet/src/Experimental/Orchestration.Flow/Model/Flow.cs index da78aba9cf28..98d98c058fbe 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Model/Flow.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Model/Flow.cs @@ -26,7 +26,7 @@ public sealed class Flow : FlowStep public Flow(string name, string goal) : base(goal, null) { this.Name = name; - this._steps = new List(); + this._steps = []; } /// diff --git a/dotnet/src/Experimental/Orchestration.Flow/Model/FlowStep.cs b/dotnet/src/Experimental/Orchestration.Flow/Model/FlowStep.cs index c659ed4a9617..dea670c38b6b 100644 --- a/dotnet/src/Experimental/Orchestration.Flow/Model/FlowStep.cs +++ b/dotnet/src/Experimental/Orchestration.Flow/Model/FlowStep.cs @@ -13,13 +13,13 @@ namespace Microsoft.SemanticKernel.Experimental.Orchestration; /// public class FlowStep { - private readonly List _requires = new(); + private readonly List _requires = []; - private readonly List _provides = new(); + private readonly List _provides = []; - private readonly List _passthrough = new(); + private readonly List _passthrough = []; - private Dictionary _pluginTypes = new(); + private Dictionary _pluginTypes = []; private Func, IEnumerable>? _pluginsFactory; @@ -100,7 +100,7 @@ private List GetPlugins(Dictionary globalPlugins, Kerne { try { - return Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, new object[] { kernel }, null); + return Activator.CreateInstance(type, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, [kernel], null); } catch (MissingMethodException) { @@ -120,7 +120,7 @@ private List GetPlugins(Dictionary globalPlugins, Kerne private static Dictionary GetPluginTypes(List? value) { - Dictionary plugins = new(); + Dictionary plugins = []; if (value is not null) { @@ -209,7 +209,7 @@ public IEnumerable LoadPlugins(Kernel kernel, Dictionary(); + return []; } /// diff --git a/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelFunctionHelpersTests.cs b/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelFunctionHelpersTests.cs index 04e58b1d918e..473c4342fa1a 100644 --- a/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelFunctionHelpersTests.cs +++ b/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelFunctionHelpersTests.cs @@ -48,7 +48,7 @@ public async Task ItRendersAsyncFunctionsAsync() public async Task ItRendersFunctionHelpersWithPositionalArgumentsAsync() { // Arrange and Act - var template = "{{Foo-Combine \"Bar\" \"Baz\"}}"; // Use positional arguments instead of hashed arguments + var template = """{{Foo-Combine "Bar" "Baz"}}"""; // Use positional arguments instead of hashed arguments var result = await this.RenderPromptTemplateAsync(template); // Assert @@ -83,7 +83,7 @@ public async Task ItThrowsExceptionWhenPositionalArgumentNumberIsIncorrectAsync( public async Task ItRendersFunctionHelpersWitHashArgumentsAsync() { // Arrange and Act - var template = "{{Foo-Combine x=\"Bar\" y=\"Baz\"}}"; // Use positional arguments instead of hashed arguments + var template = """{{Foo-Combine x="Bar" y="Baz"}}"""; // Use positional arguments instead of hashed arguments var result = await this.RenderPromptTemplateAsync(template); // Assert @@ -94,7 +94,7 @@ public async Task ItRendersFunctionHelpersWitHashArgumentsAsync() public async Task ShouldThrowExceptionWhenMissingRequiredParameterAsync() { // Arrange and Act - var template = "{{Foo-Combine x=\"Bar\"}}"; + var template = """{{Foo-Combine x="Bar"}}"""; // Assert var exception = await Assert.ThrowsAsync(() => this.RenderPromptTemplateAsync(template)); @@ -116,7 +116,7 @@ public async Task ShouldThrowExceptionWhenArgumentsAreNotProvidedAsync() public async Task ShouldThrowExceptionWhenFunctionHelperHasInvalidParameterTypeAsync() { // Arrange and Act - var template = "{{Foo-StringifyInt x=\"twelve\"}}"; + var template = """{{Foo-StringifyInt x="twelve"}}"""; // Assert var exception = await Assert.ThrowsAsync(() => this.RenderPromptTemplateAsync(template)); @@ -127,7 +127,7 @@ public async Task ShouldThrowExceptionWhenFunctionHelperHasInvalidParameterTypeA public async Task ShouldThrowExceptionWhenFunctionHelperIsNotDefinedAsync() { // Arrange and Act - var template = "{{Foo-Random x=\"random\"}}"; + var template = """{{Foo-Random x="random"}}"""; // Assert var exception = await Assert.ThrowsAsync(() => this.RenderPromptTemplateAsync(template)); diff --git a/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelSystemHelpersTests.cs b/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelSystemHelpersTests.cs index c413e050cb5c..a5fc3ada1a5f 100644 --- a/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelSystemHelpersTests.cs +++ b/dotnet/src/Extensions/Extensions.UnitTests/PromptTemplates/Handlebars/Helpers/KernelSystemHelpersTests.cs @@ -24,7 +24,7 @@ public KernelSystemHelpersTests() public async Task ItRendersTemplateWithMessageHelperAsync() { // Arrange - var template = "{{#message role=\"title\"}}Hello World!{{/message}}"; + var template = """{{#message role="title"}}Hello World!{{/message}}"""; // Act var result = await this.RenderPromptTemplateAsync(template); @@ -63,7 +63,7 @@ public async Task ItRendersTemplateWithJsonHelperAsync(object json) var result = await this.RenderPromptTemplateAsync(template, arguments); // Assert - Assert.Equal("{\"name\":\"Alice\",\"age\":25}", result); + Assert.Equal("""{"name":"Alice","age":25}""", result); } [Fact] @@ -147,7 +147,7 @@ public async Task ItRendersTemplateWithArrayHelperAsync() public async Task ItRendersTemplateWithArrayHelperAndVariableReferenceAsync() { // Arrange - var template = @"{{array ""hi"" "" "" name ""!"" ""Welcome to"" "" "" Address.City}}"; + var template = """{{array "hi" " " name "!" "Welcome to" " " Address.City}}"""; var arguments = new KernelArguments { { "name", "Alice" }, @@ -191,7 +191,7 @@ public async Task ItRendersTemplateWithRangeHelperAsync() public async Task ItRendersTemplateWithConcatHelperAsync() { // Arrange - var template = "{{concat \"Hello\" \" \" name \"!\"}}"; + var template = """{{concat "Hello" " " name "!"}}"""; var arguments = new KernelArguments { { "name", "Alice" } @@ -208,7 +208,7 @@ public async Task ItRendersTemplateWithConcatHelperAsync() public async Task ItRendersTemplateWithdSetAndConcatHelpersAsync() { // Arrange - var template = "{{set name=\"name\" value=\"Alice\"}}{{concat \"Hello\" \" \" name \"!\"}}"; + var template = """{{set name="name" value="Alice"}}{{concat "Hello" " " name "!"}}"""; // Act var result = await this.RenderPromptTemplateAsync(template); diff --git a/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplate.cs b/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplate.cs index ddd88b6df40b..49e01cf284c6 100644 --- a/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplate.cs +++ b/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplate.cs @@ -94,7 +94,7 @@ private void RegisterHelpers( /// private KernelArguments GetVariables(KernelArguments? arguments) { - KernelArguments result = new(); + KernelArguments result = []; foreach (var p in this._promptModel.InputVariables) { diff --git a/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplateOptions.cs b/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplateOptions.cs index 2fbd155cd47e..78be0f2480eb 100644 --- a/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplateOptions.cs +++ b/dotnet/src/Extensions/PromptTemplates.Handlebars/HandlebarsPromptTemplateOptions.cs @@ -55,9 +55,9 @@ public sealed class HandlebarsPromptTemplateOptions : HandlebarsHelpersOptions public HandlebarsPromptTemplateOptions() { this.PrefixSeparator = "-"; - this.Categories = new Category[] { + this.Categories = [ Category.Math, // Enables basic math operations (https://github.com/Handlebars-Net/Handlebars.Net.Helpers/wiki/Math) Category.String // Enables string manipulation (https://github.com/Handlebars-Net/Handlebars.Net.Helpers/wiki/String) - }; + ]; } } diff --git a/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcKernelExtensions.cs b/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcKernelExtensions.cs index 00a88fcc1fb9..ad32f27d6cb6 100644 --- a/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcKernelExtensions.cs +++ b/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcKernelExtensions.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Net.Http; using System.Text.Json.Nodes; using System.Threading; @@ -200,8 +199,6 @@ private static KernelFunction CreateGrpcFunction( GrpcOperation operation, ILoggerFactory loggerFactory) { - var operationParameters = operation.GetParameters(); - async Task ExecuteAsync(KernelArguments arguments, CancellationToken cancellationToken) { try @@ -217,7 +214,7 @@ async Task ExecuteAsync(KernelArguments arguments, CancellationToken return KernelFunctionFactory.CreateFromMethod( method: ExecuteAsync, - parameters: operationParameters.ToList(), + parameters: GrpcOperation.CreateParameters(), description: operation.Name, functionName: operation.Name, loggerFactory: loggerFactory); diff --git a/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcOperationExtensions.cs b/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcOperationExtensions.cs deleted file mode 100644 index ea6029a71da2..000000000000 --- a/dotnet/src/Functions/Functions.Grpc/Extensions/GrpcOperationExtensions.cs +++ /dev/null @@ -1,39 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Collections.Generic; -using Microsoft.SemanticKernel.Plugins.Grpc.Model; - -namespace Microsoft.SemanticKernel.Plugins.Grpc; - -#pragma warning disable RCS1175 // Unused 'this' parameter 'operation'. - -/// -/// Class for extensions methods for the class. -/// -internal static class GrpcOperationExtensions -{ - /// - /// Returns list of gRPC operation parameters. - /// TODO: not an extension method, `operation` is never used. - /// - /// The list of parameters. - public static IReadOnlyList GetParameters(this GrpcOperation operation) - { - var parameters = new KernelParameterMetadata[] - { - // Register the "address" parameter so that it's possible to override it if needed. - new(GrpcOperation.AddressArgumentName) - { - Description = "Address for gRPC channel to use.", - }, - - // Register the "payload" parameter to be used as gRPC operation request message. - new(GrpcOperation.PayloadArgumentName) - { - Description = "gRPC request message.", - }, - }; - - return parameters; - } -} diff --git a/dotnet/src/Functions/Functions.Grpc/GrpcOperationRunner.cs b/dotnet/src/Functions/Functions.Grpc/GrpcOperationRunner.cs index 35a86334e43e..b5898f22f222 100644 --- a/dotnet/src/Functions/Functions.Grpc/GrpcOperationRunner.cs +++ b/dotnet/src/Functions/Functions.Grpc/GrpcOperationRunner.cs @@ -60,29 +60,28 @@ public async Task RunAsync(GrpcOperation operation, KernelArguments var channelOptions = new GrpcChannelOptions { HttpClient = this._httpClient, DisposeHttpClient = false }; - using (var channel = GrpcChannel.ForAddress(address, channelOptions)) - { - var requestType = BuildGrpcOperationDataContractType(operation.Request); + using var channel = GrpcChannel.ForAddress(address, channelOptions); - var responseType = BuildGrpcOperationDataContractType(operation.Response); + var requestType = BuildGrpcOperationDataContractType(operation.Request); - var method = new Method - ( - MethodType.Unary, - operation.FullServiceName, - operation.Name, - this.CreateMarshaller(requestType), - this.CreateMarshaller(responseType) - ); + var responseType = BuildGrpcOperationDataContractType(operation.Response); - var invoker = channel.CreateCallInvoker(); + var method = new Method + ( + MethodType.Unary, + operation.FullServiceName, + operation.Name, + this.CreateMarshaller(requestType), + this.CreateMarshaller(responseType) + ); - var request = this.GenerateOperationRequest(operation, requestType, stringArgument); + var invoker = channel.CreateCallInvoker(); - var response = await invoker.AsyncUnaryCall(method, null, new CallOptions(cancellationToken: cancellationToken), request).ConfigureAwait(false); + var request = this.GenerateOperationRequest(operation, requestType, stringArgument); - return ConvertResponse(response, responseType); - } + var response = await invoker.AsyncUnaryCall(method, null, new CallOptions(cancellationToken: cancellationToken), request).ConfigureAwait(false); + + return ConvertResponse(response, responseType); } /// @@ -116,9 +115,11 @@ private static JsonObject ConvertResponse(object response, Type responseType) var content = JsonSerializer.Serialize(response, responseType, s_camelCaseOptions); //First iteration allowing to associate additional metadata with the returned content. - var result = new JsonObject(); - result.Add("content", content); - result.Add("contentType", "application/json; charset=utf-8"); + var result = new JsonObject + { + { "content", content }, + { "contentType", "application/json; charset=utf-8" } + }; return result; } @@ -225,7 +226,7 @@ private static TypeInfo BuildGrpcOperationDataContractType(GrpcOperationDataCont getterIl.Emit(OpCodes.Ret); //Creating the property set method and binding it to the private filed - var setterBuilder = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, new[] { propertyType }); + var setterBuilder = typeBuilder.DefineMethod("set_" + propertyName, MethodAttributes.Public | MethodAttributes.SpecialName | MethodAttributes.HideBySig, null, [propertyType]); var setterIl = setterBuilder.GetILGenerator(); setterIl.Emit(OpCodes.Ldarg_0); setterIl.Emit(OpCodes.Ldarg_1); @@ -237,12 +238,12 @@ private static TypeInfo BuildGrpcOperationDataContractType(GrpcOperationDataCont propertyBuilder.SetSetMethod(setterBuilder); //Add ProtoMember attribute to the data contract with tag/number - var dataMemberAttributeBuilder = new CustomAttributeBuilder(typeof(ProtoMemberAttribute).GetConstructor(new[] { typeof(int) })!, new object[] { field.Number }); + var dataMemberAttributeBuilder = new CustomAttributeBuilder(typeof(ProtoMemberAttribute).GetConstructor([typeof(int)])!, [field.Number]); propertyBuilder.SetCustomAttribute(dataMemberAttributeBuilder); } //Add ProtoContract attribute to the data contract - var dataContractAttributeBuilder = new CustomAttributeBuilder(typeof(ProtoContractAttribute).GetConstructor(Type.EmptyTypes)!, Array.Empty()); + var dataContractAttributeBuilder = new CustomAttributeBuilder(typeof(ProtoContractAttribute).GetConstructor(Type.EmptyTypes)!, []); typeBuilder.SetCustomAttribute(dataContractAttributeBuilder); return typeBuilder.CreateTypeInfo() ?? diff --git a/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperation.cs b/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperation.cs index 64afb6ae0f94..ee5f25c17c90 100644 --- a/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperation.cs +++ b/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperation.cs @@ -1,5 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. +using System.Collections.Generic; + namespace Microsoft.SemanticKernel.Plugins.Grpc.Model; /// @@ -81,4 +83,23 @@ public string FullServiceName /// Specifier to prevent name clashes between types. /// public string? Package { get; set; } + + /// + /// Returns list of gRPC operation parameters. + /// + /// The list of parameters. + internal static List CreateParameters() => + [ + // Register the "address" parameter so that it's possible to override it if needed. + new(GrpcOperation.AddressArgumentName) + { + Description = "Address for gRPC channel to use.", + }, + + // Register the "payload" parameter to be used as gRPC operation request message. + new(GrpcOperation.PayloadArgumentName) + { + Description = "gRPC request message.", + }, + ]; } diff --git a/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperationDataContractType.cs b/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperationDataContractType.cs index 7be7599cec7a..800843f61340 100644 --- a/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperationDataContractType.cs +++ b/dotnet/src/Functions/Functions.Grpc/Model/GrpcOperationDataContractType.cs @@ -26,5 +26,5 @@ public GrpcOperationDataContractType(string name, IList /// List of fields /// - public IList Fields { get; } = new List(); + public IList Fields { get; } = []; } diff --git a/dotnet/src/Functions/Functions.Grpc/Protobuf/ProtoDocumentParser.cs b/dotnet/src/Functions/Functions.Grpc/Protobuf/ProtoDocumentParser.cs index 08f9ab35ca87..d791a971a3f4 100644 --- a/dotnet/src/Functions/Functions.Grpc/Protobuf/ProtoDocumentParser.cs +++ b/dotnet/src/Functions/Functions.Grpc/Protobuf/ProtoDocumentParser.cs @@ -58,10 +58,10 @@ private List GetGrpcOperations(FileDescriptorProto model) var responseContract = this.CreateDataContract(model.MessageTypes, method.OutputType, model.Package, method.Name); - var operation = new GrpcOperation(service.Name, method.Name, requestContract, responseContract); - operation.Package = model.Package; - - operations.Add(operation); + operations.Add(new GrpcOperation(service.Name, method.Name, requestContract, responseContract) + { + Package = model.Package + }); } } @@ -87,11 +87,8 @@ private GrpcOperationDataContractType CreateDataContract(IList typeName = fullTypeName.Replace($"{package}.", ""); } - var messageType = allMessageTypes.SingleOrDefault(mt => mt.Name == fullTypeName || mt.Name == typeName); - if (messageType == null) - { + var messageType = allMessageTypes.SingleOrDefault(mt => mt.Name == fullTypeName || mt.Name == typeName) ?? throw new KernelException($"No '{fullTypeName}' message type is found while resolving data contracts for the '{methodName}' method."); - } var fields = this.GetDataContractFields(messageType.Fields); diff --git a/dotnet/src/Functions/Functions.OpenApi.Extensions/Extensions/ApiManifestKernelExtensions.cs b/dotnet/src/Functions/Functions.OpenApi.Extensions/Extensions/ApiManifestKernelExtensions.cs index 92fb5af7328b..4ce437e4718e 100644 --- a/dotnet/src/Functions/Functions.OpenApi.Extensions/Extensions/ApiManifestKernelExtensions.cs +++ b/dotnet/src/Functions/Functions.OpenApi.Extensions/Extensions/ApiManifestKernelExtensions.cs @@ -117,7 +117,7 @@ public static async Task CreatePluginFromApiManifestAsync( continue; } - requestUrls.Add(UriTemplate, new List() { Method }); + requestUrls.Add(UriTemplate, [Method]); } var predicate = OpenApiFilterService.CreatePredicate(null, null, requestUrls, openApiDocument); diff --git a/dotnet/src/Functions/Functions.OpenApi/DocumentLoader.cs b/dotnet/src/Functions/Functions.OpenApi/DocumentLoader.cs index 14c6cdcb6b72..3f9c0a1d7fbf 100644 --- a/dotnet/src/Functions/Functions.OpenApi/DocumentLoader.cs +++ b/dotnet/src/Functions/Functions.OpenApi/DocumentLoader.cs @@ -40,6 +40,8 @@ internal static async Task LoadDocumentFromFilePathAsync( ILogger logger, CancellationToken cancellationToken) { + cancellationToken.ThrowIfCancellationRequested(); + var pluginJson = string.Empty; if (!File.Exists(filePath)) @@ -49,10 +51,8 @@ internal static async Task LoadDocumentFromFilePathAsync( logger.LogTrace("Importing document from {0}", filePath); - using (var sr = File.OpenText(filePath)) - { - return await sr.ReadToEndAsync().ConfigureAwait(false); // must await here to avoid stream reader being disposed before the string is read - } + using var sr = File.OpenText(filePath); + return await sr.ReadToEndAsync().ConfigureAwait(false); // must await here to avoid stream reader being disposed before the string is read } internal static async Task LoadDocumentFromStreamAsync(Stream stream) diff --git a/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiFunctionExecutionParameters.cs b/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiFunctionExecutionParameters.cs index 7b3cf5f9c141..4c17f11d7518 100644 --- a/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiFunctionExecutionParameters.cs +++ b/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiFunctionExecutionParameters.cs @@ -91,6 +91,6 @@ public OpenApiFunctionExecutionParameters( this.IgnoreNonCompliantErrors = ignoreNonCompliantErrors; this.EnableDynamicPayload = enableDynamicOperationPayload; this.EnablePayloadNamespacing = enablePayloadNamespacing; - this.OperationsToExclude = operationsToExclude ?? new List(); + this.OperationsToExclude = operationsToExclude ?? []; } } diff --git a/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiKernelExtensions.cs b/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiKernelExtensions.cs index cb6133dbec5f..3c9974ce0709 100644 --- a/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiKernelExtensions.cs +++ b/dotnet/src/Functions/Functions.OpenApi/Extensions/OpenApiKernelExtensions.cs @@ -327,7 +327,7 @@ async Task ExecuteAsync(KernelArguments variables, Can DefaultValue = p.DefaultValue ?? string.Empty, IsRequired = p.IsRequired, ParameterType = p.Type switch { "string" => typeof(string), "boolean" => typeof(bool), _ => null }, - Schema = p.Schema ?? (p.Type is null ? null : KernelJsonSchema.Parse($"{{\"type\":\"{p.Type}\"}}")), + Schema = p.Schema ?? (p.Type is null ? null : KernelJsonSchema.Parse($$"""{"type":"{{p.Type}}"}""")), }) .ToList(); @@ -374,7 +374,7 @@ private static string ConvertOperationIdToValidFunctionName(string operationId, result += CultureInfo.CurrentCulture.TextInfo.ToTitleCase(formattedToken.ToLower(CultureInfo.CurrentCulture)); } - logger.LogInformation("Operation name \"{0}\" converted to \"{1}\" to comply with SK Function name requirements. Use \"{2}\" when invoking function.", operationId, result, result); + logger.LogInformation("""Operation name "{0}" converted to "{1}" to comply with SK Function name requirements. Use "{2}" when invoking function.""", operationId, result, result); return result; } diff --git a/dotnet/src/Functions/Functions.OpenApi/Extensions/RestApiOperationExtensions.cs b/dotnet/src/Functions/Functions.OpenApi/Extensions/RestApiOperationExtensions.cs index 86786c08b8a8..814dc233a812 100644 --- a/dotnet/src/Functions/Functions.OpenApi/Extensions/RestApiOperationExtensions.cs +++ b/dotnet/src/Functions/Functions.OpenApi/Extensions/RestApiOperationExtensions.cs @@ -105,17 +105,17 @@ private static List GetPayloadParameters(RestApiOpera // So, returning artificial 'payload' parameter instead. if (operation.Payload.MediaType == MediaTypeTextPlain) { - return new List { CreatePayloadArtificialParameter(operation) }; + return [CreatePayloadArtificialParameter(operation)]; } return GetParametersFromPayloadMetadata(operation.Payload.Properties, enableNamespacing); } // Adding artificial 'payload' and 'content-type' in case parameters from payload metadata are not required. - return new List { + return [ CreatePayloadArtificialParameter(operation), CreateContentTypeArtificialParameter(operation) - }; + ]; } /// @@ -209,5 +209,5 @@ private static string GetPropertyName(RestApiOperationPayloadProperty property, private const string MediaTypeTextPlain = "text/plain"; private static readonly Regex s_invalidSymbolsRegex = new("[^0-9A-Za-z_]+"); - private static readonly string[] s_preferredResponses = new string[] { "200", "201", "202", "203", "204", "205", "206", "207", "208", "226", "2XX", "default" }; + private static readonly string[] s_preferredResponses = ["200", "201", "202", "203", "204", "205", "206", "207", "208", "226", "2XX", "default"]; } diff --git a/dotnet/src/Functions/Functions.OpenApi/OpenApi/OpenApiDocumentParser.cs b/dotnet/src/Functions/Functions.OpenApi/OpenApi/OpenApiDocumentParser.cs index 325d20c01bac..516b54155aeb 100644 --- a/dotnet/src/Functions/Functions.OpenApi/OpenApi/OpenApiDocumentParser.cs +++ b/dotnet/src/Functions/Functions.OpenApi/OpenApi/OpenApiDocumentParser.cs @@ -71,11 +71,11 @@ public async Task> ParseAsync( /// /// List of supported Media Types. /// - private static readonly List s_supportedMediaTypes = new() - { + private static readonly List s_supportedMediaTypes = + [ "application/json", "text/plain" - }; + ]; private readonly OpenApiStreamReader _openApiReader = new(); private readonly ILogger _logger; @@ -290,7 +290,7 @@ private static List GetPayloadProperties(string { if (schema == null) { - return new List(); + return []; } if (level > PayloadPropertiesHierarchyMaxDepth) diff --git a/dotnet/src/Functions/Functions.OpenApi/RestApiOperationRunner.cs b/dotnet/src/Functions/Functions.OpenApi/RestApiOperationRunner.cs index 732b59d0dac4..0683f7e6a508 100644 --- a/dotnet/src/Functions/Functions.OpenApi/RestApiOperationRunner.cs +++ b/dotnet/src/Functions/Functions.OpenApi/RestApiOperationRunner.cs @@ -387,11 +387,7 @@ private Uri BuildsOperationUrl(RestApiOperation operation, IDictionary()); + this._request = new GrpcOperationDataContractType("fake-name", []); - this._response = new GrpcOperationDataContractType("fake-name", new List()); + this._response = new GrpcOperationDataContractType("fake-name", []); this._operation = new GrpcOperation("fake-service-name", "fake-operation-name", this._response, this._response); } @@ -29,11 +27,11 @@ public GrpcOperationExtensionsTests() public void ThereShouldBeAddressParameter() { // Act - var parameters = this._operation.GetParameters(); + var parameters = GrpcOperation.CreateParameters(); // Assert Assert.NotNull(parameters); - Assert.True(parameters.Any()); + Assert.NotEmpty(parameters); var addressParameter = parameters.SingleOrDefault(p => p.Name == "address"); Assert.NotNull(addressParameter); @@ -44,11 +42,11 @@ public void ThereShouldBeAddressParameter() public void ThereShouldBePayloadParameter() { // Act - var parameters = this._operation.GetParameters(); + var parameters = GrpcOperation.CreateParameters(); // Assert Assert.NotNull(parameters); - Assert.True(parameters.Any()); + Assert.NotEmpty(parameters); var payloadParameter = parameters.SingleOrDefault(p => p.Name == "payload"); Assert.NotNull(payloadParameter); diff --git a/dotnet/src/Functions/Functions.UnitTests/Grpc/GrpcRunnerTests.cs b/dotnet/src/Functions/Functions.UnitTests/Grpc/GrpcRunnerTests.cs index 3c5cddb36922..944868999241 100644 --- a/dotnet/src/Functions/Functions.UnitTests/Grpc/GrpcRunnerTests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/Grpc/GrpcRunnerTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. using System; -using System.Collections.Generic; using System.Net.Http; using System.Net.Http.Headers; using System.Net.Mime; @@ -44,22 +43,26 @@ public async Task ShouldUseAddressProvidedInGrpcOperationAsync() { // Arrange this._httpMessageHandlerStub.ResponseToReturn.Version = new Version(2, 0); - this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent(new byte[] { 0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114 }); + this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent([0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114]); this._httpMessageHandlerStub.ResponseToReturn.Content.Headers.Add("Content-Type", "application/grpc"); this._httpMessageHandlerStub.ResponseToReturn.TrailingHeaders.Add("grpc-status", "0"); - var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", new List() { new("name", 1, "TYPE_STRING") }); + var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", [new("name", 1, "TYPE_STRING")]); - var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", new List() { new("message", 1, "TYPE_STRING") }); + var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", [new("message", 1, "TYPE_STRING")]); var sut = new GrpcOperationRunner(this._httpClient); - var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata); - operation.Package = "greet"; - operation.Address = "https://fake-random-test-host"; + var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata) + { + Package = "greet", + Address = "https://fake-random-test-host" + }; - var arguments = new KernelArguments(); - arguments.Add("payload", JsonSerializer.Serialize(new { name = "author" })); + var arguments = new KernelArguments + { + { "payload", JsonSerializer.Serialize(new { name = "author" }) } + }; // Act var result = await sut.RunAsync(operation, arguments); @@ -74,23 +77,27 @@ public async Task ShouldUseAddressOverrideFromArgumentsAsync() { // Arrange this._httpMessageHandlerStub.ResponseToReturn.Version = new Version(2, 0); - this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent(new byte[] { 0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114 }); + this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent([0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114]); this._httpMessageHandlerStub.ResponseToReturn.Content.Headers.Add("Content-Type", "application/grpc"); this._httpMessageHandlerStub.ResponseToReturn.TrailingHeaders.Add("grpc-status", "0"); - var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", new List() { new("name", 1, "TYPE_STRING") }); + var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", [new("name", 1, "TYPE_STRING")]); - var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", new List() { new("message", 1, "TYPE_STRING") }); + var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", [new("message", 1, "TYPE_STRING")]); var sut = new GrpcOperationRunner(this._httpClient); - var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata); - operation.Package = "greet"; - operation.Address = "https://fake-random-test-host"; + var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata) + { + Package = "greet", + Address = "https://fake-random-test-host" + }; - var arguments = new KernelArguments(); - arguments.Add("payload", JsonSerializer.Serialize(new { name = "author" })); - arguments.Add("address", "https://fake-random-test-host-from-args"); + var arguments = new KernelArguments + { + { "payload", JsonSerializer.Serialize(new { name = "author" }) }, + { "address", "https://fake-random-test-host-from-args" } + }; // Act var result = await sut.RunAsync(operation, arguments); @@ -107,23 +114,27 @@ public async Task ShouldRunOperationsWithSimpleDataContractAsync() //The byte array is copied from intercepted gRPC call to a local gPRC service created using this guide - https://learn.microsoft.com/en-us/aspnet/core/tutorials/grpc/grpc-start?view=aspnetcore-7.0&tabs=visual-studio //since there's no simple way to obtain/create serialized content of gRPC response. - this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent(new byte[] { 0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114 }); + this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent([0, 0, 0, 0, 14, 10, 12, 72, 101, 108, 108, 111, 32, 97, 117, 116, 104, 111, 114]); this._httpMessageHandlerStub.ResponseToReturn.Version = new Version(2, 0); this._httpMessageHandlerStub.ResponseToReturn.Content.Headers.Add("Content-Type", "application/grpc"); this._httpMessageHandlerStub.ResponseToReturn.TrailingHeaders.Add("grpc-status", "0"); - var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", new List() { new("name", 1, "TYPE_STRING") }); + var requestMetadata = new GrpcOperationDataContractType("greet.HelloRequest", [new("name", 1, "TYPE_STRING")]); - var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", new List() { new("message", 1, "TYPE_STRING") }); + var responseMetadata = new GrpcOperationDataContractType("greet.HelloReply", [new("message", 1, "TYPE_STRING")]); var sut = new GrpcOperationRunner(this._httpClient); - var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata); - operation.Package = "greet"; - operation.Address = "https://fake-random-test-host"; + var operation = new GrpcOperation("Greeter", "SayHello", requestMetadata, responseMetadata) + { + Package = "greet", + Address = "https://fake-random-test-host" + }; - var arguments = new KernelArguments(); - arguments.Add("payload", JsonSerializer.Serialize(new { name = "author" })); + var arguments = new KernelArguments + { + { "payload", JsonSerializer.Serialize(new { name = "author" }) } + }; // Act var result = await sut.RunAsync(operation, arguments); @@ -174,8 +185,10 @@ private sealed class HttpMessageHandlerStub : DelegatingHandler public HttpMessageHandlerStub() { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json) + }; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/dotnet/src/Functions/Functions.UnitTests/Grpc/Protobuf/TestPlugins/ResourcePluginsProvider.cs b/dotnet/src/Functions/Functions.UnitTests/Grpc/Protobuf/TestPlugins/ResourcePluginsProvider.cs index 015b67eace1e..a774b57efeba 100644 --- a/dotnet/src/Functions/Functions.UnitTests/Grpc/Protobuf/TestPlugins/ResourcePluginsProvider.cs +++ b/dotnet/src/Functions/Functions.UnitTests/Grpc/Protobuf/TestPlugins/ResourcePluginsProvider.cs @@ -16,12 +16,7 @@ public static Stream LoadFromResource(string resourceName) { var type = typeof(ResourcePluginsProvider); - var stream = type.Assembly.GetManifestResourceStream(type, resourceName); - if (stream == null) - { + return type.Assembly.GetManifestResourceStream(type, resourceName) ?? throw new MissingManifestResourceException($"Unable to load gRPC plugin from assembly resource '{resourceName}'."); - } - - return stream; } } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/Extensions/RestApiOperationExtensionsTests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/Extensions/RestApiOperationExtensionsTests.cs index e20836b38309..5c1f497e7b73 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/Extensions/RestApiOperationExtensionsTests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/Extensions/RestApiOperationExtensionsTests.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. using System; -using System.Collections.Generic; using System.Linq; using System.Net.Http; using Microsoft.SemanticKernel; @@ -244,10 +243,10 @@ public void ItShouldThrowExceptionIfPayloadMetadataDescribingParametersIsMissing public void ItShouldSetAlternativeNameToParametersForPutAndPostOperation(string method) { //Arrange - var latitude = new RestApiOperationPayloadProperty("location.latitude", "number", false, new List()); - var place = new RestApiOperationPayloadProperty("place", "string", true, new List()); + var latitude = new RestApiOperationPayloadProperty("location.latitude", "number", false, []); + var place = new RestApiOperationPayloadProperty("place", "string", true, []); - var payload = new RestApiOperationPayload("application/json", new[] { place, latitude }); + var payload = new RestApiOperationPayload("application/json", [place, latitude]); var operation = CreateTestOperation(method, payload); @@ -274,7 +273,7 @@ private static RestApiOperation CreateTestOperation(string method, RestApiOperat path: "fake-path", method: new HttpMethod(method), description: "fake-description", - parameters: new List(), + parameters: [], payload: payload); } @@ -284,55 +283,55 @@ private static RestApiOperationPayload CreateTestJsonPayload() name: "name", type: "string", isRequired: true, - properties: new List(), + properties: [], description: "The name."); var leader = new RestApiOperationPayloadProperty( name: "leader", type: "string", isRequired: true, - properties: new List(), + properties: [], description: "The leader."); var landmarks = new RestApiOperationPayloadProperty( name: "landmarks", type: "array", isRequired: false, - properties: new List(), + properties: [], description: "The landmarks."); var location = new RestApiOperationPayloadProperty( name: "location", type: "object", isRequired: true, - properties: new[] { landmarks }, + properties: [landmarks], description: "The location."); var rulingCouncil = new RestApiOperationPayloadProperty( name: "rulingCouncil", type: "object", isRequired: true, - properties: new[] { leader }, + properties: [leader], description: "The ruling council."); var population = new RestApiOperationPayloadProperty( name: "population", type: "integer", isRequired: true, - properties: new List(), + properties: [], description: "The population."); var hasMagicWards = new RestApiOperationPayloadProperty( name: "hasMagicWards", type: "boolean", isRequired: false, - properties: new List()); + properties: []); - return new RestApiOperationPayload("application/json", new[] { name, location, rulingCouncil, population, hasMagicWards }); + return new RestApiOperationPayload("application/json", [name, location, rulingCouncil, population, hasMagicWards]); } private static RestApiOperationPayload CreateTestTextPayload() { - return new RestApiOperationPayload("text/plain", new List()); + return new RestApiOperationPayload("text/plain", []); } } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/HttpMessageHandlerStub.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/HttpMessageHandlerStub.cs index ec503c11abe5..3a8c835eba3f 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/HttpMessageHandlerStub.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/HttpMessageHandlerStub.cs @@ -27,20 +27,26 @@ internal sealed class HttpMessageHandlerStub : DelegatingHandler public HttpMessageHandlerStub() { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json) + }; } public HttpMessageHandlerStub(Stream responseToReturn) { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StreamContent(responseToReturn); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StreamContent(responseToReturn) + }; } public void ResetResponse() { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json) + }; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV20Tests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV20Tests.cs index ab3150adb130..bdc4a59f88ec 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV20Tests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV20Tests.cs @@ -289,7 +289,7 @@ public async Task ItCanParseResponsesSuccessfullyAsync() Assert.NotNull(response.Schema); Assert.Equal("string", response.Schema.RootElement.GetProperty("type").GetString()); Assert.Equal( - JsonSerializer.Serialize(KernelJsonSchema.Parse("{\"type\": \"string\"}")), + JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"type": "string"}""")), JsonSerializer.Serialize(response.Schema)); } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV30Tests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV30Tests.cs index 46dfdf8da801..da69026737b6 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV30Tests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV30Tests.cs @@ -362,7 +362,7 @@ public async Task ItCanParseResponsesSuccessfullyAsync() Assert.NotNull(response.Schema); Assert.Equal("string", response.Schema.RootElement.GetProperty("type").GetString()); Assert.Equal( - JsonSerializer.Serialize(KernelJsonSchema.Parse("{\"type\": \"string\"}")), + JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"type": "string"}""")), JsonSerializer.Serialize(response.Schema)); } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV31Tests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV31Tests.cs index b927829e2e18..3f10380d2a58 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV31Tests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/OpenApiDocumentParserV31Tests.cs @@ -339,7 +339,7 @@ public async Task ItCanParseResponsesSuccessfullyAsync() Assert.NotNull(response.Schema); Assert.Equal("string", response.Schema.RootElement.GetProperty("type").GetString()); Assert.Equal( - JsonSerializer.Serialize(KernelJsonSchema.Parse("{\"type\": \"string\"}")), + JsonSerializer.Serialize(KernelJsonSchema.Parse("""{"type": "string"}""")), JsonSerializer.Serialize(response.Schema)); } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationRunnerTests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationRunnerTests.cs index c50c26d18f7b..232d0aaf3282 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationRunnerTests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationRunnerTests.cs @@ -63,7 +63,7 @@ public async Task ItCanRunCreateAndUpdateOperationsWithJsonPayloadSuccessfullyAs "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -98,7 +98,7 @@ public async Task ItCanRunCreateAndUpdateOperationsWithJsonPayloadSuccessfullyAs var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var deserializedPayload = await JsonNode.ParseAsync(new MemoryStream(messageContent)); Assert.NotNull(deserializedPayload); @@ -134,7 +134,7 @@ public async Task ItCanRunCreateAndUpdateOperationsWithPlainTextPayloadSuccessfu "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -160,7 +160,7 @@ public async Task ItCanRunCreateAndUpdateOperationsWithPlainTextPayloadSuccessfu var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var payloadText = Encoding.UTF8.GetString(messageContent, 0, messageContent.Length); Assert.Equal("fake-input-value", payloadText); @@ -293,14 +293,14 @@ public async Task ItShouldBuildJsonPayloadDynamicallyAsync() // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Application.Json); - List payloadProperties = new() - { - new("name", "string", true, new List()), - new("attributes", "object", false, new List() - { - new("enabled", "boolean", false, new List()), - }) - }; + List payloadProperties = + [ + new("name", "string", true, []), + new("attributes", "object", false, + [ + new("enabled", "boolean", false, []), + ]) + ]; var payload = new RestApiOperationPayload(MediaTypeNames.Application.Json, payloadProperties); @@ -310,13 +310,15 @@ public async Task ItShouldBuildJsonPayloadDynamicallyAsync() "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); - var arguments = new KernelArguments(); - arguments.Add("name", "fake-name-value"); - arguments.Add("enabled", true); + var arguments = new KernelArguments + { + { "name", "fake-name-value" }, + { "enabled", true } + }; var sut = new RestApiOperationRunner(this._httpClient, this._authenticationHandlerMock.Object, enableDynamicPayload: true); @@ -329,7 +331,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyAsync() var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var deserializedPayload = await JsonNode.ParseAsync(new MemoryStream(messageContent)); Assert.NotNull(deserializedPayload); @@ -351,18 +353,18 @@ public async Task ItShouldBuildJsonPayloadDynamicallyUsingPayloadMetadataDataTyp // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Application.Json); - List payloadProperties = new() - { - new("name", "string", true, new List()), - new("attributes", "object", false, new List() - { - new("enabled", "boolean", false, new List()), - new("cardinality", "number", false, new List()), - new("coefficient", "number", false, new List()), - new("count", "integer", false, new List()), - new("params", "array", false, new List()), - }) - }; + List payloadProperties = + [ + new("name", "string", true, []), + new("attributes", "object", false, + [ + new("enabled", "boolean", false, []), + new("cardinality", "number", false, []), + new("coefficient", "number", false, []), + new("count", "integer", false, []), + new("params", "array", false, []), + ]) + ]; var payload = new RestApiOperationPayload(MediaTypeNames.Application.Json, payloadProperties); @@ -372,17 +374,19 @@ public async Task ItShouldBuildJsonPayloadDynamicallyUsingPayloadMetadataDataTyp "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); - var arguments = new KernelArguments(); - arguments.Add("name", "fake-string-value"); - arguments.Add("enabled", "true"); - arguments.Add("cardinality", 8); - arguments.Add("coefficient", "0.8"); - arguments.Add("count", 1); - arguments.Add("params", "[1,2,3]"); + var arguments = new KernelArguments + { + { "name", "fake-string-value" }, + { "enabled", "true" }, + { "cardinality", 8 }, + { "coefficient", "0.8" }, + { "count", 1 }, + { "params", "[1,2,3]" } + }; var sut = new RestApiOperationRunner(this._httpClient, this._authenticationHandlerMock.Object, enableDynamicPayload: true); @@ -434,22 +438,22 @@ public async Task ItShouldBuildJsonPayloadDynamicallyResolvingArgumentsByFullNam // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Application.Json); - List payloadProperties = new() - { - new("upn", "string", true, new List()), - new("receiver", "object", false, new List() - { - new("upn", "string", false, new List()), - new("alternative", "object", false, new List() - { - new("upn", "string", false, new List()), - }), - }), - new("cc", "object", false, new List() - { - new("upn", "string", false, new List()), - }) - }; + List payloadProperties = + [ + new("upn", "string", true, []), + new("receiver", "object", false, + [ + new("upn", "string", false, []), + new("alternative", "object", false, + [ + new("upn", "string", false, []), + ]), + ]), + new("cc", "object", false, + [ + new("upn", "string", false, []), + ]) + ]; var payload = new RestApiOperationPayload(MediaTypeNames.Application.Json, payloadProperties); @@ -459,15 +463,17 @@ public async Task ItShouldBuildJsonPayloadDynamicallyResolvingArgumentsByFullNam "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); - var arguments = new KernelArguments(); - arguments.Add("upn", "fake-sender-upn"); - arguments.Add("receiver.upn", "fake-receiver-upn"); - arguments.Add("receiver.alternative.upn", "fake-receiver-alternative-upn"); - arguments.Add("cc.upn", "fake-cc-upn"); + var arguments = new KernelArguments + { + { "upn", "fake-sender-upn" }, + { "receiver.upn", "fake-receiver-upn" }, + { "receiver.alternative.upn", "fake-receiver-alternative-upn" }, + { "cc.upn", "fake-cc-upn" } + }; var sut = new RestApiOperationRunner( this._httpClient, @@ -484,7 +490,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyResolvingArgumentsByFullNam var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var deserializedPayload = await JsonNode.ParseAsync(new MemoryStream(messageContent)); Assert.NotNull(deserializedPayload); @@ -527,7 +533,7 @@ public async Task ItShouldThrowExceptionIfPayloadMetadataDoesNotHaveContentTypeA "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -554,7 +560,7 @@ public async Task ItShouldThrowExceptionIfContentTypeArgumentIsNotProvidedAsync( "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -577,7 +583,7 @@ public async Task ItShouldUsePayloadArgumentForPlainTextContentTypeWhenBuildingP // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Text.Plain); - var payload = new RestApiOperationPayload(MediaTypeNames.Text.Plain, new List()); + var payload = new RestApiOperationPayload(MediaTypeNames.Text.Plain, []); var operation = new RestApiOperation( "fake-id", @@ -585,7 +591,7 @@ public async Task ItShouldUsePayloadArgumentForPlainTextContentTypeWhenBuildingP "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); @@ -605,7 +611,7 @@ public async Task ItShouldUsePayloadArgumentForPlainTextContentTypeWhenBuildingP var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var payloadText = Encoding.UTF8.GetString(messageContent, 0, messageContent.Length); Assert.Equal("fake-input-value", payloadText); @@ -625,7 +631,7 @@ public async Task ItShouldUsePayloadAndContentTypeArgumentsIfDynamicPayloadBuild "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -646,7 +652,7 @@ public async Task ItShouldUsePayloadAndContentTypeArgumentsIfDynamicPayloadBuild var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var payloadText = Encoding.UTF8.GetString(messageContent, 0, messageContent.Length); Assert.Equal("fake-input-value", payloadText); @@ -658,10 +664,10 @@ public async Task ItShouldBuildJsonPayloadDynamicallyExcludingOptionalParameters // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Application.Json); - List payloadProperties = new() - { - new("upn", "string", false, new List()), - }; + List payloadProperties = + [ + new("upn", "string", false, []), + ]; var payload = new RestApiOperationPayload(MediaTypeNames.Application.Json, payloadProperties); @@ -671,7 +677,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyExcludingOptionalParameters "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); @@ -689,7 +695,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyExcludingOptionalParameters // Assert var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var deserializedPayload = await JsonNode.ParseAsync(new MemoryStream(messageContent)); Assert.NotNull(deserializedPayload); @@ -704,10 +710,10 @@ public async Task ItShouldBuildJsonPayloadDynamicallyIncludingOptionalParameters // Arrange this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("fake-content", Encoding.UTF8, MediaTypeNames.Application.Json); - List payloadProperties = new() - { - new("upn", "string", false, new List()), - }; + List payloadProperties = + [ + new("upn", "string", false, []), + ]; var payload = new RestApiOperationPayload(MediaTypeNames.Application.Json, payloadProperties); @@ -717,7 +723,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyIncludingOptionalParameters "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload ); @@ -735,7 +741,7 @@ public async Task ItShouldBuildJsonPayloadDynamicallyIncludingOptionalParameters // Assert var messageContent = this._httpMessageHandlerStub.RequestContent; Assert.NotNull(messageContent); - Assert.True(messageContent.Length != 0); + Assert.NotEmpty(messageContent); var deserializedPayload = await JsonNode.ParseAsync(new MemoryStream(messageContent)); Assert.NotNull(deserializedPayload); @@ -772,7 +778,7 @@ public async Task ItShouldAddRequiredQueryStringParametersIfTheirArgumentsProvid "fake-path", HttpMethod.Get, "fake-description", - new List() { firstParameter, secondParameter }, + [firstParameter, secondParameter], payload: null ); @@ -820,7 +826,7 @@ public async Task ItShouldAddNotRequiredQueryStringParametersIfTheirArgumentsPro "fake-path", HttpMethod.Get, "fake-description", - new List() { firstParameter, secondParameter }, + [firstParameter, secondParameter], payload: null ); @@ -868,7 +874,7 @@ public async Task ItShouldSkipNotRequiredQueryStringParametersIfNoArgumentsProvi "fake-path", HttpMethod.Get, "fake-description", - new List() { firstParameter, secondParameter }, + [firstParameter, secondParameter], payload: null ); @@ -907,7 +913,7 @@ public async Task ItShouldThrowExceptionIfNoArgumentProvidedForRequiredQueryStri "fake-path", HttpMethod.Get, "fake-description", - new List() { parameter }, + [parameter], payload: null ); @@ -938,7 +944,7 @@ public async Task ItShouldReadContentAsStringSuccessfullyAsync(string contentTyp "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -971,7 +977,7 @@ public async Task ItShouldReadContentAsStringSuccessfullyAsync(string contentTyp public async Task ItShouldReadContentAsBytesSuccessfullyAsync(string contentType) { // Arrange - this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent(new byte[] { 00, 01, 02 }); + this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent([00, 01, 02]); this._httpMessageHandlerStub.ResponseToReturn.Content.Headers.ContentType = new MediaTypeHeaderValue(contentType); var operation = new RestApiOperation( @@ -980,7 +986,7 @@ public async Task ItShouldReadContentAsBytesSuccessfullyAsync(string contentType "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -1015,7 +1021,7 @@ public async Task ItShouldThrowExceptionForUnsupportedContentTypeAsync() "fake-path", HttpMethod.Post, "fake-description", - new List(), + [], payload: null ); @@ -1086,7 +1092,7 @@ public async Task ItShouldReturnExpectedSchemaAsync(string expectedStatusCode, p "fake-path", HttpMethod.Get, "fake-description", - new List(), + [], null, responses.ToDictionary(item => item.Item1, item => item.Item2) ); @@ -1094,7 +1100,7 @@ public async Task ItShouldReturnExpectedSchemaAsync(string expectedStatusCode, p var sut = new RestApiOperationRunner(this._httpClient, this._authenticationHandlerMock.Object); // Act - var result = await sut.RunAsync(operation, new KernelArguments()); + var result = await sut.RunAsync(operation, []); Assert.NotNull(result); var expected = responses.First(r => r.Item1 == expectedStatusCode).Item2.Schema; diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationTests.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationTests.cs index ed05fb800c6c..73d8fae0478c 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationTests.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/RestApiOperationTests.cs @@ -27,7 +27,7 @@ public void ItShouldUseHostUrlIfNoOverrideProvided() "/", HttpMethod.Get, "fake_description", - new List() + [] ); var arguments = new Dictionary(); @@ -49,7 +49,7 @@ public void ItShouldUseHostUrlOverrideIfProvided() "/", HttpMethod.Get, "fake_description", - new List() + [] ); var fakeHostUrlOverride = "https://fake-random-test-host-override"; @@ -456,7 +456,7 @@ public void ItSupportsMultipleEqualNamedServices() [Fact] public void ItIsntNeededInDIContexts() { - KernelPluginCollection plugins = new() { KernelPluginFactory.CreateFromFunctions("plugin1") }; + KernelPluginCollection plugins = [KernelPluginFactory.CreateFromFunctions("plugin1")]; var serviceCollection = new ServiceCollection(); serviceCollection.AddAzureOpenAIChatCompletion(deploymentName: "abcd", modelId: "efg", endpoint: "https://hijk", apiKey: "lmnop"); @@ -484,12 +484,12 @@ public void ItIsntNeededInDIContexts() // but it's not recommended. //** WORKAROUND - Dictionary> mapping = new(); + Dictionary> mapping = []; foreach (var descriptor in serviceCollection) { if (!mapping.TryGetValue(descriptor.ServiceType, out HashSet? keys)) { - mapping[descriptor.ServiceType] = keys = new HashSet(); + mapping[descriptor.ServiceType] = keys = []; } keys.Add(descriptor.ServiceKey); } @@ -524,7 +524,7 @@ public void ItFindsPluginCollectionToUse() KernelPlugin plugin3 = KernelPluginFactory.CreateFromFunctions("plugin3"); IKernelBuilder builder = Kernel.CreateBuilder(); - builder.Services.AddTransient(_ => new(new[] { plugin1, plugin2, plugin3 })); + builder.Services.AddTransient(_ => new([plugin1, plugin2, plugin3])); Kernel kernel1 = builder.Build(); Assert.Equal(3, kernel1.Plugins.Count); @@ -544,7 +544,7 @@ public void ItAddsTheRightTypesInAddKernel() Assert.NotNull(builder); Assert.Throws(() => builder.Build()); - builder.Services.AddSingleton>(new Dictionary()); + builder.Services.AddSingleton>([]); IServiceProvider provider = sc.BuildServiceProvider(); diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestPlugins/ResourcePluginsProvider.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestPlugins/ResourcePluginsProvider.cs index ed3480ca1e9e..db93c284602c 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestPlugins/ResourcePluginsProvider.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestPlugins/ResourcePluginsProvider.cs @@ -16,12 +16,7 @@ public static Stream LoadFromResource(string resourceName) { var type = typeof(ResourcePluginsProvider); - var stream = type.Assembly.GetManifestResourceStream(type, resourceName); - if (stream == null) - { + return type.Assembly.GetManifestResourceStream(type, resourceName) ?? throw new MissingManifestResourceException($"Unable to load OpenAPI plugin from assembly resource '{resourceName}'."); - } - - return stream; } } diff --git a/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestResponses/ResourceResponseProvider.cs b/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestResponses/ResourceResponseProvider.cs index 68210678f2a0..4e2ad7d262bb 100644 --- a/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestResponses/ResourceResponseProvider.cs +++ b/dotnet/src/Functions/Functions.UnitTests/OpenApi/TestResponses/ResourceResponseProvider.cs @@ -16,11 +16,8 @@ public static string LoadFromResource(string resourceName) { var type = typeof(ResourceResponseProvider); - var stream = type.Assembly.GetManifestResourceStream(type, resourceName); - if (stream == null) - { + var stream = type.Assembly.GetManifestResourceStream(type, resourceName) ?? throw new MissingManifestResourceException($"Unable to load OpenAPI response from assembly resource '{resourceName}'."); - } using var reader = new StreamReader(stream); return reader.ReadToEnd(); diff --git a/dotnet/src/Functions/Functions.Yaml/KernelFunctionYaml.cs b/dotnet/src/Functions/Functions.Yaml/KernelFunctionYaml.cs index 0c7039c5530f..ec2a26fc2b61 100644 --- a/dotnet/src/Functions/Functions.Yaml/KernelFunctionYaml.cs +++ b/dotnet/src/Functions/Functions.Yaml/KernelFunctionYaml.cs @@ -36,7 +36,7 @@ public static KernelFunction FromPromptYaml( // dealing with the different deserialization outputs of JSON/YAML prompt configurations is being evaluated. foreach (var inputVariable in promptTemplateConfig.InputVariables) { - if (inputVariable.Default is not null && inputVariable.Default is not string) + if (inputVariable.Default is not null and not string) { throw new NotSupportedException($"Default value for input variable '{inputVariable.Name}' must be a string. " + $"This is a temporary limitation; future updates are expected to remove this constraint. Prompt function - '{promptTemplateConfig.Name ?? promptTemplateConfig.Description}'."); diff --git a/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiChatCompletionTests.cs b/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiChatCompletionTests.cs index 8a214d51acdf..112781875c47 100644 --- a/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiChatCompletionTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiChatCompletionTests.cs @@ -72,11 +72,11 @@ public async Task ChatGenerationVisionBinaryDataAsync(ServiceType serviceType) // Arrange Memory image = await File.ReadAllBytesAsync("./TestData/test_image_001.jpg"); var chatHistory = new ChatHistory(); - var messageContent = new ChatMessageContent(AuthorRole.User, items: new ChatMessageContentItemCollection() - { + var messageContent = new ChatMessageContent(AuthorRole.User, items: + [ new TextContent("This is an image with a car. Which color is it? You can chose from red, blue, green, and yellow"), new ImageContent(image) { MimeType = "image/jpeg" } - }); + ]); chatHistory.Add(messageContent); var sut = this.GetChatServiceWithVision(serviceType); @@ -98,11 +98,11 @@ public async Task ChatStreamingVisionBinaryDataAsync(ServiceType serviceType) // Arrange Memory image = await File.ReadAllBytesAsync("./TestData/test_image_001.jpg"); var chatHistory = new ChatHistory(); - var messageContent = new ChatMessageContent(AuthorRole.User, items: new ChatMessageContentItemCollection() - { + var messageContent = new ChatMessageContent(AuthorRole.User, items: + [ new TextContent("This is an image with a car. Which color is it? You can chose from red, blue, green, and yellow"), new ImageContent(image) { MimeType = "image/jpeg" } - }); + ]); chatHistory.Add(messageContent); var sut = this.GetChatServiceWithVision(serviceType); @@ -126,11 +126,11 @@ public async Task ChatGenerationVisionUriAsync(ServiceType serviceType) // Arrange Uri imageUri = new("gs://generativeai-downloads/images/scones.jpg"); // needs setup var chatHistory = new ChatHistory(); - var messageContent = new ChatMessageContent(AuthorRole.User, items: new ChatMessageContentItemCollection() - { + var messageContent = new ChatMessageContent(AuthorRole.User, items: + [ new TextContent("This is an image with a car. Which color is it? You can chose from red, blue, green, and yellow"), new ImageContent(imageUri) { MimeType = "image/jpeg" } - }); + ]); chatHistory.Add(messageContent); var sut = this.GetChatServiceWithVision(serviceType); @@ -152,11 +152,11 @@ public async Task ChatStreamingVisionUriAsync(ServiceType serviceType) // Arrange Uri imageUri = new("gs://generativeai-downloads/images/scones.jpg"); // needs setup var chatHistory = new ChatHistory(); - var messageContent = new ChatMessageContent(AuthorRole.User, items: new ChatMessageContentItemCollection() - { + var messageContent = new ChatMessageContent(AuthorRole.User, items: + [ new TextContent("This is an image with a car. Which color is it? You can chose from red, blue, green, and yellow"), new ImageContent(imageUri) { MimeType = "image/jpeg" } - }); + ]); chatHistory.Add(messageContent); var sut = this.GetChatServiceWithVision(serviceType); diff --git a/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiFunctionCallingTests.cs b/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiFunctionCallingTests.cs index 252b853a51e6..6a920d315994 100644 --- a/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiFunctionCallingTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/GoogleVertexAI/Gemini/GeminiFunctionCallingTests.cs @@ -300,12 +300,12 @@ public sealed class CustomerPlugin [return: Description("List of customers.")] public string[] GetCustomers() { - return new[] - { + return + [ "John Kowalski", "Anna Nowak", "Steve Smith", - }; + ]; } [KernelFunction(nameof(GetCustomerAge))] diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/Chroma/ChromaMemoryStoreTests.cs b/dotnet/src/IntegrationTests/Connectors/Memory/Chroma/ChromaMemoryStoreTests.cs index 9c7aad26dbe6..9bd457ddc172 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/Chroma/ChromaMemoryStoreTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/Chroma/ChromaMemoryStoreTests.cs @@ -25,8 +25,10 @@ public sealed class ChromaMemoryStoreTests : IDisposable public ChromaMemoryStoreTests() { - this._httpClient = new(); - this._httpClient.BaseAddress = new Uri(BaseAddress); + this._httpClient = new() + { + BaseAddress = new Uri(BaseAddress) + }; this._chromaMemoryStore = new(this._httpClient); } diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/Milvus/MilvusMemoryStoreTests.cs b/dotnet/src/IntegrationTests/Connectors/Memory/Milvus/MilvusMemoryStoreTests.cs index 9f1b67ecdaf8..a54dabfaf9d5 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/Milvus/MilvusMemoryStoreTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/Milvus/MilvusMemoryStoreTests.cs @@ -87,7 +87,7 @@ public async Task GetAsync(bool withEmbeddings) Assert.Equal(new DateTimeOffset(2023, 1, 1, 12, 0, 0, TimeSpan.Zero), record.Timestamp); Assert.Equal( - withEmbeddings ? new[] { 10f, 11f, 12f, 13f, 14f } : Array.Empty(), + withEmbeddings ? [10f, 11f, 12f, 13f, 14f] : [], record.Embedding.ToArray()); } @@ -110,7 +110,7 @@ public async Task GetBatchAsync(bool withEmbeddings) await this.Store.CreateCollectionAsync(CollectionName); await this.InsertSampleDataAsync(); - List records = this.Store.GetBatchAsync(CollectionName, new[] { "Some id", "Some other id" }, withEmbeddings: withEmbeddings).ToEnumerable().ToList(); + List records = this.Store.GetBatchAsync(CollectionName, ["Some id", "Some other id"], withEmbeddings: withEmbeddings).ToEnumerable().ToList(); Assert.Collection(records.OrderBy(r => r.Metadata.Id), r => @@ -125,7 +125,7 @@ public async Task GetBatchAsync(bool withEmbeddings) Assert.Equal(new DateTimeOffset(2023, 1, 1, 12, 0, 0, TimeSpan.Zero), r.Timestamp); Assert.Equal( - withEmbeddings ? new[] { 10f, 11f, 12f, 13f, 14f } : Array.Empty(), + withEmbeddings ? [10f, 11f, 12f, 13f, 14f] : [], r.Embedding.ToArray()); }, r => @@ -140,7 +140,7 @@ public async Task GetBatchAsync(bool withEmbeddings) Assert.Null(r.Timestamp); Assert.Equal( - withEmbeddings ? new[] { 20f, 21f, 22f, 23f, 24f } : Array.Empty(), + withEmbeddings ? [20f, 21f, 22f, 23f, 24f] : [], r.Embedding.ToArray()); }); } @@ -166,7 +166,7 @@ public async Task RemoveBatchAsync() Assert.NotNull(await this.Store.GetAsync(CollectionName, "Some id")); Assert.NotNull(await this.Store.GetAsync(CollectionName, "Some other id")); - await this.Store.RemoveBatchAsync(CollectionName, new[] { "Some id", "Some other id" }); + await this.Store.RemoveBatchAsync(CollectionName, ["Some id", "Some other id"]); Assert.Null(await this.Store.GetAsync(CollectionName, "Some id")); Assert.Null(await this.Store.GetAsync(CollectionName, "Some other id")); } @@ -200,7 +200,7 @@ public async Task GetNearestMatchesAsync(bool withEmbeddings) Assert.Equal(new DateTimeOffset(2023, 1, 1, 12, 0, 0, TimeSpan.Zero), r.Timestamp); Assert.Equal( - withEmbeddings ? new[] { 10f, 11f, 12f, 13f, 14f } : Array.Empty(), + withEmbeddings ? [10f, 11f, 12f, 13f, 14f] : [], r.Embedding.ToArray()); }, r => @@ -215,7 +215,7 @@ public async Task GetNearestMatchesAsync(bool withEmbeddings) Assert.Null(r.Timestamp); Assert.Equal( - withEmbeddings ? new[] { 20f, 21f, 22f, 23f, 24f } : Array.Empty(), + withEmbeddings ? [20f, 21f, 22f, 23f, 24f] : [], r.Embedding.ToArray()); }); } @@ -254,14 +254,14 @@ public async Task GetNearestMatchAsync(bool withEmbeddings) Assert.Equal("Some other id", record.Metadata.Id); Assert.Equal( - withEmbeddings ? new[] { 20f, 21f, 22f, 23f, 24f } : Array.Empty(), + withEmbeddings ? [20f, 21f, 22f, 23f, 24f] : [], record.Embedding.ToArray()); } private async Task> InsertSampleDataAsync() { - IAsyncEnumerable ids = this.Store.UpsertBatchAsync(CollectionName, new[] - { + IAsyncEnumerable ids = this.Store.UpsertBatchAsync(CollectionName, + [ new MemoryRecord( new MemoryRecordMetadata( isReference: true, @@ -284,9 +284,9 @@ private async Task> InsertSampleDataAsync() new[] { 20f, 21f, 22f, 23f, 24f }, key: null, timestamp: null), - }); + ]); - List idList = new(); + List idList = []; await foreach (string id in ids) { diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/DataHelper.cs b/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/DataHelper.cs index 646cfc27c588..fd0a634b47be 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/DataHelper.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/DataHelper.cs @@ -16,10 +16,8 @@ internal static class DataHelper static DataHelper() { VectorSearchTestRecords = CreateBatchRecords(8); - VectorSearchTestEmbedding = new[] { 1, 0.699f, 0.701f }; - VectorSearchExpectedResults = VectorSearchTestRecords - .OrderByDescending(r => TensorPrimitives.CosineSimilarity(r.Embedding.Span, VectorSearchTestEmbedding)) - .ToArray(); + VectorSearchTestEmbedding = [1, 0.699f, 0.701f]; + VectorSearchExpectedResults = [.. VectorSearchTestRecords.OrderByDescending(r => TensorPrimitives.CosineSimilarity(r.Embedding.Span, VectorSearchTestEmbedding))]; } public static MemoryRecord CreateRecord(string id) => diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/MongoDBMemoryStoreTests.cs b/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/MongoDBMemoryStoreTests.cs index f692c3cedd13..c7c475f068c7 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/MongoDBMemoryStoreTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/MongoDB/MongoDBMemoryStoreTests.cs @@ -13,17 +13,12 @@ namespace SemanticKernel.IntegrationTests.Connectors.MongoDB; /// /// Integration tests of . /// -public class MongoDBMemoryStoreTests : IClassFixture +public class MongoDBMemoryStoreTests(MongoDBMemoryStoreTestsFixture fixture) : IClassFixture { // If null, all tests will be enabled private const string? SkipReason = "MongoDB Atlas cluster is required"; - private readonly MongoDBMemoryStoreTestsFixture _fixture; - - public MongoDBMemoryStoreTests(MongoDBMemoryStoreTestsFixture fixture) - { - this._fixture = fixture; - } + private readonly MongoDBMemoryStoreTestsFixture _fixture = fixture; [Fact(Skip = SkipReason)] public async Task ItCanCreateAndGetCollectionAsync() @@ -276,7 +271,7 @@ public async Task ItCanTryBatchRemovingMixedExistingAndNonExistingRecordsAsync() var collectionName = GetRandomName(); var memoryStore = this._fixture.MemoryStore; var testRecords = DataHelper.CreateBatchRecords(10); - var ids = testRecords.Select(t => t.Metadata.Id).Concat(new[] { "a", "b", "c" }).ToArray(); + var ids = testRecords.Select(t => t.Metadata.Id).Concat(["a", "b", "c"]).ToArray(); // Act await memoryStore.CreateCollectionAsync(collectionName); diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/Postgres/PostgresMemoryStoreTests.cs b/dotnet/src/IntegrationTests/Connectors/Memory/Postgres/PostgresMemoryStoreTests.cs index 6435dc67da69..19126a090874 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/Postgres/PostgresMemoryStoreTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/Postgres/PostgresMemoryStoreTests.cs @@ -41,8 +41,10 @@ public async Task InitializeAsync() this._connectionString = connectionString; this._databaseName = $"sk_it_{Guid.NewGuid():N}"; - NpgsqlConnectionStringBuilder connectionStringBuilder = new(this._connectionString); - connectionStringBuilder.Database = this._databaseName; + NpgsqlConnectionStringBuilder connectionStringBuilder = new(this._connectionString) + { + Database = this._databaseName + }; NpgsqlDataSourceBuilder dataSourceBuilder = new(connectionStringBuilder.ToString()); dataSourceBuilder.UseVector(); @@ -150,7 +152,7 @@ public async Task ItCanUpsertAndRetrieveARecordWithNoTimestampAsync() id: "test", text: "text", description: "description", - embedding: new ReadOnlyMemory(new float[] { 1, 2, 3 }), + embedding: new ReadOnlyMemory([1, 2, 3]), key: null, timestamp: null); string collection = "test_collection"; @@ -281,7 +283,7 @@ public async Task ItCanListAllDatabaseCollectionsAsync() { // Arrange using PostgresMemoryStore memoryStore = this.CreateMemoryStore(); - string[] testCollections = { "random_collection1", "random_collection2", "random_collection3" }; + string[] testCollections = ["random_collection1", "random_collection2", "random_collection3"]; await memoryStore.CreateCollectionAsync(testCollections[0]); await memoryStore.CreateCollectionAsync(testCollections[1]); await memoryStore.CreateCollectionAsync(testCollections[2]); @@ -571,7 +573,7 @@ public async Task ItCanBatchRemoveRecordsAsync() IEnumerable records = this.CreateBatchRecords(numRecords); await memoryStore.CreateCollectionAsync(collection); - List keys = new(); + List keys = []; // Act await foreach (var key in memoryStore.UpsertBatchAsync(collection, records)) @@ -634,10 +636,8 @@ private async Task CreateDatabaseAsync() using NpgsqlDataSource dataSource = NpgsqlDataSource.Create(this._connectionString); await using (NpgsqlConnection conn = await dataSource.OpenConnectionAsync()) { - await using (NpgsqlCommand command = new($"CREATE DATABASE \"{this._databaseName}\"", conn)) - { - await command.ExecuteNonQueryAsync(); - } + await using NpgsqlCommand command = new($"CREATE DATABASE \"{this._databaseName}\"", conn); + await command.ExecuteNonQueryAsync(); } await using (NpgsqlConnection conn = await this._dataSource.OpenConnectionAsync()) @@ -654,13 +654,9 @@ private async Task CreateDatabaseAsync() private async Task DropDatabaseAsync() { using NpgsqlDataSource dataSource = NpgsqlDataSource.Create(this._connectionString); - await using (NpgsqlConnection conn = await dataSource.OpenConnectionAsync()) - { - await using (NpgsqlCommand command = new($"DROP DATABASE IF EXISTS \"{this._databaseName}\"", conn)) - { - await command.ExecuteNonQueryAsync(); - } - } + await using NpgsqlConnection conn = await dataSource.OpenConnectionAsync(); + await using NpgsqlCommand command = new($"DROP DATABASE IF EXISTS \"{this._databaseName}\"", conn); + await command.ExecuteNonQueryAsync(); } private PostgresMemoryStore CreateMemoryStore() diff --git a/dotnet/src/IntegrationTests/Connectors/OpenAI/ChatHistoryTests.cs b/dotnet/src/IntegrationTests/Connectors/OpenAI/ChatHistoryTests.cs index b9ad2697e128..9f729d9e0ac6 100644 --- a/dotnet/src/IntegrationTests/Connectors/OpenAI/ChatHistoryTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/OpenAI/ChatHistoryTests.cs @@ -49,7 +49,7 @@ public async Task ItSerializesAndDeserializesChatHistoryAsync() var kernel = builder.Build(); OpenAIPromptExecutionSettings settings = new() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }; - ChatHistory history = new(); + ChatHistory history = []; // Act history.AddUserMessage("Make me a special poem"); @@ -80,7 +80,7 @@ public async Task ItUsesChatSystemPromptFromSettingsAsync() string systemPrompt = "You are batman. If asked who you are, say 'I am Batman!'"; OpenAIPromptExecutionSettings settings = new() { ChatSystemPrompt = systemPrompt }; - ChatHistory history = new(); + ChatHistory history = []; // Act history.AddUserMessage("Who are you?"); diff --git a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAICompletionTests.cs b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAICompletionTests.cs index af7976d7634d..9146cd0883fb 100644 --- a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAICompletionTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAICompletionTests.cs @@ -139,7 +139,7 @@ public async Task AzureOpenAIStreamingTestAsync(bool useChatModel, string prompt await foreach (var content in target.InvokeStreamingAsync(plugins["ChatPlugin"]["Chat"], new() { [InputParameterName] = prompt })) { fullResult.Append(content); - }; + } // Assert Assert.Contains(expectedAnswerContains, fullResult.ToString(), StringComparison.OrdinalIgnoreCase); @@ -373,7 +373,7 @@ public async Task CompletionWithDifferentLineEndingsAsync(string lineEnding, AIS var prompt = "Given a json input and a request. Apply the request on the json input and return the result. " + $"Put the result in between tags{lineEnding}" + - $"Input:{lineEnding}{{\"name\": \"John\", \"age\": 30}}{lineEnding}{lineEnding}Request:{lineEnding}name"; + $$"""Input:{{lineEnding}}{"name": "John", "age": 30}{{lineEnding}}{{lineEnding}}Request:{{lineEnding}}name"""; const string ExpectedAnswerContains = "John"; @@ -440,15 +440,16 @@ public async Task MultipleServiceLoadPromptConfigTestAsync() var prompt = "Where is the most famous fish market in Seattle, Washington, USA?"; var defaultPromptModel = new PromptTemplateConfig(prompt) { Name = "FishMarket1" }; - var azurePromptModel = PromptTemplateConfig.FromJson( - @"{ - ""name"": ""FishMarket2"", - ""execution_settings"": { - ""azure-text-davinci-003"": { - ""max_tokens"": 256 + var azurePromptModel = PromptTemplateConfig.FromJson(""" + { + "name": "FishMarket2", + "execution_settings": { + "azure-text-davinci-003": { + "max_tokens": 256 } } - }"); + } + """); azurePromptModel.Template = prompt; var defaultFunc = target.CreateFunctionFromPrompt(defaultPromptModel); @@ -519,7 +520,7 @@ public async Task SemanticKernelVersionHeaderIsSentAsync() private readonly XunitLogger _logger; private readonly RedirectOutput _testOutputHelper; - private readonly Dictionary> _serviceConfiguration = new(); + private readonly Dictionary> _serviceConfiguration = []; public void Dispose() { diff --git a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAITextEmbeddingTests.cs b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAITextEmbeddingTests.cs index 3b1ec3ca3055..bd4bbddcfaf2 100644 --- a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAITextEmbeddingTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAITextEmbeddingTests.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Configuration; using Microsoft.SemanticKernel.Connectors.OpenAI; @@ -39,7 +38,7 @@ public async Task OpenAITestAsync(string testInputString) // Act var singleResult = await embeddingGenerator.GenerateEmbeddingAsync(testInputString); - var batchResult = await embeddingGenerator.GenerateEmbeddingsAsync(new List { testInputString, testInputString, testInputString }); + var batchResult = await embeddingGenerator.GenerateEmbeddingsAsync([testInputString, testInputString, testInputString]); // Assert Assert.Equal(AdaVectorLength, singleResult.Length); @@ -60,7 +59,7 @@ public async Task AzureOpenAITestAsync(string testInputString) // Act var singleResult = await embeddingGenerator.GenerateEmbeddingAsync(testInputString); - var batchResult = await embeddingGenerator.GenerateEmbeddingsAsync(new List { testInputString, testInputString, testInputString }); + var batchResult = await embeddingGenerator.GenerateEmbeddingsAsync([testInputString, testInputString, testInputString]); // Assert Assert.Equal(AdaVectorLength, singleResult.Length); diff --git a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAIToolsTests.cs b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAIToolsTests.cs index 37fb04a412c3..807c75f495ad 100644 --- a/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAIToolsTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/OpenAI/OpenAIToolsTests.cs @@ -136,7 +136,7 @@ public async Task CanAutoInvokeKernelFunctionFromPromptAsync() kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions( "NewsProvider", "Delivers up-to-date news content.", - new[] { promptFunction })); + [promptFunction])); // Act OpenAIPromptExecutionSettings settings = new() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }; @@ -161,7 +161,7 @@ public async Task CanAutoInvokeKernelFunctionFromPromptStreamingAsync() kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions( "NewsProvider", "Delivers up-to-date news content.", - new[] { promptFunction })); + [promptFunction])); // Act OpenAIPromptExecutionSettings settings = new() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }; diff --git a/dotnet/src/IntegrationTests/Connectors/Weaviate/WeaviateMemoryStoreTests.cs b/dotnet/src/IntegrationTests/Connectors/Weaviate/WeaviateMemoryStoreTests.cs index 8976c841f844..4fdc591d3ad9 100644 --- a/dotnet/src/IntegrationTests/Connectors/Weaviate/WeaviateMemoryStoreTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Weaviate/WeaviateMemoryStoreTests.cs @@ -231,7 +231,7 @@ public async Task BatchCrudOperationsAsync() timestamp: timestamp3); await this._weaviateMemoryStore.CreateCollectionAsync(collectionName); - var response = await this._weaviateMemoryStore.UpsertBatchAsync(collectionName, new[] { memoryRecord1, memoryRecord2, memoryRecord3 }).ToListAsync(); + var response = await this._weaviateMemoryStore.UpsertBatchAsync(collectionName, [memoryRecord1, memoryRecord2, memoryRecord3]).ToListAsync(); Assert.Equal(id1, response[0]); Assert.Equal(id2, response[1]); Assert.Equal(id3, response[2]); @@ -275,8 +275,8 @@ public async Task BatchCrudOperationsAsync() Assert.Equal(memoryRecord3.Metadata.ExternalSourceName, closest.Value.Item1.Metadata.ExternalSourceName); Assert.Equal(memoryRecord3.Metadata.IsReference, closest.Value.Item1.Metadata.IsReference); - await this._weaviateMemoryStore.RemoveBatchAsync(collectionName, new[] { id1, id2, id3 }); - var memoryRecordsAfterDeletion = await this._weaviateMemoryStore.GetBatchAsync(collectionName, new[] { id1, id2, id3 }).ToListAsync(); + await this._weaviateMemoryStore.RemoveBatchAsync(collectionName, [id1, id2, id3]); + var memoryRecordsAfterDeletion = await this._weaviateMemoryStore.GetBatchAsync(collectionName, [id1, id2, id3]).ToListAsync(); Assert.Empty(memoryRecordsAfterDeletion); } diff --git a/dotnet/src/IntegrationTests/Extensions/KernelFunctionExtensionsTests.cs b/dotnet/src/IntegrationTests/Extensions/KernelFunctionExtensionsTests.cs index fa75469cb3e0..f1df6f8b9a3c 100644 --- a/dotnet/src/IntegrationTests/Extensions/KernelFunctionExtensionsTests.cs +++ b/dotnet/src/IntegrationTests/Extensions/KernelFunctionExtensionsTests.cs @@ -16,13 +16,8 @@ namespace SemanticKernel.IntegrationTests; -public sealed class KernelFunctionExtensionsTests : IDisposable +public sealed class KernelFunctionExtensionsTests(ITestOutputHelper output) : IDisposable { - public KernelFunctionExtensionsTests(ITestOutputHelper output) - { - this._logger = new RedirectOutput(output); - } - [Fact] public async Task ItSupportsFunctionCallsAsync() { @@ -101,7 +96,7 @@ public async Task ItSupportsInvokeHandlebarsPromptAsync() Assert.Equal("Hey johndoe1234@example.com", actual.GetValue()); } - private readonly RedirectOutput _logger; + private readonly RedirectOutput _logger = new(output); public void Dispose() { @@ -116,7 +111,7 @@ private sealed class RedirectTextGenerationService : ITextGenerationService public Task> GetTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings, Kernel? kernel, CancellationToken cancellationToken) { - return Task.FromResult>(new List { new(prompt) }); + return Task.FromResult>([new(prompt)]); } public IAsyncEnumerable GetStreamingTextContentsAsync(string prompt, PromptExecutionSettings? executionSettings = null, Kernel? kernel = null, CancellationToken cancellationToken = default) diff --git a/dotnet/src/IntegrationTests/Planners/Handlebars/HandlebarsPlannerTests.cs b/dotnet/src/IntegrationTests/Planners/Handlebars/HandlebarsPlannerTests.cs index f68ff2217c8d..275aac311968 100644 --- a/dotnet/src/IntegrationTests/Planners/Handlebars/HandlebarsPlannerTests.cs +++ b/dotnet/src/IntegrationTests/Planners/Handlebars/HandlebarsPlannerTests.cs @@ -127,7 +127,7 @@ private Kernel InitializeKernel(bool useEmbeddings = false, bool useChatModel = { builder.Services.AddAzureOpenAIChatCompletion( deploymentName: azureOpenAIConfiguration.ChatDeploymentName!, - modelId: azureOpenAIConfiguration.ChatModelId!, + modelId: azureOpenAIConfiguration.ChatModelId, endpoint: azureOpenAIConfiguration.Endpoint, apiKey: azureOpenAIConfiguration.ApiKey); } @@ -144,7 +144,7 @@ private Kernel InitializeKernel(bool useEmbeddings = false, bool useChatModel = { builder.Services.AddAzureOpenAITextEmbeddingGeneration( deploymentName: azureOpenAIEmbeddingsConfiguration.DeploymentName, - modelId: azureOpenAIEmbeddingsConfiguration.EmbeddingModelId!, + modelId: azureOpenAIEmbeddingsConfiguration.EmbeddingModelId, endpoint: azureOpenAIEmbeddingsConfiguration.Endpoint, apiKey: azureOpenAIEmbeddingsConfiguration.ApiKey); } diff --git a/dotnet/src/IntegrationTests/Planners/Stepwise/FunctionCallingStepwisePlannerTests.cs b/dotnet/src/IntegrationTests/Planners/Stepwise/FunctionCallingStepwisePlannerTests.cs index 35a71de45fe2..3d26a8bc4b5f 100644 --- a/dotnet/src/IntegrationTests/Planners/Stepwise/FunctionCallingStepwisePlannerTests.cs +++ b/dotnet/src/IntegrationTests/Planners/Stepwise/FunctionCallingStepwisePlannerTests.cs @@ -85,10 +85,10 @@ public async Task DoesNotThrowWhenPluginFunctionThrowsNonCriticalExceptionAsync( kernel.Plugins.Add( KernelPluginFactory.CreateFromFunctions( "Email", - new[] { + [ KernelFunctionFactory.CreateFromMethod(emailPluginFake.WritePoemAsync), KernelFunctionFactory.CreateFromMethod(emailPluginFake.SendEmailAsync), - })); + ])); var planner = new FunctionCallingStepwisePlanner( new FunctionCallingStepwisePlannerOptions() { MaxIterations = 5 }); @@ -116,10 +116,10 @@ public async Task ThrowsWhenPluginFunctionThrowsCriticalExceptionAsync() kernel.Plugins.Add( KernelPluginFactory.CreateFromFunctions( "Email", - new[] { + [ KernelFunctionFactory.CreateFromMethod(emailPluginFake.WriteJokeAsync), KernelFunctionFactory.CreateFromMethod(emailPluginFake.SendEmailAsync), - })); + ])); var planner = new FunctionCallingStepwisePlanner( new FunctionCallingStepwisePlannerOptions() { MaxIterations = 5 }); @@ -143,7 +143,7 @@ public async Task CanExecutePromptFunctionAsync() kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions( "NewsProvider", "Delivers up-to-date news content.", - new[] { promptFunction })); + [promptFunction])); var planner = new FunctionCallingStepwisePlanner( new FunctionCallingStepwisePlannerOptions() { MaxIterations = 2 }); diff --git a/dotnet/src/IntegrationTests/Plugins/PluginTests.cs b/dotnet/src/IntegrationTests/Plugins/PluginTests.cs index a9e7ca8363d2..8275a99e7423 100644 --- a/dotnet/src/IntegrationTests/Plugins/PluginTests.cs +++ b/dotnet/src/IntegrationTests/Plugins/PluginTests.cs @@ -31,11 +31,13 @@ public async Task QueryKlarnaOpenAIPluginAsync( new Uri(pluginEndpoint), new OpenAIFunctionExecutionParameters(httpClient)); - var arguments = new KernelArguments(); - arguments["q"] = query; - arguments["size"] = size; - arguments["max_price"] = budget; - arguments["countryCode"] = countryCode; + var arguments = new KernelArguments + { + ["q"] = query, + ["size"] = size, + ["max_price"] = budget, + ["countryCode"] = countryCode + }; // Act await plugin[functionName].InvokeAsync(kernel, arguments); @@ -61,11 +63,13 @@ public async Task QueryKlarnaOpenApiPluginAsync( new Uri(pluginEndpoint), new OpenApiFunctionExecutionParameters(httpClient)); - var arguments = new KernelArguments(); - arguments["q"] = query; - arguments["size"] = size.ToString(System.Globalization.CultureInfo.InvariantCulture); - arguments["max_price"] = budget; - arguments["countryCode"] = countryCode; + var arguments = new KernelArguments + { + ["q"] = query, + ["size"] = size.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["max_price"] = budget, + ["countryCode"] = countryCode + }; // Act await plugin[functionName].InvokeAsync(kernel, arguments); @@ -91,11 +95,13 @@ public async Task QueryKlarnaOpenApiPluginRunAsync( new Uri(pluginEndpoint), new OpenApiFunctionExecutionParameters(httpClient)); - var arguments = new KernelArguments(); - arguments["q"] = query; - arguments["size"] = size; - arguments["budget"] = budget.ToString(System.Globalization.CultureInfo.InvariantCulture); - arguments["countryCode"] = countryCode; + var arguments = new KernelArguments + { + ["q"] = query, + ["size"] = size, + ["budget"] = budget.ToString(System.Globalization.CultureInfo.InvariantCulture), + ["countryCode"] = countryCode + }; // Act var result = (await kernel.InvokeAsync(plugin[functionName], arguments)).GetValue(); @@ -111,7 +117,7 @@ public async Task QueryKlarnaOpenApiPluginRunAsync( [InlineData("https://raw.githubusercontent.com/sisbell/chatgpt-plugin-store/main/manifests/instacart.com.json", "Instacart", "create", - "{\"title\":\"Shopping List\", \"ingredients\": [\"Flour\"], \"question\": \"what ingredients do I need to make chocolate cookies?\", \"partner_name\": \"OpenAI\" }" + """{"title":"Shopping List", "ingredients": ["Flour"], "question": "what ingredients do I need to make chocolate cookies?", "partner_name": "OpenAI" }""" )] public async Task QueryInstacartPluginAsync( string pluginEndpoint, @@ -129,8 +135,10 @@ public async Task QueryInstacartPluginAsync( new Uri(pluginEndpoint), new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = false }); - var arguments = new KernelArguments(); - arguments["payload"] = payload; + var arguments = new KernelArguments + { + ["payload"] = payload + }; // Act await plugin[functionName].InvokeAsync(kernel, arguments); @@ -140,7 +148,7 @@ public async Task QueryInstacartPluginAsync( [InlineData("Plugins/instacart-ai-plugin.json", "Instacart", "create", - "{\"title\":\"Shopping List\", \"ingredients\": [\"Flour\"], \"question\": \"what ingredients do I need to make chocolate cookies?\", \"partner_name\": \"OpenAI\" }" + """{"title":"Shopping List", "ingredients": ["Flour"], "question": "what ingredients do I need to make chocolate cookies?", "partner_name": "OpenAI" }""" )] public async Task QueryInstacartPluginFromStreamAsync( string pluginFilePath, @@ -149,30 +157,30 @@ public async Task QueryInstacartPluginFromStreamAsync( string payload) { // Arrange - using (var stream = System.IO.File.OpenRead(pluginFilePath)) - { - var kernel = new Kernel(); - using HttpClient httpClient = new(); + using var stream = System.IO.File.OpenRead(pluginFilePath); + using HttpClient httpClient = new(); + var kernel = new Kernel(); - // note that this plugin is not compliant according to the underlying validator in SK - var plugin = await kernel.ImportPluginFromOpenAIAsync( - name, - stream, - new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = false }); + // note that this plugin is not compliant according to the underlying validator in SK + var plugin = await kernel.ImportPluginFromOpenAIAsync( + name, + stream, + new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = false }); - var arguments = new KernelArguments(); - arguments["payload"] = payload; + var arguments = new KernelArguments + { + ["payload"] = payload + }; - // Act - await plugin[functionName].InvokeAsync(kernel, arguments); - } + // Act + await plugin[functionName].InvokeAsync(kernel, arguments); } [Theory] [InlineData("Plugins/instacart-ai-plugin.json", "Instacart", "create", - "{\"title\":\"Shopping List\", \"ingredients\": [\"Flour\"], \"question\": \"what ingredients do I need to make chocolate cookies?\", \"partner_name\": \"OpenAI\" }" + """{"title":"Shopping List", "ingredients": ["Flour"], "question": "what ingredients do I need to make chocolate cookies?", "partner_name": "OpenAI" }""" )] public async Task QueryInstacartPluginUsingRelativeFilePathAsync( string pluginFilePath, @@ -190,8 +198,10 @@ public async Task QueryInstacartPluginUsingRelativeFilePathAsync( pluginFilePath, new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = false }); - var arguments = new KernelArguments(); - arguments["payload"] = payload; + var arguments = new KernelArguments + { + ["payload"] = payload + }; // Act await plugin[functionName].InvokeAsync(kernel, arguments); @@ -205,26 +215,26 @@ public async Task QueryInstacartPluginWithDynamicPayloadAsync( string functionName) { // Arrange - using (var stream = System.IO.File.OpenRead(pluginFilePath)) + using var stream = System.IO.File.OpenRead(pluginFilePath); + using HttpClient httpClient = new(); + var kernel = new Kernel(); + + // note that this plugin is not compliant according to the underlying validator in SK + var plugin = await kernel.ImportPluginFromOpenAIAsync( + name, + stream, + new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = true }); + + var arguments = new KernelArguments { - var kernel = new Kernel(); - using HttpClient httpClient = new(); - - // note that this plugin is not compliant according to the underlying validator in SK - var plugin = await kernel.ImportPluginFromOpenAIAsync( - name, - stream, - new OpenAIFunctionExecutionParameters(httpClient) { IgnoreNonCompliantErrors = true, EnableDynamicPayload = true }); ; - - var arguments = new KernelArguments(); - arguments["title"] = "Shopping List"; - arguments["ingredients"] = new string[] { "Flour", "Sugar", "Eggs" }; - arguments["instructions"] = new string[] { "Cream softened butter and granulated sugar", "Add eggs one at a time, mix well, and stir in vanilla extract", "Combine dry ingredients and mix" }; - arguments["question"] = "what ingredients do I need to make chocolate cookies?"; - arguments["partner_name"] = "OpenAI"; - - // Act - await plugin[functionName].InvokeAsync(kernel, arguments); - } + ["title"] = "Shopping List", + ["ingredients"] = new string[] { "Flour", "Sugar", "Eggs" }, + ["instructions"] = new string[] { "Cream softened butter and granulated sugar", "Add eggs one at a time, mix well, and stir in vanilla extract", "Combine dry ingredients and mix" }, + ["question"] = "what ingredients do I need to make chocolate cookies?", + ["partner_name"] = "OpenAI" + }; + + // Act + await plugin[functionName].InvokeAsync(kernel, arguments); } } diff --git a/dotnet/src/IntegrationTests/RedirectOutput.cs b/dotnet/src/IntegrationTests/RedirectOutput.cs index 34cac5ba9654..1e4643dd8fe5 100644 --- a/dotnet/src/IntegrationTests/RedirectOutput.cs +++ b/dotnet/src/IntegrationTests/RedirectOutput.cs @@ -8,16 +8,10 @@ namespace SemanticKernel.IntegrationTests; -public class RedirectOutput : TextWriter, ILogger, ILoggerFactory +public class RedirectOutput(ITestOutputHelper output) : TextWriter, ILogger, ILoggerFactory { - private readonly ITestOutputHelper _output; - private readonly StringBuilder _logs; - - public RedirectOutput(ITestOutputHelper output) - { - this._output = output; - this._logs = new StringBuilder(); - } + private readonly ITestOutputHelper _output = output; + private readonly StringBuilder _logs = new(); public override Encoding Encoding { get; } = Encoding.UTF8; diff --git a/dotnet/src/IntegrationTests/TestSettings/AzureOpenAIConfiguration.cs b/dotnet/src/IntegrationTests/TestSettings/AzureOpenAIConfiguration.cs index d8663b240f55..e530110f9322 100644 --- a/dotnet/src/IntegrationTests/TestSettings/AzureOpenAIConfiguration.cs +++ b/dotnet/src/IntegrationTests/TestSettings/AzureOpenAIConfiguration.cs @@ -6,33 +6,21 @@ namespace SemanticKernel.IntegrationTests.TestSettings; [SuppressMessage("Performance", "CA1812:Internal class that is apparently never instantiated", Justification = "Configuration classes are instantiated through IConfiguration.")] -internal sealed class AzureOpenAIConfiguration +internal sealed class AzureOpenAIConfiguration(string serviceId, string deploymentName, string endpoint, string apiKey, string? chatDeploymentName = null, string? modelId = null, string? chatModelId = null, string? embeddingModelId = null) { - public string ServiceId { get; set; } + public string ServiceId { get; set; } = serviceId; - public string DeploymentName { get; set; } + public string DeploymentName { get; set; } = deploymentName; - public string ModelId { get; set; } + public string ModelId { get; set; } = modelId ?? deploymentName; - public string? ChatDeploymentName { get; set; } + public string? ChatDeploymentName { get; set; } = chatDeploymentName ?? deploymentName; - public string ChatModelId { get; set; } + public string ChatModelId { get; set; } = chatModelId ?? deploymentName; - public string EmbeddingModelId { get; set; } + public string EmbeddingModelId { get; set; } = embeddingModelId ?? "text-embedding-ada-002"; - public string Endpoint { get; set; } + public string Endpoint { get; set; } = endpoint; - public string ApiKey { get; set; } - - public AzureOpenAIConfiguration(string serviceId, string deploymentName, string endpoint, string apiKey, string? chatDeploymentName = null, string? modelId = null, string? chatModelId = null, string? embeddingModelId = null) - { - this.ServiceId = serviceId; - this.DeploymentName = deploymentName; - this.ModelId = modelId ?? deploymentName; - this.ChatDeploymentName = deploymentName; - this.ChatModelId = chatModelId ?? deploymentName; - this.EmbeddingModelId = embeddingModelId ?? "text-embedding-ada-002"; - this.Endpoint = endpoint; - this.ApiKey = apiKey; - } + public string ApiKey { get; set; } = apiKey; } diff --git a/dotnet/src/IntegrationTests/TestSettings/OpenAIConfiguration.cs b/dotnet/src/IntegrationTests/TestSettings/OpenAIConfiguration.cs index ae6d41f66504..cb3884e3bdfc 100644 --- a/dotnet/src/IntegrationTests/TestSettings/OpenAIConfiguration.cs +++ b/dotnet/src/IntegrationTests/TestSettings/OpenAIConfiguration.cs @@ -6,18 +6,10 @@ namespace SemanticKernel.IntegrationTests.TestSettings; [SuppressMessage("Performance", "CA1812:Internal class that is apparently never instantiated", Justification = "Configuration classes are instantiated through IConfiguration.")] -internal sealed class OpenAIConfiguration +internal sealed class OpenAIConfiguration(string serviceId, string modelId, string apiKey, string? chatModelId = null) { - public string ServiceId { get; set; } - public string ModelId { get; set; } - public string? ChatModelId { get; set; } - public string ApiKey { get; set; } - - public OpenAIConfiguration(string serviceId, string modelId, string apiKey, string? chatModelId = null) - { - this.ServiceId = serviceId; - this.ModelId = modelId; - this.ChatModelId = chatModelId; - this.ApiKey = apiKey; - } + public string ServiceId { get; set; } = serviceId; + public string ModelId { get; set; } = modelId; + public string? ChatModelId { get; set; } = chatModelId; + public string ApiKey { get; set; } = apiKey; } diff --git a/dotnet/src/IntegrationTests/XunitLogger.cs b/dotnet/src/IntegrationTests/XunitLogger.cs index b1f97444ba86..80e0808a84e7 100644 --- a/dotnet/src/IntegrationTests/XunitLogger.cs +++ b/dotnet/src/IntegrationTests/XunitLogger.cs @@ -9,14 +9,9 @@ namespace SemanticKernel.IntegrationTests; /// /// A logger that writes to the Xunit test output /// -internal sealed class XunitLogger : ILoggerFactory, ILogger, IDisposable +internal sealed class XunitLogger(ITestOutputHelper output) : ILoggerFactory, ILogger, IDisposable { - private readonly ITestOutputHelper _output; - - public XunitLogger(ITestOutputHelper output) - { - this._output = output; - } + private readonly ITestOutputHelper _output = output; /// public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) diff --git a/dotnet/src/InternalUtilities/planning/Extensions/ReadOnlyFunctionCollectionPlannerExtensions.cs b/dotnet/src/InternalUtilities/planning/Extensions/ReadOnlyFunctionCollectionPlannerExtensions.cs index efa6d8806485..6d03dc2d4083 100644 --- a/dotnet/src/InternalUtilities/planning/Extensions/ReadOnlyFunctionCollectionPlannerExtensions.cs +++ b/dotnet/src/InternalUtilities/planning/Extensions/ReadOnlyFunctionCollectionPlannerExtensions.cs @@ -133,7 +133,7 @@ internal static async Task> GetAvailableFunc } else { - result = new List(); + result = []; // Remember functions in memory so that they can be searched. await RememberFunctionsAsync(semanticMemoryConfig.Memory, availableFunctions, cancellationToken).ConfigureAwait(false); diff --git a/dotnet/src/InternalUtilities/planning/PlannerOptions.cs b/dotnet/src/InternalUtilities/planning/PlannerOptions.cs index 463b9b5d032c..305e4b5f59f1 100644 --- a/dotnet/src/InternalUtilities/planning/PlannerOptions.cs +++ b/dotnet/src/InternalUtilities/planning/PlannerOptions.cs @@ -14,12 +14,12 @@ public abstract class PlannerOptions /// /// A list of plugins to exclude from the plan creation request. /// - public HashSet ExcludedPlugins { get; } = new(); + public HashSet ExcludedPlugins { get; } = []; /// /// A list of functions to exclude from the plan creation request. /// - public HashSet ExcludedFunctions { get; } = new(); + public HashSet ExcludedFunctions { get; } = []; /// /// Callback to get the available functions for planning (optional). diff --git a/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionParameters.cs b/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionParameters.cs index 6bd4438b28c1..0e7372ec21a8 100644 --- a/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionParameters.cs +++ b/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionParameters.cs @@ -20,11 +20,11 @@ internal sealed class JsonSchemaFunctionParameters /// The list of required properties. /// [JsonPropertyName("required")] - public List Required { get; set; } = new List(); + public List Required { get; set; } = []; /// /// A dictionary of properties name => JSON Schema. /// [JsonPropertyName("properties")] - public Dictionary Properties { get; set; } = new Dictionary(); + public Dictionary Properties { get; set; } = []; } diff --git a/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionView.cs b/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionView.cs index 41f0d5ec8e7f..6273f2258d93 100644 --- a/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionView.cs +++ b/dotnet/src/InternalUtilities/planning/Schema/JsonSchemaFunctionView.cs @@ -32,5 +32,5 @@ internal sealed class JsonSchemaFunctionView /// The function response. /// [JsonPropertyName("responses")] - public Dictionary FunctionResponses { get; set; } = new Dictionary(); + public Dictionary FunctionResponses { get; set; } = []; } diff --git a/dotnet/src/InternalUtilities/planning/SemanticMemoryConfig.cs b/dotnet/src/InternalUtilities/planning/SemanticMemoryConfig.cs index f7dfa8eab1d2..0d6ac49dfba0 100644 --- a/dotnet/src/InternalUtilities/planning/SemanticMemoryConfig.cs +++ b/dotnet/src/InternalUtilities/planning/SemanticMemoryConfig.cs @@ -13,7 +13,7 @@ public class SemanticMemoryConfig /// /// A list of functions to be included regardless of relevancy. /// - public HashSet<(string PluginName, string FunctionName)> IncludedFunctions { get; } = new(); + public HashSet<(string PluginName, string FunctionName)> IncludedFunctions { get; } = []; /// /// Semantic memory to use for filtering function lookup during plan creation. diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs index 34f0de31ec3c..4d33cbeb6339 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/NullableAttributes.cs @@ -116,7 +116,7 @@ internal sealed class MemberNotNullAttribute : Attribute /// The field or property member that is promised to be not-null. /// [SuppressMessage("Design", "CA1019:Define accessors for attribute arguments")] - public MemberNotNullAttribute(string member) => this.Members = new[] { member }; + public MemberNotNullAttribute(string member) => this.Members = [member]; /// Initializes the attribute with the list of field and property members. /// @@ -144,7 +144,7 @@ internal sealed class MemberNotNullWhenAttribute : Attribute public MemberNotNullWhenAttribute(bool returnValue, string member) { this.ReturnValue = returnValue; - this.Members = new[] { member }; + this.Members = [member]; } /// Initializes the attribute with the specified return value condition and list of field and property members. diff --git a/dotnet/src/InternalUtilities/src/Diagnostics/Verify.cs b/dotnet/src/InternalUtilities/src/Diagnostics/Verify.cs index 118330f9a1c4..48f1847cc8b7 100644 --- a/dotnet/src/InternalUtilities/src/Diagnostics/Verify.cs +++ b/dotnet/src/InternalUtilities/src/Diagnostics/Verify.cs @@ -20,7 +20,7 @@ internal static class Verify /// Equivalent of ArgumentNullException.ThrowIfNull /// [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void NotNull([NotNull] object? obj, [CallerArgumentExpression("obj")] string? paramName = null) + internal static void NotNull([NotNull] object? obj, [CallerArgumentExpression(nameof(obj))] string? paramName = null) { if (obj is null) { @@ -29,7 +29,7 @@ internal static void NotNull([NotNull] object? obj, [CallerArgumentExpression("o } [MethodImpl(MethodImplOptions.AggressiveInlining)] - internal static void NotNullOrWhiteSpace([NotNull] string? str, [CallerArgumentExpression("str")] string? paramName = null) + internal static void NotNullOrWhiteSpace([NotNull] string? str, [CallerArgumentExpression(nameof(str))] string? paramName = null) { NotNull(str, paramName); if (string.IsNullOrWhiteSpace(str)) @@ -38,7 +38,7 @@ internal static void NotNullOrWhiteSpace([NotNull] string? str, [CallerArgumentE } } - internal static void NotNullOrEmpty(IList list, [CallerArgumentExpression("list")] string? paramName = null) + internal static void NotNullOrEmpty(IList list, [CallerArgumentExpression(nameof(list))] string? paramName = null) { NotNull(list, paramName); if (list.Count == 0) @@ -47,7 +47,7 @@ internal static void NotNullOrEmpty(IList list, [CallerArgumentExpression( } } - public static void True(bool condition, string message, [CallerArgumentExpression("condition")] string? paramName = null) + public static void True(bool condition, string message, [CallerArgumentExpression(nameof(condition))] string? paramName = null) { if (!condition) { @@ -55,7 +55,7 @@ public static void True(bool condition, string message, [CallerArgumentExpressio } } - internal static void ValidPluginName([NotNull] string? pluginName, IReadOnlyKernelPluginCollection? plugins = null, [CallerArgumentExpression("pluginName")] string? paramName = null) + internal static void ValidPluginName([NotNull] string? pluginName, IReadOnlyKernelPluginCollection? plugins = null, [CallerArgumentExpression(nameof(pluginName))] string? paramName = null) { NotNullOrWhiteSpace(pluginName); if (!s_asciiLettersDigitsUnderscoresRegex.IsMatch(pluginName)) @@ -69,7 +69,7 @@ internal static void ValidPluginName([NotNull] string? pluginName, IReadOnlyKern } } - internal static void ValidFunctionName([NotNull] string? functionName, [CallerArgumentExpression("functionName")] string? paramName = null) + internal static void ValidFunctionName([NotNull] string? functionName, [CallerArgumentExpression(nameof(functionName))] string? paramName = null) { NotNullOrWhiteSpace(functionName); if (!s_asciiLettersDigitsUnderscoresRegex.IsMatch(functionName)) @@ -78,7 +78,7 @@ internal static void ValidFunctionName([NotNull] string? functionName, [CallerAr } } - internal static void ValidFilename([NotNull] string? filename, [CallerArgumentExpression("filename")] string? paramName = null) + internal static void ValidFilename([NotNull] string? filename, [CallerArgumentExpression(nameof(filename))] string? paramName = null) { NotNullOrWhiteSpace(filename); if (!s_filenameRegex.IsMatch(filename)) @@ -87,7 +87,7 @@ internal static void ValidFilename([NotNull] string? filename, [CallerArgumentEx } } - public static void ValidateUrl(string url, bool allowQuery = false, [CallerArgumentExpression("url")] string? paramName = null) + public static void ValidateUrl(string url, bool allowQuery = false, [CallerArgumentExpression(nameof(url))] string? paramName = null) { NotNullOrWhiteSpace(url, paramName); @@ -107,7 +107,7 @@ public static void ValidateUrl(string url, bool allowQuery = false, [CallerArgum } } - internal static void StartsWith(string text, string prefix, string message, [CallerArgumentExpression("text")] string? textParamName = null) + internal static void StartsWith(string text, string prefix, string message, [CallerArgumentExpression(nameof(text))] string? textParamName = null) { Debug.Assert(prefix is not null); diff --git a/dotnet/src/InternalUtilities/src/Http/HttpResponseStream.cs b/dotnet/src/InternalUtilities/src/Http/HttpResponseStream.cs index 5173ff7cfdc2..c63899e52ee1 100644 --- a/dotnet/src/InternalUtilities/src/Http/HttpResponseStream.cs +++ b/dotnet/src/InternalUtilities/src/Http/HttpResponseStream.cs @@ -11,10 +11,10 @@ namespace Microsoft.SemanticKernel.Http; /// [SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "This class is an internal utility.")] [ExcludeFromCodeCoverage] -internal sealed class HttpResponseStream : Stream +internal sealed class HttpResponseStream(Stream stream, HttpResponseMessage response) : Stream { - private readonly Stream _stream; - private readonly HttpResponseMessage _response; + private readonly Stream _stream = stream; + private readonly HttpResponseMessage _response = response; public override bool CanRead => this._stream.CanRead; @@ -51,12 +51,6 @@ public override void Write(byte[] buffer, int offset, int count) this._stream.Write(buffer, offset, count); } - public HttpResponseStream(Stream stream, HttpResponseMessage response) - { - this._stream = stream; - this._response = response; - } - protected override void Dispose(bool disposing) { base.Dispose(disposing); diff --git a/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.ReflectionHelpers.cs b/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.ReflectionHelpers.cs index a1ee0831c72d..29d4fba7d24d 100644 --- a/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.ReflectionHelpers.cs +++ b/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.ReflectionHelpers.cs @@ -106,7 +106,7 @@ private static bool TryGetStringEnumConverterValues(JsonTypeInfo typeInfo, JsonC { var namingPolicy = (JsonNamingPolicy?)namingPolicyField!.GetValue(converter)!; string[] names = Enum.GetNames(typeInfo.Type); - values = new JsonArray(); + values = []; foreach (string name in names) { string effectiveName = namingPolicy?.ConvertName(name) ?? name; diff --git a/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.cs b/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.cs index 116f58f84f85..dc8fac862558 100644 --- a/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.cs +++ b/dotnet/src/InternalUtilities/src/Schema/JsonSchemaMapper.cs @@ -122,10 +122,10 @@ public static JsonObject GetJsonSchema(this JsonSerializerOptions options, Metho state.Pop(); - (paramSchemas ??= new()).Add(parameter.Name, paramSchema); + (paramSchemas ??= []).Add(parameter.Name, paramSchema); if (isRequired) { - (requiredParams ??= new()).Add((JsonNode)parameter.Name); + (requiredParams ??= []).Add((JsonNode)parameter.Name); } } @@ -190,7 +190,7 @@ private static JsonObject MapJsonSchemaCore( if (!IsBuiltInConverter(effectiveConverter)) { - return new JsonObject(); // We can't make any schema determinations if a custom converter is used + return []; // We can't make any schema determinations if a custom converter is used } if (isCacheable && state.TryGetGeneratedSchemaPath(type, parentNullableOfT, customConverter, isNullableReferenceType, customNumberHandling, out string? typePath)) @@ -257,7 +257,7 @@ private static JsonObject MapJsonSchemaCore( } state.Push(AnyOfPropertyName); - anyOfTypes = new JsonArray(); + anyOfTypes = []; int i = 0; foreach (JsonDerivedType derivedType in derivedTypes) @@ -304,14 +304,14 @@ private static JsonObject MapJsonSchemaCore( } else if (numberHandling is JsonNumberHandling.AllowNamedFloatingPointLiterals) { - anyOfTypes = new JsonArray - { + anyOfTypes = + [ (JsonNode)new JsonObject { [TypePropertyName] = MapSchemaType(schemaType) }, (JsonNode)new JsonObject { [EnumPropertyName] = new JsonArray { (JsonNode)"NaN", (JsonNode)"Infinity", (JsonNode)"-Infinity" }, }, - }; + ]; schemaType = JsonSchemaType.Any; // reset the parent setting } @@ -358,8 +358,8 @@ private static JsonObject MapJsonSchemaCore( if (emitsTypeDiscriminator) { Debug.Assert(derivedTypeDiscriminator?.Value is not null); - (properties ??= new()).Add(derivedTypeDiscriminator!.Value); - (requiredProperties ??= new()).Add((JsonNode)derivedTypeDiscriminator.Value.Key); + (properties ??= []).Add(derivedTypeDiscriminator!.Value); + (requiredProperties ??= []).Add((JsonNode)derivedTypeDiscriminator.Value.Key); } Func parameterInfoMapper = ResolveJsonConstructorParameterMapper(typeInfo); @@ -429,11 +429,11 @@ private static JsonObject MapJsonSchemaCore( state.Pop(); - (properties ??= new()).Add(property.Name, propertySchema); + (properties ??= []).Add(property.Name, propertySchema); if (isRequired) { - (requiredProperties ??= new()).Add((JsonNode)property.Name); + (requiredProperties ??= []).Add((JsonNode)property.Name); } } @@ -454,8 +454,8 @@ private static JsonObject MapJsonSchemaCore( // { "properties" : { "$type" : { "const" : "discriminator" }, "$values" : { "type" : "array", "items" : { ... } } } } schemaType = JsonSchemaType.Object; - (properties ??= new()).Add(derivedTypeDiscriminator!.Value); - (requiredProperties ??= new()).Add((JsonNode)derivedTypeDiscriminator.Value.Key); + (properties ??= []).Add(derivedTypeDiscriminator!.Value); + (requiredProperties ??= []).Add((JsonNode)derivedTypeDiscriminator.Value.Key); state.Push(PropertiesPropertyName); state.Push(StjValuesMetadataProperty); @@ -492,8 +492,8 @@ private static JsonObject MapJsonSchemaCore( if (emitsTypeDiscriminator) { Debug.Assert(derivedTypeDiscriminator?.Value is not null); - (properties ??= new()).Add(derivedTypeDiscriminator!.Value); - (requiredProperties ??= new()).Add((JsonNode)derivedTypeDiscriminator.Value.Key); + (properties ??= []).Add(derivedTypeDiscriminator!.Value); + (requiredProperties ??= []).Add((JsonNode)derivedTypeDiscriminator.Value.Key); } state.Push(AdditionalPropertiesPropertyName); @@ -753,8 +753,8 @@ private enum JsonSchemaType Object = 64, } - private static readonly JsonSchemaType[] s_schemaValues = new[] - { + private static readonly JsonSchemaType[] s_schemaValues = + [ // NB the order of these values influences order of types in the rendered schema JsonSchemaType.String, JsonSchemaType.Integer, @@ -763,7 +763,7 @@ private enum JsonSchemaType JsonSchemaType.Array, JsonSchemaType.Object, JsonSchemaType.Null, - }; + ]; private static JsonNode? MapSchemaType(JsonSchemaType schemaType) { diff --git a/dotnet/src/InternalUtilities/src/Schema/Polyfills/NullabilityInfoContext.cs b/dotnet/src/InternalUtilities/src/Schema/Polyfills/NullabilityInfoContext.cs index 8a7ff516c457..f7693ce8eb3e 100644 --- a/dotnet/src/InternalUtilities/src/Schema/Polyfills/NullabilityInfoContext.cs +++ b/dotnet/src/InternalUtilities/src/Schema/Polyfills/NullabilityInfoContext.cs @@ -17,8 +17,8 @@ namespace System.Reflection internal sealed class NullabilityInfoContext { private const string CompilerServicesNameSpace = "System.Runtime.CompilerServices"; - private readonly Dictionary _publicOnlyModules = new(); - private readonly Dictionary _context = new(); + private readonly Dictionary _publicOnlyModules = []; + private readonly Dictionary _context = []; internal static bool IsSupported { get; } = AppContext.TryGetSwitch("System.Reflection.NullabilityInfoContext.IsSupported", out bool isSupported) ? isSupported : true; @@ -348,7 +348,7 @@ private NullabilityInfo GetNullabilityInfo(MemberInfo memberInfo, Type type, Nul { NullabilityState state = NullabilityState.Unknown; NullabilityInfo? elementState = null; - NullabilityInfo[] genericArgumentsState = Array.Empty(); + NullabilityInfo[] genericArgumentsState = []; Type underlyingType = type; if (underlyingType.IsByRef || underlyingType.IsPointer) diff --git a/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs b/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs index ae9efbe969b9..94785e17c762 100644 --- a/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs +++ b/dotnet/src/InternalUtilities/src/System/NonNullCollection.cs @@ -22,7 +22,7 @@ internal sealed class NonNullCollection : IList, IReadOnlyList /// /// Initializes a new instance of the class. /// - public NonNullCollection() => this._items = new(); + public NonNullCollection() => this._items = []; /// /// Initializes a new instance of the class. diff --git a/dotnet/src/InternalUtilities/src/Text/SseReader.cs b/dotnet/src/InternalUtilities/src/Text/SseReader.cs index c8506e597812..21a06d3bbb6c 100644 --- a/dotnet/src/InternalUtilities/src/Text/SseReader.cs +++ b/dotnet/src/InternalUtilities/src/Text/SseReader.cs @@ -15,18 +15,12 @@ namespace Microsoft.SemanticKernel.Text; /// SSE specification /// [ExcludeFromCodeCoverage] -internal sealed class SseReader : IDisposable +internal sealed class SseReader(Stream stream) : IDisposable { - private readonly Stream _stream; - private readonly StreamReader _reader; + private readonly Stream _stream = stream; + private readonly StreamReader _reader = new(stream); private string? _lastEventName; - public SseReader(Stream stream) - { - this._stream = stream; - this._reader = new StreamReader(stream); - } - public SseLine? ReadSingleDataEvent() { while (this.ReadLine() is { } line) diff --git a/dotnet/src/InternalUtilities/test/HttpMessageHandlerStub.cs b/dotnet/src/InternalUtilities/test/HttpMessageHandlerStub.cs index 6c6fbe761df8..d492fcd12dbb 100644 --- a/dotnet/src/InternalUtilities/test/HttpMessageHandlerStub.cs +++ b/dotnet/src/InternalUtilities/test/HttpMessageHandlerStub.cs @@ -26,8 +26,10 @@ internal sealed class HttpMessageHandlerStub : DelegatingHandler public HttpMessageHandlerStub() { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent("{}", Encoding.UTF8, MediaTypeNames.Application.Json) + }; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/dotnet/src/InternalUtilities/test/MultipleHttpMessageHandlerStub.cs b/dotnet/src/InternalUtilities/test/MultipleHttpMessageHandlerStub.cs index c3706e0211e3..f81410a8928b 100644 --- a/dotnet/src/InternalUtilities/test/MultipleHttpMessageHandlerStub.cs +++ b/dotnet/src/InternalUtilities/test/MultipleHttpMessageHandlerStub.cs @@ -15,17 +15,17 @@ internal sealed class MultipleHttpMessageHandlerStub : DelegatingHandler { private int _callIteration = 0; - public List RequestHeaders { get; private set; } = new(); + public List RequestHeaders { get; private set; } = []; - public List ContentHeaders { get; private set; } = new(); + public List ContentHeaders { get; private set; } = []; - public List RequestContents { get; private set; } = new(); + public List RequestContents { get; private set; } = []; - public List RequestUris { get; private set; } = new(); + public List RequestUris { get; private set; } = []; - public List Methods { get; private set; } = new(); + public List Methods { get; private set; } = []; - public List ResponsesToReturn { get; set; } = new(); + public List ResponsesToReturn { get; set; } = []; internal HttpClient CreateHttpClient() => new(this, false); diff --git a/dotnet/src/Planners/Planners.Core.UnitTests/Planning/PlanTests.cs b/dotnet/src/Planners/Planners.Core.UnitTests/Planning/PlanTests.cs index bbbb264263fc..176683726c1c 100644 --- a/dotnet/src/Planners/Planners.Core.UnitTests/Planning/PlanTests.cs +++ b/dotnet/src/Planners/Planners.Core.UnitTests/Planning/PlanTests.cs @@ -699,7 +699,7 @@ public async Task CanExecutePlanWithExpandedAsync() var planStep = new Plan(function); planStep.Parameters.Set("input", "Function input."); - planStep.Parameters.Set("payload", @"{""prop"":""value"", ""$prop"": 3, ""prop2"": ""my name is $pop and $var""}"); + planStep.Parameters.Set("payload", """{"prop":"value", "$prop": 3, "prop2": "my name is $pop and $var"}"""); plan.AddSteps(planStep); plan.State.Set("var", "foobar"); diff --git a/dotnet/src/Planners/Planners.Core.UnitTests/Sequential/SequentialPlanParserTests.cs b/dotnet/src/Planners/Planners.Core.UnitTests/Sequential/SequentialPlanParserTests.cs index c1208eac4051..c36e7b912fa6 100644 --- a/dotnet/src/Planners/Planners.Core.UnitTests/Sequential/SequentialPlanParserTests.cs +++ b/dotnet/src/Planners/Planners.Core.UnitTests/Sequential/SequentialPlanParserTests.cs @@ -281,7 +281,7 @@ public void CanCreatePlanWithOtherText(string goalText, string planText) } [Theory] - [InlineData(@" ")] + [InlineData(""" """)] [InlineData("\n \n")] [InlineData("\n \n")] public void CanCreatePlanWithOpenApiPlugin(string planText) diff --git a/dotnet/src/Planners/Planners.Core/Action/ActionPlanner.cs b/dotnet/src/Planners/Planners.Core/Action/ActionPlanner.cs index 63028013ecf0..88834246d77e 100644 --- a/dotnet/src/Planners/Planners.Core/Action/ActionPlanner.cs +++ b/dotnet/src/Planners/Planners.Core/Action/ActionPlanner.cs @@ -310,7 +310,7 @@ private void PopulateList(StringBuilder list, IEnumerable TryGetActionObservationAsync(SystemStep step) step.Action, JsonSerializer.Serialize(step.ActionVariables)); // add [thought and] action to chat history - var actionMessage = $"{Action} {{\"action\": \"{step.Action}\",\"action_variables\": {JsonSerializer.Serialize(step.ActionVariables)}}}"; + var actionMessage = $$"""{{Action}} {"action": "{{step.Action}}","action_variables": {{JsonSerializer.Serialize(step.ActionVariables)}}}"""; var message = string.IsNullOrEmpty(step.Thought) ? actionMessage : $"{Thought} {step.Thought}\n{actionMessage}"; chatHistory.AddAssistantMessage(message); diff --git a/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/HandlebarsPlannerTests.cs b/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/HandlebarsPlannerTests.cs index 4abdaecbaacc..813a8269f653 100644 --- a/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/HandlebarsPlannerTests.cs +++ b/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/HandlebarsPlannerTests.cs @@ -230,20 +230,20 @@ public async Task ItThrowsIfStrictlyOnePlanCantBeIdentifiedAsync() private Kernel CreateKernelWithMockCompletionResult(string testPlanString, KernelPluginCollection? plugins = null) { - plugins ??= new KernelPluginCollection(); + plugins ??= []; var chatMessage = new ChatMessageContent(AuthorRole.Assistant, testPlanString); var chatCompletion = new Mock(); chatCompletion .Setup(cc => cc.GetChatMessageContentsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) - .ReturnsAsync(new List { chatMessage }); + .ReturnsAsync([chatMessage]); var serviceSelector = new Mock(); IChatCompletionService resultService = chatCompletion.Object; - PromptExecutionSettings resultSettings = new(); + PromptExecutionSettings? resultSettings = new(); serviceSelector - .Setup(ss => ss.TrySelectAIService(It.IsAny(), It.IsAny(), It.IsAny(), out resultService!, out resultSettings!)) + .Setup(ss => ss.TrySelectAIService(It.IsAny(), It.IsAny(), It.IsAny(), out resultService!, out resultSettings)) .Returns(true); var serviceCollection = new ServiceCollection(); @@ -253,23 +253,20 @@ private Kernel CreateKernelWithMockCompletionResult(string testPlanString, Kerne return new Kernel(serviceCollection.BuildServiceProvider(), plugins); } - private KernelPluginCollection CreatePluginCollection() - { - return new() - { - KernelPluginFactory.CreateFromFunctions("email", "Email functions", new[] - { + private KernelPluginCollection CreatePluginCollection() => + [ + KernelPluginFactory.CreateFromFunctions("email", "Email functions", + [ KernelFunctionFactory.CreateFromMethod(() => "MOCK FUNCTION CALLED", "SendEmail", "Send an e-mail"), KernelFunctionFactory.CreateFromMethod(() => "MOCK FUNCTION CALLED", "GetEmailAddress", "Get an e-mail address") - }), - KernelPluginFactory.CreateFromFunctions("WriterPlugin", "Writer functions", new[] - { + ]), + KernelPluginFactory.CreateFromFunctions("WriterPlugin", "Writer functions", + [ KernelFunctionFactory.CreateFromMethod(() => "MOCK FUNCTION CALLED", "Translate", "Translate something"), - }), - KernelPluginFactory.CreateFromFunctions("SummarizePlugin", "Summarize functions", new[] - { + ]), + KernelPluginFactory.CreateFromFunctions("SummarizePlugin", "Summarize functions", + [ KernelFunctionFactory.CreateFromMethod(() => "MOCK FUNCTION CALLED", "Summarize", "Summarize something"), - }) - }; - } + ]) + ]; } diff --git a/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/KernelParameterMetadataExtensionsTests.cs b/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/KernelParameterMetadataExtensionsTests.cs index fdd99f73801f..b5386e0ac1dc 100644 --- a/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/KernelParameterMetadataExtensionsTests.cs +++ b/dotnet/src/Planners/Planners.Handlebars.UnitTests/Handlebars/KernelParameterMetadataExtensionsTests.cs @@ -213,7 +213,7 @@ public void ReturnsParameterWithParameterTypeForPrimitiveOrStringSchemaType() foreach (var pair in schemaTypeMap) { - var schema = KernelJsonSchema.Parse($"{{\"type\": \"{pair.Key}\"}}"); + var schema = KernelJsonSchema.Parse($$"""{"type": "{{pair.Key}}"}"""); var parameter = new KernelParameterMetadata("test") { Schema = schema }; // Act @@ -228,7 +228,7 @@ public void ReturnsParameterWithParameterTypeForPrimitiveOrStringSchemaType() public void ReturnsParameterWithSchemaForNonPrimitiveOrStringSchemaType() { // Arrange - var schema = KernelJsonSchema.Parse("{\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}}}"); + var schema = KernelJsonSchema.Parse("""{"type": "object", "properties": {"name": {"type": "string"}}}"""); var parameter = new KernelParameterMetadata("test") { Schema = schema }; // Act @@ -243,7 +243,7 @@ public void ReturnsParameterWithSchemaForNonPrimitiveOrStringSchemaType() public void ReturnsIndentedJsonStringForJsonElement() { // Arrange - var jsonProperties = KernelJsonSchema.Parse("{\"name\": \"Alice\", \"age\": 25}").RootElement; + var jsonProperties = KernelJsonSchema.Parse("""{"name": "Alice", "age": 25}""").RootElement; // Act var result = jsonProperties.ToJsonString(); @@ -260,7 +260,7 @@ public void ReturnsIndentedJsonStringForJsonElement() public void ReturnsParameterNameAndSchemaType() { // Arrange - var schema = KernelJsonSchema.Parse("{\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}}}"); + var schema = KernelJsonSchema.Parse("""{"type": "object", "properties": {"name": {"type": "string"}}}"""); var parameter = new KernelParameterMetadata("test") { Schema = schema }; // Act @@ -274,7 +274,7 @@ public void ReturnsParameterNameAndSchemaType() public void ConvertsReturnParameterMetadataToParameterMetadata() { // Arrange - var schema = KernelJsonSchema.Parse("{\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}}}"); + var schema = KernelJsonSchema.Parse("""{"type": "object", "properties": {"name": {"type": "string"}}}"""); var returnParameter = new KernelReturnParameterMetadata() { Description = "test", ParameterType = typeof(object), Schema = schema }; // Act @@ -292,7 +292,7 @@ public void ConvertsReturnParameterMetadataToParameterMetadata() public void ConvertsParameterMetadataToReturnParameterMetadata() { // Arrange - var schema = KernelJsonSchema.Parse("{\"type\": \"object\", \"properties\": {\"name\": {\"type\": \"string\"}}}"); + var schema = KernelJsonSchema.Parse("""{"type": "object", "properties": {"name": {"type": "string"}}}"""); var parameter = new KernelParameterMetadata("test") { Description = "test", ParameterType = typeof(object), Schema = schema }; // Act diff --git a/dotnet/src/Planners/Planners.Handlebars/Handlebars/Extensions/KernelParameterMetadataExtensions.cs b/dotnet/src/Planners/Planners.Handlebars/Handlebars/Extensions/KernelParameterMetadataExtensions.cs index 05d25f9674aa..a50380716421 100644 --- a/dotnet/src/Planners/Planners.Handlebars/Handlebars/Extensions/KernelParameterMetadataExtensions.cs +++ b/dotnet/src/Planners/Planners.Handlebars/Handlebars/Extensions/KernelParameterMetadataExtensions.cs @@ -20,7 +20,7 @@ internal static class KernelParameterMetadataExtensions /// Checks if stringified type is primitive or string /// public static bool IsPrimitiveOrStringType(string type) => - type == "string" || type == "number" || type == "integer" || type == "boolean"; + type is "string" or "number" or "integer" or "boolean"; /// /// Converts non-primitive types to a data class definition and returns a hash set of complex type metadata. @@ -35,7 +35,7 @@ public static bool IsPrimitiveOrStringType(string type) => /// public static HashSet ToHandlebarsParameterTypeMetadata(this Type type) { - return type.ToHandlebarsParameterTypeMetadata(new HashSet()); + return type.ToHandlebarsParameterTypeMetadata([]); } private static HashSet ToHandlebarsParameterTypeMetadata(this Type type, HashSet processedTypes) diff --git a/dotnet/src/Planners/Planners.Handlebars/Handlebars/HandlebarsPlanner.cs b/dotnet/src/Planners/Planners.Handlebars/Handlebars/HandlebarsPlanner.cs index 742bc9e615de..97bdaf43579c 100644 --- a/dotnet/src/Planners/Planners.Handlebars/Handlebars/HandlebarsPlanner.cs +++ b/dotnet/src/Planners/Planners.Handlebars/Handlebars/HandlebarsPlanner.cs @@ -27,7 +27,7 @@ public sealed class HandlebarsPlanner public static readonly HandlebarsPromptTemplateOptions PromptTemplateOptions = new() { // Options for built-in Handlebars helpers - Categories = new Category[] { Category.DateTime }, + Categories = [Category.DateTime], UseCategoryPrefix = false, // Custom helpers @@ -124,8 +124,8 @@ private List GetAvailableFunctionsManual( out HashSet complexParameterTypes, out Dictionary complexParameterSchemas) { - complexParameterTypes = new(); - complexParameterSchemas = new(); + complexParameterTypes = []; + complexParameterSchemas = []; var functionsMetadata = new List(); foreach (var kernelFunction in availableFunctions) diff --git a/dotnet/src/Planners/Planners.Handlebars/Handlebars/Models/HandlebarsParameterTypeMetadata.cs b/dotnet/src/Planners/Planners.Handlebars/Handlebars/Models/HandlebarsParameterTypeMetadata.cs index 2d845360738b..eb7a656c3da0 100644 --- a/dotnet/src/Planners/Planners.Handlebars/Handlebars/Models/HandlebarsParameterTypeMetadata.cs +++ b/dotnet/src/Planners/Planners.Handlebars/Handlebars/Models/HandlebarsParameterTypeMetadata.cs @@ -18,7 +18,7 @@ internal sealed class HandlebarsParameterTypeMetadata /// If this is a complex type, this will contain the properties of the complex type. /// [JsonPropertyName("properties")] - public List Properties { get; set; } = new(); + public List Properties { get; set; } = []; // Override the Equals method to compare the property values public override bool Equals(object obj) diff --git a/dotnet/src/Planners/Planners.OpenAI/Utils/EmbeddedResource.cs b/dotnet/src/Planners/Planners.OpenAI/Utils/EmbeddedResource.cs index c887f5e35470..8395297d301a 100644 --- a/dotnet/src/Planners/Planners.OpenAI/Utils/EmbeddedResource.cs +++ b/dotnet/src/Planners/Planners.OpenAI/Utils/EmbeddedResource.cs @@ -11,11 +11,11 @@ internal static class EmbeddedResource internal static string Read(string name) { - var assembly = typeof(EmbeddedResource).GetTypeInfo().Assembly; - if (assembly == null) { throw new FileNotFoundException($"[{s_namespace}] {name} assembly not found"); } + var assembly = typeof(EmbeddedResource).GetTypeInfo().Assembly ?? + throw new FileNotFoundException($"[{s_namespace}] {name} assembly not found"); - using Stream? resource = assembly.GetManifestResourceStream($"{s_namespace}." + name); - if (resource == null) { throw new FileNotFoundException($"[{s_namespace}] {name} resource not found"); } + using Stream? resource = assembly.GetManifestResourceStream($"{s_namespace}." + name) ?? + throw new FileNotFoundException($"[{s_namespace}] {name} resource not found"); using var reader = new StreamReader(resource); return reader.ReadToEnd(); diff --git a/dotnet/src/Plugins/Plugins.Document/OpenXml/Extensions/WordprocessingDocumentEx.cs b/dotnet/src/Plugins/Plugins.Document/OpenXml/Extensions/WordprocessingDocumentEx.cs index 0097bac47a4f..0ca5df544fed 100644 --- a/dotnet/src/Plugins/Plugins.Document/OpenXml/Extensions/WordprocessingDocumentEx.cs +++ b/dotnet/src/Plugins/Plugins.Document/OpenXml/Extensions/WordprocessingDocumentEx.cs @@ -27,17 +27,8 @@ internal static string ReadText(this WordprocessingDocument wordprocessingDocume { StringBuilder sb = new(); - var mainPart = wordprocessingDocument.MainDocumentPart; - if (mainPart is null) - { - throw new InvalidOperationException("The main document part is missing."); - } - - var body = mainPart.Document.Body; - if (body is null) - { - throw new InvalidOperationException("The document body is missing."); - } + var mainPart = wordprocessingDocument.MainDocumentPart ?? throw new InvalidOperationException("The main document part is missing."); + var body = mainPart.Document.Body ?? throw new InvalidOperationException("The document body is missing."); var paras = body.Descendants(); if (paras != null) @@ -58,17 +49,8 @@ internal static void AppendText(this WordprocessingDocument wordprocessingDocume throw new ArgumentNullException(nameof(text)); } - MainDocumentPart? mainPart = wordprocessingDocument.MainDocumentPart; - if (mainPart is null) - { - throw new InvalidOperationException("The main document part is missing."); - } - - Body? body = mainPart.Document.Body; - if (body is null) - { - throw new InvalidOperationException("The document body is missing."); - } + MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart ?? throw new InvalidOperationException("The main document part is missing."); + Body body = mainPart.Document.Body ?? throw new InvalidOperationException("The document body is missing."); Paragraph para = body.AppendChild(new Paragraph()); Run run = para.AppendChild(new Run()); diff --git a/dotnet/src/Plugins/Plugins.Memory/Collections/MinHeap.cs b/dotnet/src/Plugins/Plugins.Memory/Collections/MinHeap.cs index cf711e13c93d..b4f0efe67345 100644 --- a/dotnet/src/Plugins/Plugins.Memory/Collections/MinHeap.cs +++ b/dotnet/src/Plugins/Plugins.Memory/Collections/MinHeap.cs @@ -15,7 +15,7 @@ internal sealed class MinHeap : IEnumerable where T : IComparable private const int DefaultCapacity = 7; private const int MinCapacity = 0; - private static readonly T[] s_emptyBuffer = Array.Empty(); + private static readonly T[] s_emptyBuffer = []; private T[] _items; private int _count; diff --git a/dotnet/src/Plugins/Plugins.MsGraph/CalendarPlugin.cs b/dotnet/src/Plugins/Plugins.MsGraph/CalendarPlugin.cs index 78d424d9690d..9b62a1f3cd5c 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/CalendarPlugin.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/CalendarPlugin.cs @@ -27,7 +27,7 @@ public sealed class CalendarPlugin WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; - private static readonly char[] s_separator = { ',', ';' }; + private static readonly char[] s_separator = [',', ';']; /// /// Initializes a new instance of the class. diff --git a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphClientLoggingHandler.cs b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphClientLoggingHandler.cs index 9efe68358de4..c71733176f6f 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphClientLoggingHandler.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphClientLoggingHandler.cs @@ -24,13 +24,13 @@ public class MsGraphClientLoggingHandler : DelegatingHandler /// private const string ClientRequestIdHeaderName = "client-request-id"; - private readonly List _headerNamesToLog = new() - { + private readonly List _headerNamesToLog = + [ ClientRequestIdHeaderName, "request-id", "x-ms-ags-diagnostic", "Date" - }; + ]; private readonly ILogger _logger; diff --git a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphConfiguration.cs b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphConfiguration.cs index 6a8e3e593b2a..69ee1f0c82d0 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphConfiguration.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/Client/MsGraphConfiguration.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Linq; namespace Microsoft.SemanticKernel.Plugins.MsGraph.Connectors.Client; @@ -30,7 +29,7 @@ public class MsGraphConfiguration /// nested types not working with IConfigurationSection.Get. /// See https://github.com/dotnet/runtime/issues/77677 /// - public IEnumerable Scopes { get; set; } = Enumerable.Empty(); + public IEnumerable Scopes { get; set; } = []; /// /// Gets or sets the redirect URI to use. diff --git a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/MicrosoftToDoConnector.cs b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/MicrosoftToDoConnector.cs index 1c37d98dab7f..6053dfdec84e 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/Connectors/MicrosoftToDoConnector.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/Connectors/MicrosoftToDoConnector.cs @@ -62,7 +62,7 @@ public async Task> GetTaskListsAsync(Cancell .Todo.Lists .Request().GetAsync(cancellationToken).ConfigureAwait(false); - List taskLists = lists.ToList(); + List taskLists = [.. lists]; while (lists.Count != 0 && lists.NextPageRequest != null) { @@ -90,7 +90,7 @@ public async Task> GetTasksAsync(string listId, .Todo.Lists[listId] .Tasks.Request().Filter(filterValue).GetAsync(cancellationToken).ConfigureAwait(false); - List tasks = tasksPage.ToList(); + List tasks = [.. tasksPage]; while (tasksPage.Count != 0 && tasksPage.NextPageRequest != null) { diff --git a/dotnet/src/Plugins/Plugins.MsGraph/EmailPlugin.cs b/dotnet/src/Plugins/Plugins.MsGraph/EmailPlugin.cs index 4e502ae51278..d4aefd72d64b 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/EmailPlugin.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/EmailPlugin.cs @@ -26,7 +26,7 @@ public sealed class EmailPlugin WriteIndented = false, DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, }; - private static readonly char[] s_separator = { ',', ';' }; + private static readonly char[] s_separator = [',', ';']; /// /// Initializes a new instance of the class. diff --git a/dotnet/src/Plugins/Plugins.MsGraph/Models/CalendarEvent.cs b/dotnet/src/Plugins/Plugins.MsGraph/Models/CalendarEvent.cs index 935aec562780..ebe98274ebed 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/Models/CalendarEvent.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/Models/CalendarEvent.cs @@ -2,7 +2,6 @@ using System; using System.Collections.Generic; -using System.Linq; namespace Microsoft.SemanticKernel.Plugins.MsGraph.Models; @@ -39,5 +38,5 @@ public class CalendarEvent /// /// Attendees of the event. /// - public IEnumerable? Attendees { get; set; } = Enumerable.Empty(); + public IEnumerable? Attendees { get; set; } = []; } diff --git a/dotnet/src/Plugins/Plugins.MsGraph/TaskListPlugin.cs b/dotnet/src/Plugins/Plugins.MsGraph/TaskListPlugin.cs index 3a548ae80fca..6c0649721090 100644 --- a/dotnet/src/Plugins/Plugins.MsGraph/TaskListPlugin.cs +++ b/dotnet/src/Plugins/Plugins.MsGraph/TaskListPlugin.cs @@ -61,11 +61,8 @@ public async Task AddTaskAsync( [Description("Reminder for the task in DateTimeOffset (optional)")] string? reminder = null, CancellationToken cancellationToken = default) { - TaskManagementTaskList? defaultTaskList = await this._connector.GetDefaultTaskListAsync(cancellationToken).ConfigureAwait(false); - if (defaultTaskList == null) - { + TaskManagementTaskList defaultTaskList = await this._connector.GetDefaultTaskListAsync(cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("No default task list found."); - } TaskManagementTask task = new( id: Guid.NewGuid().ToString(), @@ -86,11 +83,8 @@ public async Task GetDefaultTasksAsync( [Description("Whether to include completed tasks (optional)")] string includeCompleted = "false", CancellationToken cancellationToken = default) { - TaskManagementTaskList? defaultTaskList = await this._connector.GetDefaultTaskListAsync(cancellationToken).ConfigureAwait(false); - if (defaultTaskList == null) - { + TaskManagementTaskList defaultTaskList = await this._connector.GetDefaultTaskListAsync(cancellationToken).ConfigureAwait(false) ?? throw new InvalidOperationException("No default task list found."); - } if (!bool.TryParse(includeCompleted, out bool includeCompletedValue)) { diff --git a/dotnet/src/Plugins/Plugins.UnitTests/Memory/VolatileMemoryStoreTests.cs b/dotnet/src/Plugins/Plugins.UnitTests/Memory/VolatileMemoryStoreTests.cs index 0c50a7add840..d087cc49774e 100644 --- a/dotnet/src/Plugins/Plugins.UnitTests/Memory/VolatileMemoryStoreTests.cs +++ b/dotnet/src/Plugins/Plugins.UnitTests/Memory/VolatileMemoryStoreTests.cs @@ -251,7 +251,7 @@ public async Task RemovingNonExistingRecordDoesNothingAsync() public async Task ItCanListAllDatabaseCollectionsAsync() { // Arrange - string[] testCollections = { "test_collection5", "test_collection6", "test_collection7" }; + string[] testCollections = ["test_collection5", "test_collection6", "test_collection7"]; this._collectionNum += 3; await this._db.CreateCollectionAsync(testCollections[0]); await this._db.CreateCollectionAsync(testCollections[1]); @@ -539,7 +539,7 @@ public async Task ItCanBatchRemoveRecordsAsync() await this._db.CreateCollectionAsync(collection); IEnumerable records = this.CreateBatchRecords(numRecords); - List keys = new(); + List keys = []; await foreach (var key in this._db.UpsertBatchAsync(collection, records)) { keys.Add(key); @@ -573,7 +573,7 @@ public async Task CollectionsCanBeDeletedAsync() // Assert collections = this._db.GetCollectionsAsync().ToEnumerable(); numCollections = collections.Count(); - Assert.True(numCollections == 0); + Assert.Equal(0, numCollections); this._collectionNum = 0; } #pragma warning restore CA1851 // Possible multiple enumerations of 'IEnumerable' collection diff --git a/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/CalendarPluginTests.cs b/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/CalendarPluginTests.cs index 05e31967b40d..d9f16493ec68 100644 --- a/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/CalendarPluginTests.cs +++ b/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/CalendarPluginTests.cs @@ -22,7 +22,7 @@ public async Task AddEventAsyncSucceedsAsync() string anyLocation = Guid.NewGuid().ToString(); DateTimeOffset anyStartTime = DateTimeOffset.Now + TimeSpan.FromDays(1); DateTimeOffset anyEndTime = DateTimeOffset.Now + TimeSpan.FromDays(1.1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; CalendarEvent expected = new() { @@ -60,7 +60,7 @@ public async Task AddEventAsyncWithoutLocationSucceedsAsync() string anySubject = Guid.NewGuid().ToString(); DateTimeOffset anyStartTime = DateTimeOffset.Now + TimeSpan.FromDays(1); DateTimeOffset anyEndTime = DateTimeOffset.Now + TimeSpan.FromDays(1.1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; CalendarEvent expected = new() { @@ -99,7 +99,7 @@ public async Task AddEventAsyncWithoutContentSucceedsAsync() string anyLocation = Guid.NewGuid().ToString(); DateTimeOffset anyStartTime = DateTimeOffset.Now + TimeSpan.FromDays(1); DateTimeOffset anyEndTime = DateTimeOffset.Now + TimeSpan.FromDays(1.1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; CalendarEvent expected = new() { @@ -177,7 +177,7 @@ public async Task AddEventAsyncWithoutStartFailsAsync() string anySubject = Guid.NewGuid().ToString(); string anyLocation = Guid.NewGuid().ToString(); DateTimeOffset anyEndTime = DateTimeOffset.Now + TimeSpan.FromDays(1.1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; Mock connectorMock = new(); @@ -202,7 +202,7 @@ public async Task AddEventAsyncWithoutEndFailsAsync() string anySubject = Guid.NewGuid().ToString(); string anyLocation = Guid.NewGuid().ToString(); DateTimeOffset anyStartTime = DateTimeOffset.Now + TimeSpan.FromDays(1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; Mock connectorMock = new(); @@ -227,7 +227,7 @@ public async Task AddEventAsyncWithoutSubjectFailsAsync() string anyLocation = Guid.NewGuid().ToString(); DateTimeOffset anyStartTime = DateTimeOffset.Now + TimeSpan.FromDays(1); DateTimeOffset anyEndTime = DateTimeOffset.Now + TimeSpan.FromDays(1.1); - string[] anyAttendees = new[] { Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyAttendees = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; Mock connectorMock = new(); diff --git a/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/OrganizationHierarchyPluginTests.cs b/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/OrganizationHierarchyPluginTests.cs index 9f90a5b9079c..eeaa18446803 100644 --- a/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/OrganizationHierarchyPluginTests.cs +++ b/dotnet/src/Plugins/Plugins.UnitTests/MsGraph/OrganizationHierarchyPluginTests.cs @@ -17,7 +17,7 @@ public class OrganizationHierarchyPluginTests public async Task GetMyDirectReportsEmailAsyncSucceedsAsync() { // Arrange - string[] anyDirectReportsEmail = { Guid.NewGuid().ToString(), Guid.NewGuid().ToString() }; + string[] anyDirectReportsEmail = [Guid.NewGuid().ToString(), Guid.NewGuid().ToString()]; Mock connectorMock = new(); connectorMock.Setup(c => c.GetDirectReportsEmailAsync(It.IsAny())).ReturnsAsync(anyDirectReportsEmail); OrganizationHierarchyPlugin target = new(connectorMock.Object); diff --git a/dotnet/src/Plugins/Plugins.UnitTests/Web/WebSearchEngineSkillTests.cs b/dotnet/src/Plugins/Plugins.UnitTests/Web/WebSearchEngineSkillTests.cs index 5f740a7ca556..852e20ce8f05 100644 --- a/dotnet/src/Plugins/Plugins.UnitTests/Web/WebSearchEngineSkillTests.cs +++ b/dotnet/src/Plugins/Plugins.UnitTests/Web/WebSearchEngineSkillTests.cs @@ -16,7 +16,7 @@ public sealed class WebSearchEnginePluginTests public async Task SearchAsyncSucceedsAsync() { // Arrange - IEnumerable expected = new[] { Guid.NewGuid().ToString() }; + IEnumerable expected = [Guid.NewGuid().ToString()]; Mock connectorMock = new(); connectorMock.Setup(c => c.SearchAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) @@ -37,7 +37,7 @@ public async Task SearchAsyncSucceedsAsync() public async Task GetSearchResultsSucceedsAsync() { // Arrange - IEnumerable expected = new List(); + IEnumerable expected = []; Mock connectorMock = new(); connectorMock.Setup(c => c.SearchAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())) diff --git a/dotnet/src/Plugins/Plugins.Web/Bing/BingConnector.cs b/dotnet/src/Plugins/Plugins.Web/Bing/BingConnector.cs index 8fa1ca1378b4..89119d99a0b6 100644 --- a/dotnet/src/Plugins/Plugins.Web/Bing/BingConnector.cs +++ b/dotnet/src/Plugins/Plugins.Web/Bing/BingConnector.cs @@ -77,7 +77,7 @@ public async Task> SearchAsync(string query, int count = 1, in WebSearchResponse? data = JsonSerializer.Deserialize(json); - List? returnValues = new(); + List? returnValues = []; if (data?.WebPages?.Value != null) { if (typeof(T) == typeof(string)) @@ -87,13 +87,7 @@ public async Task> SearchAsync(string query, int count = 1, in } else if (typeof(T) == typeof(WebPage)) { - List? webPages = new(); - - foreach (var webPage in data.WebPages.Value) - - { - webPages.Add(webPage); - } + List? webPages = [.. data.WebPages.Value]; returnValues = webPages.Take(count).ToList() as List; } else diff --git a/dotnet/src/Plugins/Plugins.Web/Google/GoogleConnector.cs b/dotnet/src/Plugins/Plugins.Web/Google/GoogleConnector.cs index 6cfcde2a4634..3c1e5739d02e 100644 --- a/dotnet/src/Plugins/Plugins.Web/Google/GoogleConnector.cs +++ b/dotnet/src/Plugins/Plugins.Web/Google/GoogleConnector.cs @@ -80,7 +80,7 @@ public async Task> SearchAsync( var results = await search.ExecuteAsync(cancellationToken).ConfigureAwait(false); - List? returnValues = new(); + List? returnValues = []; if (results.Items != null) { if (typeof(T) == typeof(string)) @@ -89,7 +89,7 @@ public async Task> SearchAsync( } else if (typeof(T) == typeof(WebPage)) { - List webPages = new(); + List webPages = []; foreach (var item in results.Items) { WebPage webPage = new() diff --git a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatHistory.cs b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatHistory.cs index e15d46965de7..fda7be0d0c8c 100644 --- a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatHistory.cs +++ b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatHistory.cs @@ -24,7 +24,7 @@ public class ChatHistory : IList, IReadOnlyList public ChatHistory() { - this._messages = new(); + this._messages = []; } /// @@ -35,7 +35,7 @@ public ChatHistory(string systemMessage) { Verify.NotNullOrWhiteSpace(systemMessage); - this._messages = new(); + this._messages = []; this.AddSystemMessage(systemMessage); } diff --git a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatMessageContentItemCollection.cs b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatMessageContentItemCollection.cs index e8f990fc3a57..82937601b7bc 100644 --- a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatMessageContentItemCollection.cs +++ b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatMessageContentItemCollection.cs @@ -18,7 +18,7 @@ public class ChatMessageContentItemCollection : IList, IReadOnlyL /// public ChatMessageContentItemCollection() { - this._items = new(); + this._items = []; } /// diff --git a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatPromptParser.cs b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatPromptParser.cs index dae1b777d03d..269b07de7967 100644 --- a/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatPromptParser.cs +++ b/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/ChatPromptParser.cs @@ -53,7 +53,7 @@ private static bool TryParse(List nodes, [NotNullWhen(true)] out Cha foreach (var node in nodes.Where(IsValidChatMessage)) { - (chatHistory ??= new()).Add(ParseChatNode(node)); + (chatHistory ??= []).Add(ParseChatNode(node)); } return chatHistory is not null; @@ -66,7 +66,7 @@ private static bool TryParse(List nodes, [NotNullWhen(true)] out Cha /// object. private static ChatMessageContent ParseChatNode(PromptNode node) { - ChatMessageContentItemCollection items = new(); + ChatMessageContentItemCollection items = []; foreach (var childNode in node.ChildNodes.Where(childNode => childNode.Content is not null)) { if (childNode.TagName.Equals(ImageTagName, StringComparison.OrdinalIgnoreCase)) diff --git a/dotnet/src/SemanticKernel.Abstractions/AI/Embeddings/EmbeddingGenerationServiceExtensions.cs b/dotnet/src/SemanticKernel.Abstractions/AI/Embeddings/EmbeddingGenerationServiceExtensions.cs index a674e1f6eb2c..c09e9a79463d 100644 --- a/dotnet/src/SemanticKernel.Abstractions/AI/Embeddings/EmbeddingGenerationServiceExtensions.cs +++ b/dotnet/src/SemanticKernel.Abstractions/AI/Embeddings/EmbeddingGenerationServiceExtensions.cs @@ -33,6 +33,6 @@ public static async Task> GenerateEmbeddingAsync public Dictionary Attributes { - get => this._attributes ??= new(); + get => this._attributes ??= []; set => this._attributes = value; } @@ -36,7 +36,7 @@ public Dictionary Attributes /// public List ChildNodes { - get => this._childNodes ??= new(); + get => this._childNodes ??= []; set => this._childNodes = value; } diff --git a/dotnet/src/SemanticKernel.Abstractions/AI/XmlPromptParser.cs b/dotnet/src/SemanticKernel.Abstractions/AI/XmlPromptParser.cs index 4ee204b8a39d..ba0a2df3a004 100644 --- a/dotnet/src/SemanticKernel.Abstractions/AI/XmlPromptParser.cs +++ b/dotnet/src/SemanticKernel.Abstractions/AI/XmlPromptParser.cs @@ -51,7 +51,7 @@ public static bool TryParse(string prompt, [NotNullWhen(true)] out List public ChatMessageContentItemCollection Items { - get => this._items ??= new ChatMessageContentItemCollection(); + get => this._items ??= []; set => this._items = value; } diff --git a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunction.cs b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunction.cs index 2eb2535d58a3..80074898f647 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunction.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunction.cs @@ -157,7 +157,7 @@ public async Task InvokeAsync( ILogger logger = kernel.LoggerFactory.CreateLogger(this.Name) ?? NullLogger.Instance; // Ensure arguments are initialized. - arguments ??= new KernelArguments(); + arguments ??= []; logger.LogFunctionInvoking(this.Name); logger.LogFunctionArguments(arguments); @@ -299,7 +299,7 @@ public async IAsyncEnumerable InvokeStreamingAsync( using var activity = s_activitySource.StartActivity(this.Name); ILogger logger = kernel.LoggerFactory.CreateLogger(this.Name) ?? NullLogger.Instance; - arguments ??= new KernelArguments(); + arguments ??= []; logger.LogFunctionStreamingInvoking(this.Name); logger.LogFunctionArguments(arguments); diff --git a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunctionMetadata.cs b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunctionMetadata.cs index 7f6d3796217d..069a29d5b037 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunctionMetadata.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelFunctionMetadata.cs @@ -16,7 +16,7 @@ public sealed class KernelFunctionMetadata /// The description of the function. private string _description = string.Empty; /// The function's parameters. - private IReadOnlyList _parameters = Array.Empty(); + private IReadOnlyList _parameters = []; /// The function's return parameter. private KernelReturnParameterMetadata? _returnParameter; diff --git a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs index ee467cadad98..9ba7e2db8d75 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs @@ -96,16 +96,14 @@ public IList GetFunctionsMetadata() IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator(); /// Debugger type proxy for the kernel plugin. - private sealed class TypeProxy + private sealed class TypeProxy(KernelPlugin plugin) { - private readonly KernelPlugin _plugin; - - public TypeProxy(KernelPlugin plugin) => this._plugin = plugin; + private readonly KernelPlugin _plugin = plugin; public string Name => this._plugin.Name; public string Description => this._plugin.Description; - public KernelFunction[] Functions => this._plugin.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase).ToArray(); + public KernelFunction[] Functions => [.. this._plugin.OrderBy(f => f.Name, StringComparer.OrdinalIgnoreCase)]; } } diff --git a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginCollection.cs b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginCollection.cs index a1671a99cbd8..5928e6fd3ab7 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginCollection.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginCollection.cs @@ -5,7 +5,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Linq; #pragma warning disable RCS1168 // Parameter name differs from base name. #pragma warning disable CA1725 // Parameter names should match base declaration @@ -148,6 +147,6 @@ private sealed class TypeProxy public TypeProxy(KernelPluginCollection collection) => this._collection = collection; [DebuggerBrowsable(DebuggerBrowsableState.RootHidden)] - public KernelPlugin[] Plugins => this._collection._plugins.Values.ToArray(); + public KernelPlugin[] Plugins => [.. this._collection._plugins.Values]; } } diff --git a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginExtensions.cs b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginExtensions.cs index e334e4d00fe7..a997420db824 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginExtensions.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPluginExtensions.cs @@ -83,7 +83,7 @@ public static IList GetFunctionsMetadata(this IEnumerabl { Verify.NotNull(plugins); - List metadata = new(); + List metadata = []; foreach (KernelPlugin plugin in plugins) { metadata.AddRange(plugin.GetFunctionsMetadata()); diff --git a/dotnet/src/SemanticKernel.Abstractions/Kernel.cs b/dotnet/src/SemanticKernel.Abstractions/Kernel.cs index 54b4df1361cc..e942b1004ca7 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Kernel.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Kernel.cs @@ -134,7 +134,7 @@ public Kernel Clone() => /// public KernelPluginCollection Plugins => this._plugins ?? - Interlocked.CompareExchange(ref this._plugins, new KernelPluginCollection(), null) ?? + Interlocked.CompareExchange(ref this._plugins, [], null) ?? this._plugins; /// @@ -143,7 +143,7 @@ public Kernel Clone() => [Experimental("SKEXP0001")] public IList FunctionFilters => this._functionFilters ?? - Interlocked.CompareExchange(ref this._functionFilters, new NonNullCollection(), null) ?? + Interlocked.CompareExchange(ref this._functionFilters, [], null) ?? this._functionFilters; /// @@ -152,7 +152,7 @@ public Kernel Clone() => [Experimental("SKEXP0001")] public IList PromptFilters => this._promptFilters ?? - Interlocked.CompareExchange(ref this._promptFilters, new NonNullCollection(), null) ?? + Interlocked.CompareExchange(ref this._promptFilters, [], null) ?? this._promptFilters; /// @@ -202,7 +202,7 @@ public CultureInfo Culture /// public IDictionary Data => this._data ?? - Interlocked.CompareExchange(ref this._data, new Dictionary(), null) ?? + Interlocked.CompareExchange(ref this._data, [], null) ?? this._data; #region GetServices @@ -270,7 +270,7 @@ public IEnumerable GetAllServices() where T : class return keys.SelectMany(key => this.Services.GetKeyedServices(key)); } - return Enumerable.Empty(); + return []; } } diff --git a/dotnet/src/SemanticKernel.Abstractions/Memory/NullMemory.cs b/dotnet/src/SemanticKernel.Abstractions/Memory/NullMemory.cs index 02e8823d57ef..1bbf72e429a8 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Memory/NullMemory.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Memory/NullMemory.cs @@ -87,7 +87,7 @@ public Task> GetCollectionsAsync( Kernel? kernel = null, CancellationToken cancellationToken = default) { - return Task.FromResult>(new List()); + return Task.FromResult>([]); } private NullMemory() diff --git a/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/PromptTemplateConfig.cs b/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/PromptTemplateConfig.cs index f650ae7b1c3a..11d0aab28f7d 100644 --- a/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/PromptTemplateConfig.cs +++ b/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/PromptTemplateConfig.cs @@ -159,7 +159,7 @@ public string Template [JsonPropertyName("input_variables")] public List InputVariables { - get => this._inputVariables ??= new(); + get => this._inputVariables ??= []; set { Verify.NotNull(value); @@ -182,7 +182,7 @@ public List InputVariables [JsonPropertyName("execution_settings")] public Dictionary ExecutionSettings { - get => this._executionSettings ??= new(); + get => this._executionSettings ??= []; set { Verify.NotNull(value); @@ -225,7 +225,7 @@ public void AddExecutionSettings(PromptExecutionSettings settings, string? servi /// internal IReadOnlyList GetKernelParametersMetadata() { - KernelParameterMetadata[] result = Array.Empty(); + KernelParameterMetadata[] result = []; if (this._inputVariables is List inputVariables) { result = new KernelParameterMetadata[inputVariables.Count]; diff --git a/dotnet/src/SemanticKernel.Core/Contents/StreamingMethodContent.cs b/dotnet/src/SemanticKernel.Core/Contents/StreamingMethodContent.cs index e6751607c5e3..a9c136fdc367 100644 --- a/dotnet/src/SemanticKernel.Core/Contents/StreamingMethodContent.cs +++ b/dotnet/src/SemanticKernel.Core/Contents/StreamingMethodContent.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Collections.Generic; using System.Text; @@ -27,7 +26,7 @@ public override byte[] ToByteArray() // By default if a native value is not Byte[] we output the UTF8 string representation of the value return this.Content?.ToString() is string s ? Encoding.UTF8.GetBytes(s) : - Array.Empty(); + []; } /// diff --git a/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFactory.cs b/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFactory.cs index 3af9a7b48fde..4bfd0256859a 100644 --- a/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFactory.cs +++ b/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFactory.cs @@ -115,7 +115,7 @@ public static KernelFunction CreateFromPrompt( /// /// Wraps the specified settings into a dictionary with the default service ID as the key. /// - [return: NotNullIfNotNull("settings")] + [return: NotNullIfNotNull(nameof(settings))] private static Dictionary? CreateSettingsDictionary(PromptExecutionSettings? settings) => settings is null ? null : new Dictionary(1) diff --git a/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs b/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs index 97edf83be30c..685af2f1c4de 100644 --- a/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs +++ b/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs @@ -153,7 +153,7 @@ private delegate ValueTask ImplementationFunc( KernelArguments arguments, CancellationToken cancellationToken); - private static readonly object[] s_cancellationTokenNoneArray = new object[] { CancellationToken.None }; + private static readonly object[] s_cancellationTokenNoneArray = [CancellationToken.None]; private readonly ImplementationFunc _function; private record struct MethodDetails(string Name, string Description, ImplementationFunc Function, List Parameters, KernelReturnParameterMetadata ReturnParameter); @@ -211,7 +211,7 @@ private static MethodDetails GetMethodDetails(string? functionName, MethodInfo m // Build up a list of KernelParameterMetadata for the parameters we expect to be populated // from arguments. Some arguments are populated specially, not from arguments, and thus // we don't want to advertize their metadata, e.g. CultureInfo, ILoggerFactory, etc. - List argParameterViews = new(); + List argParameterViews = []; // Get marshaling funcs for parameters and build up the parameter metadata. var parameters = method.GetParameters(); @@ -241,7 +241,7 @@ private static MethodDetails GetMethodDetails(string? functionName, MethodInfo m ValueTask Function(Kernel kernel, KernelFunction function, KernelArguments arguments, CancellationToken cancellationToken) { // Create the arguments. - object?[] args = parameterFuncs.Length != 0 ? new object?[parameterFuncs.Length] : Array.Empty(); + object?[] args = parameterFuncs.Length != 0 ? new object?[parameterFuncs.Length] : []; for (int i = 0; i < args.Length; i++) { args[i] = parameterFuncs[i](function, kernel, arguments, cancellationToken); @@ -583,7 +583,7 @@ private static (Type ReturnType, Func()); + var taskResult = Invoke(taskResultGetter, result, []); return new FunctionResult(function, taskResult, kernel.Culture); } ); @@ -597,10 +597,10 @@ private static (Type ReturnType, Func { - Task task = (Task)Invoke(valueTaskAsTask, ThrowIfNullResult(result), Array.Empty())!; + Task task = (Task)Invoke(valueTaskAsTask, ThrowIfNullResult(result), [])!; await task.ConfigureAwait(false); - var taskResult = Invoke(asTaskResultGetter, task, Array.Empty()); + var taskResult = Invoke(asTaskResultGetter, task, []); return new FunctionResult(function, taskResult, kernel.Culture); } ); diff --git a/dotnet/src/SemanticKernel.Core/KernelExtensions.cs b/dotnet/src/SemanticKernel.Core/KernelExtensions.cs index f9ba83eaeb89..ffdcda2aa32d 100644 --- a/dotnet/src/SemanticKernel.Core/KernelExtensions.cs +++ b/dotnet/src/SemanticKernel.Core/KernelExtensions.cs @@ -853,12 +853,12 @@ public static Kernel Build(this IKernelBuilder builder) // that such functionality will work when KernelBuilder is used to build the kernel but not when the IServiceProvider // is created via other means, such as if Kernel is directly created by DI. However, it allows us to create the APIs // the way we want them for the longer term and then subsequently fix the implementation when M.E.DI is fixed. - Dictionary> typeToKeyMappings = new(); + Dictionary> typeToKeyMappings = []; foreach (ServiceDescriptor serviceDescriptor in services) { if (!typeToKeyMappings.TryGetValue(serviceDescriptor.ServiceType, out HashSet? keys)) { - typeToKeyMappings[serviceDescriptor.ServiceType] = keys = new(); + typeToKeyMappings[serviceDescriptor.ServiceType] = keys = []; } keys.Add(serviceDescriptor.ServiceKey); diff --git a/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/CodeBlock.cs b/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/CodeBlock.cs index f0f438a3b459..1ac02dbd9930 100644 --- a/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/CodeBlock.cs +++ b/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/CodeBlock.cs @@ -35,20 +35,20 @@ public CodeBlock(string? content, ILoggerFactory? loggerFactory = null) public CodeBlock(List tokens, string? content, ILoggerFactory? loggerFactory = null) : base(content?.Trim(), loggerFactory) { - this._tokens = tokens; + this.Blocks = tokens; } /// /// Gets the list of blocks. /// - public List Blocks => this._tokens; + public List Blocks { get; } /// public override bool IsValid(out string errorMsg) { errorMsg = ""; - foreach (Block token in this._tokens) + foreach (Block token in this.Blocks) { if (!token.IsValid(out errorMsg)) { @@ -57,14 +57,14 @@ public override bool IsValid(out string errorMsg) } } - if (this._tokens.Count > 0 && this._tokens[0].Type == BlockTypes.NamedArg) + if (this.Blocks.Count > 0 && this.Blocks[0].Type == BlockTypes.NamedArg) { errorMsg = "Unexpected named argument found. Expected function name first."; this.Logger.LogError(errorMsg); return false; } - if (this._tokens.Count > 1 && !this.IsValidFunctionCall(out errorMsg)) + if (this.Blocks.Count > 1 && !this.IsValidFunctionCall(out errorMsg)) { return false; } @@ -87,27 +87,26 @@ public override bool IsValid(out string errorMsg) this.Logger.LogTrace("Rendering code: `{Content}`", this.Content); } - return this._tokens[0].Type switch + return this.Blocks[0].Type switch { - BlockTypes.Value or BlockTypes.Variable => new ValueTask(((ITextRendering)this._tokens[0]).Render(arguments)), - BlockTypes.FunctionId => this.RenderFunctionCallAsync((FunctionIdBlock)this._tokens[0], kernel, arguments, cancellationToken), - _ => throw new KernelException($"Unexpected first token type: {this._tokens[0].Type:G}"), + BlockTypes.Value or BlockTypes.Variable => new ValueTask(((ITextRendering)this.Blocks[0]).Render(arguments)), + BlockTypes.FunctionId => this.RenderFunctionCallAsync((FunctionIdBlock)this.Blocks[0], kernel, arguments, cancellationToken), + _ => throw new KernelException($"Unexpected first token type: {this.Blocks[0].Type:G}"), }; } #region private ================================================================================ private bool _validated; - private readonly List _tokens; private async ValueTask RenderFunctionCallAsync(FunctionIdBlock fBlock, Kernel kernel, KernelArguments? arguments, CancellationToken cancellationToken) { // If the code syntax is {{functionName $varName}} use $varName instead of $input // If the code syntax is {{functionName 'value'}} use "value" instead of $input - if (this._tokens.Count > 1) + if (this.Blocks.Count > 1) { //Cloning the original arguments to avoid side effects - arguments added to the original arguments collection as a result of rendering template variables. - arguments = this.EnrichFunctionArguments(kernel, fBlock, arguments is null ? new KernelArguments() : new KernelArguments(arguments)); + arguments = this.EnrichFunctionArguments(kernel, fBlock, arguments is null ? [] : new KernelArguments(arguments)); } try { @@ -125,23 +124,23 @@ public override bool IsValid(out string errorMsg) private bool IsValidFunctionCall(out string errorMsg) { errorMsg = ""; - if (this._tokens[0].Type != BlockTypes.FunctionId) + if (this.Blocks[0].Type != BlockTypes.FunctionId) { - errorMsg = $"Unexpected second token found: {this._tokens[1].Content}"; + errorMsg = $"Unexpected second token found: {this.Blocks[1].Content}"; this.Logger.LogError(errorMsg); return false; } - if (this._tokens[1].Type is not BlockTypes.Value and not BlockTypes.Variable and not BlockTypes.NamedArg) + if (this.Blocks[1].Type is not BlockTypes.Value and not BlockTypes.Variable and not BlockTypes.NamedArg) { errorMsg = "The first arg of a function must be a quoted string, variable or named argument"; this.Logger.LogError(errorMsg); return false; } - for (int i = 2; i < this._tokens.Count; i++) + for (int i = 2; i < this.Blocks.Count; i++) { - if (this._tokens[i].Type is not BlockTypes.NamedArg) + if (this.Blocks[i].Type is not BlockTypes.NamedArg) { errorMsg = $"Functions only support named arguments after the first argument. Argument {i} is not named."; this.Logger.LogError(errorMsg); @@ -164,7 +163,7 @@ private bool IsValidFunctionCall(out string errorMsg) /// Occurs when any argument other than the first is not a named argument. private KernelArguments EnrichFunctionArguments(Kernel kernel, FunctionIdBlock fBlock, KernelArguments arguments) { - var firstArg = this._tokens[1]; + var firstArg = this.Blocks[1]; // Sensitive data, logging as trace, disabled by default if (this.Logger.IsEnabled(LogLevel.Trace)) @@ -178,7 +177,7 @@ private KernelArguments EnrichFunctionArguments(Kernel kernel, FunctionIdBlock f // Check if the function has parameters to be set if (functionMetadata.Parameters.Count == 0) { - throw new ArgumentException($"Function {fBlock.PluginName}.{fBlock.FunctionName} does not take any arguments but it is being called in the template with {this._tokens.Count - 1} arguments."); + throw new ArgumentException($"Function {fBlock.PluginName}.{fBlock.FunctionName} does not take any arguments but it is being called in the template with {this.Blocks.Count - 1} arguments."); } string? firstPositionalParameterName = null; @@ -190,7 +189,7 @@ private KernelArguments EnrichFunctionArguments(Kernel kernel, FunctionIdBlock f // Gets the function first parameter name firstPositionalParameterName = functionMetadata.Parameters[0].Name; - firstPositionalInputValue = ((ITextRendering)this._tokens[1]).Render(arguments); + firstPositionalInputValue = ((ITextRendering)this.Blocks[1]).Render(arguments); // Type check is avoided and marshalling is done by the function itself // Keep previous trust information when updating the input @@ -198,14 +197,14 @@ private KernelArguments EnrichFunctionArguments(Kernel kernel, FunctionIdBlock f namedArgsStartIndex++; } - for (int i = namedArgsStartIndex; i < this._tokens.Count; i++) + for (int i = namedArgsStartIndex; i < this.Blocks.Count; i++) { // When casting fails because the block isn't a NamedArg, arg is null - if (this._tokens[i] is not NamedArgBlock arg) + if (this.Blocks[i] is not NamedArgBlock arg) { var errorMsg = "Functions support up to one positional argument"; this.Logger.LogError(errorMsg); - throw new KernelException($"Unexpected first token type: {this._tokens[i].Type:G}"); + throw new KernelException($"Unexpected first token type: {this.Blocks[i].Type:G}"); } // Sensitive data, logging as trace, disabled by default diff --git a/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/NamedArgBlock.cs b/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/NamedArgBlock.cs index 2da0df2dd1b2..af7eb4370e14 100644 --- a/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/NamedArgBlock.cs +++ b/dotnet/src/SemanticKernel.Core/TemplateEngine/Blocks/NamedArgBlock.cs @@ -184,10 +184,10 @@ private static string[] GetTrimmedParts(string? text) { if (text == null) { - return System.Array.Empty(); + return []; } - string[] parts = text.Split(new char[] { Symbols.NamedArgBlockSeparator }, 2); + string[] parts = text.Split([Symbols.NamedArgBlockSeparator], 2); string[] result = new string[parts.Length]; if (parts.Length > 0) { diff --git a/dotnet/src/SemanticKernel.Core/TemplateEngine/CodeTokenizer.cs b/dotnet/src/SemanticKernel.Core/TemplateEngine/CodeTokenizer.cs index 44206060aaf0..346fc9c72752 100644 --- a/dotnet/src/SemanticKernel.Core/TemplateEngine/CodeTokenizer.cs +++ b/dotnet/src/SemanticKernel.Core/TemplateEngine/CodeTokenizer.cs @@ -32,7 +32,7 @@ namespace Microsoft.SemanticKernel.TemplateEngine; /// [letter] ::= "a" | "b" ... | "z" | "A" | "B" ... | "Z" /// [digit] ::= "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" /// -internal sealed class CodeTokenizer +internal sealed class CodeTokenizer(ILoggerFactory? loggerFactory = null) { private enum TokenTypes { @@ -43,12 +43,7 @@ private enum TokenTypes NamedArg = 4, } - private readonly ILoggerFactory _loggerFactory; - - public CodeTokenizer(ILoggerFactory? loggerFactory = null) - { - this._loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; - } + private readonly ILoggerFactory _loggerFactory = loggerFactory ?? NullLoggerFactory.Instance; /// /// Tokenize a code block, without checking for syntax errors @@ -61,7 +56,7 @@ public List Tokenize(string? text) text = text?.Trim(); // Render NULL to "" - if (string.IsNullOrEmpty(text)) { return new List(); } + if (string.IsNullOrEmpty(text)) { return []; } // Track what type of token we're reading TokenTypes currentTokenType = TokenTypes.None; diff --git a/dotnet/src/SemanticKernel.Core/TemplateEngine/TemplateTokenizer.cs b/dotnet/src/SemanticKernel.Core/TemplateEngine/TemplateTokenizer.cs index 274102771df0..a18f4d8aa156 100644 --- a/dotnet/src/SemanticKernel.Core/TemplateEngine/TemplateTokenizer.cs +++ b/dotnet/src/SemanticKernel.Core/TemplateEngine/TemplateTokenizer.cs @@ -57,13 +57,13 @@ public List Tokenize(string? text) // Render NULL to "" if (string.IsNullOrEmpty(text)) { - return new List { new TextBlock(string.Empty, this._loggerFactory) }; + return [new TextBlock(string.Empty, this._loggerFactory)]; } // If the template is "empty" return the content as a text block if (text!.Length < MinCodeBlockLength) { - return new List { new TextBlock(text, this._loggerFactory) }; + return [new TextBlock(text, this._loggerFactory)]; } var blocks = new List(); diff --git a/dotnet/src/SemanticKernel.Core/Text/TextChunker.cs b/dotnet/src/SemanticKernel.Core/Text/TextChunker.cs index 38f7b94182dc..50064389d9b8 100644 --- a/dotnet/src/SemanticKernel.Core/Text/TextChunker.cs +++ b/dotnet/src/SemanticKernel.Core/Text/TextChunker.cs @@ -42,7 +42,7 @@ public StringListWithTokenCount(TokenCounter? tokenCounter) public List ToStringList() => this.Values.Select(v => v.Value).ToList(); - private List<(string Value, int TokenCount)> Values { get; } = new(); + private List<(string Value, int TokenCount)> Values { get; } = []; public string ValueAt(int i) => this.Values[i].Value; @@ -56,9 +56,9 @@ public StringListWithTokenCount(TokenCounter? tokenCounter) /// The number of tokens in the input string. public delegate int TokenCounter(string input); - private static readonly char[] s_spaceChar = new[] { ' ' }; - private static readonly string?[] s_plaintextSplitOptions = new[] { "\n\r", ".。.", "?!", ";", ":", ",,、", ")]}", " ", "-", null }; - private static readonly string?[] s_markdownSplitOptions = new[] { ".。.", "?!", ";", ":", ",,、", ")]}", " ", "-", "\n\r", null }; + private static readonly char[] s_spaceChar = [' ']; + private static readonly string?[] s_plaintextSplitOptions = ["\n\r", ".。.", "?!", ";", ":", ",,、", ")]}", " ", "-", null]; + private static readonly string?[] s_markdownSplitOptions = [".\u3002\uFF0E", "?!", ";", ":", ",\uFF0C\u3001", ")]}", " ", "-", "\n\r", null]; /// /// Split plain text into lines. @@ -119,7 +119,7 @@ private static List InternalSplitTextParagraphs(IEnumerable line // Optimize empty inputs if we can efficiently determine the're empty if (lines is ICollection c && c.Count == 0) { - return new List(); + return []; } var chunkHeaderTokens = chunkHeader is { Length: > 0 } ? GetTokenCount(chunkHeader, tokenCounter) : 0; @@ -137,7 +137,7 @@ private static List InternalSplitTextParagraphs(IEnumerable line private static List BuildParagraph(IEnumerable truncatedLines, int maxTokensPerParagraph, TokenCounter? tokenCounter) { StringBuilder paragraphBuilder = new(); - List paragraphs = new(); + List paragraphs = []; foreach (string line in truncatedLines) { diff --git a/dotnet/src/SemanticKernel.UnitTests/Events/FunctionInvokedEventArgsTests.cs b/dotnet/src/SemanticKernel.UnitTests/Events/FunctionInvokedEventArgsTests.cs index 0a338523b9ba..0bc622e05dba 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Events/FunctionInvokedEventArgsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Events/FunctionInvokedEventArgsTests.cs @@ -16,7 +16,7 @@ public void ResultValuePropertyShouldBeInitializedByOriginalOne() //Arrange var originalResults = new FunctionResult(KernelFunctionFactory.CreateFromMethod(() => { }), 36, CultureInfo.InvariantCulture); - var sut = new FunctionInvokedEventArgs(KernelFunctionFactory.CreateFromMethod(() => { }), new KernelArguments(), originalResults); + var sut = new FunctionInvokedEventArgs(KernelFunctionFactory.CreateFromMethod(() => { }), [], originalResults); //Assert Assert.Equal(36, sut.ResultValue); @@ -28,7 +28,7 @@ public void ResultValuePropertyShouldBeUpdated() //Arrange var originalResults = new FunctionResult(KernelFunctionFactory.CreateFromMethod(() => { }), 36, CultureInfo.InvariantCulture); - var sut = new FunctionInvokedEventArgs(KernelFunctionFactory.CreateFromMethod(() => { }), new KernelArguments(), originalResults); + var sut = new FunctionInvokedEventArgs(KernelFunctionFactory.CreateFromMethod(() => { }), [], originalResults); //Act sut.SetResultValue(72); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelArgumentsTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelArgumentsTests.cs index b1aa98d7a5a3..a9d1625e79e7 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelArgumentsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelArgumentsTests.cs @@ -11,7 +11,7 @@ public class KernelArgumentsTests [Fact] public void ItCanBeCreatedWithNoArguments() { - KernelArguments sut = new() { }; + KernelArguments sut = []; Assert.Null(sut.ExecutionSettings); Assert.Empty(sut); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelBuilderTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelBuilderTests.cs index f17ccd29f5d8..7a64abf85d06 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelBuilderTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelBuilderTests.cs @@ -146,7 +146,7 @@ public void ItSupportsMultipleEqualNamedServices() [Fact] public void ItIsntNeededInDIContexts() { - KernelPluginCollection plugins = new() { KernelPluginFactory.CreateFromFunctions("plugin1") }; + KernelPluginCollection plugins = [KernelPluginFactory.CreateFromFunctions("plugin1")]; var serviceCollection = new ServiceCollection(); serviceCollection.AddAzureOpenAIChatCompletion(deploymentName: "abcd", modelId: "efg", endpoint: "https://hijk", apiKey: "lmnop"); @@ -174,12 +174,12 @@ public void ItIsntNeededInDIContexts() // but it's not recommended. //** WORKAROUND - Dictionary> mapping = new(); + Dictionary> mapping = []; foreach (var descriptor in serviceCollection) { if (!mapping.TryGetValue(descriptor.ServiceType, out HashSet? keys)) { - mapping[descriptor.ServiceType] = keys = new HashSet(); + mapping[descriptor.ServiceType] = keys = []; } keys.Add(descriptor.ServiceKey); } @@ -234,7 +234,7 @@ public void ItAddsTheRightTypesInAddKernel() Assert.NotNull(builder); Assert.Throws(() => builder.Build()); - builder.Services.AddSingleton>(new Dictionary()); + builder.Services.AddSingleton>([]); IServiceProvider provider = sc.BuildServiceProvider(); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionExtensionsTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionExtensionsTests.cs index 2168a5435176..e29db7cf11ef 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionExtensionsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionExtensionsTests.cs @@ -18,21 +18,21 @@ public async Task InvokeAsyncOfTShouldMatchFunctionResultValueAsync(object? expe var testFunction = KernelFunctionFactory.CreateFromMethod(() => expectedValue, functionName: "Test"); var kernel = new Kernel(); - var resultValueInvokeSignature2 = await testFunction.InvokeAsync(kernel, new KernelArguments()); + var resultValueInvokeSignature2 = await testFunction.InvokeAsync(kernel, []); Assert.Equal(expectedValue, resultValueInvokeSignature2); } public class ComplexObjectTestData : IEnumerable { - private readonly List _data = new() - { - new object?[] { null }, - new object?[] { 1 }, - new object?[] { "Bogus" }, - new object?[] { DateTime.Now }, - new object?[] { new { Id = 2, Name = "Object2" } } - }; + private readonly List _data = + [ + [null], + [1], + ["Bogus"], + [DateTime.Now], + [new { Id = 2, Name = "Object2" }] + ]; public IEnumerator GetEnumerator() => this._data.GetEnumerator(); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests1.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests1.cs index 765a43e15948..143e5343ab20 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests1.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests1.cs @@ -152,8 +152,10 @@ static string Test(string someVar) return "abc"; } - var arguments = new KernelArguments(); - arguments["someVar"] = s_expected; + var arguments = new KernelArguments + { + ["someVar"] = s_expected + }; // Act var function = KernelFunctionFactory.CreateFromMethod(Test, loggerFactory: this._logger.Object); @@ -180,8 +182,10 @@ public async Task ItSupportsInstanceStringStringNullableAsync() return "abc"; } - var arguments = new KernelArguments(); - arguments["someVar"] = s_expected; + var arguments = new KernelArguments + { + ["someVar"] = s_expected + }; // Act Func method = Test; @@ -210,8 +214,10 @@ async Task TestAsync(string canary) s_actual = canary; } - var arguments = new KernelArguments(); - arguments["canary"] = s_expected; + var arguments = new KernelArguments + { + ["canary"] = s_expected + }; // Act Func method = TestAsync; @@ -618,7 +624,7 @@ public async Task ItSupportNullDefaultValuesOverInputAsync() [Fact] public async Task ItSupportFunctionResultAsync() { - FunctionResult Test() => new(s_nopFunction, "fake-result", CultureInfo.InvariantCulture); + static FunctionResult Test() => new(s_nopFunction, "fake-result", CultureInfo.InvariantCulture); // Act var function = KernelFunctionFactory.CreateFromMethod(Test); @@ -636,7 +642,7 @@ public async Task ItSupportFunctionResultAsync() public async Task ItSupportFunctionResultTaskAsync() { // Arrange - Task Test() + static Task Test() { var functionResult = new FunctionResult(s_nopFunction, "fake-result", CultureInfo.InvariantCulture); return Task.FromResult(functionResult); @@ -658,7 +664,7 @@ Task Test() public async Task ItSupportFunctionResultValueTaskAsync() { // Arrange - ValueTask Test() + static ValueTask Test() { var functionResult = new FunctionResult(s_nopFunction, "fake-result", CultureInfo.InvariantCulture); return ValueTask.FromResult(functionResult); @@ -682,13 +688,15 @@ public async Task ItSupportsConvertingFromManyTypesAsync() static string Test(int a, long b, decimal c, Guid d, DateTimeOffset e, DayOfWeek? f) => $"{a} {b} {c} {d} {e:R} {f}"; - var arguments = new KernelArguments(); - arguments["a"] = "1"; - arguments["b"] = -2; - arguments["c"] = "1234"; - arguments["d"] = Guid.Parse("7e08cc00-1d71-4558-81ed-69929499dea1"); - arguments["e"] = "Thu, 25 May 2023 20:17:30 GMT"; - arguments["f"] = DayOfWeek.Monday; + var arguments = new KernelArguments + { + ["a"] = "1", + ["b"] = -2, + ["c"] = "1234", + ["d"] = Guid.Parse("7e08cc00-1d71-4558-81ed-69929499dea1"), + ["e"] = "Thu, 25 May 2023 20:17:30 GMT", + ["f"] = DayOfWeek.Monday + }; // Act var function = KernelFunctionFactory.CreateFromMethod(Test); @@ -706,8 +714,10 @@ public async Task ItSupportsConvertingFromTypeConverterAttributedTypesAsync() { static int Test(MyCustomType mct) => mct.Value * 2; - var arguments = new KernelArguments(); - arguments["mct"] = "42"; + var arguments = new KernelArguments + { + ["mct"] = "42" + }; // Act var function = KernelFunctionFactory.CreateFromMethod(Test); @@ -1034,8 +1044,10 @@ public async Task ItThrowsWhenItFailsToConvertAnArgumentAsync() { static string Test(Guid g) => g.ToString(); - var arguments = new KernelArguments(); - arguments["g"] = "7e08cc00-1d71-4558-81ed-69929499dxyz"; + var arguments = new KernelArguments + { + ["g"] = "7e08cc00-1d71-4558-81ed-69929499dxyz" + }; // Act var function = KernelFunctionFactory.CreateFromMethod(Test); @@ -1121,8 +1133,10 @@ public async Task ItCanReturnComplexTypeAsync() // Arrange static MyCustomType TestCustomType(MyCustomType instance) => instance; - var arguments = new KernelArguments(); - arguments["instance"] = "42"; + var arguments = new KernelArguments + { + ["instance"] = "42" + }; var function = KernelFunctionFactory.CreateFromMethod(TestCustomType); @@ -1157,7 +1171,7 @@ static async IAsyncEnumerable TestAsyncEnumerableTypeAsync() var function = KernelFunctionFactory.CreateFromMethod(TestAsyncEnumerableTypeAsync); // Act - FunctionResult result = await function.InvokeAsync(this._kernel, new KernelArguments()); + FunctionResult result = await function.InvokeAsync(this._kernel, []); // Assert Assert.NotNull(result); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests2.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests2.cs index 7705646ca842..20f5cbcddca3 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests2.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromMethodTests2.cs @@ -44,7 +44,7 @@ public void ItDoesNotThrowForValidFunctionsViaPlugin() .Where(m => m.Name is not "GetType" and not "Equals" and not "GetHashCode" and not "ToString") .ToArray(); - KernelFunction[] functions = KernelPluginFactory.CreateFromObject(pluginInstance).ToArray(); + KernelFunction[] functions = [.. KernelPluginFactory.CreateFromObject(pluginInstance)]; // Act Assert.Equal(methods.Length, functions.Length); @@ -87,8 +87,10 @@ async Task ExecuteAsync(string done) public async Task ItCanImportMethodFunctionsWithExternalReferencesAsync() { // Arrange - var arguments = new KernelArguments(); - arguments["done"] = "NO"; + var arguments = new KernelArguments + { + ["done"] = "NO" + }; // Note: This is an important edge case that affects the function signature and how delegates // are handled internally: the function references an external variable and cannot be static. @@ -122,7 +124,7 @@ public async Task ItFlowsSpecialArgumentsIntoFunctionsAsync() builder.Services.AddLogging(c => c.SetMinimumLevel(LogLevel.Warning)); Kernel kernel = builder.Build(); kernel.Culture = new CultureInfo("fr-FR"); - KernelArguments args = new(); + KernelArguments args = []; using CancellationTokenSource cts = new(); bool invoked = false; diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromPromptTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromPromptTests.cs index 02a67e516fc9..12ecda629295 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromPromptTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionFromPromptTests.cs @@ -70,8 +70,6 @@ public async Task ItUsesChatSystemPromptWhenProvidedAsync(string? providedSystem builder.Services.AddKeyedSingleton("x", mockTextGeneration.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; var openAIExecutionSettings = providedSystemChatPrompt is null ? new OpenAIPromptExecutionSettings() : new OpenAIPromptExecutionSettings @@ -79,6 +77,7 @@ public async Task ItUsesChatSystemPromptWhenProvidedAsync(string? providedSystem ChatSystemPrompt = providedSystemChatPrompt }; + var promptConfig = new PromptTemplateConfig("template"); promptConfig.AddExecutionSettings(openAIExecutionSettings); var func = kernel.CreateFunctionFromPrompt(promptConfig); @@ -105,8 +104,7 @@ public async Task ItUsesServiceIdWhenProvidedAsync() builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; + var promptConfig = new PromptTemplateConfig("template"); promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service1"); var func = kernel.CreateFunctionFromPrompt(promptConfig); @@ -130,8 +128,7 @@ public async Task ItFailsIfInvalidServiceIdIsProvidedAsync() builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; + var promptConfig = new PromptTemplateConfig("template"); promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service3"); var func = kernel.CreateFunctionFromPrompt(promptConfig); @@ -492,14 +489,14 @@ public async Task InvokeAsyncWithMultipleServicesUsesServiceFromKernelArgumentsE KernelFunction function = KernelFunctionFactory.CreateFromPrompt("Prompt"); // Act - KernelArguments arguments1 = new(); + KernelArguments arguments1 = []; arguments1.ExecutionSettings = new Dictionary() { { "service1", new OpenAIPromptExecutionSettings { MaxTokens = 1000 } } }; var result1 = await kernel.InvokeAsync(function, arguments1); - KernelArguments arguments2 = new(); + KernelArguments arguments2 = []; arguments2.ExecutionSettings = new Dictionary() { { "service2", new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } @@ -533,14 +530,14 @@ public async Task InvokeAsyncWithMultipleServicesUsesKernelArgumentsExecutionSet KernelFunction function2 = KernelFunctionFactory.CreateFromPrompt(new PromptTemplateConfig { Template = "Prompt2", ExecutionSettings = new() { ["service2"] = new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } }); // Act - KernelArguments arguments1 = new(); + KernelArguments arguments1 = []; arguments1.ExecutionSettings = new Dictionary() { { "service2", new OpenAIPromptExecutionSettings { MaxTokens = 2000 } } }; var result1 = await kernel.InvokeAsync(function1, arguments1); - KernelArguments arguments2 = new(); + KernelArguments arguments2 = []; arguments2.ExecutionSettings = new Dictionary() { { "service1", new OpenAIPromptExecutionSettings { MaxTokens = 1000 } } @@ -593,7 +590,7 @@ public async Task InvokeAsyncWithPromptRenderedHooksExecutesModifiedPromptAsync( mockTextCompletion.Setup(m => m.GetTextContentsAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny())).ReturnsAsync(new List { mockTextContent }); #pragma warning disable CS0618 // Events are deprecated - void MyRenderedHandler(object? sender, PromptRenderedEventArgs e) + static void MyRenderedHandler(object? sender, PromptRenderedEventArgs e) { e.RenderedPrompt += " USE SHORT, CLEAR, COMPLETE SENTENCES."; } diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionMetadataTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionMetadataTests.cs index 1801fa770d8a..2851ebdd1a0b 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionMetadataTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelFunctionMetadataTests.cs @@ -51,7 +51,7 @@ public void ItReturnsFunctionReturnParameter() { Description = "ReturnParameterA", ParameterType = typeof(string), - Schema = KernelJsonSchema.Parse("{\"type\": \"object\" }"), + Schema = KernelJsonSchema.Parse("""{"type": "object" }"""), }; // Act @@ -62,7 +62,7 @@ public void ItReturnsFunctionReturnParameter() Assert.Equal("ReturnParameterA", funcViewA.ReturnParameter.Description); Assert.Equal(typeof(string), funcViewA.ReturnParameter.ParameterType); - Assert.Equivalent(KernelJsonSchema.Parse("{\"type\": \"object\" }"), funcViewA.ReturnParameter.Schema); + Assert.Equivalent(KernelJsonSchema.Parse("""{"type": "object" }"""), funcViewA.ReturnParameter.Schema); } [Fact] diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelParameterMetadataTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelParameterMetadataTests.cs index a73b5f97b696..3cce65bf10da 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelParameterMetadataTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelParameterMetadataTests.cs @@ -40,7 +40,7 @@ public void ItRoundtripsArguments() Assert.Equal("v", m.DefaultValue); Assert.True(m.IsRequired); Assert.Equal(typeof(int), m.ParameterType); - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"object\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"object" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] @@ -66,21 +66,21 @@ public void ItCantInferSchemaFromUnsupportedType() public void ItIncludesDescriptionInSchema() { var m = new KernelParameterMetadata("p") { Description = "something neat", ParameterType = typeof(int) }; - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\", \"description\":\"something neat\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"integer", "description":"something neat" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] public void ItIncludesDefaultValueInSchema() { var m = new KernelParameterMetadata("p") { DefaultValue = "42", ParameterType = typeof(int) }; - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\", \"description\":\"(default value: 42)\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"integer", "description":"(default value: 42)" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] public void ItIncludesDescriptionAndDefaultValueInSchema() { var m = new KernelParameterMetadata("p") { Description = "something neat", DefaultValue = "42", ParameterType = typeof(int) }; - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\", \"description\":\"something neat (default value: 42)\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"integer", "description":"something neat (default value: 42)" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelPluginCollectionTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelPluginCollectionTests.cs index aa07754c4713..a544d5ee3364 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelPluginCollectionTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelPluginCollectionTests.cs @@ -18,7 +18,7 @@ public void ItHasExpectedDefaultValues() { KernelPluginCollection c; - c = new(); + c = []; Assert.Equal(0, c.Count); Assert.NotNull(c.GetEnumerator()); Assert.False(c.GetEnumerator().MoveNext()); @@ -208,7 +208,7 @@ public void ItThrowsForInvalidArguments() Assert.Throws(() => new KernelPluginCollection(null!)); Assert.Throws(() => new KernelPluginCollection(new KernelPlugin[] { null! })); - KernelPluginCollection c = new(); + KernelPluginCollection c = []; Assert.Throws(() => c.Add(null!)); Assert.Throws(() => c.Remove(null!)); Assert.Throws(() => c.Contains(null!)); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelReturnParameterMetadataTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelReturnParameterMetadataTests.cs index ef5ac36eb2d5..c879b9805ff4 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/KernelReturnParameterMetadataTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/KernelReturnParameterMetadataTests.cs @@ -14,25 +14,25 @@ public class KernelReturnParameterMetadataTests [Fact] public void ItRoundtripsArguments() { - var m = new KernelReturnParameterMetadata { Description = "something", ParameterType = typeof(int), Schema = KernelJsonSchema.Parse("{ \"type\":\"object\" }") }; + var m = new KernelReturnParameterMetadata { Description = "something", ParameterType = typeof(int), Schema = KernelJsonSchema.Parse("""{ "type":"object" }""") }; Assert.Equal("something", m.Description); Assert.Equal(typeof(int), m.ParameterType); - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"object\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"object" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] public void ItInfersSchemaFromType() { - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\" }")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(int) }.Schema)); - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"number\" }")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(double) }.Schema)); - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"string\" }")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(string) }.Schema)); ; + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"integer" }""")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(int) }.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"number" }""")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(double) }.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"string" }""")), JsonSerializer.Serialize(new KernelReturnParameterMetadata { ParameterType = typeof(string) }.Schema)); } [Fact] public void ItIncludesDescriptionInSchema() { var m = new KernelReturnParameterMetadata { Description = "d", ParameterType = typeof(int) }; - Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("{ \"type\":\"integer\", \"description\":\"d\" }")), JsonSerializer.Serialize(m.Schema)); + Assert.Equal(JsonSerializer.Serialize(KernelJsonSchema.Parse("""{ "type":"integer", "description":"d" }""")), JsonSerializer.Serialize(m.Schema)); } [Fact] diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/MultipleModelTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/MultipleModelTests.cs index 8e26fb850c52..c87bc36727a1 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/MultipleModelTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/MultipleModelTests.cs @@ -28,8 +28,7 @@ public async Task ItUsesServiceIdWhenProvidedAsync() builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; + var promptConfig = new PromptTemplateConfig("template"); promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service1"); var func = kernel.CreateFunctionFromPrompt(promptConfig); @@ -53,8 +52,7 @@ public async Task ItFailsIfInvalidServiceIdIsProvidedAsync() builder.Services.AddKeyedSingleton("service2", mockTextGeneration2.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; + var promptConfig = new PromptTemplateConfig("template"); promptConfig.AddExecutionSettings(new PromptExecutionSettings(), "service3"); var func = kernel.CreateFunctionFromPrompt(promptConfig); @@ -86,8 +84,7 @@ public async Task ItUsesServiceIdByOrderAsync(string[] serviceIds, int[] callCou builder.Services.AddKeyedSingleton("service3", mockTextGeneration3.Object); Kernel kernel = builder.Build(); - var promptConfig = new PromptTemplateConfig(); - promptConfig.Template = "template"; + var promptConfig = new PromptTemplateConfig("template"); foreach (var serviceId in serviceIds) { promptConfig.AddExecutionSettings(new PromptExecutionSettings(), serviceId); @@ -122,41 +119,43 @@ public async Task ItUsesServiceIdWithJsonPromptTemplateConfigAsync() builder.Services.AddKeyedSingleton("service3", mockTextGeneration3.Object); Kernel kernel = builder.Build(); - var json = @"{ - ""template"": ""template"", - ""description"": ""Semantic function"", -""input_variables"": - [ - { - ""name"": ""input variable name"", - ""description"": ""input variable description"", - ""default"": ""default value"", - ""is_required"": true - } - ], - ""execution_settings"": { - ""service2"": { - ""max_tokens"": 100, - ""temperature"": 0.2, - ""top_p"": 0.0, - ""presence_penalty"": 0.0, - ""frequency_penalty"": 0.0, - ""stop_sequences"": [ - ""\n"" - ] - }, - ""service3"": { - ""max_tokens"": 100, - ""temperature"": 0.4, - ""top_p"": 0.0, - ""presence_penalty"": 0.0, - ""frequency_penalty"": 0.0, - ""stop_sequences"": [ - ""\n"" - ] - } - } -}"; + var json = """ + { + "template": "template", + "description": "Semantic function", + "input_variables": + [ + { + "name": "input variable name", + "description": "input variable description", + "default": "default value", + "is_required": true + } + ], + "execution_settings": { + "service2": { + "max_tokens": 100, + "temperature": 0.2, + "top_p": 0.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "stop_sequences": [ + "\n" + ] + }, + "service3": { + "max_tokens": 100, + "temperature": 0.4, + "top_p": 0.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "stop_sequences": [ + "\n" + ] + } + } + } + """; var promptConfig = PromptTemplateConfig.FromJson(json); var func = kernel.CreateFunctionFromPrompt(promptConfig); diff --git a/dotnet/src/SemanticKernel.UnitTests/Functions/OrderedAIServiceSelectorTests.cs b/dotnet/src/SemanticKernel.UnitTests/Functions/OrderedAIServiceSelectorTests.cs index b32eae6d48de..15b001c13c99 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Functions/OrderedAIServiceSelectorTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Functions/OrderedAIServiceSelectorTests.cs @@ -24,7 +24,7 @@ public void ItThrowsAKernelExceptionForNoServices() // Act // Assert - Assert.Throws(() => serviceSelector.SelectAIService(kernel, function, new KernelArguments())); + Assert.Throws(() => serviceSelector.SelectAIService(kernel, function, [])); } [Fact] @@ -39,7 +39,7 @@ public void ItGetsAIServiceConfigurationForSingleAIService() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.NotNull(aiService); @@ -58,7 +58,7 @@ public void ItGetsAIServiceConfigurationForSingleTextGeneration() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.NotNull(aiService); @@ -81,7 +81,7 @@ public void ItGetsAIServiceConfigurationForTextGenerationByServiceId() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.Equal(kernel.GetRequiredService("service2"), aiService); @@ -106,7 +106,7 @@ public void ItThrowsAKernelExceptionForNotFoundService() // Act // Assert - Assert.Throws(() => serviceSelector.SelectAIService(kernel, function, new KernelArguments())); + Assert.Throws(() => serviceSelector.SelectAIService(kernel, function, [])); } [Fact] @@ -121,7 +121,7 @@ public void ItUsesDefaultServiceForNoExecutionSettings() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.Equal(kernel.GetRequiredService("service2"), aiService); @@ -142,7 +142,7 @@ public void ItUsesDefaultServiceAndSettingsForDefaultExecutionSettings() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.Equal(kernel.GetRequiredService("service2"), aiService); @@ -165,7 +165,7 @@ public void ItUsesDefaultServiceAndSettingsForDefaultId() var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.Equal(kernel.GetRequiredService("service2"), aiService); @@ -198,7 +198,7 @@ public void ItGetsAIServiceConfigurationByOrder(string[] serviceIds, string expe var serviceSelector = new OrderedAIServiceSelector(); // Act - (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, new KernelArguments()); + (var aiService, var defaultExecutionSettings) = serviceSelector.SelectAIService(kernel, function, []); // Assert Assert.Equal(kernel.GetRequiredService(expectedModelId), aiService); @@ -243,7 +243,7 @@ private sealed class TextGenerationService : ITextGenerationService { public IReadOnlyDictionary Attributes => this._attributes; - private readonly Dictionary _attributes = new(); + private readonly Dictionary _attributes = []; public TextGenerationService(string modelId) { diff --git a/dotnet/src/SemanticKernel.UnitTests/HttpMessageHandlerStub.cs b/dotnet/src/SemanticKernel.UnitTests/HttpMessageHandlerStub.cs index f36d48d19f42..f3f5222ebf47 100644 --- a/dotnet/src/SemanticKernel.UnitTests/HttpMessageHandlerStub.cs +++ b/dotnet/src/SemanticKernel.UnitTests/HttpMessageHandlerStub.cs @@ -25,8 +25,10 @@ internal sealed class HttpMessageHandlerStub : DelegatingHandler public HttpMessageHandlerStub() { - this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK); - this.ResponseToReturn.Content = new StringContent("{}", Encoding.UTF8, "application/json"); + this.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.OK) + { + Content = new StringContent("{}", Encoding.UTF8, "application/json") + }; } protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) diff --git a/dotnet/src/SemanticKernel.UnitTests/KernelExtensionsTests.cs b/dotnet/src/SemanticKernel.UnitTests/KernelExtensionsTests.cs index b10ffcfdabc0..74505a3cb1c9 100644 --- a/dotnet/src/SemanticKernel.UnitTests/KernelExtensionsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/KernelExtensionsTests.cs @@ -29,14 +29,14 @@ public async Task InvokeAsyncOfTShouldMatchFunctionResultValueAsync(object? expe public class ComplexObjectTestData : IEnumerable { - private readonly List _data = new() - { - new object?[] { null }, - new object?[] { 1 }, - new object?[] { "Bogus" }, - new object?[] { DateTime.Now }, - new object?[] { new { Id = 2, Name = "Object2" } } - }; + private readonly List _data = + [ + [null], + [1], + ["Bogus"], + [DateTime.Now], + [new { Id = 2, Name = "Object2" }] + ]; public IEnumerator GetEnumerator() => this._data.GetEnumerator(); diff --git a/dotnet/src/SemanticKernel.UnitTests/Memory/MemoryRecordTests.cs b/dotnet/src/SemanticKernel.UnitTests/Memory/MemoryRecordTests.cs index b6dafc228a5e..44523c917548 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Memory/MemoryRecordTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Memory/MemoryRecordTests.cs @@ -15,7 +15,7 @@ public class MemoryRecordTests private readonly string _description = "description"; private readonly string _externalSourceName = "externalSourceName"; private readonly string _additionalMetadata = "value"; - private readonly ReadOnlyMemory _embedding = new(new float[] { 1, 2, 3 }); + private readonly ReadOnlyMemory _embedding = new([1, 2, 3]); [Fact] public void ItCanBeConstructedFromMetadataAndVector() @@ -83,14 +83,16 @@ public void ItCanBeCreatedToRepresentExternalData() public void ItCanBeCreatedFromSerializedMetadata() { // Arrange - string jsonString = @"{ - ""is_reference"": false, - ""id"": ""Id"", - ""text"": ""text"", - ""description"": ""description"", - ""external_source_name"": ""externalSourceName"", - ""additional_metadata"": ""value"" - }"; + string jsonString = """ + { + "is_reference": false, + "id": "Id", + "text": "text", + "description": "description", + "external_source_name": "externalSourceName", + "additional_metadata": "value" + } + """; // Act var memoryRecord = MemoryRecord.FromJsonMetadata(jsonString, this._embedding); @@ -109,22 +111,24 @@ public void ItCanBeCreatedFromSerializedMetadata() public void ItCanBeDeserializedFromJson() { // Arrange - string jsonString = @"{ - ""metadata"": { - ""is_reference"": false, - ""id"": ""Id"", - ""text"": ""text"", - ""description"": ""description"", - ""external_source_name"": ""externalSourceName"", - ""additional_metadata"": ""value"" - }, - ""embedding"": - [ - 1, - 2, - 3 - ] - }"; + string jsonString = """ + { + "metadata": { + "is_reference": false, + "id": "Id", + "text": "text", + "description": "description", + "external_source_name": "externalSourceName", + "additional_metadata": "value" + }, + "embedding": + [ + 1, + 2, + 3 + ] + } + """; // Act var memoryRecord = JsonSerializer.Deserialize(jsonString); @@ -144,24 +148,26 @@ public void ItCanBeDeserializedFromJson() public void ItCanBeSerialized() { // Arrange - string jsonString = @"{ - ""embedding"": - [ - 1, - 2, - 3 - ], - ""metadata"": { - ""is_reference"": false, - ""external_source_name"": ""externalSourceName"", - ""id"": ""Id"", - ""description"": ""description"", - ""text"": ""text"", - ""additional_metadata"": ""value"" - }, - ""key"": ""key"", - ""timestamp"": null - }"; + string jsonString = """ + { + "embedding": + [ + 1, + 2, + 3 + ], + "metadata": { + "is_reference": false, + "external_source_name": "externalSourceName", + "id": "Id", + "description": "description", + "text": "text", + "additional_metadata": "value" + }, + "key": "key", + "timestamp": null + } + """; var metadata = new MemoryRecordMetadata( isReference: this._isReference, id: this._id, @@ -186,14 +192,16 @@ public void ItCanBeSerialized() public void ItsMetadataCanBeSerialized() { // Arrange - string jsonString = @"{ - ""is_reference"": false, - ""external_source_name"": ""externalSourceName"", - ""id"": ""Id"", - ""description"": ""description"", - ""text"": ""text"", - ""additional_metadata"": ""value"" - }"; + string jsonString = """ + { + "is_reference": false, + "external_source_name": "externalSourceName", + "id": "Id", + "description": "description", + "text": "text", + "additional_metadata": "value" + } + """; var metadata = new MemoryRecordMetadata( isReference: this._isReference, diff --git a/dotnet/src/SemanticKernel.UnitTests/Prompt/XmlPromptParserTests.cs b/dotnet/src/SemanticKernel.UnitTests/Prompt/XmlPromptParserTests.cs index 95f99b8b6648..01e2282e9586 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Prompt/XmlPromptParserTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Prompt/XmlPromptParserTests.cs @@ -59,7 +59,7 @@ Test line with tab. new("message") { Attributes = { { "role", "user" } }, - ChildNodes = new List { new("audio") { Attributes = { { "src", "https://fake-link-to-audio" } } } } + ChildNodes = [new("audio") { Attributes = { { "src", "https://fake-link-to-audio" } } }] }, }; diff --git a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/AggregatorPromptTemplateFactoryTests.cs b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/AggregatorPromptTemplateFactoryTests.cs index a4bea7ac0f48..d0f5f1531cda 100644 --- a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/AggregatorPromptTemplateFactoryTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/AggregatorPromptTemplateFactoryTests.cs @@ -94,14 +94,9 @@ public bool TryCreate(PromptTemplateConfig templateConfig, out IPromptTemplate? } } - private sealed class MyPromptTemplate1 : IPromptTemplate + private sealed class MyPromptTemplate1(PromptTemplateConfig promptConfig) : IPromptTemplate { - private readonly PromptTemplateConfig _promptModel; - - public MyPromptTemplate1(PromptTemplateConfig promptConfig) - { - this._promptModel = promptConfig; - } + private readonly PromptTemplateConfig _promptModel = promptConfig; public Task RenderAsync(Kernel kernel, KernelArguments? arguments = null, CancellationToken cancellationToken = default) { @@ -124,14 +119,9 @@ public bool TryCreate(PromptTemplateConfig templateConfig, out IPromptTemplate? } } - private sealed class MyPromptTemplate2 : IPromptTemplate + private sealed class MyPromptTemplate2(PromptTemplateConfig promptConfig) : IPromptTemplate { - private readonly PromptTemplateConfig _promptModel; - - public MyPromptTemplate2(PromptTemplateConfig promptConfig) - { - this._promptModel = promptConfig; - } + private readonly PromptTemplateConfig _promptModel = promptConfig; public Task RenderAsync(Kernel kernel, KernelArguments? arguments = null, CancellationToken cancellationToken = default) { diff --git a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/KernelPromptTemplateTests.cs b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/KernelPromptTemplateTests.cs index 4a36104b7d3e..656de9a9e22b 100644 --- a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/KernelPromptTemplateTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/KernelPromptTemplateTests.cs @@ -34,7 +34,7 @@ public KernelPromptTemplateTests(ITestOutputHelper testOutputHelper) public void ItAddsMissingVariables() { // Arrange - var template = "This {{$x11}} {{$a}}{{$missing}} test template {{p.bar $b}} and {{p.foo c='literal \"c\"' d = $d}} and {{p.baz ename=$e}}"; + var template = """This {{$x11}} {{$a}}{{$missing}} test template {{p.bar $b}} and {{p.foo c='literal "c"' d = $d}} and {{p.baz ename=$e}}"""; var promptTemplateConfig = new PromptTemplateConfig(template); // Act @@ -104,7 +104,7 @@ public void ItDoesNotDuplicateExistingParameters() public async Task ItRendersVariablesValuesAndFunctionsAsync() { // Arrange - var template = "This {{$x11}} {{$a}}{{$missing}} test template {{p.bar $b}} and {{p.food c='literal \"c\"' d = $d}}"; + var template = """This {{$x11}} {{$a}}{{$missing}} test template {{p.bar $b}} and {{p.food c='literal "c"' d = $d}}"""; this._kernel.ImportPluginFromFunctions("p", new[] { @@ -124,7 +124,7 @@ public async Task ItRendersVariablesValuesAndFunctionsAsync() var renderedPrompt = await target.RenderAsync(this._kernel, this._arguments); // Assert - Assert.Equal("This is a test template with function that accepts the positional argument 'input' and another one with literal \"c\" and 'd'", renderedPrompt); + Assert.Equal("""This is a test template with function that accepts the positional argument 'input' and another one with literal "c" and 'd'""", renderedPrompt); } [Fact] @@ -360,7 +360,7 @@ string MyFunctionAsync( var result = await target.RenderAsync(this._kernel, this._arguments); // Assert - Assert.Equal("foo-[8/25/2023] Mario (42): \"Let's-a go!\"-baz", result); + Assert.Equal("""foo-[8/25/2023] Mario (42): "Let's-a go!"-baz""", result); } [Fact] @@ -407,7 +407,7 @@ string MyFunctionAsync( var result = await target.RenderAsync(this._kernel, this._arguments); // Assert - Assert.Equal("foo-[8/25/2023] Mario (42): \"Let's-a go!\"-baz", result); + Assert.Equal("""foo-[8/25/2023] Mario (42): "Let's-a go!"-baz""", result); } [Fact] diff --git a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/PromptTemplateConfigTests.cs b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/PromptTemplateConfigTests.cs index 4bc23a79589b..22f27974f41c 100644 --- a/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/PromptTemplateConfigTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/PromptTemplate/PromptTemplateConfigTests.cs @@ -14,13 +14,15 @@ public class PromptTemplateConfigTests public void DeserializingDoNotExpectChatSystemPromptToExist() { // Arrange - string configPayload = @"{ - ""max_tokens"": 60, - ""temperature"": 0.5, - ""top_p"": 0.0, - ""presence_penalty"": 0.0, - ""frequency_penalty"": 0.0 - }"; + string configPayload = """ + { + "max_tokens": 60, + "temperature": 0.5, + "top_p": 0.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0 + } + """; // Act var settings = JsonSerializer.Deserialize(configPayload); @@ -34,14 +36,16 @@ public void DeserializingDoNotExpectChatSystemPromptToExist() public void DeserializingExpectChatSystemPromptToExists() { // Arrange - string configPayload = @"{ - ""max_tokens"": 60, - ""temperature"": 0.5, - ""top_p"": 0.0, - ""presence_penalty"": 0.0, - ""frequency_penalty"": 0.0, - ""chat_system_prompt"": ""I am a prompt"" - }"; + string configPayload = """ + { + "max_tokens": 60, + "temperature": 0.5, + "top_p": 0.0, + "presence_penalty": 0.0, + "frequency_penalty": 0.0, + "chat_system_prompt": "I am a prompt" + } + """; // Act var settings = JsonSerializer.Deserialize(configPayload); diff --git a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/CodeBlockTests.cs b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/CodeBlockTests.cs index e9beab7c851a..9b9621650d18 100644 --- a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/CodeBlockTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/CodeBlockTests.cs @@ -68,8 +68,8 @@ public void ItChecksValidityOfInternalBlocks() var invalidBlock = new VarBlock(""); // Act - var codeBlock1 = new CodeBlock(new List { validBlock1, validBlock2 }, ""); - var codeBlock2 = new CodeBlock(new List { validBlock1, invalidBlock }, ""); + var codeBlock1 = new CodeBlock([validBlock1, validBlock2], ""); + var codeBlock2 = new CodeBlock([validBlock1, invalidBlock], ""); // Assert Assert.True(codeBlock1.IsValid(out _)); @@ -86,13 +86,13 @@ public void ItRequiresAValidFunctionCall() var namedArgBlock = new NamedArgBlock("varName='foo'"); // Act - var codeBlock1 = new CodeBlock(new List { funcId, valBlock }, ""); - var codeBlock2 = new CodeBlock(new List { funcId, varBlock }, ""); - var codeBlock3 = new CodeBlock(new List { funcId, funcId }, ""); - var codeBlock4 = new CodeBlock(new List { funcId, varBlock, varBlock }, ""); - var codeBlock5 = new CodeBlock(new List { funcId, varBlock, namedArgBlock }, ""); - var codeBlock6 = new CodeBlock(new List { varBlock, valBlock }, ""); - var codeBlock7 = new CodeBlock(new List { namedArgBlock }, ""); + var codeBlock1 = new CodeBlock([funcId, valBlock], ""); + var codeBlock2 = new CodeBlock([funcId, varBlock], ""); + var codeBlock3 = new CodeBlock([funcId, funcId], ""); + var codeBlock4 = new CodeBlock([funcId, varBlock, varBlock], ""); + var codeBlock5 = new CodeBlock([funcId, varBlock, namedArgBlock], ""); + var codeBlock6 = new CodeBlock([varBlock, valBlock], ""); + var codeBlock7 = new CodeBlock([namedArgBlock], ""); // Assert Assert.True(codeBlock1.IsValid(out _)); @@ -141,7 +141,7 @@ public async Task ItRendersCodeBlockConsistingOfJustAVarBlock2Async() var varBlock = new VarBlock("$varName"); // Act - var codeBlock = new CodeBlock(new List { varBlock }, ""); + var codeBlock = new CodeBlock([varBlock], ""); var result = await codeBlock.RenderCodeAsync(this._kernel, arguments); // Assert @@ -168,7 +168,7 @@ public async Task ItRendersCodeBlockConsistingOfJustAValBlock2Async() var valBlock = new ValBlock("'arrivederci'"); // Act - var codeBlock = new CodeBlock(new List { valBlock }, ""); + var codeBlock = new CodeBlock([valBlock], ""); var result = await codeBlock.RenderCodeAsync(this._kernel); // Assert @@ -197,7 +197,7 @@ public async Task ItInvokesFunctionWithCustomVariableAsync() this._kernel.ImportPluginFromFunctions("plugin", new[] { function }); // Act - var codeBlock = new CodeBlock(new List { funcId, varBlock }, ""); + var codeBlock = new CodeBlock([funcId, varBlock], ""); var result = await codeBlock.RenderCodeAsync(this._kernel, arguments); // Assert @@ -225,7 +225,7 @@ public async Task ItInvokesFunctionWithCustomValueAsync() this._kernel.ImportPluginFromFunctions("plugin", new[] { function }); // Act - var codeBlock = new CodeBlock(new List { funcBlock, valBlock }, ""); + var codeBlock = new CodeBlock([funcBlock, valBlock], ""); var result = await codeBlock.RenderCodeAsync(this._kernel); // Assert @@ -241,9 +241,11 @@ public async Task ItInvokesFunctionWithNamedArgsAsync() const string FooValue = "bar"; const string BobValue = "bob's value"; - var arguments = new KernelArguments(); - arguments["bob"] = BobValue; - arguments["input"] = Value; + var arguments = new KernelArguments + { + ["bob"] = BobValue, + ["input"] = Value + }; var funcId = new FunctionIdBlock("plugin.function"); var namedArgBlock1 = new NamedArgBlock($"foo='{FooValue}'"); @@ -262,7 +264,7 @@ public async Task ItInvokesFunctionWithNamedArgsAsync() this._kernel.ImportPluginFromFunctions("plugin", new[] { function }); // Act - var codeBlock = new CodeBlock(new List { funcId, namedArgBlock1, namedArgBlock2 }, ""); + var codeBlock = new CodeBlock([funcId, namedArgBlock1, namedArgBlock2], ""); var result = await codeBlock.RenderCodeAsync(this._kernel, arguments); // Assert @@ -288,9 +290,9 @@ public async Task ItReturnsArgumentValueAndTypeAsync() }, "f") }); // Act - var functionWithPositionedArgument = new CodeBlock(new List { funcId, varBlock }, ""); - var functionWithNamedArgument = new CodeBlock(new List { funcId, namedArgBlock }, ""); - var variable = new CodeBlock(new List { varBlock }, ""); + var functionWithPositionedArgument = new CodeBlock([funcId, varBlock], ""); + var functionWithNamedArgument = new CodeBlock([funcId, namedArgBlock], ""); + var variable = new CodeBlock([varBlock], ""); // Assert function positional argument passed to the the function with no changes await functionWithPositionedArgument.RenderCodeAsync(this._kernel, new() { ["p1"] = expectedValue, ["var"] = expectedValue }); @@ -313,9 +315,11 @@ public async Task ItDoesNotMutateOriginalArgumentsAsync() const string FooValue = "bar"; const string BobValue = "bob's value"; - var arguments = new KernelArguments(); - arguments["bob"] = BobValue; - arguments["input"] = Value; + var arguments = new KernelArguments + { + ["bob"] = BobValue, + ["input"] = Value + }; var funcId = new FunctionIdBlock("plugin.function"); var namedArgBlock1 = new NamedArgBlock($"foo='{FooValue}'"); @@ -326,7 +330,7 @@ public async Task ItDoesNotMutateOriginalArgumentsAsync() this._kernel.ImportPluginFromFunctions("plugin", new[] { function }); // Act - var codeBlock = new CodeBlock(new List { funcId, namedArgBlock1, namedArgBlock2 }, ""); + var codeBlock = new CodeBlock([funcId, namedArgBlock1, namedArgBlock2], ""); await codeBlock.RenderCodeAsync(this._kernel, arguments); // Assert @@ -343,9 +347,11 @@ public async Task ItThrowsWhenArgumentsAreProvidedToAParameterlessFunctionAsync( const string FooValue = "foo's value"; const string BobValue = "bob's value"; - var arguments = new KernelArguments(); - arguments["bob"] = BobValue; - arguments["input"] = Value; + var arguments = new KernelArguments + { + ["bob"] = BobValue, + ["input"] = Value + }; var blockList = new List { @@ -428,8 +434,10 @@ public async Task ItCallsPromptFunctionMatchArgumentWithNamedArgsAsync() builder.Services.AddSingleton(mockTextCompletion.Object); var kernel = builder.Build(); - var arguments = new KernelArguments(); - arguments["foo"] = FooValue; + var arguments = new KernelArguments + { + ["foo"] = FooValue + }; var blockList = new List { @@ -472,9 +480,11 @@ public async Task ItThrowsWhenArgumentsAreAmbiguousAsync() const string FooValue = "foo's value"; const string BobValue = "bob's value"; - var arguments = new KernelArguments(); - arguments["bob"] = BobValue; - arguments["input"] = Value; + var arguments = new KernelArguments + { + ["bob"] = BobValue, + ["input"] = Value + }; var funcId = new FunctionIdBlock("plugin.function"); var namedArgBlock1 = new ValBlock($"'{FooValue}'"); @@ -493,7 +503,7 @@ public async Task ItThrowsWhenArgumentsAreAmbiguousAsync() this._kernel.ImportPluginFromFunctions("plugin", new[] { function }); // Act - var codeBlock = new CodeBlock(new List { funcId, namedArgBlock1, namedArgBlock2 }, ""); + var codeBlock = new CodeBlock([funcId, namedArgBlock1, namedArgBlock2], ""); var exception = await Assert.ThrowsAsync(async () => await codeBlock.RenderCodeAsync(this._kernel, arguments)); Assert.Contains(FooValue, exception.Message, StringComparison.OrdinalIgnoreCase); } diff --git a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/NamedArgBlockTests.cs b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/NamedArgBlockTests.cs index 2e6fb7052ecf..1107ef89235c 100644 --- a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/NamedArgBlockTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/NamedArgBlockTests.cs @@ -251,7 +251,7 @@ public void ItRendersToNullWithNoArgument() var target = new NamedArgBlock("a=$var"); // Act - var result = target.GetValue(new KernelArguments()); + var result = target.GetValue([]); // Assert Assert.Null(result); diff --git a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/VarBlockTests.cs b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/VarBlockTests.cs index 6dba0af78c94..38e3eb9214e7 100644 --- a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/VarBlockTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/Blocks/VarBlockTests.cs @@ -43,7 +43,7 @@ public void ItRendersToNullWithNoArgument() var target = new VarBlock("$var"); // Act - var result = target.Render(new KernelArguments()); + var result = target.Render([]); // Assert Assert.Null(result); diff --git a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/CodeTokenizerTests.cs b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/CodeTokenizerTests.cs index d6c185386547..90078e038cc1 100644 --- a/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/CodeTokenizerTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/TemplateEngine/CodeTokenizerTests.cs @@ -119,8 +119,10 @@ public void ItParsesMultiNamedArgFunctionCalls() { // Arrange var template1 = "x.y first=$foo second='bar'"; - var arguments = new KernelArguments(); - arguments["foo"] = "fooValue"; + var arguments = new KernelArguments + { + ["foo"] = "fooValue" + }; // Act var blocks1 = this._target.Tokenize(template1); diff --git a/dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs b/dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs index e14b69de1aa3..807282a2778a 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Text/TextChunkerTests.cs @@ -28,11 +28,11 @@ public void CanSplitPlainTextLines() [Fact] public void CanSplitMarkdownParagraphs() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { "This is a test of the emergency broadcast system.", @@ -48,11 +48,11 @@ public void CanSplitMarkdownParagraphs() [Fact] public void CanSplitMarkdownParagraphsWithOverlap() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -71,11 +71,11 @@ public void CanSplitMarkdownParagraphsWithOverlap() [Fact] public void CanSplitTextParagraphs() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -92,11 +92,11 @@ public void CanSplitTextParagraphs() [Fact] public void CanSplitTextParagraphsWithOverlap() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -130,7 +130,7 @@ public void CanSplitMarkDownLines() [Fact] public void CanSplitTextParagraphsWithEmptyInput() { - List input = new(); + List input = []; var expected = new List(); @@ -142,7 +142,7 @@ public void CanSplitTextParagraphsWithEmptyInput() [Fact] public void CanSplitMarkdownParagraphsWithEmptyInput() { - List input = new(); + List input = []; var expected = new List(); @@ -154,13 +154,13 @@ public void CanSplitMarkdownParagraphsWithEmptyInput() [Fact] public void CanSplitTextParagraphsEvenly() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test.", "A small note. And another. And once again. Seriously, this is the end. We're finished. All set. Bye.", "Done." - }; + ]; var expected = new[] { @@ -180,13 +180,13 @@ public void CanSplitTextParagraphsEvenly() [Fact] public void CanSplitTextParagraphsOnNewlines() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system\r\nThis is only a test", "We repeat this is only a test\nA unit test", "A small note\nAnd another\r\nAnd once again\rSeriously this is the end\nWe're finished\nAll set\nBye\n", "Done" - }; + ]; var expected = new[] { @@ -206,13 +206,13 @@ public void CanSplitTextParagraphsOnNewlines() [Fact] public void CanSplitTextParagraphsOnPunctuation() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test", "We repeat, this is only a test? A unit test", "A small note! And another? And once again! Seriously, this is the end. We're finished. All set. Bye.", "Done." - }; + ]; var expected = new[] { @@ -233,13 +233,13 @@ public void CanSplitTextParagraphsOnPunctuation() [Fact] public void CanSplitTextParagraphsOnSemicolons() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system; This is only a test", "We repeat; this is only a test; A unit test", "A small note; And another; And once again; Seriously, this is the end; We're finished; All set; Bye.", "Done." - }; + ]; var expected = new[] { @@ -259,13 +259,13 @@ public void CanSplitTextParagraphsOnSemicolons() [Fact] public void CanSplitTextParagraphsOnColons() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system: This is only a test", "We repeat: this is only a test: A unit test", "A small note: And another: And once again: Seriously, this is the end: We're finished: All set: Bye.", "Done." - }; + ]; var expected = new[] { @@ -285,13 +285,13 @@ public void CanSplitTextParagraphsOnColons() [Fact] public void CanSplitTextParagraphsOnCommas() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system, This is only a test", "We repeat, this is only a test, A unit test", "A small note, And another, And once again, Seriously, this is the end, We're finished, All set, Bye.", "Done." - }; + ]; var expected = new[] { @@ -311,13 +311,13 @@ public void CanSplitTextParagraphsOnCommas() [Fact] public void CanSplitTextParagraphsOnClosingBrackets() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system) This is only a test", "We repeat) this is only a test) A unit test", "A small note] And another) And once again] Seriously this is the end} We're finished} All set} Bye.", "Done." - }; + ]; var expected = new[] { @@ -337,13 +337,13 @@ public void CanSplitTextParagraphsOnClosingBrackets() [Fact] public void CanSplitTextParagraphsOnSpaces() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system This is only a test", "We repeat this is only a test A unit test", "A small note And another And once again Seriously this is the end We're finished All set Bye.", "Done." - }; + ]; var expected = new[] { @@ -363,13 +363,13 @@ public void CanSplitTextParagraphsOnSpaces() [Fact] public void CanSplitTextParagraphsOnHyphens() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system-This is only a test", "We repeat-this is only a test-A unit test", "A small note-And another-And once again-Seriously, this is the end-We're finished-All set-Bye.", "Done." - }; + ]; var expected = new[] { @@ -389,14 +389,14 @@ public void CanSplitTextParagraphsOnHyphens() [Fact] public void CanSplitTextParagraphsWithNoDelimiters() { - List input = new() - { + List input = + [ "Thisisatestoftheemergencybroadcastsystem", "Thisisonlyatest", "WerepeatthisisonlyatestAunittest", "AsmallnoteAndanotherAndonceagain", "SeriouslythisistheendWe'refinishedAllsetByeDoneThisOneWillBeSplitToMeetTheLimit", - }; + ]; var expected = new[] { @@ -432,13 +432,13 @@ public void CanSplitTextParagraphsWithNoDelimiters() [Fact] public void CanSplitMarkdownParagraphsOnNewlines() { - List input = new() - { + List input = + [ "This_is_a_test_of_the_emergency_broadcast_system\r\nThis_is_only_a_test", "We_repeat_this_is_only_a_test\nA_unit_test", "A_small_note\nAnd_another\r\nAnd_once_again\rSeriously_this_is_the_end\nWe're_finished\nAll_set\nBye\n", "Done" - }; + ]; var expected = new[] { @@ -497,11 +497,11 @@ public void CanSplitPlainTextLinesWithCustomTokenCounter() [Fact] public void CanSplitMarkdownParagraphsWithCustomTokenCounter() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { "This is a test of the emergency broadcast system.", @@ -517,11 +517,11 @@ public void CanSplitMarkdownParagraphsWithCustomTokenCounter() [Fact] public void CanSplitMarkdownParagraphsWithOverlapAndCustomTokenCounter() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -540,11 +540,11 @@ public void CanSplitMarkdownParagraphsWithOverlapAndCustomTokenCounter() [Fact] public void CanSplitTextParagraphsWithCustomTokenCounter() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -561,11 +561,11 @@ public void CanSplitTextParagraphsWithCustomTokenCounter() [Fact] public void CanSplitTextParagraphsWithOverlapAndCustomTokenCounter() { - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -600,11 +600,11 @@ public void CanSplitMarkDownLinesWithCustomTokenCounter() public void CanSplitMarkdownParagraphsWithHeader() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { $"{ChunkHeader}This is a test of the emergency broadcast system.", @@ -621,11 +621,11 @@ public void CanSplitMarkdownParagraphsWithHeader() public void CanSplitMarkdownParagraphsWithOverlapAndHeader() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -645,11 +645,11 @@ public void CanSplitMarkdownParagraphsWithOverlapAndHeader() public void CanSplitTextParagraphsWithHeader() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -667,11 +667,11 @@ public void CanSplitTextParagraphsWithHeader() public void CanSplitTextParagraphsWithOverlapAndHeader() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -691,11 +691,11 @@ public void CanSplitTextParagraphsWithOverlapAndHeader() public void CanSplitMarkdownParagraphsWithHeaderAndCustomTokenCounter() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { $"{ChunkHeader}This is a test of the emergency broadcast system.", @@ -712,11 +712,11 @@ public void CanSplitMarkdownParagraphsWithHeaderAndCustomTokenCounter() public void CanSplitMarkdownParagraphsWithOverlapAndHeaderAndCustomTokenCounter() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -736,11 +736,11 @@ public void CanSplitMarkdownParagraphsWithOverlapAndHeaderAndCustomTokenCounter( public void CanSplitTextParagraphsWithHeaderAndCustomTokenCounter() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { @@ -758,11 +758,11 @@ public void CanSplitTextParagraphsWithHeaderAndCustomTokenCounter() public void CanSplitTextParagraphsWithOverlapAndHeaderAndCustomTokenCounter() { const string ChunkHeader = "DOCUMENT NAME: test.txt\n\n"; - List input = new() - { + List input = + [ "This is a test of the emergency broadcast system. This is only a test.", "We repeat, this is only a test. A unit test." - }; + ]; var expected = new[] { diff --git a/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpClientExtensionsTests.cs b/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpClientExtensionsTests.cs index 2b5ed9ed526f..4ddea22d4b5a 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpClientExtensionsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpClientExtensionsTests.cs @@ -56,8 +56,10 @@ public async Task ShouldReturnHttpResponseForSuccessfulRequestAsync() public async Task ShouldThrowHttpOperationExceptionForFailedRequestAsync() { //Arrange - this._httpMessageHandlerStub.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError); - this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("{\"details\": \"fake-response-content\"}", Encoding.UTF8, "application/json"); + this._httpMessageHandlerStub.ResponseToReturn = new HttpResponseMessage(System.Net.HttpStatusCode.InternalServerError) + { + Content = new StringContent("""{"details": "fake-response-content"}""", Encoding.UTF8, "application/json") + }; using var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://fake-random-test-host"); @@ -71,7 +73,7 @@ public async Task ShouldThrowHttpOperationExceptionForFailedRequestAsync() Assert.Equal("Response status code does not indicate success: 500 (Internal Server Error).", exception.Message); - Assert.Equal("{\"details\": \"fake-response-content\"}", exception.ResponseContent); + Assert.Equal("""{"details": "fake-response-content"}""", exception.ResponseContent); Assert.True(exception.InnerException is HttpRequestException); } diff --git a/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpContentExtensionsTests.cs b/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpContentExtensionsTests.cs index 5b8ea7e0dec1..e7ec210a577a 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpContentExtensionsTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Utilities/HttpContentExtensionsTests.cs @@ -37,7 +37,7 @@ public HttpContentExtensionsTests() public async Task ShouldReturnHttpContentAsStringAsync() { //Arrange - this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("{\"details\": \"fake-response-content\"}", Encoding.UTF8, "application/json"); + this._httpMessageHandlerStub.ResponseToReturn.Content = new StringContent("""{"details": "fake-response-content"}""", Encoding.UTF8, "application/json"); using var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://fake-random-test-host"); @@ -49,14 +49,14 @@ public async Task ShouldReturnHttpContentAsStringAsync() //Assert Assert.False(string.IsNullOrEmpty(result)); - Assert.Equal("{\"details\": \"fake-response-content\"}", result); + Assert.Equal("""{"details": "fake-response-content"}""", result); } [Fact] public async Task ShouldReturnHttpContentAsStreamAsync() { //Arrange - using var expectedStream = new MemoryStream(Encoding.Default.GetBytes("{\"details\": \"fake-response-content\"}")); + using var expectedStream = new MemoryStream(Encoding.Default.GetBytes("""{"details": "fake-response-content"}""")); this._httpMessageHandlerStub.ResponseToReturn.Content = new StreamContent(expectedStream); @@ -72,14 +72,14 @@ public async Task ShouldReturnHttpContentAsStreamAsync() using var streamReader = new StreamReader(actualStream); var content = await streamReader.ReadToEndAsync(); - Assert.Equal("{\"details\": \"fake-response-content\"}", content); + Assert.Equal("""{"details": "fake-response-content"}""", content); } [Fact] public async Task ShouldReturnHttpContentAsByteArrayAsync() { //Arrange - this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent(new byte[] { 1, 2, 3 }); + this._httpMessageHandlerStub.ResponseToReturn.Content = new ByteArrayContent([1, 2, 3]); using var requestMessage = new HttpRequestMessage(HttpMethod.Get, "https://fake-random-test-host"); diff --git a/dotnet/src/SemanticKernel.UnitTests/Utilities/InternalTypeConverterTests.cs b/dotnet/src/SemanticKernel.UnitTests/Utilities/InternalTypeConverterTests.cs index 91ca7ab24d8f..34419b024662 100644 --- a/dotnet/src/SemanticKernel.UnitTests/Utilities/InternalTypeConverterTests.cs +++ b/dotnet/src/SemanticKernel.UnitTests/Utilities/InternalTypeConverterTests.cs @@ -115,8 +115,7 @@ public void ItCanConvertManyTypes() public void ItCallsCustomConverterSpecifiedByTypeConverterAttribute() { // Arrange - var customType = new MyCustomType(); - customType.Value = 4; + var customType = new MyCustomType { Value = 4 }; // Act var result = InternalTypeConverter.ConvertToString(customType, CultureInfo.InvariantCulture);