From 3dd55f4e0e1a4db1a6b0f39f9e997158de900252 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Tue, 16 Jan 2024 10:44:42 +0000 Subject: [PATCH 01/24] Preparing 1.1 release --- dotnet/nuget/nuget-package.props | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/nuget/nuget-package.props b/dotnet/nuget/nuget-package.props index 41dec908c035..bd20f4cd3f05 100644 --- a/dotnet/nuget/nuget-package.props +++ b/dotnet/nuget/nuget-package.props @@ -1,7 +1,7 @@ - 1.0.2 + 1.1.0 $(VersionPrefix)-$(VersionSuffix) $(VersionPrefix) From 6f663541791f0d58fa3e3a01e19cefeb0576a63b Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Wed, 24 Apr 2024 17:02:30 +0100 Subject: [PATCH 02/24] Restructure WIP --- .../Example01_Agent.cs | 0 .../Example02_Plugins.cs | 0 .../{AgentSyntax => Agents}/Example03_Chat.cs | 0 .../Example11_OpenAIAssistant.cs | 0 .../Example12_OpenAIAssistant_Plugins.cs | 0 ...ample13_OpenAIAssistant_CodeInterpreter.cs | 0 .../Example14_OpenAIAssistant_Retrieval.cs | 0 .../Example15_OpenAIAssistant_ChartMaker.cs | 0 .../Example16_MixedChat.cs | 0 .../Agents}/Example70_Agents.cs | 0 .../Agents}/Example71_AgentDelegation.cs | 0 .../Agents}/Example72_AgentCollaboration.cs | 0 .../Agents}/Example73_AgentAuthoring.cs | 0 .../Agents}/Example75_AgentTools.cs | 0 .../Agents}/Example79_ChatCompletionAgent.cs | 0 .../Agents}/Example85_AgentCharts.cs | 0 .../{AgentSyntax => Agents}/README.md | 0 .../AudioToText}/Example82_Audio.cs | 32 ----- .../Example59_OpenAIFunctionCalling.cs | 0 .../Example98_GeminiFunctionCalling.cs | 0 .../ChatCompletion}/Example17_ChatGPT.cs | 0 .../Example33_StreamingChat.cs | 0 .../Example36_MultiCompletion.cs | 0 .../Example37_CompletionIdentity.cs | 0 .../Example44_MultiChatCompletion.cs | 0 .../Example45_MultiStreamingChatCompletion.cs | 0 .../ChatCompletion}/Example49_LogitBias.cs | 0 .../Example52_CustomOpenAIClient.cs | 0 .../Example54_AzureChatCompletionWithData.cs | 0 .../ChatCompletion}/Example61_MultipleLLMs.cs | 0 .../Example67_KernelStreaming.cs | 0 .../ChatCompletion}/Example68_GPTVision.cs | 0 .../Example87_ChatHistorySerialization.cs | 0 .../Example95_GeminiGetModelResult.cs | 0 .../Example96_GeminiChatCompletion.cs | 0 .../ChatCompletion}/Example97_GeminiVision.cs | 0 .../Example08_RetryHandler.cs | 0 .../Example40_DIContainer.cs | 0 .../Example41_HttpClientUsage.cs | 0 .../Example42_KernelBuilder.cs | 0 .../Filtering}/Example57_KernelHooks.cs | 0 .../Filtering/Example76_Filters copy 2.cs} | 0 .../Concepts/Filtering/Example76_Filters.cs | 123 ++++++++++++++++++ .../Filtering/Example76_PromptFilter.cs | 123 ++++++++++++++++++ .../Functions}/Example01_MethodFunctions.cs | 0 .../Functions}/Example03_Arguments.cs | 0 .../Example05_InlineFunctionDefinition.cs | 0 .../Functions}/Example09_FunctionTypes.cs | 0 .../Functions}/Example43_GetModelResult.cs | 0 ...ateMethodFunctionsWithMultipleArguments.cs | 0 .../Example60_AdvancedMethodFunctions.cs | 0 .../Example77_StronglyTypedFunctionResult.cs | 0 .../ImageToText}/Example86_ImageToText.cs | 0 .../Kernel/Example42_KernelBuilder.cs | 103 +++++++++++++++ .../Example58_ConfigureExecutionSettings.cs | 0 .../Example62_CustomAIServiceSelector.cs | 0 .../LocalModels}/Example16_CustomLLM.cs | 0 .../LocalModels}/Example20_HuggingFace.cs | 0 .../Example88_CustomMessageAPIEndpoint.cs | 0 .../Memory}/Example14_SemanticMemory.cs | 0 .../Memory}/Example15_TextMemoryPlugin.cs | 0 .../Memory}/Example25_ReadOnlyMemoryStore.cs | 0 .../Memory}/Example55_TextChunker.cs | 0 .../Memory}/Example81_TextEmbedding.cs | 0 .../Example99_GeminiEmbeddingGeneration.cs | 0 .../Planners}/Example65_HandlebarsPlanner.cs | 0 ...xample66_FunctionCallingStepwisePlanner.cs | 0 ...xample10_DescribeAllPluginsAndFunctions.cs | 0 .../Example13_ConversationSummaryPlugin.cs | 0 .../Plugins}/Example21_OpenAIPlugins.cs | 0 .../Example22_OpenAIPlugin_AzureKeyVault.cs | 0 .../Plugins}/Example23_OpenAPIPlugin.cs | 0 .../Plugins}/Example24_OpenApiPlugin_Jira.cs | 0 .../Plugins}/Example35_GrpcPlugins.cs | 0 .../Plugins}/Example48_GroundednessChecks.cs | 0 .../Plugins}/Example69_MutableKernelPlugin.cs | 0 .../Plugins}/Example83_ApiManifest.cs | 0 .../Example06_TemplateLanguage.cs | 0 .../Example27_PromptFunctionsUsingChatGPT.cs | 0 .../Example30_ChatWithPrompts.cs | 0 .../Example63_ChatCompletionPrompts.cs | 0 .../Example64_MultiplePromptTemplates.cs | 0 .../RAG}/Example78_RAG.cs | 0 ...Example80_FunctionCallingPlannerWithRAG.cs | 0 dotnet/samples/Concepts/README.md | 43 +++--- .../Resources/22-ai-plugin.json | 0 .../Resources/22-openapi.json | 0 .../Resources/30-system-prompt.txt | 0 .../Resources/30-user-context.txt | 0 .../Resources/30-user-prompt.txt | 0 .../Resources/65-prompt-override.handlebars | 0 .../Resources/Agents/ParrotAgent.yaml | 0 .../Resources/Agents/ToolAgent.yaml | 0 .../Agents}/travelinfo.txt | 0 .../Resources/EmbeddedResource.cs | 0 .../Resources/EnglishRoberta/dict.txt | 0 .../Resources/EnglishRoberta/encoder.json | 0 .../Resources/EnglishRoberta/vocab.bpe | 0 .../Resources/GenerateStory.yaml | 0 .../Resources/GenerateStoryHandlebars.yaml | 0 .../chat-gpt-retrieval-plugin-open-api.yaml | 0 .../Resources/sample_image.jpg | Bin .../Resources/test_audio.wav | Bin .../Resources/test_image.jpg | Bin .../Resources/travelinfo.txt | 0 .../Search}/Example07_BingAndGooglePlugins.cs | 0 .../Search}/Example11_WebSearchQueries.cs | 0 .../Search}/Example84_AzureAISearchPlugin.cs | 0 .../Example32_StreamingCompletion.cs | 0 .../Concepts/TextToAudio/Example82_Audio.cs | 55 ++++++++ .../TextToImage}/Example18_DallE.cs | 0 .../RepoUtils/ConfigurationException.cs | 20 --- .../RepoUtils/ConsoleLogger.cs | 37 ------ .../ConfigurationNotFoundException.cs | 2 - .../samples}/EnumerableExtensions.cs | 2 - .../InternalUtilities/samples}/Env.cs | 2 - .../samples}/ObjectExtensions.cs | 2 - .../samples}/PlanExtensions.cs | 2 - .../InternalUtilities/samples}/RepoFiles.cs | 2 - .../samples/SamplesInternalUtilities.props | 5 + .../samples}/TextOutputHelperExtensions.cs | 2 - .../InternalUtilities/samples}/XunitLogger.cs | 2 - .../samples}/YourAppException.cs | 2 - 123 files changed, 430 insertions(+), 129 deletions(-) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example01_Agent.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example02_Plugins.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example03_Chat.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example11_OpenAIAssistant.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example12_OpenAIAssistant_Plugins.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example13_OpenAIAssistant_CodeInterpreter.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example14_OpenAIAssistant_Retrieval.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example15_OpenAIAssistant_ChartMaker.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/Example16_MixedChat.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example70_Agents.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example71_AgentDelegation.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example72_AgentCollaboration.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example73_AgentAuthoring.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example75_AgentTools.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example79_ChatCompletionAgent.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Agents}/Example85_AgentCharts.cs (100%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/README.md (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/AudioToText}/Example82_Audio.cs (62%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/AutoFunctionCalling}/Example59_OpenAIFunctionCalling.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/AutoFunctionCalling}/Example98_GeminiFunctionCalling.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example17_ChatGPT.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example33_StreamingChat.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example36_MultiCompletion.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example37_CompletionIdentity.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example44_MultiChatCompletion.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example45_MultiStreamingChatCompletion.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example49_LogitBias.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example52_CustomOpenAIClient.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example54_AzureChatCompletionWithData.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example61_MultipleLLMs.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example67_KernelStreaming.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example68_GPTVision.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example87_ChatHistorySerialization.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example95_GeminiGetModelResult.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example96_GeminiChatCompletion.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ChatCompletion}/Example97_GeminiVision.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/DependencyInjection}/Example08_RetryHandler.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/DependencyInjection}/Example40_DIContainer.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/DependencyInjection}/Example41_HttpClientUsage.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/DependencyInjection}/Example42_KernelBuilder.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Filtering}/Example57_KernelHooks.cs (100%) rename dotnet/samples/{KernelSyntaxExamples/Example76_Filters.cs => Concepts/Filtering/Example76_Filters copy 2.cs} (100%) create mode 100644 dotnet/samples/Concepts/Filtering/Example76_Filters.cs create mode 100644 dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example01_MethodFunctions.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example03_Arguments.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example05_InlineFunctionDefinition.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example09_FunctionTypes.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example43_GetModelResult.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example56_TemplateMethodFunctionsWithMultipleArguments.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example60_AdvancedMethodFunctions.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Functions}/Example77_StronglyTypedFunctionResult.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/ImageToText}/Example86_ImageToText.cs (100%) create mode 100644 dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs rename dotnet/samples/{KernelSyntaxExamples => Concepts/Kernel}/Example58_ConfigureExecutionSettings.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Kernel}/Example62_CustomAIServiceSelector.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/LocalModels}/Example16_CustomLLM.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/LocalModels}/Example20_HuggingFace.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/LocalModels}/Example88_CustomMessageAPIEndpoint.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example14_SemanticMemory.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example15_TextMemoryPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example25_ReadOnlyMemoryStore.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example55_TextChunker.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example81_TextEmbedding.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Memory}/Example99_GeminiEmbeddingGeneration.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Planners}/Example65_HandlebarsPlanner.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Planners}/Example66_FunctionCallingStepwisePlanner.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example10_DescribeAllPluginsAndFunctions.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example13_ConversationSummaryPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example21_OpenAIPlugins.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example22_OpenAIPlugin_AzureKeyVault.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example23_OpenAPIPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example24_OpenApiPlugin_Jira.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example35_GrpcPlugins.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example48_GroundednessChecks.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example69_MutableKernelPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Plugins}/Example83_ApiManifest.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/PromptTemplates}/Example06_TemplateLanguage.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/PromptTemplates}/Example27_PromptFunctionsUsingChatGPT.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/PromptTemplates}/Example30_ChatWithPrompts.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/PromptTemplates}/Example63_ChatCompletionPrompts.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/PromptTemplates}/Example64_MultiplePromptTemplates.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/RAG}/Example78_RAG.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/RAG}/Example80_FunctionCallingPlannerWithRAG.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/22-ai-plugin.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/22-openapi.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/30-system-prompt.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/30-user-context.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/30-user-prompt.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/65-prompt-override.handlebars (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/Agents/ParrotAgent.yaml (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/Agents/ToolAgent.yaml (100%) rename dotnet/samples/Concepts/{AgentSyntax/Resources => Resources/Agents}/travelinfo.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/EmbeddedResource.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/EnglishRoberta/dict.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/EnglishRoberta/encoder.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/EnglishRoberta/vocab.bpe (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/GenerateStory.yaml (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/GenerateStoryHandlebars.yaml (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/chat-gpt-retrieval-plugin-open-api.yaml (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/sample_image.jpg (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/test_audio.wav (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/test_image.jpg (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts}/Resources/travelinfo.txt (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Search}/Example07_BingAndGooglePlugins.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Search}/Example11_WebSearchQueries.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Search}/Example84_AzureAISearchPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/TextGeneration}/Example32_StreamingCompletion.cs (100%) create mode 100644 dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs rename dotnet/samples/{KernelSyntaxExamples => Concepts/TextToImage}/Example18_DallE.cs (100%) delete mode 100644 dotnet/samples/KernelSyntaxExamples/RepoUtils/ConfigurationException.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/RepoUtils/ConsoleLogger.cs rename dotnet/{samples/KernelSyntaxExamples/Reliability => src/InternalUtilities/samples}/ConfigurationNotFoundException.cs (96%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/EnumerableExtensions.cs (98%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/Env.cs (97%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/ObjectExtensions.cs (94%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/PlanExtensions.cs (94%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/RepoFiles.cs (98%) create mode 100644 dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/TextOutputHelperExtensions.cs (98%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/XunitLogger.cs (97%) rename dotnet/{samples/KernelSyntaxExamples/RepoUtils => src/InternalUtilities/samples}/YourAppException.cs (94%) diff --git a/dotnet/samples/Concepts/AgentSyntax/Example01_Agent.cs b/dotnet/samples/Concepts/Agents/Example01_Agent.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example01_Agent.cs rename to dotnet/samples/Concepts/Agents/Example01_Agent.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example02_Plugins.cs b/dotnet/samples/Concepts/Agents/Example02_Plugins.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example02_Plugins.cs rename to dotnet/samples/Concepts/Agents/Example02_Plugins.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example03_Chat.cs b/dotnet/samples/Concepts/Agents/Example03_Chat.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example03_Chat.cs rename to dotnet/samples/Concepts/Agents/Example03_Chat.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example11_OpenAIAssistant.cs b/dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example11_OpenAIAssistant.cs rename to dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example12_OpenAIAssistant_Plugins.cs b/dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example12_OpenAIAssistant_Plugins.cs rename to dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example13_OpenAIAssistant_CodeInterpreter.cs b/dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example13_OpenAIAssistant_CodeInterpreter.cs rename to dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example14_OpenAIAssistant_Retrieval.cs b/dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example14_OpenAIAssistant_Retrieval.cs rename to dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example15_OpenAIAssistant_ChartMaker.cs b/dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example15_OpenAIAssistant_ChartMaker.cs rename to dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/Example16_MixedChat.cs b/dotnet/samples/Concepts/Agents/Example16_MixedChat.cs similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Example16_MixedChat.cs rename to dotnet/samples/Concepts/Agents/Example16_MixedChat.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs b/dotnet/samples/Concepts/Agents/Example70_Agents.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example70_Agents.cs rename to dotnet/samples/Concepts/Agents/Example70_Agents.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs b/dotnet/samples/Concepts/Agents/Example71_AgentDelegation.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example71_AgentDelegation.cs rename to dotnet/samples/Concepts/Agents/Example71_AgentDelegation.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs b/dotnet/samples/Concepts/Agents/Example72_AgentCollaboration.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example72_AgentCollaboration.cs rename to dotnet/samples/Concepts/Agents/Example72_AgentCollaboration.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs b/dotnet/samples/Concepts/Agents/Example73_AgentAuthoring.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example73_AgentAuthoring.cs rename to dotnet/samples/Concepts/Agents/Example73_AgentAuthoring.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs b/dotnet/samples/Concepts/Agents/Example75_AgentTools.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example75_AgentTools.cs rename to dotnet/samples/Concepts/Agents/Example75_AgentTools.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs b/dotnet/samples/Concepts/Agents/Example79_ChatCompletionAgent.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example79_ChatCompletionAgent.cs rename to dotnet/samples/Concepts/Agents/Example79_ChatCompletionAgent.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example85_AgentCharts.cs b/dotnet/samples/Concepts/Agents/Example85_AgentCharts.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example85_AgentCharts.cs rename to dotnet/samples/Concepts/Agents/Example85_AgentCharts.cs diff --git a/dotnet/samples/Concepts/AgentSyntax/README.md b/dotnet/samples/Concepts/Agents/README.md similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/README.md rename to dotnet/samples/Concepts/Agents/README.md diff --git a/dotnet/samples/KernelSyntaxExamples/Example82_Audio.cs b/dotnet/samples/Concepts/AudioToText/Example82_Audio.cs similarity index 62% rename from dotnet/samples/KernelSyntaxExamples/Example82_Audio.cs rename to dotnet/samples/Concepts/AudioToText/Example82_Audio.cs index e5cb891e5894..b1bea0d283eb 100644 --- a/dotnet/samples/KernelSyntaxExamples/Example82_Audio.cs +++ b/dotnet/samples/Concepts/AudioToText/Example82_Audio.cs @@ -21,38 +21,6 @@ public sealed class Example82_Audio(ITestOutputHelper output) : BaseTest(output) private const string AudioToTextModel = "whisper-1"; private const string AudioFilename = "test_audio.wav"; - [Fact(Skip = "Uncomment the line to write the audio file output before running this test.")] - public async Task TextToAudioAsync() - { - // Create a kernel with OpenAI text to audio service - var kernel = Kernel.CreateBuilder() - .AddOpenAITextToAudio( - modelId: TextToAudioModel, - apiKey: TestConfiguration.OpenAI.ApiKey) - .Build(); - - var textToAudioService = kernel.GetRequiredService(); - - string sampleText = "Hello, my name is John. I am a software engineer. I am working on a project to convert text to audio."; - - // Set execution settings (optional) - OpenAITextToAudioExecutionSettings executionSettings = new() - { - Voice = "alloy", // The voice to use when generating the audio. - // Supported voices are alloy, echo, fable, onyx, nova, and shimmer. - ResponseFormat = "mp3", // The format to audio in. - // Supported formats are mp3, opus, aac, and flac. - Speed = 1.0f // The speed of the generated audio. - // Select a value from 0.25 to 4.0. 1.0 is the default. - }; - - // Convert text to audio - AudioContent audioContent = await textToAudioService.GetAudioContentAsync(sampleText, executionSettings); - - // Save audio content to a file - // await File.WriteAllBytesAsync(AudioFilePath, audioContent.Data!.ToArray()); - } - [Fact(Skip = "Setup and run TextToAudioAsync before running this test.")] public async Task AudioToTextAsync() { diff --git a/dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs b/dotnet/samples/Concepts/AutoFunctionCalling/Example59_OpenAIFunctionCalling.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example59_OpenAIFunctionCalling.cs rename to dotnet/samples/Concepts/AutoFunctionCalling/Example59_OpenAIFunctionCalling.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs b/dotnet/samples/Concepts/AutoFunctionCalling/Example98_GeminiFunctionCalling.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example98_GeminiFunctionCalling.cs rename to dotnet/samples/Concepts/AutoFunctionCalling/Example98_GeminiFunctionCalling.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example17_ChatGPT.cs b/dotnet/samples/Concepts/ChatCompletion/Example17_ChatGPT.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example17_ChatGPT.cs rename to dotnet/samples/Concepts/ChatCompletion/Example17_ChatGPT.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example33_StreamingChat.cs b/dotnet/samples/Concepts/ChatCompletion/Example33_StreamingChat.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example33_StreamingChat.cs rename to dotnet/samples/Concepts/ChatCompletion/Example33_StreamingChat.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example36_MultiCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Example36_MultiCompletion.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example36_MultiCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/Example36_MultiCompletion.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs b/dotnet/samples/Concepts/ChatCompletion/Example37_CompletionIdentity.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example37_CompletionIdentity.cs rename to dotnet/samples/Concepts/ChatCompletion/Example37_CompletionIdentity.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example44_MultiChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example44_MultiChatCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example45_MultiStreamingChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Example45_MultiStreamingChatCompletion.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example45_MultiStreamingChatCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/Example45_MultiStreamingChatCompletion.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example49_LogitBias.cs b/dotnet/samples/Concepts/ChatCompletion/Example49_LogitBias.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example49_LogitBias.cs rename to dotnet/samples/Concepts/ChatCompletion/Example49_LogitBias.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example52_CustomOpenAIClient.cs b/dotnet/samples/Concepts/ChatCompletion/Example52_CustomOpenAIClient.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example52_CustomOpenAIClient.cs rename to dotnet/samples/Concepts/ChatCompletion/Example52_CustomOpenAIClient.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example54_AzureChatCompletionWithData.cs b/dotnet/samples/Concepts/ChatCompletion/Example54_AzureChatCompletionWithData.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example54_AzureChatCompletionWithData.cs rename to dotnet/samples/Concepts/ChatCompletion/Example54_AzureChatCompletionWithData.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs b/dotnet/samples/Concepts/ChatCompletion/Example61_MultipleLLMs.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example61_MultipleLLMs.cs rename to dotnet/samples/Concepts/ChatCompletion/Example61_MultipleLLMs.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example67_KernelStreaming.cs b/dotnet/samples/Concepts/ChatCompletion/Example67_KernelStreaming.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example67_KernelStreaming.cs rename to dotnet/samples/Concepts/ChatCompletion/Example67_KernelStreaming.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs b/dotnet/samples/Concepts/ChatCompletion/Example68_GPTVision.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example68_GPTVision.cs rename to dotnet/samples/Concepts/ChatCompletion/Example68_GPTVision.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs b/dotnet/samples/Concepts/ChatCompletion/Example87_ChatHistorySerialization.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example87_ChatHistorySerialization.cs rename to dotnet/samples/Concepts/ChatCompletion/Example87_ChatHistorySerialization.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example95_GeminiGetModelResult.cs b/dotnet/samples/Concepts/ChatCompletion/Example95_GeminiGetModelResult.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example95_GeminiGetModelResult.cs rename to dotnet/samples/Concepts/ChatCompletion/Example95_GeminiGetModelResult.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example96_GeminiChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Example96_GeminiChatCompletion.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example96_GeminiChatCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/Example96_GeminiChatCompletion.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs b/dotnet/samples/Concepts/ChatCompletion/Example97_GeminiVision.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example97_GeminiVision.cs rename to dotnet/samples/Concepts/ChatCompletion/Example97_GeminiVision.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example08_RetryHandler.cs b/dotnet/samples/Concepts/DependencyInjection/Example08_RetryHandler.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example08_RetryHandler.cs rename to dotnet/samples/Concepts/DependencyInjection/Example08_RetryHandler.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs b/dotnet/samples/Concepts/DependencyInjection/Example40_DIContainer.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example40_DIContainer.cs rename to dotnet/samples/Concepts/DependencyInjection/Example40_DIContainer.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example41_HttpClientUsage.cs b/dotnet/samples/Concepts/DependencyInjection/Example41_HttpClientUsage.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example41_HttpClientUsage.cs rename to dotnet/samples/Concepts/DependencyInjection/Example41_HttpClientUsage.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example42_KernelBuilder.cs b/dotnet/samples/Concepts/DependencyInjection/Example42_KernelBuilder.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example42_KernelBuilder.cs rename to dotnet/samples/Concepts/DependencyInjection/Example42_KernelBuilder.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example57_KernelHooks.cs b/dotnet/samples/Concepts/Filtering/Example57_KernelHooks.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example57_KernelHooks.cs rename to dotnet/samples/Concepts/Filtering/Example57_KernelHooks.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs b/dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example76_Filters.cs rename to dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs diff --git a/dotnet/samples/Concepts/Filtering/Example76_Filters.cs b/dotnet/samples/Concepts/Filtering/Example76_Filters.cs new file mode 100644 index 000000000000..aa7818ebc8a7 --- /dev/null +++ b/dotnet/samples/Concepts/Filtering/Example76_Filters.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SemanticKernel; +using Xunit; +using Xunit.Abstractions; + +namespace Examples; + +public class Example76_Filters(ITestOutputHelper output) : BaseTest(output) +{ + /// + /// Shows how to use function and prompt filters in Kernel. + /// + [Fact] + public async Task FunctionAndPromptFiltersAsync() + { + var builder = Kernel.CreateBuilder(); + + builder.AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey); + + builder.Services.AddSingleton(this.Output); + + // Add filters with DI + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + + var kernel = builder.Build(); + + // Add filter without DI + kernel.PromptFilters.Add(new FirstPromptFilter(this.Output)); + + var function = kernel.CreateFunctionFromPrompt("What is Seattle", functionName: "MyFunction"); + kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: [function])); + var result = await kernel.InvokeAsync(kernel.Plugins["MyPlugin"]["MyFunction"]); + + WriteLine(result); + } + + #region Filters + + private sealed class FirstFunctionFilter(ITestOutputHelper output) : IFunctionFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnFunctionInvoking(FunctionInvokingContext context) => + this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnFunctionInvoked(FunctionInvokedContext context) => + this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + private sealed class SecondFunctionFilter(ITestOutputHelper output) : IFunctionFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnFunctionInvoking(FunctionInvokingContext context) => + this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnFunctionInvoked(FunctionInvokedContext context) => + this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + private sealed class FirstPromptFilter(ITestOutputHelper output) : IPromptFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnPromptRendering(PromptRenderingContext context) => + this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendering)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnPromptRendered(PromptRenderedContext context) => + this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendered)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + #endregion + + #region Filter capabilities + + private sealed class FunctionFilterExample : IFunctionFilter + { + public void OnFunctionInvoked(FunctionInvokedContext context) + { + // Example: get function result value + var value = context.Result.GetValue(); + + // Example: override function result value + context.SetResultValue("new result value"); + + // Example: get token usage from metadata + var usage = context.Result.Metadata?["Usage"]; + } + + public void OnFunctionInvoking(FunctionInvokingContext context) + { + // Example: override kernel arguments + context.Arguments["input"] = "new input"; + + // Example: cancel function execution + context.Cancel = true; + } + } + + private sealed class PromptFilterExample : IPromptFilter + { + public void OnPromptRendered(PromptRenderedContext context) + { + // Example: override rendered prompt before sending it to AI + context.RenderedPrompt = "Safe prompt"; + } + + public void OnPromptRendering(PromptRenderingContext context) + { + // Example: get function information + var functionName = context.Function.Name; + } + } + + #endregion +} diff --git a/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs b/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs new file mode 100644 index 000000000000..aa7818ebc8a7 --- /dev/null +++ b/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs @@ -0,0 +1,123 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.SemanticKernel; +using Xunit; +using Xunit.Abstractions; + +namespace Examples; + +public class Example76_Filters(ITestOutputHelper output) : BaseTest(output) +{ + /// + /// Shows how to use function and prompt filters in Kernel. + /// + [Fact] + public async Task FunctionAndPromptFiltersAsync() + { + var builder = Kernel.CreateBuilder(); + + builder.AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey); + + builder.Services.AddSingleton(this.Output); + + // Add filters with DI + builder.Services.AddSingleton(); + builder.Services.AddSingleton(); + + var kernel = builder.Build(); + + // Add filter without DI + kernel.PromptFilters.Add(new FirstPromptFilter(this.Output)); + + var function = kernel.CreateFunctionFromPrompt("What is Seattle", functionName: "MyFunction"); + kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: [function])); + var result = await kernel.InvokeAsync(kernel.Plugins["MyPlugin"]["MyFunction"]); + + WriteLine(result); + } + + #region Filters + + private sealed class FirstFunctionFilter(ITestOutputHelper output) : IFunctionFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnFunctionInvoking(FunctionInvokingContext context) => + this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnFunctionInvoked(FunctionInvokedContext context) => + this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + private sealed class SecondFunctionFilter(ITestOutputHelper output) : IFunctionFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnFunctionInvoking(FunctionInvokingContext context) => + this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnFunctionInvoked(FunctionInvokedContext context) => + this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + private sealed class FirstPromptFilter(ITestOutputHelper output) : IPromptFilter + { + private readonly ITestOutputHelper _output = output; + + public void OnPromptRendering(PromptRenderingContext context) => + this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendering)} - {context.Function.PluginName}.{context.Function.Name}"); + + public void OnPromptRendered(PromptRenderedContext context) => + this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendered)} - {context.Function.PluginName}.{context.Function.Name}"); + } + + #endregion + + #region Filter capabilities + + private sealed class FunctionFilterExample : IFunctionFilter + { + public void OnFunctionInvoked(FunctionInvokedContext context) + { + // Example: get function result value + var value = context.Result.GetValue(); + + // Example: override function result value + context.SetResultValue("new result value"); + + // Example: get token usage from metadata + var usage = context.Result.Metadata?["Usage"]; + } + + public void OnFunctionInvoking(FunctionInvokingContext context) + { + // Example: override kernel arguments + context.Arguments["input"] = "new input"; + + // Example: cancel function execution + context.Cancel = true; + } + } + + private sealed class PromptFilterExample : IPromptFilter + { + public void OnPromptRendered(PromptRenderedContext context) + { + // Example: override rendered prompt before sending it to AI + context.RenderedPrompt = "Safe prompt"; + } + + public void OnPromptRendering(PromptRenderingContext context) + { + // Example: get function information + var functionName = context.Function.Name; + } + } + + #endregion +} diff --git a/dotnet/samples/KernelSyntaxExamples/Example01_MethodFunctions.cs b/dotnet/samples/Concepts/Functions/Example01_MethodFunctions.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example01_MethodFunctions.cs rename to dotnet/samples/Concepts/Functions/Example01_MethodFunctions.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example03_Arguments.cs b/dotnet/samples/Concepts/Functions/Example03_Arguments.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example03_Arguments.cs rename to dotnet/samples/Concepts/Functions/Example03_Arguments.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example05_InlineFunctionDefinition.cs b/dotnet/samples/Concepts/Functions/Example05_InlineFunctionDefinition.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example05_InlineFunctionDefinition.cs rename to dotnet/samples/Concepts/Functions/Example05_InlineFunctionDefinition.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example09_FunctionTypes.cs b/dotnet/samples/Concepts/Functions/Example09_FunctionTypes.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example09_FunctionTypes.cs rename to dotnet/samples/Concepts/Functions/Example09_FunctionTypes.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example43_GetModelResult.cs b/dotnet/samples/Concepts/Functions/Example43_GetModelResult.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example43_GetModelResult.cs rename to dotnet/samples/Concepts/Functions/Example43_GetModelResult.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs b/dotnet/samples/Concepts/Functions/Example56_TemplateMethodFunctionsWithMultipleArguments.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example56_TemplateMethodFunctionsWithMultipleArguments.cs rename to dotnet/samples/Concepts/Functions/Example56_TemplateMethodFunctionsWithMultipleArguments.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example60_AdvancedMethodFunctions.cs b/dotnet/samples/Concepts/Functions/Example60_AdvancedMethodFunctions.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example60_AdvancedMethodFunctions.cs rename to dotnet/samples/Concepts/Functions/Example60_AdvancedMethodFunctions.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example77_StronglyTypedFunctionResult.cs b/dotnet/samples/Concepts/Functions/Example77_StronglyTypedFunctionResult.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example77_StronglyTypedFunctionResult.cs rename to dotnet/samples/Concepts/Functions/Example77_StronglyTypedFunctionResult.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example86_ImageToText.cs b/dotnet/samples/Concepts/ImageToText/Example86_ImageToText.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example86_ImageToText.cs rename to dotnet/samples/Concepts/ImageToText/Example86_ImageToText.cs diff --git a/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs b/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs new file mode 100644 index 000000000000..d58f1f61f9a8 --- /dev/null +++ b/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft. All rights reserved. + +// ========================================================================================================== +// The easier way to instantiate the Semantic Kernel is to use KernelBuilder. +// You can access the builder using Kernel.CreateBuilder(). + +using System.Diagnostics; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.Plugins.Core; +using Xunit; +using Xunit.Abstractions; + +namespace Examples; + +public class Example42_KernelBuilder(ITestOutputHelper output) : BaseTest(output) +{ + [Fact] + public void BuildKernelWithAzureChatCompletion() + { + // KernelBuilder provides a simple way to configure a Kernel. This constructs a kernel + // with logging and an Azure OpenAI chat completion service configured. + Kernel kernel1 = Kernel.CreateBuilder() + .AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey, + modelId: TestConfiguration.AzureOpenAI.ChatModelId) + .Build(); + } + + [Fact] + public void BuildKernelUsingServiceCollection() + { + // For greater flexibility and to incorporate arbitrary services, KernelBuilder.Services + // provides direct access to an underlying IServiceCollection. + IKernelBuilder builder = Kernel.CreateBuilder(); + builder.Services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)) + .AddHttpClient() + .AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey, + modelId: TestConfiguration.AzureOpenAI.ChatModelId); + Kernel kernel2 = builder.Build(); + } + + [Fact] + public void BuildKernelWithPlugins() + { + // Plugins may also be configured via the corresponding Plugins property. + var builder = Kernel.CreateBuilder(); + builder.Plugins.AddFromType(); + Kernel kernel3 = builder.Build(); + } + + [Fact] + public void BuildKernelUsingServiceProvider() + { + // Every call to KernelBuilder.Build creates a new Kernel instance, with a new service provider + // and a new plugin collection. + var builder = Kernel.CreateBuilder(); + Debug.Assert(!ReferenceEquals(builder.Build(), builder.Build())); + + // KernelBuilder provides a convenient API for creating Kernel instances. However, it is just a + // wrapper around a service collection, ultimately constructing a Kernel + // using the public constructor that's available for anyone to use directly if desired. + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)); + services.AddHttpClient(); + services.AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey, + modelId: TestConfiguration.AzureOpenAI.ChatModelId); + Kernel kernel4 = new(services.BuildServiceProvider()); + + // Kernels can also be constructed and resolved via such a dependency injection container. + services.AddTransient(); + Kernel kernel5 = services.BuildServiceProvider().GetRequiredService(); + } + + [Fact] + public void BuildKernelUsingServiceCollectionExtension() + { + // In fact, the AddKernel method exists to simplify this, registering a singleton KernelPluginCollection + // that can be populated automatically with all IKernelPlugins registered in the collection, and a + // transient Kernel that can then automatically be constructed from the service provider and resulting + // plugins collection. + var services = new ServiceCollection(); + services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)); + services.AddHttpClient(); + services.AddKernel().AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey, + modelId: TestConfiguration.AzureOpenAI.ChatModelId); + services.AddSingleton(sp => KernelPluginFactory.CreateFromType(serviceProvider: sp)); + services.AddSingleton(sp => KernelPluginFactory.CreateFromType(serviceProvider: sp)); + Kernel kernel6 = services.BuildServiceProvider().GetRequiredService(); + } +} diff --git a/dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs b/dotnet/samples/Concepts/Kernel/Example58_ConfigureExecutionSettings.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example58_ConfigureExecutionSettings.cs rename to dotnet/samples/Concepts/Kernel/Example58_ConfigureExecutionSettings.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example62_CustomAIServiceSelector.cs b/dotnet/samples/Concepts/Kernel/Example62_CustomAIServiceSelector.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example62_CustomAIServiceSelector.cs rename to dotnet/samples/Concepts/Kernel/Example62_CustomAIServiceSelector.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs b/dotnet/samples/Concepts/LocalModels/Example16_CustomLLM.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example16_CustomLLM.cs rename to dotnet/samples/Concepts/LocalModels/Example16_CustomLLM.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs b/dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example20_HuggingFace.cs rename to dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example88_CustomMessageAPIEndpoint.cs b/dotnet/samples/Concepts/LocalModels/Example88_CustomMessageAPIEndpoint.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example88_CustomMessageAPIEndpoint.cs rename to dotnet/samples/Concepts/LocalModels/Example88_CustomMessageAPIEndpoint.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example14_SemanticMemory.cs b/dotnet/samples/Concepts/Memory/Example14_SemanticMemory.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example14_SemanticMemory.cs rename to dotnet/samples/Concepts/Memory/Example14_SemanticMemory.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs b/dotnet/samples/Concepts/Memory/Example15_TextMemoryPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs rename to dotnet/samples/Concepts/Memory/Example15_TextMemoryPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs b/dotnet/samples/Concepts/Memory/Example25_ReadOnlyMemoryStore.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example25_ReadOnlyMemoryStore.cs rename to dotnet/samples/Concepts/Memory/Example25_ReadOnlyMemoryStore.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs b/dotnet/samples/Concepts/Memory/Example55_TextChunker.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example55_TextChunker.cs rename to dotnet/samples/Concepts/Memory/Example55_TextChunker.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example81_TextEmbedding.cs b/dotnet/samples/Concepts/Memory/Example81_TextEmbedding.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example81_TextEmbedding.cs rename to dotnet/samples/Concepts/Memory/Example81_TextEmbedding.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example99_GeminiEmbeddingGeneration.cs b/dotnet/samples/Concepts/Memory/Example99_GeminiEmbeddingGeneration.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example99_GeminiEmbeddingGeneration.cs rename to dotnet/samples/Concepts/Memory/Example99_GeminiEmbeddingGeneration.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example65_HandlebarsPlanner.cs b/dotnet/samples/Concepts/Planners/Example65_HandlebarsPlanner.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example65_HandlebarsPlanner.cs rename to dotnet/samples/Concepts/Planners/Example65_HandlebarsPlanner.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs b/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example66_FunctionCallingStepwisePlanner.cs rename to dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example10_DescribeAllPluginsAndFunctions.cs b/dotnet/samples/Concepts/Plugins/Example10_DescribeAllPluginsAndFunctions.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example10_DescribeAllPluginsAndFunctions.cs rename to dotnet/samples/Concepts/Plugins/Example10_DescribeAllPluginsAndFunctions.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example13_ConversationSummaryPlugin.cs b/dotnet/samples/Concepts/Plugins/Example13_ConversationSummaryPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example13_ConversationSummaryPlugin.cs rename to dotnet/samples/Concepts/Plugins/Example13_ConversationSummaryPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs b/dotnet/samples/Concepts/Plugins/Example21_OpenAIPlugins.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example21_OpenAIPlugins.cs rename to dotnet/samples/Concepts/Plugins/Example21_OpenAIPlugins.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs b/dotnet/samples/Concepts/Plugins/Example22_OpenAIPlugin_AzureKeyVault.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example22_OpenAIPlugin_AzureKeyVault.cs rename to dotnet/samples/Concepts/Plugins/Example22_OpenAIPlugin_AzureKeyVault.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example23_OpenAPIPlugin.cs b/dotnet/samples/Concepts/Plugins/Example23_OpenAPIPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example23_OpenAPIPlugin.cs rename to dotnet/samples/Concepts/Plugins/Example23_OpenAPIPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs b/dotnet/samples/Concepts/Plugins/Example24_OpenApiPlugin_Jira.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example24_OpenApiPlugin_Jira.cs rename to dotnet/samples/Concepts/Plugins/Example24_OpenApiPlugin_Jira.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs b/dotnet/samples/Concepts/Plugins/Example35_GrpcPlugins.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example35_GrpcPlugins.cs rename to dotnet/samples/Concepts/Plugins/Example35_GrpcPlugins.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example48_GroundednessChecks.cs b/dotnet/samples/Concepts/Plugins/Example48_GroundednessChecks.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example48_GroundednessChecks.cs rename to dotnet/samples/Concepts/Plugins/Example48_GroundednessChecks.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example69_MutableKernelPlugin.cs b/dotnet/samples/Concepts/Plugins/Example69_MutableKernelPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example69_MutableKernelPlugin.cs rename to dotnet/samples/Concepts/Plugins/Example69_MutableKernelPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs b/dotnet/samples/Concepts/Plugins/Example83_ApiManifest.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example83_ApiManifest.cs rename to dotnet/samples/Concepts/Plugins/Example83_ApiManifest.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example06_TemplateLanguage.cs b/dotnet/samples/Concepts/PromptTemplates/Example06_TemplateLanguage.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example06_TemplateLanguage.cs rename to dotnet/samples/Concepts/PromptTemplates/Example06_TemplateLanguage.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example27_PromptFunctionsUsingChatGPT.cs b/dotnet/samples/Concepts/PromptTemplates/Example27_PromptFunctionsUsingChatGPT.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example27_PromptFunctionsUsingChatGPT.cs rename to dotnet/samples/Concepts/PromptTemplates/Example27_PromptFunctionsUsingChatGPT.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example30_ChatWithPrompts.cs b/dotnet/samples/Concepts/PromptTemplates/Example30_ChatWithPrompts.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example30_ChatWithPrompts.cs rename to dotnet/samples/Concepts/PromptTemplates/Example30_ChatWithPrompts.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example63_ChatCompletionPrompts.cs b/dotnet/samples/Concepts/PromptTemplates/Example63_ChatCompletionPrompts.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example63_ChatCompletionPrompts.cs rename to dotnet/samples/Concepts/PromptTemplates/Example63_ChatCompletionPrompts.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example64_MultiplePromptTemplates.cs b/dotnet/samples/Concepts/PromptTemplates/Example64_MultiplePromptTemplates.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example64_MultiplePromptTemplates.cs rename to dotnet/samples/Concepts/PromptTemplates/Example64_MultiplePromptTemplates.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example78_RAG.cs b/dotnet/samples/Concepts/RAG/Example78_RAG.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example78_RAG.cs rename to dotnet/samples/Concepts/RAG/Example78_RAG.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs b/dotnet/samples/Concepts/RAG/Example80_FunctionCallingPlannerWithRAG.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example80_FunctionCallingPlannerWithRAG.cs rename to dotnet/samples/Concepts/RAG/Example80_FunctionCallingPlannerWithRAG.cs diff --git a/dotnet/samples/Concepts/README.md b/dotnet/samples/Concepts/README.md index 42a9f499fab0..7c3311fe0f41 100644 --- a/dotnet/samples/Concepts/README.md +++ b/dotnet/samples/Concepts/README.md @@ -2,25 +2,24 @@ This section contains code snippets that demonstrate the usage of Semantic Kernel features. -| Features | Description | -| -------- | ----------- | -| Functions | Invoking [`Method`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs) or [`Prompt`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromPrompt.cs) functions with [`Kernel`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Kernel.cs) | -| Chat Completion | Using [`ChatCompletion`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/IChatCompletionService.cs) messaging capable service with models | -| Text Generation | Using [`TextGeneration`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextGeneration/ITextGenerationService.cs) capable service with models | -| Text to Image | Using [`TextToImage`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToImage/ITextToImageService.cs) services to generate images | -| Image to Text | Using [`ImageToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ImageToText/IImageToTextService.cs) services to describe images | -| Text to Audio | Using [`TextToAudio`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToAudio/ITextToAudioService.cs) services to generate audio | -| Audio to Text | Using [`AudioToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/AudioToText/IAudioToTextService.cs) services to describe audio | -| Telemetry | Code examples how to setup and use [`Telemetry`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/docs/TELEMETRY.md) | -| Logging | Code examples how to setup and use [`Logging`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/docs/TELEMETRY.md#logging) | -| Dependency Injection | Examples on using `DI Container` with SK | -| Plugins | Different ways of creating and using [`Plugins`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs) | -| Auto Function Calling | Using `Auto Function Calling` to allow function call capable models to invoke Kernel Functions automatically | -| Filters | Different ways of filtering with Kernel | -| Memory | Using [`Memory`](https://github.com/microsoft/semantic-kernel/tree/main/dotnet/src/SemanticKernel.Abstractions/Memory) AI concepts | -| Search | Using search services information | -| Templates | Using [`Templates`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/IPromptTemplate.cs) with parametrization for `Prompt` rendering | -| RAG | Different ways of `RAG` (Retrieval-Augmented Generation) | -| Local Models | Using services against `LocalModels` to run models locally | -| Agents | Different ways of using [`Agents`](./AgentSyntax/README.md) | -| AgentSyntax | ⚠️ Work in progress: Moving into [`Agents`](./AgentSyntax/README.md). | \ No newline at end of file +| Features | Description | +| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Functions | Invoking [`Method`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs) or [`Prompt`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromPrompt.cs) functions with [`Kernel`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Kernel.cs) | +| Chat Completion | Using [`ChatCompletion`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/IChatCompletionService.cs) messaging capable service with models | +| Text Generation | Using [`TextGeneration`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextGeneration/ITextGenerationService.cs) capable service with models | +| Text to Image | Using [`TextToImage`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToImage/ITextToImageService.cs) services to generate images | +| Image to Text | Using [`ImageToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ImageToText/IImageToTextService.cs) services to describe images | +| Text to Audio | Using [`TextToAudio`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToAudio/ITextToAudioService.cs) services to generate audio | +| Audio to Text | Using [`AudioToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/AudioToText/IAudioToTextService.cs) services to describe audio | +| Telemetry | Code examples how to setup and use [`Telemetry`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/docs/TELEMETRY.md) | +| Dependency Injection | Examples on using `DI Container` with SK | +| Plugins | Different ways of creating and using [`Plugins`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs) | +| Auto Function Calling | Using `Auto Function Calling` to allow function call capable models to invoke Kernel Functions automatically | +| Filters | Different ways of filtering with Kernel | +| Memory | Using [`Memory`](https://github.com/microsoft/semantic-kernel/tree/main/dotnet/src/SemanticKernel.Abstractions/Memory) AI concepts | +| Search | Using search services information | +| PromptTemplates | Using [`Templates`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/IPromptTemplate.cs) with parametrization for `Prompt` rendering | +| RAG | Different ways of `RAG` (Retrieval-Augmented Generation) | +| Local Models | Using services against `LocalModels` to run models locally | +| Agents | Different ways of using [`Agents`](./AgentSyntax/README.md) | +| AgentSyntax | ⚠️ Work in progress: Moving into [`Agents`](./AgentSyntax/README.md). | diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/22-ai-plugin.json b/dotnet/samples/Concepts/Resources/22-ai-plugin.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/22-ai-plugin.json rename to dotnet/samples/Concepts/Resources/22-ai-plugin.json diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/22-openapi.json b/dotnet/samples/Concepts/Resources/22-openapi.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/22-openapi.json rename to dotnet/samples/Concepts/Resources/22-openapi.json diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/30-system-prompt.txt b/dotnet/samples/Concepts/Resources/30-system-prompt.txt similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/30-system-prompt.txt rename to dotnet/samples/Concepts/Resources/30-system-prompt.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/30-user-context.txt b/dotnet/samples/Concepts/Resources/30-user-context.txt similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/30-user-context.txt rename to dotnet/samples/Concepts/Resources/30-user-context.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/30-user-prompt.txt b/dotnet/samples/Concepts/Resources/30-user-prompt.txt similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/30-user-prompt.txt rename to dotnet/samples/Concepts/Resources/30-user-prompt.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/65-prompt-override.handlebars b/dotnet/samples/Concepts/Resources/65-prompt-override.handlebars similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/65-prompt-override.handlebars rename to dotnet/samples/Concepts/Resources/65-prompt-override.handlebars diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/Agents/ParrotAgent.yaml b/dotnet/samples/Concepts/Resources/Agents/ParrotAgent.yaml similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/Agents/ParrotAgent.yaml rename to dotnet/samples/Concepts/Resources/Agents/ParrotAgent.yaml diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/Agents/ToolAgent.yaml b/dotnet/samples/Concepts/Resources/Agents/ToolAgent.yaml similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/Agents/ToolAgent.yaml rename to dotnet/samples/Concepts/Resources/Agents/ToolAgent.yaml diff --git a/dotnet/samples/Concepts/AgentSyntax/Resources/travelinfo.txt b/dotnet/samples/Concepts/Resources/Agents/travelinfo.txt similarity index 100% rename from dotnet/samples/Concepts/AgentSyntax/Resources/travelinfo.txt rename to dotnet/samples/Concepts/Resources/Agents/travelinfo.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/EmbeddedResource.cs b/dotnet/samples/Concepts/Resources/EmbeddedResource.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/EmbeddedResource.cs rename to dotnet/samples/Concepts/Resources/EmbeddedResource.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/dict.txt b/dotnet/samples/Concepts/Resources/EnglishRoberta/dict.txt similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/dict.txt rename to dotnet/samples/Concepts/Resources/EnglishRoberta/dict.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/encoder.json b/dotnet/samples/Concepts/Resources/EnglishRoberta/encoder.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/encoder.json rename to dotnet/samples/Concepts/Resources/EnglishRoberta/encoder.json diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/vocab.bpe b/dotnet/samples/Concepts/Resources/EnglishRoberta/vocab.bpe similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/EnglishRoberta/vocab.bpe rename to dotnet/samples/Concepts/Resources/EnglishRoberta/vocab.bpe diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/GenerateStory.yaml b/dotnet/samples/Concepts/Resources/GenerateStory.yaml similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/GenerateStory.yaml rename to dotnet/samples/Concepts/Resources/GenerateStory.yaml diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/GenerateStoryHandlebars.yaml b/dotnet/samples/Concepts/Resources/GenerateStoryHandlebars.yaml similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/GenerateStoryHandlebars.yaml rename to dotnet/samples/Concepts/Resources/GenerateStoryHandlebars.yaml diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/chat-gpt-retrieval-plugin-open-api.yaml b/dotnet/samples/Concepts/Resources/chat-gpt-retrieval-plugin-open-api.yaml similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/chat-gpt-retrieval-plugin-open-api.yaml rename to dotnet/samples/Concepts/Resources/chat-gpt-retrieval-plugin-open-api.yaml diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/sample_image.jpg b/dotnet/samples/Concepts/Resources/sample_image.jpg similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/sample_image.jpg rename to dotnet/samples/Concepts/Resources/sample_image.jpg diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/test_audio.wav b/dotnet/samples/Concepts/Resources/test_audio.wav similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/test_audio.wav rename to dotnet/samples/Concepts/Resources/test_audio.wav diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/test_image.jpg b/dotnet/samples/Concepts/Resources/test_image.jpg similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/test_image.jpg rename to dotnet/samples/Concepts/Resources/test_image.jpg diff --git a/dotnet/samples/KernelSyntaxExamples/Resources/travelinfo.txt b/dotnet/samples/Concepts/Resources/travelinfo.txt similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Resources/travelinfo.txt rename to dotnet/samples/Concepts/Resources/travelinfo.txt diff --git a/dotnet/samples/KernelSyntaxExamples/Example07_BingAndGooglePlugins.cs b/dotnet/samples/Concepts/Search/Example07_BingAndGooglePlugins.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example07_BingAndGooglePlugins.cs rename to dotnet/samples/Concepts/Search/Example07_BingAndGooglePlugins.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example11_WebSearchQueries.cs b/dotnet/samples/Concepts/Search/Example11_WebSearchQueries.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example11_WebSearchQueries.cs rename to dotnet/samples/Concepts/Search/Example11_WebSearchQueries.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs b/dotnet/samples/Concepts/Search/Example84_AzureAISearchPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example84_AzureAISearchPlugin.cs rename to dotnet/samples/Concepts/Search/Example84_AzureAISearchPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Example32_StreamingCompletion.cs b/dotnet/samples/Concepts/TextGeneration/Example32_StreamingCompletion.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example32_StreamingCompletion.cs rename to dotnet/samples/Concepts/TextGeneration/Example32_StreamingCompletion.cs diff --git a/dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs b/dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs new file mode 100644 index 000000000000..353399ba093f --- /dev/null +++ b/dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs @@ -0,0 +1,55 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System; +using System.Threading.Tasks; +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.AudioToText; +using Microsoft.SemanticKernel.Connectors.OpenAI; +using Microsoft.SemanticKernel.TextToAudio; +using Resources; +using Xunit; +using Xunit.Abstractions; + +namespace Examples; + +/// +/// Represents a class that demonstrates audio processing functionality. +/// +public sealed class Example82_Audio(ITestOutputHelper output) : BaseTest(output) +{ + private const string TextToAudioModel = "tts-1"; + private const string AudioToTextModel = "whisper-1"; + private const string AudioFilename = "test_audio.wav"; + + [Fact(Skip = "Uncomment the line to write the audio file output before running this test.")] + public async Task TextToAudioAsync() + { + // Create a kernel with OpenAI text to audio service + var kernel = Kernel.CreateBuilder() + .AddOpenAITextToAudio( + modelId: TextToAudioModel, + apiKey: TestConfiguration.OpenAI.ApiKey) + .Build(); + + var textToAudioService = kernel.GetRequiredService(); + + string sampleText = "Hello, my name is John. I am a software engineer. I am working on a project to convert text to audio."; + + // Set execution settings (optional) + OpenAITextToAudioExecutionSettings executionSettings = new() + { + Voice = "alloy", // The voice to use when generating the audio. + // Supported voices are alloy, echo, fable, onyx, nova, and shimmer. + ResponseFormat = "mp3", // The format to audio in. + // Supported formats are mp3, opus, aac, and flac. + Speed = 1.0f // The speed of the generated audio. + // Select a value from 0.25 to 4.0. 1.0 is the default. + }; + + // Convert text to audio + AudioContent audioContent = await textToAudioService.GetAudioContentAsync(sampleText, executionSettings); + + // Save audio content to a file + // await File.WriteAllBytesAsync(AudioFilePath, audioContent.Data!.ToArray()); + } +} diff --git a/dotnet/samples/KernelSyntaxExamples/Example18_DallE.cs b/dotnet/samples/Concepts/TextToImage/Example18_DallE.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Example18_DallE.cs rename to dotnet/samples/Concepts/TextToImage/Example18_DallE.cs diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConfigurationException.cs b/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConfigurationException.cs deleted file mode 100644 index c1ea16a9b02c..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConfigurationException.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; - -namespace RepoUtils; - -public class ConfigurationException : Exception -{ - public ConfigurationException() - { - } - - public ConfigurationException(string message) : base(message) - { - } - - public ConfigurationException(string message, Exception innerException) : base(message, innerException) - { - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConsoleLogger.cs b/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConsoleLogger.cs deleted file mode 100644 index 2ab9067ca8dd..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ConsoleLogger.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using Microsoft.Extensions.Logging; - -namespace RepoUtils; - -/// -/// Basic logger printing to console -/// -internal static class ConsoleLogger -{ - internal static ILogger Logger => LoggerFactory.CreateLogger(); - - internal static ILoggerFactory LoggerFactory => s_loggerFactory.Value; - - private static readonly Lazy s_loggerFactory = new(LogBuilder); - - private static ILoggerFactory LogBuilder() - { - return Microsoft.Extensions.Logging.LoggerFactory.Create(builder => - { - builder.SetMinimumLevel(LogLevel.Warning); - - // builder.AddFilter("Microsoft", LogLevel.Trace); - // builder.AddFilter("Microsoft", LogLevel.Debug); - // builder.AddFilter("Microsoft", LogLevel.Information); - // builder.AddFilter("Microsoft", LogLevel.Warning); - // builder.AddFilter("Microsoft", LogLevel.Error); - - builder.AddFilter("Microsoft", LogLevel.Warning); - builder.AddFilter("System", LogLevel.Warning); - - builder.AddConsole(); - }); - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/Reliability/ConfigurationNotFoundException.cs b/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs similarity index 96% rename from dotnet/samples/KernelSyntaxExamples/Reliability/ConfigurationNotFoundException.cs rename to dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs index 5c0975fbf075..c637b1db7449 100644 --- a/dotnet/samples/KernelSyntaxExamples/Reliability/ConfigurationNotFoundException.cs +++ b/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs @@ -2,8 +2,6 @@ using System; -namespace Reliability; - public sealed class ConfigurationNotFoundException : Exception { public string? Section { get; } diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs b/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs similarity index 98% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs rename to dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs index 238f270b3cf9..a5a2d8ba0d9b 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/EnumerableExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs @@ -3,8 +3,6 @@ using System; using System.Collections.Generic; -namespace RepoUtils; - public static class EnumerableExtensions { public static IEnumerable> ChunkByAggregate( diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/Env.cs b/dotnet/src/InternalUtilities/samples/Env.cs similarity index 97% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/Env.cs rename to dotnet/src/InternalUtilities/samples/Env.cs index e2e1de5ff781..9ba11361d881 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/Env.cs +++ b/dotnet/src/InternalUtilities/samples/Env.cs @@ -3,8 +3,6 @@ using System; using Microsoft.Extensions.Configuration; -namespace RepoUtils; - internal sealed class Env { /// diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ObjectExtensions.cs b/dotnet/src/InternalUtilities/samples/ObjectExtensions.cs similarity index 94% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/ObjectExtensions.cs rename to dotnet/src/InternalUtilities/samples/ObjectExtensions.cs index 144074f96116..9e1338949b9a 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/ObjectExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/ObjectExtensions.cs @@ -2,8 +2,6 @@ using System.Text.Json; -namespace RepoUtils; - public static class ObjectExtensions { private static readonly JsonSerializerOptions s_jsonOptionsCache = new() { WriteIndented = true }; diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/PlanExtensions.cs b/dotnet/src/InternalUtilities/samples/PlanExtensions.cs similarity index 94% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/PlanExtensions.cs rename to dotnet/src/InternalUtilities/samples/PlanExtensions.cs index 792faf150ebb..630095611b6e 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/PlanExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/PlanExtensions.cs @@ -2,8 +2,6 @@ using Microsoft.SemanticKernel.Planning; -namespace RepoUtils; - internal static class PlanExtensions { internal static string ToPlanWithGoalString(this Plan plan, string indent = " ") diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs b/dotnet/src/InternalUtilities/samples/RepoFiles.cs similarity index 98% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs rename to dotnet/src/InternalUtilities/samples/RepoFiles.cs index 4361c37d25a0..e4eda65b2ed2 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/RepoFiles.cs +++ b/dotnet/src/InternalUtilities/samples/RepoFiles.cs @@ -3,8 +3,6 @@ using System.IO; using System.Reflection; -namespace RepoUtils; - public static class RepoFiles { /// diff --git a/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props b/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props new file mode 100644 index 000000000000..47cf9c660e02 --- /dev/null +++ b/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props @@ -0,0 +1,5 @@ + + + + + \ No newline at end of file diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/TextOutputHelperExtensions.cs b/dotnet/src/InternalUtilities/samples/TextOutputHelperExtensions.cs similarity index 98% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/TextOutputHelperExtensions.cs rename to dotnet/src/InternalUtilities/samples/TextOutputHelperExtensions.cs index 965afd76045c..cfb938a80fec 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/TextOutputHelperExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/TextOutputHelperExtensions.cs @@ -2,8 +2,6 @@ using Xunit.Abstractions; -namespace Examples; - public static class TextOutputHelperExtensions { public static void WriteLine(this ITestOutputHelper testOutputHelper, object target) diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/XunitLogger.cs b/dotnet/src/InternalUtilities/samples/XunitLogger.cs similarity index 97% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/XunitLogger.cs rename to dotnet/src/InternalUtilities/samples/XunitLogger.cs index 77575ac094c9..fb1f55fbeef0 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/XunitLogger.cs +++ b/dotnet/src/InternalUtilities/samples/XunitLogger.cs @@ -4,8 +4,6 @@ using Microsoft.Extensions.Logging; using Xunit.Abstractions; -namespace RepoUtils; - /// /// A logger that writes to the Xunit test output /// diff --git a/dotnet/samples/KernelSyntaxExamples/RepoUtils/YourAppException.cs b/dotnet/src/InternalUtilities/samples/YourAppException.cs similarity index 94% rename from dotnet/samples/KernelSyntaxExamples/RepoUtils/YourAppException.cs rename to dotnet/src/InternalUtilities/samples/YourAppException.cs index 28794dbb1b04..c29a355ebc11 100644 --- a/dotnet/samples/KernelSyntaxExamples/RepoUtils/YourAppException.cs +++ b/dotnet/src/InternalUtilities/samples/YourAppException.cs @@ -2,8 +2,6 @@ using System; -namespace RepoUtils; - public class YourAppException : Exception { public YourAppException() : base() From e9ccaa8c205eb757e0638a6eddaaf91a3e32e203 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Wed, 24 Apr 2024 17:03:36 +0100 Subject: [PATCH 03/24] Update readme --- dotnet/samples/Concepts/README.md | 42 +++++++++++++++---------------- 1 file changed, 21 insertions(+), 21 deletions(-) diff --git a/dotnet/samples/Concepts/README.md b/dotnet/samples/Concepts/README.md index 7c3311fe0f41..feabf5dff1c5 100644 --- a/dotnet/samples/Concepts/README.md +++ b/dotnet/samples/Concepts/README.md @@ -2,24 +2,24 @@ This section contains code snippets that demonstrate the usage of Semantic Kernel features. -| Features | Description | -| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| Functions | Invoking [`Method`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs) or [`Prompt`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromPrompt.cs) functions with [`Kernel`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Kernel.cs) | -| Chat Completion | Using [`ChatCompletion`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/IChatCompletionService.cs) messaging capable service with models | -| Text Generation | Using [`TextGeneration`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextGeneration/ITextGenerationService.cs) capable service with models | -| Text to Image | Using [`TextToImage`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToImage/ITextToImageService.cs) services to generate images | -| Image to Text | Using [`ImageToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ImageToText/IImageToTextService.cs) services to describe images | -| Text to Audio | Using [`TextToAudio`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToAudio/ITextToAudioService.cs) services to generate audio | -| Audio to Text | Using [`AudioToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/AudioToText/IAudioToTextService.cs) services to describe audio | -| Telemetry | Code examples how to setup and use [`Telemetry`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/docs/TELEMETRY.md) | -| Dependency Injection | Examples on using `DI Container` with SK | -| Plugins | Different ways of creating and using [`Plugins`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs) | -| Auto Function Calling | Using `Auto Function Calling` to allow function call capable models to invoke Kernel Functions automatically | -| Filters | Different ways of filtering with Kernel | -| Memory | Using [`Memory`](https://github.com/microsoft/semantic-kernel/tree/main/dotnet/src/SemanticKernel.Abstractions/Memory) AI concepts | -| Search | Using search services information | -| PromptTemplates | Using [`Templates`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/IPromptTemplate.cs) with parametrization for `Prompt` rendering | -| RAG | Different ways of `RAG` (Retrieval-Augmented Generation) | -| Local Models | Using services against `LocalModels` to run models locally | -| Agents | Different ways of using [`Agents`](./AgentSyntax/README.md) | -| AgentSyntax | ⚠️ Work in progress: Moving into [`Agents`](./AgentSyntax/README.md). | +| Features | Description | +| -------- | ----------- | +| Kernel | Using [`Kernel`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Kernel.cs) Features | +| Functions | Invoking [`Method`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromMethod.cs) or [`Prompt`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Core/Functions/KernelFunctionFromPrompt.cs) functions with [`Kernel`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Kernel.cs) | +| ChatCompletion | Using [`ChatCompletion`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ChatCompletion/IChatCompletionService.cs) messaging capable service with models | +| TextGeneration | Using [`TextGeneration`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextGeneration/ITextGenerationService.cs) capable service with models | +| TextToImage | Using [`TextToImage`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToImage/ITextToImageService.cs) services to generate images | +| ImageToText | Using [`ImageToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/ImageToText/IImageToTextService.cs) services to describe images | +| TextToAudio | Using [`TextToAudio`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/TextToAudio/ITextToAudioService.cs) services to generate audio | +| AudioToText | Using [`AudioToText`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/AI/AudioToText/IAudioToTextService.cs) services to describe audio | +| Telemetry | Code examples how to setup and use [`Telemetry`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/docs/TELEMETRY.md) | +| DependencyInjection | Examples on using `DI Container` with SK | +| Plugins | Different ways of creating and using [`Plugins`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/Functions/KernelPlugin.cs) | +| AutoFunctionCalling | Using `Auto Function Calling` to allow function call capable models to invoke Kernel Functions automatically | +| Filters | Different ways of filtering with Kernel | +| Memory | Using [`Memory`](https://github.com/microsoft/semantic-kernel/tree/main/dotnet/src/SemanticKernel.Abstractions/Memory) AI concepts | +| Search | Using search services information | +| PromptTemplates | Using [`Templates`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/IPromptTemplate.cs) with parametrization for `Prompt` rendering | +| RAG | Different ways of `RAG` (Retrieval-Augmented Generation) | +| LocalModels | Using services against `LocalModels` to run models locally | +| Agents | Different ways of using [`Agents`](./AgentSyntax/README.md) | From 194b17df631f5c8af116ee522ce59070b6161b13 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Wed, 24 Apr 2024 17:04:20 +0100 Subject: [PATCH 04/24] Clean Solution --- dotnet/SK-dotnet.sln | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/dotnet/SK-dotnet.sln b/dotnet/SK-dotnet.sln index 34e02ba0a461..a160c7a5e378 100644 --- a/dotnet/SK-dotnet.sln +++ b/dotnet/SK-dotnet.sln @@ -250,6 +250,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Functions", "Functions", "{ EndProjectSection EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Agents.OpenAI", "src\Agents\OpenAI\Agents.OpenAI.csproj", "{644A2F10-324D-429E-A1A3-887EAE64207F}" +EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Concepts", "Concepts", "{A2E102D2-7015-44CD-B8EF-C56758CD37DE}" ProjectSection(SolutionItems) = preProject samples\Concepts\README.md = samples\Concepts\README.md @@ -271,11 +272,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelemetryWithAppInsights", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "samples\GettingStarted\GettingStarted.csproj", "{1D98CF16-5156-40F0-91F0-76294B153DB3}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Tutorials", "Tutorials", "{DA5C4B1B-7194-402D-9B13-0A8A9D8FEE81}" - ProjectSection(SolutionItems) = preProject - samples\Tutorials\README.md = samples\Tutorials\README.md - EndProjectSection -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -733,7 +729,6 @@ Global {E12E15F2-6819-46EA-8892-73E3D60BE76F} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {5C813F83-9FD8-462A-9B38-865CA01C384C} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {1D98CF16-5156-40F0-91F0-76294B153DB3} = {FA3720F1-C99A-49B2-9577-A940257098BF} - {DA5C4B1B-7194-402D-9B13-0A8A9D8FEE81} = {FA3720F1-C99A-49B2-9577-A940257098BF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FBDC56A3-86AD-4323-AA0F-201E59123B83} From 65a5f42ecbb9a5c6857c94343ce34821e3109dc5 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Wed, 24 Apr 2024 17:44:58 +0100 Subject: [PATCH 05/24] Latest changes --- dotnet/SK-dotnet.sln | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/dotnet/SK-dotnet.sln b/dotnet/SK-dotnet.sln index a160c7a5e378..43b3af788608 100644 --- a/dotnet/SK-dotnet.sln +++ b/dotnet/SK-dotnet.sln @@ -272,6 +272,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelemetryWithAppInsights", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "samples\GettingStarted\GettingStarted.csproj", "{1D98CF16-5156-40F0-91F0-76294B153DB3}" EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "..\..\..\github-hack\Demo001\ConsoleApp1\ConsoleApp1.csproj", "{D8425EFB-6F30-4F66-B3EF-B630AF3D011D}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -638,6 +640,12 @@ Global {1D98CF16-5156-40F0-91F0-76294B153DB3}.Publish|Any CPU.Build.0 = Debug|Any CPU {1D98CF16-5156-40F0-91F0-76294B153DB3}.Release|Any CPU.ActiveCfg = Release|Any CPU {1D98CF16-5156-40F0-91F0-76294B153DB3}.Release|Any CPU.Build.0 = Release|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Publish|Any CPU.ActiveCfg = Debug|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Publish|Any CPU.Build.0 = Debug|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -729,6 +737,7 @@ Global {E12E15F2-6819-46EA-8892-73E3D60BE76F} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {5C813F83-9FD8-462A-9B38-865CA01C384C} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {1D98CF16-5156-40F0-91F0-76294B153DB3} = {FA3720F1-C99A-49B2-9577-A940257098BF} + {D8425EFB-6F30-4F66-B3EF-B630AF3D011D} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FBDC56A3-86AD-4323-AA0F-201E59123B83} From a40d1859c9b093cd8ba5db38edd282949b7aa355 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Thu, 25 Apr 2024 17:26:41 +0100 Subject: [PATCH 06/24] Examples structuring and renaming --- dotnet/SK-dotnet.sln | 63 ++-- .../Concepts/AgentSyntax/AgentSyntax.csproj | 55 ---- .../Configuration/ConfigurationException.cs | 32 -- .../Configuration/TestConfiguration.cs | 59 ---- .../AgentSyntax/RepoUtils/EmbeddedResource.cs | 67 ----- .../RepoUtils/TextOutputHelperExtensions.cs | 33 -- .../AgentSyntax/RepoUtils/XunitLogger.cs | 35 --- .../Concepts/Agents/Example01_Agent.cs | 54 ---- .../Concepts/Agents/Example02_Plugins.cs | 61 ---- .../samples/Concepts/Agents/Example03_Chat.cs | 100 ------ .../Agents/Example11_OpenAIAssistant.cs | 68 ----- .../Example12_OpenAIAssistant_Plugins.cs | 74 ----- ...ample13_OpenAIAssistant_CodeInterpreter.cs | 57 ---- .../Example14_OpenAIAssistant_Retrieval.cs | 76 ----- .../Example15_OpenAIAssistant_ChartMaker.cs | 88 ------ .../Concepts/Agents/Example16_MixedChat.cs | 101 ------- ...tAuthoring.cs => Legacy_AgentAuthoring.cs} | 6 +- ...5_AgentCharts.cs => Legacy_AgentCharts.cs} | 8 +- ...ration.cs => Legacy_AgentCollaboration.cs} | 7 +- ...elegation.cs => Legacy_AgentDelegation.cs} | 6 +- ...e75_AgentTools.cs => Legacy_AgentTools.cs} | 9 +- .../{Example70_Agents.cs => Legacy_Agents.cs} | 7 +- ...Agent.cs => Legacy_ChatCompletionAgent.cs} | 8 +- .../MixedChat_Agents.cs | 5 - .../OpenAIAssistant_Agent.cs | 2 - .../OpenAIAssistant_ChartMaker.cs | 3 - .../OpenAIAssistant_CodeInterpreter.cs | 2 - .../OpenAIAssistant_Retrieval.cs | 3 - ...ample82_Audio.cs => OpenAI_AudioToText.cs} | 7 +- ...onCalling.cs => Gemini_FunctionCalling.cs} | 5 +- ...onCalling.cs => OpenAI_FunctionCalling.cs} | 7 +- ... => AzureOpenAIWithData_ChatCompletion.cs} | 4 +- ...onIdentity.cs => ChatHistoryAuthorName.cs} | 10 +- ...ization.cs => ChatHistorySerialization.cs} | 5 +- .../Connectors_CustomHttpClient.cs | 40 +++ ...aming.cs => Connectors_KernelStreaming.cs} | 12 +- ...LLMs.cs => Connectors_WithMultipleLLMs.cs} | 4 +- .../Example44_MultiChatCompletion.cs | 78 ----- .../Google_GeminiChatCompletion.cs | 127 ++++++++ ...> Google_GeminiChatCompletionStreaming.cs} | 33 +- ...sult.cs => Google_GeminiGetModelResult.cs} | 5 +- ...GeminiVision.cs => Google_GeminiVision.cs} | 5 +- ...17_ChatGPT.cs => OpenAI_ChatCompletion.cs} | 5 +- ...> OpenAI_ChatCompletionMultipleChoices.cs} | 4 +- ...t.cs => OpenAI_ChatCompletionStreaming.cs} | 5 +- ...ChatCompletionStreamingMultipleChoices.cs} | 6 +- ....cs => OpenAI_ChatCompletionWithVision.cs} | 5 +- ...t.cs => OpenAI_CustomAzureOpenAIClient.cs} | 8 +- ..._LogitBias.cs => OpenAI_UsingLogitBias.cs} | 5 +- .../Concepts.csproj} | 63 ++-- ...entUsage.cs => HttpClient_Registration.cs} | 35 +-- ...tryHandler.cs => HttpClient_Resiliency.cs} | 12 +- ...42_KernelBuilder.cs => Kernel_Building.cs} | 26 +- ...e40_DIContainer.cs => Kernel_Injecting.cs} | 8 +- .../Filtering/Example76_Filters copy 2.cs | 123 -------- .../Filtering/Example76_PromptFilter.cs | 123 -------- .../{Example76_Filters.cs => Filters.cs} | 4 +- ...7_KernelHooks.cs => Legacy_KernelHooks.cs} | 7 +- .../{Example03_Arguments.cs => Arguments.cs} | 20 +- ...elResult.cs => FunctionResult_Metadata.cs} | 5 +- ...ult.cs => FunctionResult_StronglyTyped.cs} | 5 +- ..._MethodFunctions.cs => MethodFunctions.cs} | 4 +- ...nctions.cs => MethodFunctions_Advanced.cs} | 5 +- ...ctionTypes.cs => MethodFunctions_Types.cs} | 8 +- ...efinition.cs => PromptFunctions_Inline.cs} | 5 +- ...s => PromptFunctions_MultipleArguments.cs} | 4 +- ...geToText.cs => HuggingFace_ImageToText.cs} | 5 +- .../samples/Concepts/Kernel/BuildingKernel.cs | 37 +++ ...Selector.cs => CustomAIServiceSelector.cs} | 5 +- .../Kernel/Example42_KernelBuilder.cs | 103 ------- ...cutionSettings.cs => ExecutionSettings.cs} | 4 +- .../LocalModels/Example20_HuggingFace.cs | 203 ------------- .../HuggingFace_ChatCompletionWithTGI.cs | 94 ++++++ ...cs => MultipleProviders_ChatCompletion.cs} | 7 +- ...ation.cs => Gemini_EmbeddingGeneration.cs} | 31 +- .../Memory/HuggingFace_EmbeddingGeneration.cs | 38 +++ ...MemoryStore.cs => MemoryStore_ReadOnly.cs} | 8 +- ...gin.cs => Plugin_TextMemoryPluginUsage.cs} | 11 +- ...icMemory.cs => SemanticTextMemoryUsage.cs} | 6 +- ...e55_TextChunker.cs => TextChunkerUsage.cs} | 4 +- ...le81_TextEmbedding.cs => TextEmbedding.cs} | 6 +- ...xample66_FunctionCallingStepwisePlanner.cs | 2 - ...e65_HandlebarsPlanner.cs => Handlebars.cs} | 9 +- ...Manifest.cs => ApiManifestBasedPlugins.cs} | 9 +- ...Plugin.cs => ConversationSummaryPlugin.cs} | 10 +- ...> CreatePluginFromOpenAI_AzureKeyVault.cs} | 8 +- ... => CreatePluginFromOpenApiSpec_Github.cs} | 7 +- ...cs => CreatePluginFromOpenApiSpec_Jira.cs} | 11 +- ...KernelPlugin.cs => CustomMutablePlugin.cs} | 13 +- ...s.cs => DescribeAllPluginsAndFunctions.cs} | 6 +- ...dednessChecks.cs => GroundednessChecks.cs} | 6 +- ...GrpcPlugins.cs => ImportPluginFromGrpc.cs} | 2 - ...le21_OpenAIPlugins.cs => OpenAIPlugins.cs} | 6 +- ...ionPrompts.cs => ChatCompletionPrompts.cs} | 4 +- ..._ChatWithPrompts.cs => ChatWithPrompts.cs} | 5 +- ...emplates.cs => MultiplePromptTemplates.cs} | 4 +- ...atGPT.cs => PromptFunctionsWithChatGPT.cs} | 4 +- ...emplateLanguage.cs => TemplateLanguage.cs} | 4 +- ... => WithFunctionCallingStepwisePlanner.cs} | 4 +- .../RAG/{Example78_RAG.cs => WithPlugins.cs} | 10 +- .../Concepts/Resources/EmbeddedResource.cs | 10 +- .../CalendarPlugin/apimanifest.json | 0 .../ContactsPlugin/apimanifest.json | 0 .../DriveItemPlugin/apimanifest.json | 0 .../MessagesPlugin/apimanifest.json | 0 .../ComplexParamsDictionaryPlugin.cs | 21 +- .../StringParamsDictionaryPlugin.cs | 2 - .../Plugins/DictionaryPlugin/openapi.json | 0 .../Resources}/Plugins/EmailPlugin.cs | 0 .../Resources}/Plugins/JiraPlugin/README.md | 0 .../Plugins/JiraPlugin/openapi.json | 0 .../Plugins/MenuPlugin.cs | 2 +- .../Resources}/Plugins/StaticTextPlugin.cs | 0 ...oglePlugins.cs => BingAndGooglePlugins.cs} | 5 +- ...archPlugin.cs => MyAzureAISearchPlugin.cs} | 14 +- ...chQueries.cs => WebSearchQueriesPlugin.cs} | 4 +- .../Custom_TextGenerationService.cs} | 9 +- .../HuggingFace_TextGeneration.cs | 103 +++++++ ...n.cs => OpenAI_TextGenerationStreaming.cs} | 10 +- ...ample82_Audio.cs => OpenAI_TextToAudio.cs} | 9 +- ...8_DallE.cs => OpenAI_TextToImageDalle3.cs} | 5 +- .../GettingStartedWithAgents.csproj | 49 +++ .../Step1_Agent.cs | 3 - .../Step2_Plugins.cs | 27 +- .../Step3_Chat.cs | 6 - .../samples/KernelSyntaxExamples/BaseTest.cs | 52 ---- .../KernelSyntaxExamples/Example26_AADAuth.cs | 66 ---- .../Example74_FlowOrchestrator.cs | 284 ------------------ .../Example80_OpenAIFiles.cs | 72 ----- .../Step9_Safe_Chat_Prompts.cs | 245 --------------- .../AstronomyPlugin/apimanifest.json | 38 --- .../Plugins/MenuPlugin.cs | 49 --- dotnet/samples/KernelSyntaxExamples/README.md | 254 ---------------- .../InternalUtilities/samples}/BaseTest.cs | 6 +- .../samples/ConfigurationNotFoundException.cs | 2 - .../samples/EnumerableExtensions.cs | 3 - dotnet/src/InternalUtilities/samples/Env.cs | 1 - .../samples/PlanExtensions.cs | 13 - .../InternalUtilities/samples/RepoFiles.cs | 1 - .../samples/SamplesInternalUtilities.props | 2 +- .../samples}/TestConfiguration.cs | 51 +++- .../InternalUtilities/samples/XunitLogger.cs | 1 - .../samples/YourAppException.cs | 2 - 143 files changed, 776 insertions(+), 3257 deletions(-) delete mode 100644 dotnet/samples/Concepts/AgentSyntax/AgentSyntax.csproj delete mode 100644 dotnet/samples/Concepts/AgentSyntax/Configuration/ConfigurationException.cs delete mode 100644 dotnet/samples/Concepts/AgentSyntax/Configuration/TestConfiguration.cs delete mode 100644 dotnet/samples/Concepts/AgentSyntax/RepoUtils/EmbeddedResource.cs delete mode 100644 dotnet/samples/Concepts/AgentSyntax/RepoUtils/TextOutputHelperExtensions.cs delete mode 100644 dotnet/samples/Concepts/AgentSyntax/RepoUtils/XunitLogger.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example01_Agent.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example02_Plugins.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example03_Chat.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs delete mode 100644 dotnet/samples/Concepts/Agents/Example16_MixedChat.cs rename dotnet/samples/Concepts/Agents/{Example73_AgentAuthoring.cs => Legacy_AgentAuthoring.cs} (96%) rename dotnet/samples/Concepts/Agents/{Example85_AgentCharts.cs => Legacy_AgentCharts.cs} (95%) rename dotnet/samples/Concepts/Agents/{Example72_AgentCollaboration.cs => Legacy_AgentCollaboration.cs} (97%) rename dotnet/samples/Concepts/Agents/{Example71_AgentDelegation.cs => Legacy_AgentDelegation.cs} (94%) rename dotnet/samples/Concepts/Agents/{Example75_AgentTools.cs => Legacy_AgentTools.cs} (96%) rename dotnet/samples/Concepts/Agents/{Example70_Agents.cs => Legacy_Agents.cs} (97%) rename dotnet/samples/Concepts/Agents/{Example79_ChatCompletionAgent.cs => Legacy_ChatCompletionAgent.cs} (96%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/MixedChat_Agents.cs (97%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/OpenAIAssistant_Agent.cs (98%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/OpenAIAssistant_ChartMaker.cs (97%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/OpenAIAssistant_CodeInterpreter.cs (97%) rename dotnet/samples/Concepts/{AgentSyntax => Agents}/OpenAIAssistant_Retrieval.cs (97%) rename dotnet/samples/Concepts/AudioToText/{Example82_Audio.cs => OpenAI_AudioToText.cs} (90%) rename dotnet/samples/Concepts/AutoFunctionCalling/{Example98_GeminiFunctionCalling.cs => Gemini_FunctionCalling.cs} (98%) rename dotnet/samples/Concepts/AutoFunctionCalling/{Example59_OpenAIFunctionCalling.cs => OpenAI_FunctionCalling.cs} (97%) rename dotnet/samples/Concepts/ChatCompletion/{Example54_AzureChatCompletionWithData.cs => AzureOpenAIWithData_ChatCompletion.cs} (97%) rename dotnet/samples/Concepts/ChatCompletion/{Example37_CompletionIdentity.cs => ChatHistoryAuthorName.cs} (91%) rename dotnet/samples/Concepts/ChatCompletion/{Example87_ChatHistorySerialization.cs => ChatHistorySerialization.cs} (97%) create mode 100644 dotnet/samples/Concepts/ChatCompletion/Connectors_CustomHttpClient.cs rename dotnet/samples/Concepts/ChatCompletion/{Example67_KernelStreaming.cs => Connectors_KernelStreaming.cs} (88%) rename dotnet/samples/Concepts/ChatCompletion/{Example61_MultipleLLMs.cs => Connectors_WithMultipleLLMs.cs} (95%) delete mode 100644 dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs create mode 100644 dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletion.cs rename dotnet/samples/Concepts/ChatCompletion/{Example96_GeminiChatCompletion.cs => Google_GeminiChatCompletionStreaming.cs} (81%) rename dotnet/samples/Concepts/ChatCompletion/{Example95_GeminiGetModelResult.cs => Google_GeminiGetModelResult.cs} (94%) rename dotnet/samples/Concepts/ChatCompletion/{Example97_GeminiVision.cs => Google_GeminiVision.cs} (97%) rename dotnet/samples/Concepts/ChatCompletion/{Example17_ChatGPT.cs => OpenAI_ChatCompletion.cs} (96%) rename dotnet/samples/Concepts/ChatCompletion/{Example36_MultiCompletion.cs => OpenAI_ChatCompletionMultipleChoices.cs} (94%) rename dotnet/samples/Concepts/ChatCompletion/{Example33_StreamingChat.cs => OpenAI_ChatCompletionStreaming.cs} (95%) rename dotnet/samples/Concepts/ChatCompletion/{Example45_MultiStreamingChatCompletion.cs => OpenAI_ChatCompletionStreamingMultipleChoices.cs} (96%) rename dotnet/samples/Concepts/ChatCompletion/{Example68_GPTVision.cs => OpenAI_ChatCompletionWithVision.cs} (88%) rename dotnet/samples/Concepts/ChatCompletion/{Example52_CustomOpenAIClient.cs => OpenAI_CustomAzureOpenAIClient.cs} (90%) rename dotnet/samples/Concepts/ChatCompletion/{Example49_LogitBias.cs => OpenAI_UsingLogitBias.cs} (96%) rename dotnet/samples/{KernelSyntaxExamples/KernelSyntax.csproj => Concepts/Concepts.csproj} (86%) rename dotnet/samples/Concepts/DependencyInjection/{Example41_HttpClientUsage.cs => HttpClient_Registration.cs} (64%) rename dotnet/samples/Concepts/DependencyInjection/{Example08_RetryHandler.cs => HttpClient_Resiliency.cs} (85%) rename dotnet/samples/Concepts/DependencyInjection/{Example42_KernelBuilder.cs => Kernel_Building.cs} (79%) rename dotnet/samples/Concepts/DependencyInjection/{Example40_DIContainer.cs => Kernel_Injecting.cs} (90%) delete mode 100644 dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs delete mode 100644 dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs rename dotnet/samples/Concepts/Filtering/{Example76_Filters.cs => Filters.cs} (97%) rename dotnet/samples/Concepts/Filtering/{Example57_KernelHooks.cs => Legacy_KernelHooks.cs} (98%) rename dotnet/samples/Concepts/Functions/{Example03_Arguments.cs => Arguments.cs} (70%) rename dotnet/samples/Concepts/Functions/{Example43_GetModelResult.cs => FunctionResult_Metadata.cs} (94%) rename dotnet/samples/Concepts/Functions/{Example77_StronglyTypedFunctionResult.cs => FunctionResult_StronglyTyped.cs} (96%) rename dotnet/samples/Concepts/Functions/{Example01_MethodFunctions.cs => MethodFunctions.cs} (79%) rename dotnet/samples/Concepts/Functions/{Example60_AdvancedMethodFunctions.cs => MethodFunctions_Advanced.cs} (96%) rename dotnet/samples/Concepts/Functions/{Example09_FunctionTypes.cs => MethodFunctions_Types.cs} (98%) rename dotnet/samples/Concepts/Functions/{Example05_InlineFunctionDefinition.cs => PromptFunctions_Inline.cs} (93%) rename dotnet/samples/Concepts/Functions/{Example56_TemplateMethodFunctionsWithMultipleArguments.cs => PromptFunctions_MultipleArguments.cs} (95%) rename dotnet/samples/Concepts/ImageToText/{Example86_ImageToText.cs => HuggingFace_ImageToText.cs} (91%) create mode 100644 dotnet/samples/Concepts/Kernel/BuildingKernel.cs rename dotnet/samples/Concepts/Kernel/{Example62_CustomAIServiceSelector.cs => CustomAIServiceSelector.cs} (95%) delete mode 100644 dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs rename dotnet/samples/Concepts/Kernel/{Example58_ConfigureExecutionSettings.cs => ExecutionSettings.cs} (96%) delete mode 100644 dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs create mode 100644 dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs rename dotnet/samples/Concepts/LocalModels/{Example88_CustomMessageAPIEndpoint.cs => MultipleProviders_ChatCompletion.cs} (95%) rename dotnet/samples/Concepts/Memory/{Example99_GeminiEmbeddingGeneration.cs => Gemini_EmbeddingGeneration.cs} (89%) create mode 100644 dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs rename dotnet/samples/Concepts/Memory/{Example25_ReadOnlyMemoryStore.cs => MemoryStore_ReadOnly.cs} (97%) rename dotnet/samples/Concepts/Memory/{Example15_TextMemoryPlugin.cs => Plugin_TextMemoryPluginUsage.cs} (98%) rename dotnet/samples/Concepts/Memory/{Example14_SemanticMemory.cs => SemanticTextMemoryUsage.cs} (97%) rename dotnet/samples/Concepts/Memory/{Example55_TextChunker.cs => TextChunkerUsage.cs} (96%) rename dotnet/samples/Concepts/Memory/{Example81_TextEmbedding.cs => TextEmbedding.cs} (97%) rename dotnet/samples/Concepts/Planners/{Example65_HandlebarsPlanner.cs => Handlebars.cs} (98%) rename dotnet/samples/Concepts/Plugins/{Example83_ApiManifest.cs => ApiManifestBasedPlugins.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example13_ConversationSummaryPlugin.cs => ConversationSummaryPlugin.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example22_OpenAIPlugin_AzureKeyVault.cs => CreatePluginFromOpenAI_AzureKeyVault.cs} (98%) rename dotnet/samples/Concepts/Plugins/{Example23_OpenAPIPlugin.cs => CreatePluginFromOpenApiSpec_Github.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example24_OpenApiPlugin_Jira.cs => CreatePluginFromOpenApiSpec_Jira.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example69_MutableKernelPlugin.cs => CustomMutablePlugin.cs} (90%) rename dotnet/samples/Concepts/Plugins/{Example10_DescribeAllPluginsAndFunctions.cs => DescribeAllPluginsAndFunctions.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example48_GroundednessChecks.cs => GroundednessChecks.cs} (98%) rename dotnet/samples/Concepts/Plugins/{Example35_GrpcPlugins.cs => ImportPluginFromGrpc.cs} (96%) rename dotnet/samples/Concepts/Plugins/{Example21_OpenAIPlugins.cs => OpenAIPlugins.cs} (93%) rename dotnet/samples/Concepts/PromptTemplates/{Example63_ChatCompletionPrompts.cs => ChatCompletionPrompts.cs} (93%) rename dotnet/samples/Concepts/PromptTemplates/{Example30_ChatWithPrompts.cs => ChatWithPrompts.cs} (97%) rename dotnet/samples/Concepts/PromptTemplates/{Example64_MultiplePromptTemplates.cs => MultiplePromptTemplates.cs} (94%) rename dotnet/samples/Concepts/PromptTemplates/{Example27_PromptFunctionsUsingChatGPT.cs => PromptFunctionsWithChatGPT.cs} (89%) rename dotnet/samples/Concepts/PromptTemplates/{Example06_TemplateLanguage.cs => TemplateLanguage.cs} (95%) rename dotnet/samples/Concepts/RAG/{Example80_FunctionCallingPlannerWithRAG.cs => WithFunctionCallingStepwisePlanner.cs} (95%) rename dotnet/samples/Concepts/RAG/{Example78_RAG.cs => WithPlugins.cs} (90%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/ApiManifestPlugins/CalendarPlugin/apimanifest.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/ApiManifestPlugins/ContactsPlugin/apimanifest.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/ApiManifestPlugins/DriveItemPlugin/apimanifest.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/ApiManifestPlugins/MessagesPlugin/apimanifest.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs (91%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs (97%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/DictionaryPlugin/openapi.json (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/EmailPlugin.cs (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/JiraPlugin/README.md (100%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/JiraPlugin/openapi.json (100%) rename dotnet/samples/Concepts/{AgentSyntax => Resources}/Plugins/MenuPlugin.cs (96%) rename dotnet/samples/{KernelSyntaxExamples => Concepts/Resources}/Plugins/StaticTextPlugin.cs (100%) rename dotnet/samples/Concepts/Search/{Example07_BingAndGooglePlugins.cs => BingAndGooglePlugins.cs} (98%) rename dotnet/samples/Concepts/Search/{Example84_AzureAISearchPlugin.cs => MyAzureAISearchPlugin.cs} (94%) rename dotnet/samples/Concepts/Search/{Example11_WebSearchQueries.cs => WebSearchQueriesPlugin.cs} (88%) rename dotnet/samples/Concepts/{LocalModels/Example16_CustomLLM.cs => TextGeneration/Custom_TextGenerationService.cs} (95%) create mode 100644 dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs rename dotnet/samples/Concepts/TextGeneration/{Example32_StreamingCompletion.cs => OpenAI_TextGenerationStreaming.cs} (87%) rename dotnet/samples/Concepts/TextToAudio/{Example82_Audio.cs => OpenAI_TextToAudio.cs} (85%) rename dotnet/samples/Concepts/TextToImage/{Example18_DallE.cs => OpenAI_TextToImageDalle3.cs} (98%) create mode 100644 dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj rename dotnet/samples/{Concepts/AgentSyntax/Getting_Started => GettingStartedWithAgents}/Step1_Agent.cs (96%) rename dotnet/samples/{Concepts/AgentSyntax/Getting_Started => GettingStartedWithAgents}/Step2_Plugins.cs (75%) rename dotnet/samples/{Concepts/AgentSyntax/Getting_Started => GettingStartedWithAgents}/Step3_Chat.cs (96%) delete mode 100644 dotnet/samples/KernelSyntaxExamples/BaseTest.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/Example26_AADAuth.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/Example80_OpenAIFiles.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/Getting_Started/Step9_Safe_Chat_Prompts.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/AstronomyPlugin/apimanifest.json delete mode 100644 dotnet/samples/KernelSyntaxExamples/Plugins/MenuPlugin.cs delete mode 100644 dotnet/samples/KernelSyntaxExamples/README.md rename dotnet/{samples/Concepts/AgentSyntax => src/InternalUtilities/samples}/BaseTest.cs (94%) delete mode 100644 dotnet/src/InternalUtilities/samples/PlanExtensions.cs rename dotnet/{samples/KernelSyntaxExamples => src/InternalUtilities/samples}/TestConfiguration.cs (80%) diff --git a/dotnet/SK-dotnet.sln b/dotnet/SK-dotnet.sln index ff1a6e7435bf..c64294344291 100644 --- a/dotnet/SK-dotnet.sln +++ b/dotnet/SK-dotnet.sln @@ -12,8 +12,6 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{FA37 samples\README.md = samples\README.md EndProjectSection EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "KernelSyntax", "samples\KernelSyntaxExamples\KernelSyntax.csproj", "{47C6F821-5103-431F-B3B8-A2868A68BB78}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "IntegrationTests", "src\IntegrationTests\IntegrationTests.csproj", "{E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Plugins.Document", "src\Plugins\Plugins.Document\Plugins.Document.csproj", "{F94D1938-9DB7-4B24-9FF3-166DDFD96330}" @@ -253,17 +251,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Functions", "Functions", "{ EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Agents.OpenAI", "src\Agents\OpenAI\Agents.OpenAI.csproj", "{644A2F10-324D-429E-A1A3-887EAE64207F}" EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Concepts", "Concepts", "{A2E102D2-7015-44CD-B8EF-C56758CD37DE}" - ProjectSection(SolutionItems) = preProject - samples\Concepts\README.md = samples\Concepts\README.md - EndProjectSection -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Demos", "Demos", "{5D4C0700-BBB5-418F-A7B2-F392B9A18263}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LearnResources", "samples\LearnResources\LearnResources.csproj", "{B04C26BC-A933-4A53-BE17-7875EB12E012}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "AgentSyntax", "samples\Concepts\AgentSyntax\AgentSyntax.csproj", "{37847DE5-C3B0-41ED-8749-98B9F429B9E5}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CreateChatGptPlugin", "samples\Demos\CreateChatGptPlugin\Solution\CreateChatGptPlugin.csproj", "{E6204E79-EFBF-499E-9743-85199310A455}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HomeAutomation", "samples\Demos\HomeAutomation\HomeAutomation.csproj", "{CBEEF941-AEC6-42A4-A567-B5641CEFBB87}" @@ -274,7 +265,23 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "TelemetryWithAppInsights", EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GettingStarted", "samples\GettingStarted\GettingStarted.csproj", "{1D98CF16-5156-40F0-91F0-76294B153DB3}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConsoleApp1", "..\..\..\github-hack\Demo001\ConsoleApp1\ConsoleApp1.csproj", "{D8425EFB-6F30-4F66-B3EF-B630AF3D011D}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GettingStartedWithAgents", "samples\GettingStartedWithAgents\GettingStartedWithAgents.csproj", "{87DA81FE-112E-4AF5-BEFB-0B91B993F749}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "samples", "samples", "{77E141BA-AF5E-4C01-A970-6C07AC3CD55A}" + ProjectSection(SolutionItems) = preProject + src\InternalUtilities\samples\ConfigurationNotFoundException.cs = src\InternalUtilities\samples\ConfigurationNotFoundException.cs + src\InternalUtilities\samples\EnumerableExtensions.cs = src\InternalUtilities\samples\EnumerableExtensions.cs + src\InternalUtilities\samples\Env.cs = src\InternalUtilities\samples\Env.cs + src\InternalUtilities\samples\ObjectExtensions.cs = src\InternalUtilities\samples\ObjectExtensions.cs + src\InternalUtilities\samples\PlanExtensions.cs = src\InternalUtilities\samples\PlanExtensions.cs + src\InternalUtilities\samples\RepoFiles.cs = src\InternalUtilities\samples\RepoFiles.cs + src\InternalUtilities\samples\SamplesInternalUtilities.props = src\InternalUtilities\samples\SamplesInternalUtilities.props + src\InternalUtilities\samples\TextOutputHelperExtensions.cs = src\InternalUtilities\samples\TextOutputHelperExtensions.cs + src\InternalUtilities\samples\XunitLogger.cs = src\InternalUtilities\samples\XunitLogger.cs + src\InternalUtilities\samples\YourAppException.cs = src\InternalUtilities\samples\YourAppException.cs + EndProjectSection +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Concepts", "samples\Concepts\Concepts.csproj", "{925B1185-8B58-4E2D-95C9-4CA0BA9364E5}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -289,11 +296,6 @@ Global {A284C7EB-2248-4A75-B112-F5DCDE65410D}.Publish|Any CPU.Build.0 = Publish|Any CPU {A284C7EB-2248-4A75-B112-F5DCDE65410D}.Release|Any CPU.ActiveCfg = Release|Any CPU {A284C7EB-2248-4A75-B112-F5DCDE65410D}.Release|Any CPU.Build.0 = Release|Any CPU - {47C6F821-5103-431F-B3B8-A2868A68BB78}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {47C6F821-5103-431F-B3B8-A2868A68BB78}.Debug|Any CPU.Build.0 = Debug|Any CPU - {47C6F821-5103-431F-B3B8-A2868A68BB78}.Publish|Any CPU.ActiveCfg = Release|Any CPU - {47C6F821-5103-431F-B3B8-A2868A68BB78}.Release|Any CPU.ActiveCfg = Release|Any CPU - {47C6F821-5103-431F-B3B8-A2868A68BB78}.Release|Any CPU.Build.0 = Release|Any CPU {E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4}.Debug|Any CPU.Build.0 = Debug|Any CPU {E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4}.Publish|Any CPU.ActiveCfg = Release|Any CPU @@ -612,12 +614,6 @@ Global {B04C26BC-A933-4A53-BE17-7875EB12E012}.Publish|Any CPU.Build.0 = Debug|Any CPU {B04C26BC-A933-4A53-BE17-7875EB12E012}.Release|Any CPU.ActiveCfg = Release|Any CPU {B04C26BC-A933-4A53-BE17-7875EB12E012}.Release|Any CPU.Build.0 = Release|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Publish|Any CPU.ActiveCfg = Debug|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Publish|Any CPU.Build.0 = Debug|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {37847DE5-C3B0-41ED-8749-98B9F429B9E5}.Release|Any CPU.Build.0 = Release|Any CPU {E6204E79-EFBF-499E-9743-85199310A455}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {E6204E79-EFBF-499E-9743-85199310A455}.Debug|Any CPU.Build.0 = Debug|Any CPU {E6204E79-EFBF-499E-9743-85199310A455}.Publish|Any CPU.ActiveCfg = Debug|Any CPU @@ -648,19 +644,24 @@ Global {1D98CF16-5156-40F0-91F0-76294B153DB3}.Publish|Any CPU.Build.0 = Debug|Any CPU {1D98CF16-5156-40F0-91F0-76294B153DB3}.Release|Any CPU.ActiveCfg = Release|Any CPU {1D98CF16-5156-40F0-91F0-76294B153DB3}.Release|Any CPU.Build.0 = Release|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Debug|Any CPU.Build.0 = Debug|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Publish|Any CPU.ActiveCfg = Debug|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Publish|Any CPU.Build.0 = Debug|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Release|Any CPU.ActiveCfg = Release|Any CPU - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D}.Release|Any CPU.Build.0 = Release|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Debug|Any CPU.Build.0 = Debug|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Publish|Any CPU.ActiveCfg = Debug|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Publish|Any CPU.Build.0 = Debug|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Release|Any CPU.ActiveCfg = Release|Any CPU + {87DA81FE-112E-4AF5-BEFB-0B91B993F749}.Release|Any CPU.Build.0 = Release|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Publish|Any CPU.ActiveCfg = Debug|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Publish|Any CPU.Build.0 = Debug|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(NestedProjects) = preSolution {A284C7EB-2248-4A75-B112-F5DCDE65410D} = {831DDCA2-7D2C-4C31-80DB-6BDB3E1F7AE0} - {47C6F821-5103-431F-B3B8-A2868A68BB78} = {A2E102D2-7015-44CD-B8EF-C56758CD37DE} {E4B777A1-28E1-41BE-96AE-7F3EC61FD5D4} = {831DDCA2-7D2C-4C31-80DB-6BDB3E1F7AE0} {F94D1938-9DB7-4B24-9FF3-166DDFD96330} = {D6D598DF-C17C-46F4-B2B9-CDE82E2DE132} {689A5041-BAE7-448F-9BDC-4672E96249AA} = {D6D598DF-C17C-46F4-B2B9-CDE82E2DE132} @@ -737,16 +738,16 @@ Global {91B8BEAF-4ADC-4014-AC6B-C563F41A8DD1} = {6823CD5E-2ABE-41EB-B865-F86EC13F0CF9} {4DFB3897-0319-4DF2-BCFE-E6E0648297D2} = {958AD708-F048-4FAF-94ED-D2F2B92748B9} {644A2F10-324D-429E-A1A3-887EAE64207F} = {6823CD5E-2ABE-41EB-B865-F86EC13F0CF9} - {A2E102D2-7015-44CD-B8EF-C56758CD37DE} = {FA3720F1-C99A-49B2-9577-A940257098BF} {5D4C0700-BBB5-418F-A7B2-F392B9A18263} = {FA3720F1-C99A-49B2-9577-A940257098BF} {B04C26BC-A933-4A53-BE17-7875EB12E012} = {FA3720F1-C99A-49B2-9577-A940257098BF} - {37847DE5-C3B0-41ED-8749-98B9F429B9E5} = {A2E102D2-7015-44CD-B8EF-C56758CD37DE} {E6204E79-EFBF-499E-9743-85199310A455} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {CBEEF941-AEC6-42A4-A567-B5641CEFBB87} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {E12E15F2-6819-46EA-8892-73E3D60BE76F} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {5C813F83-9FD8-462A-9B38-865CA01C384C} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} {1D98CF16-5156-40F0-91F0-76294B153DB3} = {FA3720F1-C99A-49B2-9577-A940257098BF} - {D8425EFB-6F30-4F66-B3EF-B630AF3D011D} = {5D4C0700-BBB5-418F-A7B2-F392B9A18263} + {87DA81FE-112E-4AF5-BEFB-0B91B993F749} = {FA3720F1-C99A-49B2-9577-A940257098BF} + {77E141BA-AF5E-4C01-A970-6C07AC3CD55A} = {4D3DAE63-41C6-4E1C-A35A-E77BDFC40675} + {925B1185-8B58-4E2D-95C9-4CA0BA9364E5} = {FA3720F1-C99A-49B2-9577-A940257098BF} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FBDC56A3-86AD-4323-AA0F-201E59123B83} diff --git a/dotnet/samples/Concepts/AgentSyntax/AgentSyntax.csproj b/dotnet/samples/Concepts/AgentSyntax/AgentSyntax.csproj deleted file mode 100644 index 7f6111c23ef9..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/AgentSyntax.csproj +++ /dev/null @@ -1,55 +0,0 @@ - - - 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - - - AgentSyntax - - net6.0 - LatestMajor - true - false - - CS8618,IDE0009,CA1051,CA1050,CA1707,CA2007,VSTHRD111,CS1591,RCS1110,CA5394,SKEXP0001,SKEXP0010,SKEXP0110 - Library - - - - - - - runtime; build; native; contentfiles; analyzers; buildtransitive - all - - - - - - - - - - - - - - - - - - - - - - - - - Always - - - - - - - - \ No newline at end of file diff --git a/dotnet/samples/Concepts/AgentSyntax/Configuration/ConfigurationException.cs b/dotnet/samples/Concepts/AgentSyntax/Configuration/ConfigurationException.cs deleted file mode 100644 index f9d3b1d0f725..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/Configuration/ConfigurationException.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; - -namespace Configuration; - -public sealed class ConfigurationException : Exception -{ - public string? Section { get; } - public string? Key { get; } - - public ConfigurationException(string section, string key) - : base($"Configuration key '{section}:{key}' not found") - { - this.Section = section; - this.Key = key; - } - - public ConfigurationException(string section) - : base($"Configuration section '{section}' not found") - { - this.Section = section; - } - - public ConfigurationException() : base() - { - } - - public ConfigurationException(string? message, Exception? innerException) : base(message, innerException) - { - } -} diff --git a/dotnet/samples/Concepts/AgentSyntax/Configuration/TestConfiguration.cs b/dotnet/samples/Concepts/AgentSyntax/Configuration/TestConfiguration.cs deleted file mode 100644 index 5d67a9a511e5..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/Configuration/TestConfiguration.cs +++ /dev/null @@ -1,59 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Configuration; - -namespace Configuration; - -public sealed class TestConfiguration -{ - private readonly IConfigurationRoot _configRoot; - private static TestConfiguration? s_instance; - - private TestConfiguration(IConfigurationRoot configRoot) - { - this._configRoot = configRoot; - } - - public static void Initialize(IConfigurationRoot configRoot) - { - s_instance = new TestConfiguration(configRoot); - } - - public static OpenAIConfig OpenAI => LoadSection(); - public static AzureOpenAIConfig AzureOpenAI => LoadSection(); - - private static T LoadSection([CallerMemberName] string? caller = null) - { - if (s_instance == null) - { - throw new InvalidOperationException( - "TestConfiguration must be initialized with a call to Initialize(IConfigurationRoot) before accessing configuration values."); - } - - if (string.IsNullOrEmpty(caller)) - { - throw new ArgumentNullException(nameof(caller)); - } - return s_instance._configRoot.GetSection(caller).Get() ?? - throw new ConfigurationException(section: caller); - } - - public class OpenAIConfig - { - public string ModelId { get; set; } = string.Empty; - public string ChatModelId { get; set; } = string.Empty; - public string EmbeddingModelId { get; set; } = string.Empty; - public string ApiKey { get; set; } = string.Empty; - } - - public class AzureOpenAIConfig - { - public string ServiceId { get; set; } = string.Empty; - public string DeploymentName { get; set; } = string.Empty; - public string ChatDeploymentName { get; set; } = string.Empty; - public string Endpoint { get; set; } = string.Empty; - public string ApiKey { get; set; } = string.Empty; - } -} diff --git a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/EmbeddedResource.cs b/dotnet/samples/Concepts/AgentSyntax/RepoUtils/EmbeddedResource.cs deleted file mode 100644 index f9d9c7f650dc..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/EmbeddedResource.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; -using Configuration; - -namespace Resources; - -/// -/// Resource helper to load resources embedded in the assembly. By default we embed only -/// text files, so the helper is limited to returning text. -/// -/// You can find information about embedded resources here: -/// * https://learn.microsoft.com/dotnet/core/extensions/create-resource-files -/// * https://learn.microsoft.com/dotnet/api/system.reflection.assembly.getmanifestresourcestream?view=net-7.0 -/// -/// To know which resources are embedded, check the csproj file. -/// -internal static class EmbeddedResource -{ - private static readonly string? s_namespace = typeof(EmbeddedResource).Namespace; - - internal static string Read(string fileName) - { - // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. - Assembly assembly = - typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); - - // Resources are mapped like types, using the namespace and appending "." (dot) and the file name - var resourceName = $"{s_namespace}." + fileName; - using Stream resource = - assembly.GetManifestResourceStream(resourceName) ?? - throw new ConfigurationException($"{resourceName} resource not found"); - - // Return the resource content, in text format. - using var reader = new StreamReader(resource); - return reader.ReadToEnd(); - } - - internal static Stream? ReadStream(string fileName) - { - // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. - Assembly assembly = - typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); - - // Resources are mapped like types, using the namespace and appending "." (dot) and the file name - var resourceName = $"{s_namespace}." + fileName; - return assembly.GetManifestResourceStream(resourceName); - } - - internal async static Task> ReadAllAsync(string fileName) - { - await using Stream? resourceStream = ReadStream(fileName); - using var memoryStream = new MemoryStream(); - - // Copy the resource stream to the memory stream - await resourceStream!.CopyToAsync(memoryStream); - - // Convert the memory stream's buffer to ReadOnlyMemory - // Note: ToArray() creates a copy of the buffer, which is fine for converting to ReadOnlyMemory - return new ReadOnlyMemory(memoryStream.ToArray()); - } -} diff --git a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/TextOutputHelperExtensions.cs b/dotnet/samples/Concepts/AgentSyntax/RepoUtils/TextOutputHelperExtensions.cs deleted file mode 100644 index 965afd76045c..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/TextOutputHelperExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using Xunit.Abstractions; - -namespace Examples; - -public static class TextOutputHelperExtensions -{ - public static void WriteLine(this ITestOutputHelper testOutputHelper, object target) - { - testOutputHelper.WriteLine(target.ToString()); - } - - public static void WriteLine(this ITestOutputHelper testOutputHelper) - { - testOutputHelper.WriteLine(string.Empty); - } - - public static void Write(this ITestOutputHelper testOutputHelper) - { - testOutputHelper.WriteLine(string.Empty); - } - - /// - /// Current interface ITestOutputHelper does not have a Write method. This extension method adds it to make it analogous to Console.Write when used in Console apps. - /// - /// TestOutputHelper - /// Target object to write - public static void Write(this ITestOutputHelper testOutputHelper, object target) - { - testOutputHelper.WriteLine(target.ToString()); - } -} diff --git a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/XunitLogger.cs b/dotnet/samples/Concepts/AgentSyntax/RepoUtils/XunitLogger.cs deleted file mode 100644 index 77575ac094c9..000000000000 --- a/dotnet/samples/Concepts/AgentSyntax/RepoUtils/XunitLogger.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; - -namespace RepoUtils; - -/// -/// A logger that writes to the Xunit test output -/// -internal sealed class XunitLogger(ITestOutputHelper output) : ILoggerFactory, ILogger, IDisposable -{ - /// - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - => output.WriteLine(state?.ToString()); - - /// - public bool IsEnabled(LogLevel logLevel) => true; - - /// - public IDisposable BeginScope(TState state) where TState : notnull - => this; - - /// - public void Dispose() - { - // This class is marked as disposable to support the BeginScope method. - // However, there is no need to dispose anything. - } - - public ILogger CreateLogger(string categoryName) => this; - - public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException(); -} diff --git a/dotnet/samples/Concepts/Agents/Example01_Agent.cs b/dotnet/samples/Concepts/Agents/Example01_Agent.cs deleted file mode 100644 index eb2826de82c9..000000000000 --- a/dotnet/samples/Concepts/Agents/Example01_Agent.cs +++ /dev/null @@ -1,54 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace GettingStarted; - -/// -/// Demonstrate creation of and -/// eliciting its response to three explicit user messages. -/// -public class Step1_Agent(ITestOutputHelper output) : BaseTest(output) -{ - private const string ParrotName = "Parrot"; - private const string ParrotInstructions = "Repeat the user message in the voice of a pirate and then end with a parrot sound."; - - [Fact] - public async Task RunAsync() - { - // Define the agent - ChatCompletionAgent agent = - new() - { - Name = ParrotName, - Instructions = ParrotInstructions, - Kernel = this.CreateKernelWithChatCompletion(), - }; - - // Create a chat for agent interaction. For more, see: Example03_Chat. - AgentGroupChat chat = new(); - - // Respond to user input - await InvokeAgentAsync("Fortune favors the bold."); - await InvokeAgentAsync("I came, I saw, I conquered."); - await InvokeAgentAsync("Practice makes perfect."); - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example02_Plugins.cs b/dotnet/samples/Concepts/Agents/Example02_Plugins.cs deleted file mode 100644 index ea99b955ee04..000000000000 --- a/dotnet/samples/Concepts/Agents/Example02_Plugins.cs +++ /dev/null @@ -1,61 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.ChatCompletion; -using Microsoft.SemanticKernel.Connectors.OpenAI; -using Plugins; -using Xunit; -using Xunit.Abstractions; - -namespace GettingStarted; - -/// -/// Demonstrate creation of with a , -/// and then eliciting its response to explicit user messages. -/// -public class Step2_Plugins(ITestOutputHelper output) : BaseTest(output) -{ - private const string HostName = "Host"; - private const string HostInstructions = "Answer questions about the menu."; - - [Fact] - public async Task RunAsync() - { - // Define the agent - ChatCompletionAgent agent = - new() - { - Instructions = HostInstructions, - Name = HostName, - Kernel = this.CreateKernelWithChatCompletion(), - ExecutionSettings = new OpenAIPromptExecutionSettings() { ToolCallBehavior = ToolCallBehavior.AutoInvokeKernelFunctions }, - }; - - // Initialize plugin and add to the agent's Kernel (same as direct Kernel usage). - KernelPlugin plugin = KernelPluginFactory.CreateFromType(); - agent.Kernel.Plugins.Add(plugin); - - // Create a chat for agent interaction. For more, see: Example03_Chat. - AgentGroupChat chat = new(); - - // Respond to user input, invoking functions where appropriate. - await InvokeAgentAsync("Hello"); - await InvokeAgentAsync("What is the special soup?"); - await InvokeAgentAsync("What is the special drink?"); - await InvokeAgentAsync("Thank you"); - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example03_Chat.cs b/dotnet/samples/Concepts/Agents/Example03_Chat.cs deleted file mode 100644 index 687f0101f473..000000000000 --- a/dotnet/samples/Concepts/Agents/Example03_Chat.cs +++ /dev/null @@ -1,100 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Examples; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.Chat; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace GettingStarted; - -/// -/// Demonstrate creation of with -/// that inform how chat proceeds with regards to: Agent selection, chat continuation, and maximum -/// number of agent interactions. -/// -public class Step3_Chat(ITestOutputHelper output) : BaseTest(output) -{ - private const string ReviewerName = "ArtDirector"; - private const string ReviewerInstructions = - """ - You are an art director who has opinions about copywriting born of a love for David Ogilvy. - The goal is to determine is the given copy is acceptable to print. - If so, state that it is approved. - If not, provide insight on how to refine suggested copy without example. - """; - - private const string CopyWriterName = "Writer"; - private const string CopyWriterInstructions = - """ - You are a copywriter with ten years of experience and are known for brevity and a dry humor. - You're laser focused on the goal at hand. Don't waste time with chit chat. - The goal is to refine and decide on the single best copy as an expert in the field. - Consider suggestions when refining an idea. - """; - - [Fact] - public async Task RunAsync() - { - // Define the agents - ChatCompletionAgent agentReviewer = - new() - { - Instructions = ReviewerInstructions, - Name = ReviewerName, - Kernel = this.CreateKernelWithChatCompletion(), - }; - - ChatCompletionAgent agentWriter = - new() - { - Instructions = CopyWriterInstructions, - Name = CopyWriterName, - Kernel = this.CreateKernelWithChatCompletion(), - }; - - // Create a chat for agent interaction. - AgentGroupChat chat = - new(agentWriter, agentReviewer) - { - ExecutionSettings = - new() - { - // Here a TerminationStrategy subclass is used that will terminate when - // an assistant message contains the term "approve". - TerminationStrategy = - new ApprovalTerminationStrategy() - { - // Only the art-director may approve. - Agents = [agentReviewer], - // Limit total number of turns - MaximumIterations = 10, - } - } - }; - - // Invoke chat and display messages. - string input = "concept: maps made out of egg cartons."; - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync()) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - - this.WriteLine($"# IS COMPLETE: {chat.IsComplete}"); - } - - private sealed class ApprovalTerminationStrategy : TerminationStrategy - { - // Terminate when the final message contains the term "approve" - protected override Task ShouldAgentTerminateAsync(Agent agent, IReadOnlyList history, CancellationToken cancellationToken) - => Task.FromResult(history[history.Count - 1].Content?.Contains("approve", StringComparison.OrdinalIgnoreCase) ?? false); - } -} diff --git a/dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs b/dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs deleted file mode 100644 index 983c9d8d0547..000000000000 --- a/dotnet/samples/Concepts/Agents/Example11_OpenAIAssistant.cs +++ /dev/null @@ -1,68 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -/// -/// Demonstrate creation of and -/// eliciting its response to three explicit user messages. -/// -/// -/// This example demonstrates that outside of initialization (and cleanup), using -/// is no different from . -/// -public class Example11_OpenAIAssistant(ITestOutputHelper output) : BaseTest(output) -{ - private const string ParrotName = "Parrot"; - private const string ParrotInstructions = "Repeat the user message in the voice of a pirate and then end with a parrot sound."; - - [Fact] - public async Task RunAsync() - { - // Define the agent - OpenAIAssistantAgent agent = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - definition: new() - { - Instructions = ParrotInstructions, - Name = ParrotName, - ModelId = this.Model, - }); - - // Create a chat for agent interaction. - var chat = new AgentGroupChat(); - - // Respond to user input - try - { - await InvokeAgentAsync("Fortune favors the bold."); - await InvokeAgentAsync("I came, I saw, I conquered."); - await InvokeAgentAsync("Practice makes perfect."); - } - finally - { - await agent.DeleteAsync(); - } - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs b/dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs deleted file mode 100644 index f12793bf99f9..000000000000 --- a/dotnet/samples/Concepts/Agents/Example12_OpenAIAssistant_Plugins.cs +++ /dev/null @@ -1,74 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Plugins; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; -/// -/// Demonstrate creation of and -/// eliciting its response to three explicit user messages. -/// -/// -/// This example demonstrates that outside of initialization (and cleanup), using -/// is no different from -/// even with with a . -/// -public class OpenAIAssistant_Agent(ITestOutputHelper output) : BaseTest(output) -{ - private const string HostName = "Host"; - private const string HostInstructions = "Answer questions about the menu."; - - [Fact] - public async Task RunAsync() - { - // Define the agent - OpenAIAssistantAgent agent = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - new() - { - Instructions = HostInstructions, - Name = HostName, - ModelId = this.Model, - }); - - // Initialize plugin and add to the agent's Kernel (same as direct Kernel usage). - KernelPlugin plugin = KernelPluginFactory.CreateFromType(); - agent.Kernel.Plugins.Add(plugin); - - // Create a chat for agent interaction. - var chat = new AgentGroupChat(); - - // Respond to user input - try - { - await InvokeAgentAsync("Hello"); - await InvokeAgentAsync("What is the special soup?"); - await InvokeAgentAsync("What is the special drink?"); - await InvokeAgentAsync("Thank you"); - } - finally - { - await agent.DeleteAsync(); - } - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs b/dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs deleted file mode 100644 index 77a72eb94180..000000000000 --- a/dotnet/samples/Concepts/Agents/Example13_OpenAIAssistant_CodeInterpreter.cs +++ /dev/null @@ -1,57 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; -/// -/// Demonstrate using code-interpreter on . -/// -public class OpenAIAssistant_CodeInterpreter(ITestOutputHelper output) : BaseTest(output) -{ - [Fact] - public async Task RunAsync() - { - // Define the agent - OpenAIAssistantAgent agent = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - new() - { - EnableCodeInterpreter = true, // Enable code-interpreter - ModelId = this.Model, - }); - - // Create a chat for agent interaction. - var chat = new AgentGroupChat(); - - // Respond to user input - try - { - await InvokeAgentAsync("What is the solution to `3x + 2 = 14`?"); - await InvokeAgentAsync("What is the fibinacci sequence until 101?"); - } - finally - { - await agent.DeleteAsync(); - } - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs b/dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs deleted file mode 100644 index a58d9cc43aa3..000000000000 --- a/dotnet/samples/Concepts/Agents/Example14_OpenAIAssistant_Retrieval.cs +++ /dev/null @@ -1,76 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Configuration; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Microsoft.SemanticKernel.Connectors.OpenAI; -using Resources; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; -/// -/// Demonstrate using retrieval on . -/// -public class OpenAIAssistant_Retrieval(ITestOutputHelper output) : BaseTest(output) -{ - /// - /// Retrieval tool not supported on Azure OpenAI. - /// - protected override bool ForceOpenAI => true; - - [Fact] - public async Task RunAsync() - { - OpenAIFileService fileService = new(TestConfiguration.OpenAI.ApiKey); - - OpenAIFileReference uploadFile = - await fileService.UploadContentAsync( - new BinaryContent(() => Task.FromResult(EmbeddedResource.ReadStream("travelinfo.txt")!)), - new OpenAIFileUploadExecutionSettings("travelinfo.txt", OpenAIFilePurpose.Assistants)); - - WriteLine(this.ApiKey); - - // Define the agent - OpenAIAssistantAgent agent = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - new() - { - EnableRetrieval = true, // Enable retrieval - ModelId = this.Model, - FileIds = [uploadFile.Id] // Associate uploaded file - }); - - // Create a chat for agent interaction. - var chat = new AgentGroupChat(); - - // Respond to user input - try - { - await InvokeAgentAsync("Where did sam go?"); - await InvokeAgentAsync("When does the flight leave Seattle?"); - await InvokeAgentAsync("What is the hotel contact info at the destination?"); - } - finally - { - await agent.DeleteAsync(); - } - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync(agent)) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs b/dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs deleted file mode 100644 index a073b6f2610c..000000000000 --- a/dotnet/samples/Concepts/Agents/Example15_OpenAIAssistant_ChartMaker.cs +++ /dev/null @@ -1,88 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; -/// -/// Demonstrate using code-interpreter with to -/// produce image content displays the requested charts. -/// -public class OpenAIAssistant_ChartMaker(ITestOutputHelper output) : BaseTest(output) -{ - /// - /// Target Open AI services. - /// - protected override bool ForceOpenAI => true; - - private const string AgentName = "ChartMaker"; - private const string AgentInstructions = "Create charts as requested without explanation."; - - [Fact] - public async Task RunAsync() - { - // Define the agent - OpenAIAssistantAgent agent = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - new() - { - Instructions = AgentInstructions, - Name = AgentName, - EnableCodeInterpreter = true, - ModelId = this.Model, - }); - - // Create a chat for agent interaction. - var chat = new AgentGroupChat(); - - // Respond to user input - try - { - await InvokeAgentAsync( - """ - Display this data using a bar-chart: - - Banding Brown Pink Yellow Sum - X00000 339 433 126 898 - X00300 48 421 222 691 - X12345 16 395 352 763 - Others 23 373 156 552 - Sum 426 1622 856 2904 - """); - - await InvokeAgentAsync("Can you regenerate this same chart using the category names as the bar colors?"); - } - finally - { - await agent.DeleteAsync(); - } - - // Local function to invoke agent and display the conversation messages. - async Task InvokeAgentAsync(string input) - { - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var message in chat.InvokeAsync(agent)) - { - if (!string.IsNullOrWhiteSpace(message.Content)) - { - this.WriteLine($"# {message.Role} - {message.AuthorName ?? "*"}: '{message.Content}'"); - } - - foreach (var fileReference in message.Items.OfType()) - { - this.WriteLine($"# {message.Role} - {message.AuthorName ?? "*"}: #{fileReference.FileId}"); - } - } - } - } -} diff --git a/dotnet/samples/Concepts/Agents/Example16_MixedChat.cs b/dotnet/samples/Concepts/Agents/Example16_MixedChat.cs deleted file mode 100644 index c378078024b0..000000000000 --- a/dotnet/samples/Concepts/Agents/Example16_MixedChat.cs +++ /dev/null @@ -1,101 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Agents; -using Microsoft.SemanticKernel.Agents.Chat; -using Microsoft.SemanticKernel.Agents.OpenAI; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; -/// -/// Demonstrate that two different agent types are able to participate in the same conversation. -/// In this case a and participate. -/// -public class MixedChat_Agents(ITestOutputHelper output) : BaseTest(output) -{ - private const string ReviewerName = "ArtDirector"; - private const string ReviewerInstructions = - """ - You are an art director who has opinions about copywriting born of a love for David Ogilvy. - The goal is to determine is the given copy is acceptable to print. - If so, state that it is approved. - If not, provide insight on how to refine suggested copy without example. - """; - - private const string CopyWriterName = "Writer"; - private const string CopyWriterInstructions = - """ - You are a copywriter with ten years of experience and are known for brevity and a dry humor. - You're laser focused on the goal at hand. Don't waste time with chit chat. - The goal is to refine and decide on the single best copy as an expert in the field. - Consider suggestions when refining an idea. - """; - - [Fact] - public async Task RunAsync() - { - // Define the agents: one of each type - ChatCompletionAgent agentReviewer = - new() - { - Instructions = ReviewerInstructions, - Name = ReviewerName, - Kernel = this.CreateKernelWithChatCompletion(), - }; - - OpenAIAssistantAgent agentWriter = - await OpenAIAssistantAgent.CreateAsync( - kernel: this.CreateEmptyKernel(), - config: new(this.ApiKey, this.Endpoint), - new() - { - Instructions = CopyWriterInstructions, - Name = CopyWriterName, - ModelId = this.Model, - }); - - // Create a nexus for agent interaction. - var chat = - new AgentGroupChat(agentWriter, agentReviewer) - { - ExecutionSettings = - new() - { - // Here a TerminationStrategy subclass is used that will terminate when - // an assistant message contains the term "approve". - TerminationStrategy = - new ApprovalTerminationStrategy() - { - // Only the art-director may approve. - Agents = [agentReviewer], - // Limit total number of turns - MaximumIterations = 10, - } - } - }; - - // Invoke chat and display messages. - string input = "concept: maps made out of egg cartons."; - chat.AddChatMessage(new ChatMessageContent(AuthorRole.User, input)); - this.WriteLine($"# {AuthorRole.User}: '{input}'"); - - await foreach (var content in chat.InvokeAsync()) - { - this.WriteLine($"# {content.Role} - {content.AuthorName ?? "*"}: '{content.Content}'"); - } - - this.WriteLine($"# IS COMPLETE: {chat.IsComplete}"); - } - - private sealed class ApprovalTerminationStrategy : TerminationStrategy - { - // Terminate when the final message contains the term "approve" - protected override Task ShouldAgentTerminateAsync(Agent agent, IReadOnlyList history, CancellationToken cancellationToken) - => Task.FromResult(history[history.Count - 1].Content?.Contains("approve", StringComparison.OrdinalIgnoreCase) ?? false); - } -} diff --git a/dotnet/samples/Concepts/Agents/Example73_AgentAuthoring.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs similarity index 96% rename from dotnet/samples/Concepts/Agents/Example73_AgentAuthoring.cs rename to dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs index 2986f87a577d..d7ee001ca177 100644 --- a/dotnet/samples/Concepts/Agents/Example73_AgentAuthoring.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs @@ -1,10 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel.Experimental.Agents; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -12,7 +8,7 @@ namespace Examples; /// /// Showcase hiearchical Open AI Agent interactions using semantic kernel. /// -public class Example73_AgentAuthoring(ITestOutputHelper output) : BaseTest(output) +public class Legacy_AgentAuthoring(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and parallel function calling. diff --git a/dotnet/samples/Concepts/Agents/Example85_AgentCharts.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentCharts.cs similarity index 95% rename from dotnet/samples/Concepts/Agents/Example85_AgentCharts.cs rename to dotnet/samples/Concepts/Agents/Legacy_AgentCharts.cs index 683d2f53ca75..c8c81a926a31 100644 --- a/dotnet/samples/Concepts/Agents/Example85_AgentCharts.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentCharts.cs @@ -1,12 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Diagnostics; -using System.IO; -using System.Threading.Tasks; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Experimental.Agents; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -15,7 +11,7 @@ namespace Examples; /// /// Showcase usage of code_interpreter and retrieval tools. /// -public sealed class Example85_AgentCharts(ITestOutputHelper output) : BaseTest(output) +public sealed class Legacy_AgentCharts(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and parallel function calling. @@ -28,7 +24,7 @@ public sealed class Example85_AgentCharts(ITestOutputHelper output) : BaseTest(o /// and are defined. /// If 'false', Azure takes precedence. /// - private const bool ForceOpenAI = false; + private new const bool ForceOpenAI = false; /// /// Create a chart and retrieve by file_id. diff --git a/dotnet/samples/Concepts/Agents/Example72_AgentCollaboration.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentCollaboration.cs similarity index 97% rename from dotnet/samples/Concepts/Agents/Example72_AgentCollaboration.cs rename to dotnet/samples/Concepts/Agents/Legacy_AgentCollaboration.cs index d387d4bfa92c..5a9397eede64 100644 --- a/dotnet/samples/Concepts/Agents/Example72_AgentCollaboration.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentCollaboration.cs @@ -1,11 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel.Experimental.Agents; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -13,7 +8,7 @@ namespace Examples; /// /// Showcase complex Open AI Agent collaboration using semantic kernel. /// -public class Example72_AgentCollaboration(ITestOutputHelper output) : BaseTest(output) +public class Legacy_AgentCollaboration(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and function calling. diff --git a/dotnet/samples/Concepts/Agents/Example71_AgentDelegation.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentDelegation.cs similarity index 94% rename from dotnet/samples/Concepts/Agents/Example71_AgentDelegation.cs rename to dotnet/samples/Concepts/Agents/Legacy_AgentDelegation.cs index 1a1e8f293b4d..0c6339a39b31 100644 --- a/dotnet/samples/Concepts/Agents/Example71_AgentDelegation.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentDelegation.cs @@ -1,13 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Experimental.Agents; using Plugins; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -15,7 +11,7 @@ namespace Examples; /// /// Showcase complex Open AI Agent interactions using semantic kernel. /// -public class Example71_AgentDelegation(ITestOutputHelper output) : BaseTest(output) +public class Legacy_AgentDelegation(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and function calling. diff --git a/dotnet/samples/Concepts/Agents/Example75_AgentTools.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentTools.cs similarity index 96% rename from dotnet/samples/Concepts/Agents/Example75_AgentTools.cs rename to dotnet/samples/Concepts/Agents/Legacy_AgentTools.cs index c0998c3d5ad6..39ce67410cd0 100644 --- a/dotnet/samples/Concepts/Agents/Example75_AgentTools.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentTools.cs @@ -1,14 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Experimental.Agents; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -17,7 +12,7 @@ namespace Examples; /// /// Showcase usage of code_interpreter and retrieval tools. /// -public sealed class Example75_AgentTools(ITestOutputHelper output) : BaseTest(output) +public sealed class Legacy_AgentTools(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and parallel function calling. @@ -33,7 +28,7 @@ public sealed class Example75_AgentTools(ITestOutputHelper output) : BaseTest(ou /// /// NOTE: Retrieval tools is not currently available on Azure. /// - private const bool ForceOpenAI = true; + private new const bool ForceOpenAI = true; // Track agents for clean-up private readonly List _agents = []; diff --git a/dotnet/samples/Concepts/Agents/Example70_Agents.cs b/dotnet/samples/Concepts/Agents/Legacy_Agents.cs similarity index 97% rename from dotnet/samples/Concepts/Agents/Example70_Agents.cs rename to dotnet/samples/Concepts/Agents/Legacy_Agents.cs index 09346a78e306..e4d796fcabb9 100644 --- a/dotnet/samples/Concepts/Agents/Example70_Agents.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_Agents.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Experimental.Agents; using Plugins; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -15,7 +12,7 @@ namespace Examples; /// Showcase Open AI Agent integration with semantic kernel: /// https://platform.openai.com/docs/api-reference/agents /// -public class Example70_Agent(ITestOutputHelper output) : BaseTest(output) +public class Legacy_Agents(ITestOutputHelper output) : BaseTest(output) { /// /// Specific model is required that supports agents and function calling. @@ -28,7 +25,7 @@ public class Example70_Agent(ITestOutputHelper output) : BaseTest(output) /// and are defined. /// If 'false', Azure takes precedence. /// - private const bool ForceOpenAI = false; + private new const bool ForceOpenAI = false; /// /// Chat using the "Parrot" agent. diff --git a/dotnet/samples/Concepts/Agents/Example79_ChatCompletionAgent.cs b/dotnet/samples/Concepts/Agents/Legacy_ChatCompletionAgent.cs similarity index 96% rename from dotnet/samples/Concepts/Agents/Example79_ChatCompletionAgent.cs rename to dotnet/samples/Concepts/Agents/Legacy_ChatCompletionAgent.cs index 06231b66d35e..d61e427118c9 100644 --- a/dotnet/samples/Concepts/Agents/Example79_ChatCompletionAgent.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_ChatCompletionAgent.cs @@ -1,21 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; using Kusto.Cloud.Platform.Utils; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Experimental.Agents; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example79_ChatCompletionAgent(ITestOutputHelper output) : BaseTest(output) +public class Legacy_ChatCompletionAgent(ITestOutputHelper output) : BaseTest(output) { /// /// This example demonstrates a chat with the chat completion agent that utilizes the SK ChatCompletion API to communicate with LLM. diff --git a/dotnet/samples/Concepts/AgentSyntax/MixedChat_Agents.cs b/dotnet/samples/Concepts/Agents/MixedChat_Agents.cs similarity index 97% rename from dotnet/samples/Concepts/AgentSyntax/MixedChat_Agents.cs rename to dotnet/samples/Concepts/Agents/MixedChat_Agents.cs index c378078024b0..03c11f913401 100644 --- a/dotnet/samples/Concepts/AgentSyntax/MixedChat_Agents.cs +++ b/dotnet/samples/Concepts/Agents/MixedChat_Agents.cs @@ -1,14 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.Chat; using Microsoft.SemanticKernel.Agents.OpenAI; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Agent.cs b/dotnet/samples/Concepts/Agents/OpenAIAssistant_Agent.cs similarity index 98% rename from dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Agent.cs rename to dotnet/samples/Concepts/Agents/OpenAIAssistant_Agent.cs index f12793bf99f9..b21f9021b8ea 100644 --- a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Agent.cs +++ b/dotnet/samples/Concepts/Agents/OpenAIAssistant_Agent.cs @@ -1,11 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.OpenAI; using Microsoft.SemanticKernel.ChatCompletion; using Plugins; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_ChartMaker.cs b/dotnet/samples/Concepts/Agents/OpenAIAssistant_ChartMaker.cs similarity index 97% rename from dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_ChartMaker.cs rename to dotnet/samples/Concepts/Agents/OpenAIAssistant_ChartMaker.cs index a073b6f2610c..6e61631111b8 100644 --- a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_ChartMaker.cs +++ b/dotnet/samples/Concepts/Agents/OpenAIAssistant_ChartMaker.cs @@ -1,11 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.OpenAI; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_CodeInterpreter.cs b/dotnet/samples/Concepts/Agents/OpenAIAssistant_CodeInterpreter.cs similarity index 97% rename from dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_CodeInterpreter.cs rename to dotnet/samples/Concepts/Agents/OpenAIAssistant_CodeInterpreter.cs index 77a72eb94180..240d894a3b65 100644 --- a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_CodeInterpreter.cs +++ b/dotnet/samples/Concepts/Agents/OpenAIAssistant_CodeInterpreter.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.OpenAI; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Retrieval.cs b/dotnet/samples/Concepts/Agents/OpenAIAssistant_Retrieval.cs similarity index 97% rename from dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Retrieval.cs rename to dotnet/samples/Concepts/Agents/OpenAIAssistant_Retrieval.cs index a58d9cc43aa3..3af4acab5374 100644 --- a/dotnet/samples/Concepts/AgentSyntax/OpenAIAssistant_Retrieval.cs +++ b/dotnet/samples/Concepts/Agents/OpenAIAssistant_Retrieval.cs @@ -1,13 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Configuration; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.OpenAI; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/AudioToText/Example82_Audio.cs b/dotnet/samples/Concepts/AudioToText/OpenAI_AudioToText.cs similarity index 90% rename from dotnet/samples/Concepts/AudioToText/Example82_Audio.cs rename to dotnet/samples/Concepts/AudioToText/OpenAI_AudioToText.cs index b1bea0d283eb..fb3f41648880 100644 --- a/dotnet/samples/Concepts/AudioToText/Example82_Audio.cs +++ b/dotnet/samples/Concepts/AudioToText/OpenAI_AudioToText.cs @@ -1,13 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.AudioToText; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Microsoft.SemanticKernel.TextToAudio; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -15,9 +11,8 @@ namespace Examples; /// /// Represents a class that demonstrates audio processing functionality. /// -public sealed class Example82_Audio(ITestOutputHelper output) : BaseTest(output) +public sealed class OpenAI_AudioToText(ITestOutputHelper output) : BaseTest(output) { - private const string TextToAudioModel = "tts-1"; private const string AudioToTextModel = "whisper-1"; private const string AudioFilename = "test_audio.wav"; diff --git a/dotnet/samples/Concepts/AutoFunctionCalling/Example98_GeminiFunctionCalling.cs b/dotnet/samples/Concepts/AutoFunctionCalling/Gemini_FunctionCalling.cs similarity index 98% rename from dotnet/samples/Concepts/AutoFunctionCalling/Example98_GeminiFunctionCalling.cs rename to dotnet/samples/Concepts/AutoFunctionCalling/Gemini_FunctionCalling.cs index fe73b4e9c762..8caf75c71ed5 100644 --- a/dotnet/samples/Concepts/AutoFunctionCalling/Example98_GeminiFunctionCalling.cs +++ b/dotnet/samples/Concepts/AutoFunctionCalling/Gemini_FunctionCalling.cs @@ -1,17 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.Google; using xRetry; -using Xunit; using Xunit.Abstractions; namespace Examples; -public sealed class Example98_GeminiFunctionCalling(ITestOutputHelper output) : BaseTest(output) +public sealed class Gemini_FunctionCalling(ITestOutputHelper output) : BaseTest(output) { [RetryFact] public async Task GoogleAIAsync() diff --git a/dotnet/samples/Concepts/AutoFunctionCalling/Example59_OpenAIFunctionCalling.cs b/dotnet/samples/Concepts/AutoFunctionCalling/OpenAI_FunctionCalling.cs similarity index 97% rename from dotnet/samples/Concepts/AutoFunctionCalling/Example59_OpenAIFunctionCalling.cs rename to dotnet/samples/Concepts/AutoFunctionCalling/OpenAI_FunctionCalling.cs index 9413b2b0e40e..058bd145df71 100644 --- a/dotnet/samples/Concepts/AutoFunctionCalling/Example59_OpenAIFunctionCalling.cs +++ b/dotnet/samples/Concepts/AutoFunctionCalling/OpenAI_FunctionCalling.cs @@ -1,21 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use OpenAI's tool calling capability via the chat completions interface. -public class Example59_OpenAIFunctionCalling(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_FunctionCalling(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example54_AzureChatCompletionWithData.cs b/dotnet/samples/Concepts/ChatCompletion/AzureOpenAIWithData_ChatCompletion.cs similarity index 97% rename from dotnet/samples/Concepts/ChatCompletion/Example54_AzureChatCompletionWithData.cs rename to dotnet/samples/Concepts/ChatCompletion/AzureOpenAIWithData_ChatCompletion.cs index 5ee1b10dbc60..c8feec3d015a 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example54_AzureChatCompletionWithData.cs +++ b/dotnet/samples/Concepts/ChatCompletion/AzureOpenAIWithData_ChatCompletion.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; @@ -28,7 +26,7 @@ namespace Examples; /// dotnet user-secrets set "AzureAISearch:ApiKey" "{Key from your Search service resource}" /// dotnet user-secrets set "AzureAISearch:IndexName" "..." /// -public class Example54_AzureChatCompletionWithData(ITestOutputHelper output) : BaseTest(output) +public class AzureOpenAIWithData_ChatCompletion(ITestOutputHelper output) : BaseTest(output) { [RetryFact(typeof(HttpOperationException))] public async Task ExampleWithChatCompletionAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example37_CompletionIdentity.cs b/dotnet/samples/Concepts/ChatCompletion/ChatHistoryAuthorName.cs similarity index 91% rename from dotnet/samples/Concepts/ChatCompletion/Example37_CompletionIdentity.cs rename to dotnet/samples/Concepts/ChatCompletion/ChatHistoryAuthorName.cs index d9c274d95a25..350c7dd930e9 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example37_CompletionIdentity.cs +++ b/dotnet/samples/Concepts/ChatCompletion/ChatHistoryAuthorName.cs @@ -1,18 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; -// The following example shows how to use Semantic Kernel with identity associated with each chat message. -public class Example37_CompletionIdentity(ITestOutputHelper output) : BaseTest(output) +// The following example shows how to use Chat History with Author identity associated with each chat message. +public class ChatHistoryAuthorName(ITestOutputHelper output) : BaseTest(output) { /// /// Flag to force usage of OpenAI configuration if both @@ -22,7 +18,7 @@ public class Example37_CompletionIdentity(ITestOutputHelper output) : BaseTest(o /// /// NOTE: Retrieval tools is not currently available on Azure. /// - private const bool ForceOpenAI = true; + private new const bool ForceOpenAI = true; private static readonly OpenAIPromptExecutionSettings s_executionSettings = new() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example87_ChatHistorySerialization.cs b/dotnet/samples/Concepts/ChatCompletion/ChatHistorySerialization.cs similarity index 97% rename from dotnet/samples/Concepts/ChatCompletion/Example87_ChatHistorySerialization.cs rename to dotnet/samples/Concepts/ChatCompletion/ChatHistorySerialization.cs index a740e6b66af6..5acd13a600ab 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example87_ChatHistorySerialization.cs +++ b/dotnet/samples/Concepts/ChatCompletion/ChatHistorySerialization.cs @@ -1,18 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Linq; using System.Text; using System.Text.Json; using System.Text.Json.Serialization.Metadata; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example87_ChatHistorySerialization(ITestOutputHelper output) : BaseTest(output) +public class ChatHistorySerialization(ITestOutputHelper output) : BaseTest(output) { private static readonly JsonSerializerOptions s_options = new() { WriteIndented = true }; diff --git a/dotnet/samples/Concepts/ChatCompletion/Connectors_CustomHttpClient.cs b/dotnet/samples/Concepts/ChatCompletion/Connectors_CustomHttpClient.cs new file mode 100644 index 000000000000..695be864fa47 --- /dev/null +++ b/dotnet/samples/Concepts/ChatCompletion/Connectors_CustomHttpClient.cs @@ -0,0 +1,40 @@ +// Copyright (c) Microsoft. All rights reserved. + +using Microsoft.SemanticKernel; +using Xunit.Abstractions; + +namespace Examples; + +// These examples show how to use a custom HttpClient with SK connectors. +public class Connectors_CustomHttpClient(ITestOutputHelper output) : BaseTest(output) +{ + /// + /// Demonstrates the usage of the default HttpClient provided by the SK SDK. + /// + [Fact] + public void UseDefaultHttpClient() + { + var kernel = Kernel.CreateBuilder() + .AddOpenAIChatCompletion( + modelId: TestConfiguration.OpenAI.ChatModelId, + apiKey: TestConfiguration.OpenAI.ApiKey) // If you need to use the default HttpClient from the SK SDK, simply omit the argument for the httpMessageInvoker parameter. + .Build(); + } + + /// + /// Demonstrates the usage of a custom HttpClient. + /// + [Fact] + public void UseCustomHttpClient() + { + using var httpClient = new HttpClient(); + + // If you need to use a custom HttpClient, simply pass it as an argument for the httpClient parameter. + var kernel = Kernel.CreateBuilder() + .AddOpenAIChatCompletion( + modelId: TestConfiguration.OpenAI.ModelId, + apiKey: TestConfiguration.OpenAI.ApiKey, + httpClient: httpClient) + .Build(); + } +} diff --git a/dotnet/samples/Concepts/ChatCompletion/Example67_KernelStreaming.cs b/dotnet/samples/Concepts/ChatCompletion/Connectors_KernelStreaming.cs similarity index 88% rename from dotnet/samples/Concepts/ChatCompletion/Example67_KernelStreaming.cs rename to dotnet/samples/Concepts/ChatCompletion/Connectors_KernelStreaming.cs index 665eddb67e41..a25c16398fc1 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example67_KernelStreaming.cs +++ b/dotnet/samples/Concepts/ChatCompletion/Connectors_KernelStreaming.cs @@ -1,19 +1,17 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; -// This example shows how to use multiple prompt template formats. -public class Example67_KernelStreaming(ITestOutputHelper output) : BaseTest(output) +/// +/// This example shows how you can use Streaming with Kernel. +/// +/// +public class Connectors_KernelStreaming(ITestOutputHelper output) : BaseTest(output) { - /// - /// Show how to combine multiple prompt template factories. - /// [Fact] public async Task RunAsync() { diff --git a/dotnet/samples/Concepts/ChatCompletion/Example61_MultipleLLMs.cs b/dotnet/samples/Concepts/ChatCompletion/Connectors_WithMultipleLLMs.cs similarity index 95% rename from dotnet/samples/Concepts/ChatCompletion/Example61_MultipleLLMs.cs rename to dotnet/samples/Concepts/ChatCompletion/Connectors_WithMultipleLLMs.cs index f8aeddcfbb7e..30b7e05dc3f4 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example61_MultipleLLMs.cs +++ b/dotnet/samples/Concepts/ChatCompletion/Connectors_WithMultipleLLMs.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using xRetry; using Xunit.Abstractions; namespace Examples; -public class Example61_MultipleLLMs(ITestOutputHelper output) : BaseTest(output) +public class Connectors_WithMultipleLLMs(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to run a prompt function and specify a specific service to use. diff --git a/dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs deleted file mode 100644 index 280341790a17..000000000000 --- a/dotnet/samples/Concepts/ChatCompletion/Example44_MultiChatCompletion.cs +++ /dev/null @@ -1,78 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Linq; -using System.Threading.Tasks; -using Microsoft.SemanticKernel.ChatCompletion; -using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -// The following example shows how to use Semantic Kernel with Multiple Results Text Completion as streaming -public class Example44_MultiChatCompletion(ITestOutputHelper output) : BaseTest(output) -{ - [Fact] - public Task AzureOpenAIMultiChatCompletionAsync() - { - WriteLine("======== Azure OpenAI - Multiple Chat Completion ========"); - - AzureOpenAIChatCompletionService chatCompletionService = new( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId); - - return RunChatAsync(chatCompletionService); - } - - [Fact] - public Task OpenAIMultiChatCompletionAsync() - { - WriteLine("======== Open AI - Multiple Chat Completion ========"); - - OpenAIChatCompletionService chatCompletionService = new(modelId: TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey); - - return RunChatAsync(chatCompletionService); - } - - private async Task RunChatAsync(IChatCompletionService chatCompletionService) - { - var chatHistory = new ChatHistory("You are a librarian, expert about books"); - - // First user message - chatHistory.AddUserMessage("Hi, I'm looking for book 3 different book suggestions about sci-fi"); - await MessageOutputAsync(chatHistory); - - var chatExecutionSettings = new OpenAIPromptExecutionSettings() - { - MaxTokens = 1024, - ResultsPerPrompt = 2, - Temperature = 1, - TopP = 0.5, - FrequencyPenalty = 0, - }; - - // First bot assistant message - foreach (var chatMessageChoice in await chatCompletionService.GetChatMessageContentsAsync(chatHistory, chatExecutionSettings)) - { - chatHistory.Add(chatMessageChoice!); - await MessageOutputAsync(chatHistory); - } - - WriteLine(); - } - - /// - /// Outputs the last message of the chat history - /// - private Task MessageOutputAsync(ChatHistory chatHistory) - { - var message = chatHistory.Last(); - - WriteLine($"{message.Role}: {message.Content}"); - WriteLine("------------------------"); - - return Task.CompletedTask; - } -} diff --git a/dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletion.cs new file mode 100644 index 000000000000..020bc7f8f98f --- /dev/null +++ b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletion.cs @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft. All rights reserved. + +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.ChatCompletion; +using Xunit.Abstractions; + +namespace Examples; + +public sealed class Google_GeminiChatCompletion(ITestOutputHelper output) : BaseTest(output) +{ + [Fact] + public async Task GoogleAIAsync() + { + this.WriteLine("============= Google AI - Gemini Chat Completion ============="); + + string geminiApiKey = TestConfiguration.GoogleAI.ApiKey; + string geminiModelId = TestConfiguration.GoogleAI.Gemini.ModelId; + + if (geminiApiKey is null || geminiModelId is null) + { + this.WriteLine("Gemini credentials not found. Skipping example."); + return; + } + + Kernel kernel = Kernel.CreateBuilder() + .AddGoogleAIGeminiChatCompletion( + modelId: geminiModelId, + apiKey: geminiApiKey) + .Build(); + + await RunSampleAsync(kernel); + } + + [Fact] + public async Task VertexAIAsync() + { + this.WriteLine("============= Vertex AI - Gemini Chat Completion ============="); + + string geminiBearerKey = TestConfiguration.VertexAI.BearerKey; + string geminiModelId = TestConfiguration.VertexAI.Gemini.ModelId; + string geminiLocation = TestConfiguration.VertexAI.Location; + string geminiProject = TestConfiguration.VertexAI.ProjectId; + + if (geminiBearerKey is null || geminiModelId is null || geminiLocation is null || geminiProject is null) + { + this.WriteLine("Gemini vertex ai credentials not found. Skipping example."); + return; + } + + Kernel kernel = Kernel.CreateBuilder() + .AddVertexAIGeminiChatCompletion( + modelId: geminiModelId, + bearerKey: geminiBearerKey, + location: geminiLocation, + projectId: geminiProject) + .Build(); + + // To generate bearer key, you need installed google sdk or use google web console with command: + // + // gcloud auth print-access-token + // + // Above code pass bearer key as string, it is not recommended way in production code, + // especially if IChatCompletionService will be long lived, tokens generated by google sdk lives for 1 hour. + // You should use bearer key provider, which will be used to generate token on demand: + // + // Example: + // + // Kernel kernel = Kernel.CreateBuilder() + // .AddVertexAIGeminiChatCompletion( + // modelId: TestConfiguration.VertexAI.Gemini.ModelId, + // bearerKeyProvider: () => + // { + // // This is just example, in production we recommend using Google SDK to generate your BearerKey token. + // // This delegate will be called on every request, + // // when providing the token consider using caching strategy and refresh token logic when it is expired or close to expiration. + // return GetBearerKey(); + // }, + // location: TestConfiguration.VertexAI.Location, + // projectId: TestConfiguration.VertexAI.ProjectId); + + await RunSampleAsync(kernel); + } + + private async Task RunSampleAsync(Kernel kernel) + { + await SimpleChatAsync(kernel); + } + + private async Task SimpleChatAsync(Kernel kernel) + { + this.WriteLine("======== Simple Chat ========"); + + var chatHistory = new ChatHistory(); + var chat = kernel.GetRequiredService(); + + // First user message + chatHistory.AddUserMessage("Hi, I'm looking for new power tools, any suggestion?"); + await MessageOutputAsync(chatHistory); + + // First bot assistant message + var reply = await chat.GetChatMessageContentAsync(chatHistory); + chatHistory.Add(reply); + await MessageOutputAsync(chatHistory); + + // Second user message + chatHistory.AddUserMessage("I'm looking for a drill, a screwdriver and a hammer."); + await MessageOutputAsync(chatHistory); + + // Second bot assistant message + reply = await chat.GetChatMessageContentAsync(chatHistory); + chatHistory.Add(reply); + await MessageOutputAsync(chatHistory); + } + + /// + /// Outputs the last message of the chat history + /// + private Task MessageOutputAsync(ChatHistory chatHistory) + { + var message = chatHistory.Last(); + + this.WriteLine($"{message.Role}: {message.Content}"); + this.WriteLine("------------------------"); + + return Task.CompletedTask; + } +} diff --git a/dotnet/samples/Concepts/ChatCompletion/Example96_GeminiChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletionStreaming.cs similarity index 81% rename from dotnet/samples/Concepts/ChatCompletion/Example96_GeminiChatCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletionStreaming.cs index 7f63adf188e3..89785be29313 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example96_GeminiChatCompletion.cs +++ b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiChatCompletionStreaming.cs @@ -1,17 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; using System.Text; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; -public sealed class Example96_GeminiChatCompletion(ITestOutputHelper output) : BaseTest(output) +public sealed class Google_GeminiChatCompletionStreaming(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task GoogleAIAsync() @@ -88,7 +84,6 @@ public async Task VertexAIAsync() private async Task RunSampleAsync(Kernel kernel) { - await SimpleChatAsync(kernel); await StreamingChatAsync(kernel); } @@ -118,32 +113,6 @@ private async Task StreamingChatAsync(Kernel kernel) chatHistory.Add(reply); } - private async Task SimpleChatAsync(Kernel kernel) - { - this.WriteLine("======== Simple Chat ========"); - - var chatHistory = new ChatHistory(); - var chat = kernel.GetRequiredService(); - - // First user message - chatHistory.AddUserMessage("Hi, I'm looking for new power tools, any suggestion?"); - await MessageOutputAsync(chatHistory); - - // First bot assistant message - var reply = await chat.GetChatMessageContentAsync(chatHistory); - chatHistory.Add(reply); - await MessageOutputAsync(chatHistory); - - // Second user message - chatHistory.AddUserMessage("I'm looking for a drill, a screwdriver and a hammer."); - await MessageOutputAsync(chatHistory); - - // Second bot assistant message - reply = await chat.GetChatMessageContentAsync(chatHistory); - chatHistory.Add(reply); - await MessageOutputAsync(chatHistory); - } - /// /// Outputs the last message of the chat history /// diff --git a/dotnet/samples/Concepts/ChatCompletion/Example95_GeminiGetModelResult.cs b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiGetModelResult.cs similarity index 94% rename from dotnet/samples/Concepts/ChatCompletion/Example95_GeminiGetModelResult.cs rename to dotnet/samples/Concepts/ChatCompletion/Google_GeminiGetModelResult.cs index d8fef80ea6b3..41e501ceeaa9 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example95_GeminiGetModelResult.cs +++ b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiGetModelResult.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.Google; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -12,7 +9,7 @@ namespace Examples; /// /// Represents an example class for Gemini Embedding Generation with volatile memory store. /// -public sealed class Example95_GeminiGetModelResult(ITestOutputHelper output) : BaseTest(output) +public sealed class Google_GeminiGetModelResult(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task GetTokenUsageMetadataAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example97_GeminiVision.cs b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiVision.cs similarity index 97% rename from dotnet/samples/Concepts/ChatCompletion/Example97_GeminiVision.cs rename to dotnet/samples/Concepts/ChatCompletion/Google_GeminiVision.cs index 38c5ffdadcc6..93946a8fdfbf 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example97_GeminiVision.cs +++ b/dotnet/samples/Concepts/ChatCompletion/Google_GeminiVision.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.IO; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; -public sealed class Example97_GeminiVision(ITestOutputHelper output) : BaseTest(output) +public sealed class Google_GeminiVision(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task GoogleAIAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example17_ChatGPT.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs similarity index 96% rename from dotnet/samples/Concepts/ChatCompletion/Example17_ChatGPT.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs index d65d80b1ed86..3ad1c3d15479 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example17_ChatGPT.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following example shows how to use Semantic Kernel with OpenAI ChatGPT API -public class Example17_ChatGPT(ITestOutputHelper output) : BaseTest(output) +public class UsingChatGPT(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task OpenAIChatSampleAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example36_MultiCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionMultipleChoices.cs similarity index 94% rename from dotnet/samples/Concepts/ChatCompletion/Example36_MultiCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionMultipleChoices.cs index 92d5c748ff1f..2495f282ad97 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example36_MultiCompletion.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionMultipleChoices.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following example shows how to use Semantic Kernel with streaming Multiple Results Chat Completion. -public class Example36_MultiCompletion(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_ChatCompletionMultipleChoices(ITestOutputHelper output) : BaseTest(output) { [Fact] public Task AzureOpenAIMultiChatCompletionAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example33_StreamingChat.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreaming.cs similarity index 95% rename from dotnet/samples/Concepts/ChatCompletion/Example33_StreamingChat.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreaming.cs index a0e3bc987757..85cafafb95bc 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example33_StreamingChat.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreaming.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following example shows how to use Semantic Kernel with streaming Chat Completion -public class Example33_StreamingChat(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_ChatCompletionStreaming(ITestOutputHelper output) : BaseTest(output) { [Fact] public Task OpenAIChatStreamSampleAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example45_MultiStreamingChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreamingMultipleChoices.cs similarity index 96% rename from dotnet/samples/Concepts/ChatCompletion/Example45_MultiStreamingChatCompletion.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreamingMultipleChoices.cs index e1ccaa84436a..e3802b596ce5 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example45_MultiStreamingChatCompletion.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionStreamingMultipleChoices.cs @@ -1,18 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following example shows how to use Semantic Kernel with multiple streaming chat completion results. -public class Example45_MultiStreamingChatCompletion(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_ChatCompletionStreamingMultipleChoices(ITestOutputHelper output) : BaseTest(output) { [Fact] public Task AzureOpenAIMultiStreamingChatCompletionAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example68_GPTVision.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionWithVision.cs similarity index 88% rename from dotnet/samples/Concepts/ChatCompletion/Example68_GPTVision.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionWithVision.cs index fb98dd7a5423..66f66dc31280 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example68_GPTVision.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletionWithVision.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use GPT Vision model with different content types (text and image). -public class Example68_GPTVision(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_ChatCompletionWithVision(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example52_CustomOpenAIClient.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_CustomAzureOpenAIClient.cs similarity index 90% rename from dotnet/samples/Concepts/ChatCompletion/Example52_CustomOpenAIClient.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_CustomAzureOpenAIClient.cs index 1457a32c8268..10023c732ff4 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example52_CustomOpenAIClient.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_CustomAzureOpenAIClient.cs @@ -1,20 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; using Azure; using Azure.AI.OpenAI; using Azure.Core.Pipeline; using Microsoft.SemanticKernel; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; -public sealed class Example52_CustomOpenAIClient(ITestOutputHelper output) : BaseTest(output) +public sealed class OpenAI_CustomAzureOpenAIClient(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/ChatCompletion/Example49_LogitBias.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_UsingLogitBias.cs similarity index 96% rename from dotnet/samples/Concepts/ChatCompletion/Example49_LogitBias.cs rename to dotnet/samples/Concepts/ChatCompletion/OpenAI_UsingLogitBias.cs index f2ba1ea07223..c14b3fecdff0 100644 --- a/dotnet/samples/Concepts/ChatCompletion/Example49_LogitBias.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_UsingLogitBias.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -13,7 +10,7 @@ namespace Examples; * Logit_bias is an optional parameter that modifies the likelihood of specified tokens appearing in a Completion. * When using the Token Selection Biases parameter, the bias is added to the logits generated by the model prior to sampling. */ -public class Example49_LogitBias(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_UsingLogitBias(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/KernelSyntaxExamples/KernelSyntax.csproj b/dotnet/samples/Concepts/Concepts.csproj similarity index 86% rename from dotnet/samples/KernelSyntaxExamples/KernelSyntax.csproj rename to dotnet/samples/Concepts/Concepts.csproj index 3cb85526f47e..5621d11f3fac 100644 --- a/dotnet/samples/KernelSyntaxExamples/KernelSyntax.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -1,17 +1,22 @@ - + + - 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - - - KernelSyntax - net8.0 - true + enable + enable + false + true + + Concepts + + net8.0 - CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101 + CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 Library + + @@ -36,49 +41,45 @@ + + + + + + - - + + + + - - + + + + - - - - - + - - - - - - - - PreserveNewest - + - - Always - - + - \ No newline at end of file + + diff --git a/dotnet/samples/Concepts/DependencyInjection/Example41_HttpClientUsage.cs b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Registration.cs similarity index 64% rename from dotnet/samples/Concepts/DependencyInjection/Example41_HttpClientUsage.cs rename to dotnet/samples/Concepts/DependencyInjection/HttpClient_Registration.cs index 5cda7cfe27b8..c05483bbf3de 100644 --- a/dotnet/samples/Concepts/DependencyInjection/Example41_HttpClientUsage.cs +++ b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Registration.cs @@ -1,47 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Net.Http; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; // These examples show how to use HttpClient and HttpClientFactory within SK SDK. -public class Example41_HttpClientUsage(ITestOutputHelper output) : BaseTest(output) +public class HttpClient_Registration(ITestOutputHelper output) : BaseTest(output) { - /// - /// Demonstrates the usage of the default HttpClient provided by the SK SDK. - /// - [Fact] - public void UseDefaultHttpClient() - { - var kernel = Kernel.CreateBuilder() - .AddOpenAIChatCompletion( - modelId: TestConfiguration.OpenAI.ChatModelId, - apiKey: TestConfiguration.OpenAI.ApiKey) // If you need to use the default HttpClient from the SK SDK, simply omit the argument for the httpMessageInvoker parameter. - .Build(); - } - - /// - /// Demonstrates the usage of a custom HttpClient. - /// - [Fact] - public void UseCustomHttpClient() - { - using var httpClient = new HttpClient(); - - // If you need to use a custom HttpClient, simply pass it as an argument for the httpClient parameter. - var kernel = Kernel.CreateBuilder() - .AddOpenAIChatCompletion( - modelId: TestConfiguration.OpenAI.ModelId, - apiKey: TestConfiguration.OpenAI.ApiKey, - httpClient: httpClient) - .Build(); - } - /// /// Demonstrates the "basic usage" approach for HttpClientFactory. /// diff --git a/dotnet/samples/Concepts/DependencyInjection/Example08_RetryHandler.cs b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs similarity index 85% rename from dotnet/samples/Concepts/DependencyInjection/Example08_RetryHandler.cs rename to dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs index 9658574ff343..b568b1c20ba9 100644 --- a/dotnet/samples/Concepts/DependencyInjection/Example08_RetryHandler.cs +++ b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs @@ -1,20 +1,20 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Net; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Http.Resilience; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; -// This example shows how to use a retry handler within a Semantic Kernel -public class Example08_RetryHandler(ITestOutputHelper output) : BaseTest(output) +// These examples show how to use HttpClient and HttpClientFactory within SK SDK. +public class HttpClient_Resiliency(ITestOutputHelper output) : BaseTest(output) { + /// + /// Demostrates the usage of the HttpClientFactory with a custom resilience policy. + /// [Fact] public async Task RunAsync() { @@ -32,7 +32,7 @@ public async Task RunAsync() builder.Services.AddOpenAIChatCompletion("gpt-4", "BAD_KEY"); // OpenAI settings - you can set the OpenAI.ApiKey to an invalid value to see the retry policy in play Kernel kernel = builder.Build(); - var logger = kernel.LoggerFactory.CreateLogger(typeof(Example08_RetryHandler)); + var logger = kernel.LoggerFactory.CreateLogger(typeof(HttpClient_Resiliency)); const string Question = "How do I add a standard resilience handler in IHttpClientBuilder??"; logger.LogInformation("Question: {Question}", Question); diff --git a/dotnet/samples/Concepts/DependencyInjection/Example42_KernelBuilder.cs b/dotnet/samples/Concepts/DependencyInjection/Kernel_Building.cs similarity index 79% rename from dotnet/samples/Concepts/DependencyInjection/Example42_KernelBuilder.cs rename to dotnet/samples/Concepts/DependencyInjection/Kernel_Building.cs index d58f1f61f9a8..07c4acf677d6 100644 --- a/dotnet/samples/Concepts/DependencyInjection/Example42_KernelBuilder.cs +++ b/dotnet/samples/Concepts/DependencyInjection/Kernel_Building.cs @@ -9,27 +9,12 @@ using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example42_KernelBuilder(ITestOutputHelper output) : BaseTest(output) +public class Kernel_Building(ITestOutputHelper output) : BaseTest(output) { - [Fact] - public void BuildKernelWithAzureChatCompletion() - { - // KernelBuilder provides a simple way to configure a Kernel. This constructs a kernel - // with logging and an Azure OpenAI chat completion service configured. - Kernel kernel1 = Kernel.CreateBuilder() - .AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId) - .Build(); - } - [Fact] public void BuildKernelUsingServiceCollection() { @@ -46,15 +31,6 @@ public void BuildKernelUsingServiceCollection() Kernel kernel2 = builder.Build(); } - [Fact] - public void BuildKernelWithPlugins() - { - // Plugins may also be configured via the corresponding Plugins property. - var builder = Kernel.CreateBuilder(); - builder.Plugins.AddFromType(); - Kernel kernel3 = builder.Build(); - } - [Fact] public void BuildKernelUsingServiceProvider() { diff --git a/dotnet/samples/Concepts/DependencyInjection/Example40_DIContainer.cs b/dotnet/samples/Concepts/DependencyInjection/Kernel_Injecting.cs similarity index 90% rename from dotnet/samples/Concepts/DependencyInjection/Example40_DIContainer.cs rename to dotnet/samples/Concepts/DependencyInjection/Kernel_Injecting.cs index 8c8f13f7717d..9eb269d331c4 100644 --- a/dotnet/samples/Concepts/DependencyInjection/Example40_DIContainer.cs +++ b/dotnet/samples/Concepts/DependencyInjection/Kernel_Injecting.cs @@ -1,24 +1,20 @@ // Copyright (c) Microsoft. All rights reserved. -using System.IO; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following examples show how to use SK SDK in applications using DI/IoC containers. -public class Example40_DIContainer(ITestOutputHelper output) : BaseTest(output) +public class Kernel_Injecting(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() { var collection = new ServiceCollection(); - collection.AddSingleton(ConsoleLogger.LoggerFactory); + collection.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)); collection.AddOpenAITextGeneration(TestConfiguration.OpenAI.ModelId, TestConfiguration.OpenAI.ApiKey); collection.AddSingleton(); diff --git a/dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs b/dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs deleted file mode 100644 index aa7818ebc8a7..000000000000 --- a/dotnet/samples/Concepts/Filtering/Example76_Filters copy 2.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -public class Example76_Filters(ITestOutputHelper output) : BaseTest(output) -{ - /// - /// Shows how to use function and prompt filters in Kernel. - /// - [Fact] - public async Task FunctionAndPromptFiltersAsync() - { - var builder = Kernel.CreateBuilder(); - - builder.AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey); - - builder.Services.AddSingleton(this.Output); - - // Add filters with DI - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - - var kernel = builder.Build(); - - // Add filter without DI - kernel.PromptFilters.Add(new FirstPromptFilter(this.Output)); - - var function = kernel.CreateFunctionFromPrompt("What is Seattle", functionName: "MyFunction"); - kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: [function])); - var result = await kernel.InvokeAsync(kernel.Plugins["MyPlugin"]["MyFunction"]); - - WriteLine(result); - } - - #region Filters - - private sealed class FirstFunctionFilter(ITestOutputHelper output) : IFunctionFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnFunctionInvoking(FunctionInvokingContext context) => - this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnFunctionInvoked(FunctionInvokedContext context) => - this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - private sealed class SecondFunctionFilter(ITestOutputHelper output) : IFunctionFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnFunctionInvoking(FunctionInvokingContext context) => - this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnFunctionInvoked(FunctionInvokedContext context) => - this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - private sealed class FirstPromptFilter(ITestOutputHelper output) : IPromptFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnPromptRendering(PromptRenderingContext context) => - this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendering)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnPromptRendered(PromptRenderedContext context) => - this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendered)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - #endregion - - #region Filter capabilities - - private sealed class FunctionFilterExample : IFunctionFilter - { - public void OnFunctionInvoked(FunctionInvokedContext context) - { - // Example: get function result value - var value = context.Result.GetValue(); - - // Example: override function result value - context.SetResultValue("new result value"); - - // Example: get token usage from metadata - var usage = context.Result.Metadata?["Usage"]; - } - - public void OnFunctionInvoking(FunctionInvokingContext context) - { - // Example: override kernel arguments - context.Arguments["input"] = "new input"; - - // Example: cancel function execution - context.Cancel = true; - } - } - - private sealed class PromptFilterExample : IPromptFilter - { - public void OnPromptRendered(PromptRenderedContext context) - { - // Example: override rendered prompt before sending it to AI - context.RenderedPrompt = "Safe prompt"; - } - - public void OnPromptRendering(PromptRenderingContext context) - { - // Example: get function information - var functionName = context.Function.Name; - } - } - - #endregion -} diff --git a/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs b/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs deleted file mode 100644 index aa7818ebc8a7..000000000000 --- a/dotnet/samples/Concepts/Filtering/Example76_PromptFilter.cs +++ /dev/null @@ -1,123 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -public class Example76_Filters(ITestOutputHelper output) : BaseTest(output) -{ - /// - /// Shows how to use function and prompt filters in Kernel. - /// - [Fact] - public async Task FunctionAndPromptFiltersAsync() - { - var builder = Kernel.CreateBuilder(); - - builder.AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey); - - builder.Services.AddSingleton(this.Output); - - // Add filters with DI - builder.Services.AddSingleton(); - builder.Services.AddSingleton(); - - var kernel = builder.Build(); - - // Add filter without DI - kernel.PromptFilters.Add(new FirstPromptFilter(this.Output)); - - var function = kernel.CreateFunctionFromPrompt("What is Seattle", functionName: "MyFunction"); - kernel.Plugins.Add(KernelPluginFactory.CreateFromFunctions("MyPlugin", functions: [function])); - var result = await kernel.InvokeAsync(kernel.Plugins["MyPlugin"]["MyFunction"]); - - WriteLine(result); - } - - #region Filters - - private sealed class FirstFunctionFilter(ITestOutputHelper output) : IFunctionFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnFunctionInvoking(FunctionInvokingContext context) => - this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnFunctionInvoked(FunctionInvokedContext context) => - this._output.WriteLine($"{nameof(FirstFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - private sealed class SecondFunctionFilter(ITestOutputHelper output) : IFunctionFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnFunctionInvoking(FunctionInvokingContext context) => - this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoking)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnFunctionInvoked(FunctionInvokedContext context) => - this._output.WriteLine($"{nameof(SecondFunctionFilter)}.{nameof(OnFunctionInvoked)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - private sealed class FirstPromptFilter(ITestOutputHelper output) : IPromptFilter - { - private readonly ITestOutputHelper _output = output; - - public void OnPromptRendering(PromptRenderingContext context) => - this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendering)} - {context.Function.PluginName}.{context.Function.Name}"); - - public void OnPromptRendered(PromptRenderedContext context) => - this._output.WriteLine($"{nameof(FirstPromptFilter)}.{nameof(OnPromptRendered)} - {context.Function.PluginName}.{context.Function.Name}"); - } - - #endregion - - #region Filter capabilities - - private sealed class FunctionFilterExample : IFunctionFilter - { - public void OnFunctionInvoked(FunctionInvokedContext context) - { - // Example: get function result value - var value = context.Result.GetValue(); - - // Example: override function result value - context.SetResultValue("new result value"); - - // Example: get token usage from metadata - var usage = context.Result.Metadata?["Usage"]; - } - - public void OnFunctionInvoking(FunctionInvokingContext context) - { - // Example: override kernel arguments - context.Arguments["input"] = "new input"; - - // Example: cancel function execution - context.Cancel = true; - } - } - - private sealed class PromptFilterExample : IPromptFilter - { - public void OnPromptRendered(PromptRenderedContext context) - { - // Example: override rendered prompt before sending it to AI - context.RenderedPrompt = "Safe prompt"; - } - - public void OnPromptRendering(PromptRenderingContext context) - { - // Example: get function information - var functionName = context.Function.Name; - } - } - - #endregion -} diff --git a/dotnet/samples/Concepts/Filtering/Example76_Filters.cs b/dotnet/samples/Concepts/Filtering/Filters.cs similarity index 97% rename from dotnet/samples/Concepts/Filtering/Example76_Filters.cs rename to dotnet/samples/Concepts/Filtering/Filters.cs index aa7818ebc8a7..06ea854ef479 100644 --- a/dotnet/samples/Concepts/Filtering/Example76_Filters.cs +++ b/dotnet/samples/Concepts/Filtering/Filters.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example76_Filters(ITestOutputHelper output) : BaseTest(output) +public class Filters(ITestOutputHelper output) : BaseTest(output) { /// /// Shows how to use function and prompt filters in Kernel. diff --git a/dotnet/samples/Concepts/Filtering/Example57_KernelHooks.cs b/dotnet/samples/Concepts/Filtering/Legacy_KernelHooks.cs similarity index 98% rename from dotnet/samples/Concepts/Filtering/Example57_KernelHooks.cs rename to dotnet/samples/Concepts/Filtering/Legacy_KernelHooks.cs index d0e33e991d83..ceead7316a30 100644 --- a/dotnet/samples/Concepts/Filtering/Example57_KernelHooks.cs +++ b/dotnet/samples/Concepts/Filtering/Legacy_KernelHooks.cs @@ -1,18 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. using System.Text.RegularExpressions; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; #pragma warning disable CS0618 // Events are deprecated -public class Example57_KernelHooks : BaseTest +public class Legacy_KernelHooks : BaseTest { /// /// Demonstrate using kernel invocation-hooks to monitor usage: @@ -268,7 +265,7 @@ public async Task AfterInvokeCancellationAsync() private readonly string? _openAIModelId; private readonly string? _openAIApiKey; - public Example57_KernelHooks(ITestOutputHelper output) : base(output) + public Legacy_KernelHooks(ITestOutputHelper output) : base(output) { this._openAIModelId = TestConfiguration.OpenAI.ChatModelId; this._openAIApiKey = TestConfiguration.OpenAI.ApiKey; diff --git a/dotnet/samples/Concepts/Functions/Example03_Arguments.cs b/dotnet/samples/Concepts/Functions/Arguments.cs similarity index 70% rename from dotnet/samples/Concepts/Functions/Example03_Arguments.cs rename to dotnet/samples/Concepts/Functions/Arguments.cs index 4a58545edd82..eca60b26b715 100644 --- a/dotnet/samples/Concepts/Functions/Example03_Arguments.cs +++ b/dotnet/samples/Concepts/Functions/Arguments.cs @@ -1,16 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System; +using System.ComponentModel; using System.Globalization; -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Plugins; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use kernel arguments when invoking functions. -public class Example03_Arguments(ITestOutputHelper output) : BaseTest(output) +public class Arguments(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() @@ -42,4 +39,17 @@ public async Task RunAsync() // FunctionResult.ToString() automatically converts the result to string this.WriteLine($"FunctionResult.ToString() -> {functionResult}"); } + + public sealed class StaticTextPlugin + { + [KernelFunction, Description("Change all string chars to uppercase")] + public static string Uppercase([Description("Text to uppercase")] string input) => + input.ToUpperInvariant(); + + [KernelFunction, Description("Append the day variable")] + public static string AppendDay( + [Description("Text to append to")] string input, + [Description("Value of the day to append")] string day) => + input + day; + } } diff --git a/dotnet/samples/Concepts/Functions/Example43_GetModelResult.cs b/dotnet/samples/Concepts/Functions/FunctionResult_Metadata.cs similarity index 94% rename from dotnet/samples/Concepts/Functions/Example43_GetModelResult.cs rename to dotnet/samples/Concepts/Functions/FunctionResult_Metadata.cs index 83feac650734..993985fafe8c 100644 --- a/dotnet/samples/Concepts/Functions/Example43_GetModelResult.cs +++ b/dotnet/samples/Concepts/Functions/FunctionResult_Metadata.cs @@ -1,14 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example43_GetModelResult(ITestOutputHelper output) : BaseTest(output) +public class FunctionResult_Metadata(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task GetTokenUsageMetadataAsync() diff --git a/dotnet/samples/Concepts/Functions/Example77_StronglyTypedFunctionResult.cs b/dotnet/samples/Concepts/Functions/FunctionResult_StronglyTyped.cs similarity index 96% rename from dotnet/samples/Concepts/Functions/Example77_StronglyTypedFunctionResult.cs rename to dotnet/samples/Concepts/Functions/FunctionResult_StronglyTyped.cs index 637ad36b7d30..00af0d8c88a7 100644 --- a/dotnet/samples/Concepts/Functions/Example77_StronglyTypedFunctionResult.cs +++ b/dotnet/samples/Concepts/Functions/FunctionResult_StronglyTyped.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Diagnostics; using System.Text.Json; -using System.Threading.Tasks; using Azure.AI.OpenAI; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -14,7 +11,7 @@ namespace Examples; // The following example shows how to receive the results from the kernel in a strongly typed object // which stores the usage in tokens and converts the JSON result to a strongly typed object, where a validation can also // be performed -public class Example77_StronglyTypedFunctionResult(ITestOutputHelper output) : BaseTest(output) +public class FunctionResult_StronglyTyped(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Functions/Example01_MethodFunctions.cs b/dotnet/samples/Concepts/Functions/MethodFunctions.cs similarity index 79% rename from dotnet/samples/Concepts/Functions/Example01_MethodFunctions.cs rename to dotnet/samples/Concepts/Functions/MethodFunctions.cs index 16c0afe8a383..4fc11b512828 100644 --- a/dotnet/samples/Concepts/Functions/Example01_MethodFunctions.cs +++ b/dotnet/samples/Concepts/Functions/MethodFunctions.cs @@ -1,13 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example01_MethodFunctions(ITestOutputHelper output) : BaseTest(output) +public class MethodFunctions(ITestOutputHelper output) : BaseTest(output) { [Fact] public Task RunAsync() diff --git a/dotnet/samples/Concepts/Functions/Example60_AdvancedMethodFunctions.cs b/dotnet/samples/Concepts/Functions/MethodFunctions_Advanced.cs similarity index 96% rename from dotnet/samples/Concepts/Functions/Example60_AdvancedMethodFunctions.cs rename to dotnet/samples/Concepts/Functions/MethodFunctions_Advanced.cs index 5581b8ce6cf8..ae89b389121d 100644 --- a/dotnet/samples/Concepts/Functions/Example60_AdvancedMethodFunctions.cs +++ b/dotnet/samples/Concepts/Functions/MethodFunctions_Advanced.cs @@ -1,18 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; using System.Globalization; using System.Text.Json; -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows different ways how to define and execute method functions using custom and primitive types. -public class Example60_AdvancedMethodFunctions(ITestOutputHelper output) : BaseTest(output) +public class MethodFunctions_Advanced(ITestOutputHelper output) : BaseTest(output) { #region Method Functions Chaining diff --git a/dotnet/samples/Concepts/Functions/Example09_FunctionTypes.cs b/dotnet/samples/Concepts/Functions/MethodFunctions_Types.cs similarity index 98% rename from dotnet/samples/Concepts/Functions/Example09_FunctionTypes.cs rename to dotnet/samples/Concepts/Functions/MethodFunctions_Types.cs index 2c25f30bd250..11a4f07b8477 100644 --- a/dotnet/samples/Concepts/Functions/Example09_FunctionTypes.cs +++ b/dotnet/samples/Concepts/Functions/MethodFunctions_Types.cs @@ -1,22 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; using System.Globalization; -using System.IO; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example09_FunctionTypes(ITestOutputHelper output) : BaseTest(output) +public class MethodFunctions_Types(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Functions/Example05_InlineFunctionDefinition.cs b/dotnet/samples/Concepts/Functions/PromptFunctions_Inline.cs similarity index 93% rename from dotnet/samples/Concepts/Functions/Example05_InlineFunctionDefinition.cs rename to dotnet/samples/Concepts/Functions/PromptFunctions_Inline.cs index 01795f90dcaf..1cb833852b82 100644 --- a/dotnet/samples/Concepts/Functions/Example05_InlineFunctionDefinition.cs +++ b/dotnet/samples/Concepts/Functions/PromptFunctions_Inline.cs @@ -1,15 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example05_InlineFunctionDefinition(ITestOutputHelper output) : BaseTest(output) +public class PromptFunctions_Inline(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Functions/Example56_TemplateMethodFunctionsWithMultipleArguments.cs b/dotnet/samples/Concepts/Functions/PromptFunctions_MultipleArguments.cs similarity index 95% rename from dotnet/samples/Concepts/Functions/Example56_TemplateMethodFunctionsWithMultipleArguments.cs rename to dotnet/samples/Concepts/Functions/PromptFunctions_MultipleArguments.cs index a587493601aa..ff1fd688f2c8 100644 --- a/dotnet/samples/Concepts/Functions/Example56_TemplateMethodFunctionsWithMultipleArguments.cs +++ b/dotnet/samples/Concepts/Functions/PromptFunctions_MultipleArguments.cs @@ -1,17 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example56_TemplateMethodFunctionsWithMultipleArguments(ITestOutputHelper output) : BaseTest(output) +public class PromptFunctions_MultipleArguments(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to invoke a Method Function written in C# with multiple arguments diff --git a/dotnet/samples/Concepts/ImageToText/Example86_ImageToText.cs b/dotnet/samples/Concepts/ImageToText/HuggingFace_ImageToText.cs similarity index 91% rename from dotnet/samples/Concepts/ImageToText/Example86_ImageToText.cs rename to dotnet/samples/Concepts/ImageToText/HuggingFace_ImageToText.cs index 254fa99dbb64..d7ee6a908782 100644 --- a/dotnet/samples/Concepts/ImageToText/Example86_ImageToText.cs +++ b/dotnet/samples/Concepts/ImageToText/HuggingFace_ImageToText.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.HuggingFace; using Microsoft.SemanticKernel.ImageToText; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -14,7 +11,7 @@ namespace Examples; /// /// Represents a class that demonstrates image-to-text functionality. /// -public sealed class Example86_ImageToText(ITestOutputHelper output) : BaseTest(output) +public sealed class HuggingFace_ImageToText(ITestOutputHelper output) : BaseTest(output) { private const string ImageToTextModel = "Salesforce/blip-image-captioning-base"; private const string ImageFilePath = "test_image.jpg"; diff --git a/dotnet/samples/Concepts/Kernel/BuildingKernel.cs b/dotnet/samples/Concepts/Kernel/BuildingKernel.cs new file mode 100644 index 000000000000..64dde1d0b467 --- /dev/null +++ b/dotnet/samples/Concepts/Kernel/BuildingKernel.cs @@ -0,0 +1,37 @@ +// Copyright (c) Microsoft. All rights reserved. + +// ========================================================================================================== +// The easier way to instantiate the Semantic Kernel is to use KernelBuilder. +// You can access the builder using Kernel.CreateBuilder(). + +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.Plugins.Core; +using Xunit.Abstractions; + +namespace Examples; + +public class BuildingKernel(ITestOutputHelper output) : BaseTest(output) +{ + [Fact] + public void BuildKernelWithAzureChatCompletion() + { + // KernelBuilder provides a simple way to configure a Kernel. This constructs a kernel + // with logging and an Azure OpenAI chat completion service configured. + Kernel kernel1 = Kernel.CreateBuilder() + .AddAzureOpenAIChatCompletion( + deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, + endpoint: TestConfiguration.AzureOpenAI.Endpoint, + apiKey: TestConfiguration.AzureOpenAI.ApiKey, + modelId: TestConfiguration.AzureOpenAI.ChatModelId) + .Build(); + } + + [Fact] + public void BuildKernelWithPlugins() + { + // Plugins may also be configured via the corresponding Plugins property. + var builder = Kernel.CreateBuilder(); + builder.Plugins.AddFromType(); + Kernel kernel3 = builder.Build(); + } +} diff --git a/dotnet/samples/Concepts/Kernel/Example62_CustomAIServiceSelector.cs b/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs similarity index 95% rename from dotnet/samples/Concepts/Kernel/Example62_CustomAIServiceSelector.cs rename to dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs index 155c7aa3aab0..89d4785cf902 100644 --- a/dotnet/samples/Concepts/Kernel/Example62_CustomAIServiceSelector.cs +++ b/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs @@ -1,18 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Services; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example62_CustomAIServiceSelector(ITestOutputHelper output) : BaseTest(output) +public class CustomAIServiceSelector(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to use a custom AI service selector to select a specific model diff --git a/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs b/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs deleted file mode 100644 index d58f1f61f9a8..000000000000 --- a/dotnet/samples/Concepts/Kernel/Example42_KernelBuilder.cs +++ /dev/null @@ -1,103 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -// ========================================================================================================== -// The easier way to instantiate the Semantic Kernel is to use KernelBuilder. -// You can access the builder using Kernel.CreateBuilder(). - -using System.Diagnostics; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -public class Example42_KernelBuilder(ITestOutputHelper output) : BaseTest(output) -{ - [Fact] - public void BuildKernelWithAzureChatCompletion() - { - // KernelBuilder provides a simple way to configure a Kernel. This constructs a kernel - // with logging and an Azure OpenAI chat completion service configured. - Kernel kernel1 = Kernel.CreateBuilder() - .AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId) - .Build(); - } - - [Fact] - public void BuildKernelUsingServiceCollection() - { - // For greater flexibility and to incorporate arbitrary services, KernelBuilder.Services - // provides direct access to an underlying IServiceCollection. - IKernelBuilder builder = Kernel.CreateBuilder(); - builder.Services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)) - .AddHttpClient() - .AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId); - Kernel kernel2 = builder.Build(); - } - - [Fact] - public void BuildKernelWithPlugins() - { - // Plugins may also be configured via the corresponding Plugins property. - var builder = Kernel.CreateBuilder(); - builder.Plugins.AddFromType(); - Kernel kernel3 = builder.Build(); - } - - [Fact] - public void BuildKernelUsingServiceProvider() - { - // Every call to KernelBuilder.Build creates a new Kernel instance, with a new service provider - // and a new plugin collection. - var builder = Kernel.CreateBuilder(); - Debug.Assert(!ReferenceEquals(builder.Build(), builder.Build())); - - // KernelBuilder provides a convenient API for creating Kernel instances. However, it is just a - // wrapper around a service collection, ultimately constructing a Kernel - // using the public constructor that's available for anyone to use directly if desired. - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)); - services.AddHttpClient(); - services.AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId); - Kernel kernel4 = new(services.BuildServiceProvider()); - - // Kernels can also be constructed and resolved via such a dependency injection container. - services.AddTransient(); - Kernel kernel5 = services.BuildServiceProvider().GetRequiredService(); - } - - [Fact] - public void BuildKernelUsingServiceCollectionExtension() - { - // In fact, the AddKernel method exists to simplify this, registering a singleton KernelPluginCollection - // that can be populated automatically with all IKernelPlugins registered in the collection, and a - // transient Kernel that can then automatically be constructed from the service provider and resulting - // plugins collection. - var services = new ServiceCollection(); - services.AddLogging(c => c.AddConsole().SetMinimumLevel(LogLevel.Information)); - services.AddHttpClient(); - services.AddKernel().AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - apiKey: TestConfiguration.AzureOpenAI.ApiKey, - modelId: TestConfiguration.AzureOpenAI.ChatModelId); - services.AddSingleton(sp => KernelPluginFactory.CreateFromType(serviceProvider: sp)); - services.AddSingleton(sp => KernelPluginFactory.CreateFromType(serviceProvider: sp)); - Kernel kernel6 = services.BuildServiceProvider().GetRequiredService(); - } -} diff --git a/dotnet/samples/Concepts/Kernel/Example58_ConfigureExecutionSettings.cs b/dotnet/samples/Concepts/Kernel/ExecutionSettings.cs similarity index 96% rename from dotnet/samples/Concepts/Kernel/Example58_ConfigureExecutionSettings.cs rename to dotnet/samples/Concepts/Kernel/ExecutionSettings.cs index 618856ef134e..c05a1687d110 100644 --- a/dotnet/samples/Concepts/Kernel/Example58_ConfigureExecutionSettings.cs +++ b/dotnet/samples/Concepts/Kernel/ExecutionSettings.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. using System.Text.Json; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; -public sealed class Example58_ConfigureExecutionSettings(ITestOutputHelper output) : BaseTest(output) +public sealed class ExecutionSettings(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to configure model execution settings diff --git a/dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs b/dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs deleted file mode 100644 index d886a6c3b6e0..000000000000 --- a/dotnet/samples/Concepts/LocalModels/Example20_HuggingFace.cs +++ /dev/null @@ -1,203 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.ChatCompletion; -using Microsoft.SemanticKernel.Connectors.HuggingFace; -using Microsoft.SemanticKernel.Embeddings; -using xRetry; -using Xunit; -using Xunit.Abstractions; - -#pragma warning disable format // Format item can be simplified -#pragma warning disable CA1861 // Avoid constant arrays as arguments - -namespace Examples; - -// The following example shows how to use Semantic Kernel with HuggingFace API. -public class Example20_HuggingFace : BaseTest -{ - /// - /// This example uses HuggingFace Inference API to access hosted models. - /// More information here: - /// - [Fact] - public async Task RunInferenceApiExampleAsync() - { - WriteLine("\n======== HuggingFace Inference API example ========\n"); - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceTextGeneration( - model: TestConfiguration.HuggingFace.ModelId, - apiKey: TestConfiguration.HuggingFace.ApiKey) - .Build(); - - var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:"); - - var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" }); - - WriteLine(result.GetValue()); - } - - [RetryFact(typeof(HttpOperationException))] - public async Task RunInferenceApiEmbeddingAsync() - { - this.WriteLine("\n======= Hugging Face Inference API - Embedding Example ========\n"); - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceTextEmbeddingGeneration( - model: TestConfiguration.HuggingFace.EmbeddingModelId, - apiKey: TestConfiguration.HuggingFace.ApiKey) - .Build(); - - var embeddingGenerator = kernel.GetRequiredService(); - - // Generate embeddings for each chunk. - 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"); - } - - [RetryFact(typeof(HttpOperationException))] - public async Task RunStreamingExampleAsync() - { - WriteLine("\n======== HuggingFace zephyr-7b-beta streaming example ========\n"); - - const string Model = "HuggingFaceH4/zephyr-7b-beta"; - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceTextGeneration( - model: Model, - apiKey: TestConfiguration.HuggingFace.ApiKey) - .Build(); - - var settings = new HuggingFacePromptExecutionSettings { UseCache = false }; - - var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:", new HuggingFacePromptExecutionSettings - { - UseCache = false - }); - - await foreach (string text in kernel.InvokePromptStreamingAsync("Question: {{$input}}; Answer:", new(settings) { ["input"] = "What is New York?" })) - { - this.Write(text); - } - } - - /// - /// This example uses HuggingFace Llama 2 model and local HTTP server from Semantic Kernel repository. - /// How to setup local HTTP server: . - /// - /// Additional access is required to download Llama 2 model and run it locally. - /// How to get access: - /// 1. Visit and complete request access form. - /// 2. Visit and complete form "Access Llama 2 on Hugging Face". - /// Note: Your Hugging Face account email address MUST match the email you provide on the Meta website, or your request will not be approved. - /// - /// - [Fact(Skip = "Requires local model or Huggingface Pro subscription")] - public async Task RunLlamaExampleAsync() - { - WriteLine("\n======== HuggingFace Llama 2 example ========\n"); - - // HuggingFace Llama 2 model: https://huggingface.co/meta-llama/Llama-2-7b-hf - const string Model = "meta-llama/Llama-2-7b-hf"; - - // HuggingFace local HTTP server endpoint - // const string Endpoint = "http://localhost:5000/completions"; - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceTextGeneration( - model: Model, - //endpoint: Endpoint, - apiKey: TestConfiguration.HuggingFace.ApiKey) - .Build(); - - var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:"); - - var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" }); - - WriteLine(result.GetValue()); - } - - /// - /// Follow steps in to setup HuggingFace local Text Generation Inference HTTP server. - /// - [Fact(Skip = "Requires TGI (text generation inference) deployment")] - public async Task RunTGI_ChatCompletionAsync() - { - WriteLine("\n======== HuggingFace - TGI Chat Completion ========\n"); - - // This example was run against one of the chat completion (Message API) supported models from HuggingFace, listed in here: - // Starting a Local Docker i.e: - // docker run --gpus all --shm-size 1g -p 8080:80 -v "F:\temp\huggingface:/data" ghcr.io/huggingface/text-generation-inference:1.4 --model-id teknium/OpenHermes-2.5-Mistral-7B - - // HuggingFace local HTTP server endpoint - var endpoint = new Uri("http://localhost:8080"); - - const string Model = "teknium/OpenHermes-2.5-Mistral-7B"; - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceChatCompletion( - model: Model, - endpoint: endpoint) - .Build(); - - var chatCompletion = kernel.GetRequiredService(); - var chatHistory = new ChatHistory("You are a helpful assistant.") - { - new ChatMessageContent(AuthorRole.User, "What is deep learning?") - }; - - var result = await chatCompletion.GetChatMessageContentAsync(chatHistory); - - WriteLine(result.Role); - WriteLine(result.Content); - } - - /// - /// Follow steps in to setup HuggingFace local Text Generation Inference HTTP server. - /// - [Fact(Skip = "Requires TGI (text generation inference) deployment")] - public async Task RunTGI_StreamingChatCompletionAsync() - { - WriteLine("\n======== HuggingFace - TGI Chat Completion Streaming ========\n"); - - // This example was run against one of the chat completion (Message API) supported models from HuggingFace, listed in here: - // Starting a Local Docker i.e: - // docker run --gpus all --shm-size 1g -p 8080:80 -v "F:\temp\huggingface:/data" ghcr.io/huggingface/text-generation-inference:1.4 --model-id teknium/OpenHermes-2.5-Mistral-7B - - // HuggingFace local HTTP server endpoint - var endpoint = new Uri("http://localhost:8080"); - - const string Model = "teknium/OpenHermes-2.5-Mistral-7B"; - - Kernel kernel = Kernel.CreateBuilder() - .AddHuggingFaceChatCompletion( - model: Model, - endpoint: endpoint) - .Build(); - - var chatCompletion = kernel.GetRequiredService(); - var chatHistory = new ChatHistory("You are a helpful assistant.") - { - new ChatMessageContent(AuthorRole.User, "What is deep learning?") - }; - - AuthorRole? role = null; - await foreach (var chatMessageChunk in chatCompletion.GetStreamingChatMessageContentsAsync(chatHistory)) - { - if (role is null) - { - role = chatMessageChunk.Role; - Write(role); - } - Write(chatMessageChunk.Content); - } - } - - public Example20_HuggingFace(ITestOutputHelper output) : base(output) - { - } -} diff --git a/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs b/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs new file mode 100644 index 000000000000..7baee6c7a2be --- /dev/null +++ b/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs @@ -0,0 +1,94 @@ +// Copyright (c) Microsoft. All rights reserved. + +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.ChatCompletion; +using Xunit.Abstractions; + +#pragma warning disable format // Format item can be simplified +#pragma warning disable CA1861 // Avoid constant arrays as arguments + +namespace Examples; + +// The following example shows how to use Semantic Kernel with HuggingFace API. +public class HuggingFace_ChatCompletionWithTGI : BaseTest +{ + /// + /// Follow steps in to setup HuggingFace local Text Generation Inference HTTP server. + /// + [Fact(Skip = "Requires TGI (text generation inference) deployment")] + public async Task RunTGI_ChatCompletionAsync() + { + WriteLine("\n======== HuggingFace - TGI Chat Completion ========\n"); + + // This example was run against one of the chat completion (Message API) supported models from HuggingFace, listed in here: + // Starting a Local Docker i.e: + // docker run --gpus all --shm-size 1g -p 8080:80 -v "F:\temp\huggingface:/data" ghcr.io/huggingface/text-generation-inference:1.4 --model-id teknium/OpenHermes-2.5-Mistral-7B + + // HuggingFace local HTTP server endpoint + var endpoint = new Uri("http://localhost:8080"); + + const string Model = "teknium/OpenHermes-2.5-Mistral-7B"; + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceChatCompletion( + model: Model, + endpoint: endpoint) + .Build(); + + var chatCompletion = kernel.GetRequiredService(); + var chatHistory = new ChatHistory("You are a helpful assistant.") + { + new ChatMessageContent(AuthorRole.User, "What is deep learning?") + }; + + var result = await chatCompletion.GetChatMessageContentAsync(chatHistory); + + WriteLine(result.Role); + WriteLine(result.Content); + } + + /// + /// Follow steps in to setup HuggingFace local Text Generation Inference HTTP server. + /// + [Fact(Skip = "Requires TGI (text generation inference) deployment")] + public async Task RunTGI_StreamingChatCompletionAsync() + { + WriteLine("\n======== HuggingFace - TGI Chat Completion Streaming ========\n"); + + // This example was run against one of the chat completion (Message API) supported models from HuggingFace, listed in here: + // Starting a Local Docker i.e: + // docker run --gpus all --shm-size 1g -p 8080:80 -v "F:\temp\huggingface:/data" ghcr.io/huggingface/text-generation-inference:1.4 --model-id teknium/OpenHermes-2.5-Mistral-7B + + // HuggingFace local HTTP server endpoint + var endpoint = new Uri("http://localhost:8080"); + + const string Model = "teknium/OpenHermes-2.5-Mistral-7B"; + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceChatCompletion( + model: Model, + endpoint: endpoint) + .Build(); + + var chatCompletion = kernel.GetRequiredService(); + var chatHistory = new ChatHistory("You are a helpful assistant.") + { + new ChatMessageContent(AuthorRole.User, "What is deep learning?") + }; + + AuthorRole? role = null; + await foreach (var chatMessageChunk in chatCompletion.GetStreamingChatMessageContentsAsync(chatHistory)) + { + if (role is null) + { + role = chatMessageChunk.Role; + Write(role); + } + Write(chatMessageChunk.Content); + } + } + + public HuggingFace_ChatCompletionWithTGI(ITestOutputHelper output) : base(output) + { + } +} diff --git a/dotnet/samples/Concepts/LocalModels/Example88_CustomMessageAPIEndpoint.cs b/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs similarity index 95% rename from dotnet/samples/Concepts/LocalModels/Example88_CustomMessageAPIEndpoint.cs rename to dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs index 11414bce43c2..e1bacc8f14f2 100644 --- a/dotnet/samples/Concepts/LocalModels/Example88_CustomMessageAPIEndpoint.cs +++ b/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -32,7 +29,7 @@ namespace Examples; /// 2. docker run -ti -p 8080:8080 localai/localai:v2.12.3-ffmpeg-core phi-2 /// 3. Run the LocalAI examples. /// -public class Example88_CustomMessageAPIEndpoint : BaseTest +public class MultipleProviders_ChatCompletion : BaseTest { [Theory(Skip = "Manual configuration needed")] [InlineData("LMStudio", "http://localhost:1234", "llama2")] // Setup Llama2 as the model in LM Studio UI and start the Message API Server on http://localhost:1234 @@ -97,7 +94,7 @@ Sign the mail as AI Assistant. }; } - public Example88_CustomMessageAPIEndpoint(ITestOutputHelper output) : base(output) + public MultipleProviders_ChatCompletion(ITestOutputHelper output) : base(output) { } } diff --git a/dotnet/samples/Concepts/Memory/Example99_GeminiEmbeddingGeneration.cs b/dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs similarity index 89% rename from dotnet/samples/Concepts/Memory/Example99_GeminiEmbeddingGeneration.cs rename to dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs index 6ee9b43ba44c..8d7e006b698a 100644 --- a/dotnet/samples/Concepts/Memory/Example99_GeminiEmbeddingGeneration.cs +++ b/dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.Google; using Microsoft.SemanticKernel.Embeddings; using Microsoft.SemanticKernel.Memory; -using Microsoft.SemanticKernel.Plugins.Memory; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -14,7 +11,7 @@ namespace Examples; /// /// Represents an example class for Gemini Embedding Generation with volatile memory store. /// -public sealed class Example99_GeminiEmbeddingGeneration(ITestOutputHelper output) : BaseTest(output) +public sealed class Gemini_EmbeddingGeneration(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "aboutMe"; @@ -139,7 +136,7 @@ private async Task RunTextMemoryPluginSampleAsync(Kernel kernel) // The combination of the text embedding generator and the memory store makes up the 'SemanticTextMemory' object used to // store and retrieve memories. - SemanticTextMemory textMemory = new(memoryStore, embeddingGenerator); + Microsoft.SemanticKernel.Memory.SemanticTextMemory textMemory = new(memoryStore, embeddingGenerator); ///////////////////////////////////////////////////////////////////////////////////////////////////// // PART 1: Store and retrieve memories using the ISemanticTextMemory (textMemory) object. @@ -171,15 +168,15 @@ private async Task RunTextMemoryPluginSampleAsync(Kernel kernel) WriteLine("== PART 2: Saving Memories through the Kernel with TextMemoryPlugin and the 'Save' function =="); // Import the TextMemoryPlugin into the Kernel for other functions - var memoryPlugin = kernel.ImportPluginFromObject(new TextMemoryPlugin(textMemory)); + var memoryPlugin = kernel.ImportPluginFromObject(new Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin(textMemory)); // Save a memory with the Kernel WriteLine("Saving memory with key 'info5': \"My family is from New York\""); await kernel.InvokeAsync(memoryPlugin["Save"], new() { - [TextMemoryPlugin.InputParam] = "My family is from New York", - [TextMemoryPlugin.CollectionParam] = MemoryCollectionName, - [TextMemoryPlugin.KeyParam] = "info5", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.InputParam] = "My family is from New York", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.CollectionParam] = MemoryCollectionName, + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.KeyParam] = "info5", }); this.WriteLine(); @@ -214,10 +211,10 @@ private async Task RunTextMemoryPluginSampleAsync(Kernel kernel) var result = await kernel.InvokeAsync(memoryPlugin["Recall"], new() { - [TextMemoryPlugin.InputParam] = "Ask: my family is from?", - [TextMemoryPlugin.CollectionParam] = MemoryCollectionName, - [TextMemoryPlugin.LimitParam] = "2", - [TextMemoryPlugin.RelevanceParam] = "0.79", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.InputParam] = "Ask: my family is from?", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.CollectionParam] = MemoryCollectionName, + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.LimitParam] = "2", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.RelevanceParam] = "0.79", }); WriteLine($"Answer: {result.GetValue()}"); @@ -252,10 +249,10 @@ END FACTS result = await kernel.InvokePromptAsync(RecallFunctionDefinition, new(new GeminiPromptExecutionSettings { MaxTokens = 1000 }) { - [TextMemoryPlugin.InputParam] = "Where are my family from?", - [TextMemoryPlugin.CollectionParam] = MemoryCollectionName, - [TextMemoryPlugin.LimitParam] = "2", - [TextMemoryPlugin.RelevanceParam] = "0.79", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.InputParam] = "Where are my family from?", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.CollectionParam] = MemoryCollectionName, + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.LimitParam] = "2", + [Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin.RelevanceParam] = "0.79", }); WriteLine("Ask: Where are my family from?"); diff --git a/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs b/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs new file mode 100644 index 000000000000..3b33462df78a --- /dev/null +++ b/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs @@ -0,0 +1,38 @@ +// Copyright (c) Microsoft. All rights reserved. + +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.Embeddings; +using xRetry; +using Xunit.Abstractions; + +#pragma warning disable format // Format item can be simplified +#pragma warning disable CA1861 // Avoid constant arrays as arguments + +namespace Examples; + +// The following example shows how to use Semantic Kernel with HuggingFace API. +public class HuggingFace_EmbeddingGeneration : BaseTest +{ + [RetryFact(typeof(HttpOperationException))] + public async Task RunInferenceApiEmbeddingAsync() + { + this.WriteLine("\n======= Hugging Face Inference API - Embedding Example ========\n"); + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceTextEmbeddingGeneration( + model: TestConfiguration.HuggingFace.EmbeddingModelId, + apiKey: TestConfiguration.HuggingFace.ApiKey) + .Build(); + + var embeddingGenerator = kernel.GetRequiredService(); + + // Generate embeddings for each chunk. + 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"); + } + + public HuggingFace_EmbeddingGeneration(ITestOutputHelper output) : base(output) + { + } +} diff --git a/dotnet/samples/Concepts/Memory/Example25_ReadOnlyMemoryStore.cs b/dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs similarity index 97% rename from dotnet/samples/Concepts/Memory/Example25_ReadOnlyMemoryStore.cs rename to dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs index def7cbd96bca..fe0f2421b4f8 100644 --- a/dotnet/samples/Concepts/Memory/Example25_ReadOnlyMemoryStore.cs +++ b/dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs @@ -1,16 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; using System.Numerics.Tensors; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using Microsoft.SemanticKernel.Memory; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -22,7 +16,7 @@ namespace Examples; /// of has a single collection, and thus does not need to be named. /// It also assumes that the JSON formatted data can be deserialized into objects. /// -public class Example25_ReadOnlyMemoryStore(ITestOutputHelper output) : BaseTest(output) +public class MemoryStore_ReadOnly(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Memory/Example15_TextMemoryPlugin.cs b/dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs similarity index 98% rename from dotnet/samples/Concepts/Memory/Example15_TextMemoryPlugin.cs rename to dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs index 45076a49ff83..b06aff1b1ec7 100644 --- a/dotnet/samples/Concepts/Memory/Example15_TextMemoryPlugin.cs +++ b/dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.AzureAISearch; using Microsoft.SemanticKernel.Connectors.Chroma; @@ -17,14 +16,12 @@ using Microsoft.SemanticKernel.Memory; using Microsoft.SemanticKernel.Plugins.Memory; using Npgsql; -using RepoUtils; using StackExchange.Redis; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example15_TextMemoryPlugin(ITestOutputHelper output) : BaseTest(output) +public class Plugin_TextMemoryPlugin(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "aboutMe"; @@ -106,19 +103,19 @@ private IMemoryStore CreateSampleAzureAISearchMemoryStore() private IMemoryStore CreateSampleChromaMemoryStore() { - IMemoryStore store = new ChromaMemoryStore(TestConfiguration.Chroma.Endpoint, ConsoleLogger.LoggerFactory); + IMemoryStore store = new ChromaMemoryStore(TestConfiguration.Chroma.Endpoint, this.LoggerFactory); return store; } private IMemoryStore CreateSampleQdrantMemoryStore() { - IMemoryStore store = new QdrantMemoryStore(TestConfiguration.Qdrant.Endpoint, 1536, ConsoleLogger.LoggerFactory); + IMemoryStore store = new QdrantMemoryStore(TestConfiguration.Qdrant.Endpoint, 1536, this.LoggerFactory); return store; } private IMemoryStore CreateSamplePineconeMemoryStore() { - IMemoryStore store = new PineconeMemoryStore(TestConfiguration.Pinecone.Environment, TestConfiguration.Pinecone.ApiKey, ConsoleLogger.LoggerFactory); + IMemoryStore store = new PineconeMemoryStore(TestConfiguration.Pinecone.Environment, TestConfiguration.Pinecone.ApiKey, this.LoggerFactory); return store; } diff --git a/dotnet/samples/Concepts/Memory/Example14_SemanticMemory.cs b/dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs similarity index 97% rename from dotnet/samples/Concepts/Memory/Example14_SemanticMemory.cs rename to dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs index 14691b06f9cd..bd09f99fbe0c 100644 --- a/dotnet/samples/Concepts/Memory/Example14_SemanticMemory.cs +++ b/dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs @@ -1,12 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading.Tasks; using Microsoft.SemanticKernel.Connectors.AzureAISearch; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Memory; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -19,7 +15,7 @@ namespace Examples; * Semantic Memory allows to store your data like traditional DBs, * adding the ability to query it using natural language. */ -public class Example14_SemanticMemory(ITestOutputHelper output) : BaseTest(output) +public class SemanticTextMemoryUsage(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "SKGitHub"; diff --git a/dotnet/samples/Concepts/Memory/Example55_TextChunker.cs b/dotnet/samples/Concepts/Memory/TextChunkerUsage.cs similarity index 96% rename from dotnet/samples/Concepts/Memory/Example55_TextChunker.cs rename to dotnet/samples/Concepts/Memory/TextChunkerUsage.cs index 93ef5e90b8e8..d65b9986b5a2 100644 --- a/dotnet/samples/Concepts/Memory/Example55_TextChunker.cs +++ b/dotnet/samples/Concepts/Memory/TextChunkerUsage.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Diagnostics; using Microsoft.ML.Tokenizers; using Microsoft.SemanticKernel.Text; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example55_TextChunker(ITestOutputHelper output) : BaseTest(output) +public class TextChunkerUsage(ITestOutputHelper output) : BaseTest(output) { private static readonly Tokenizer s_tokenizer = Tokenizer.CreateTiktokenForModel("gpt-4"); diff --git a/dotnet/samples/Concepts/Memory/Example81_TextEmbedding.cs b/dotnet/samples/Concepts/Memory/TextEmbedding.cs similarity index 97% rename from dotnet/samples/Concepts/Memory/Example81_TextEmbedding.cs rename to dotnet/samples/Concepts/Memory/TextEmbedding.cs index f8c5c51d0ddf..3d0757d4c104 100644 --- a/dotnet/samples/Concepts/Memory/Example81_TextEmbedding.cs +++ b/dotnet/samples/Concepts/Memory/TextEmbedding.cs @@ -1,17 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.ML.Tokenizers; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Text; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example81_TextEmbedding(ITestOutputHelper output) : BaseTest(output) +public class TextEmbedding(ITestOutputHelper output) : BaseTest(output) { private const string EmbeddingModelName = "text-embedding-ada-002"; private static readonly Tokenizer s_tokenizer = Tokenizer.CreateTiktokenForModel(EmbeddingModelName); diff --git a/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs b/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs index 7337ca00bb28..90ec7817bc54 100644 --- a/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs +++ b/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Planning; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/Planners/Example65_HandlebarsPlanner.cs b/dotnet/samples/Concepts/Planners/Handlebars.cs similarity index 98% rename from dotnet/samples/Concepts/Planners/Example65_HandlebarsPlanner.cs rename to dotnet/samples/Concepts/Planners/Handlebars.cs index d1ffff5439cb..d001d9533c71 100644 --- a/dotnet/samples/Concepts/Planners/Example65_HandlebarsPlanner.cs +++ b/dotnet/samples/Concepts/Planners/Handlebars.cs @@ -1,25 +1,18 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Planning.Handlebars; using Microsoft.SemanticKernel.Plugins.OpenApi; using Plugins.DictionaryPlugin; -using RepoUtils; using Resources; using xRetry; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use the Handlebars sequential planner. -public class Example65_HandlebarsPlanner(ITestOutputHelper output) : BaseTest(output) +public class Handlebars(ITestOutputHelper output) : BaseTest(output) { private static int s_sampleIndex; diff --git a/dotnet/samples/Concepts/Plugins/Example83_ApiManifest.cs b/dotnet/samples/Concepts/Plugins/ApiManifestBasedPlugins.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example83_ApiManifest.cs rename to dotnet/samples/Concepts/Plugins/ApiManifestBasedPlugins.cs index 3c596233325f..9a87b266909f 100644 --- a/dotnet/samples/Concepts/Plugins/Example83_ApiManifest.cs +++ b/dotnet/samples/Concepts/Plugins/ApiManifestBasedPlugins.cs @@ -1,24 +1,17 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; using System.Net.Http.Headers; -using System.Threading; -using System.Threading.Tasks; using System.Web; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.MsGraph.Connectors.CredentialManagers; using Microsoft.SemanticKernel.Plugins.OpenApi; using Microsoft.SemanticKernel.Plugins.OpenApi.Extensions; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use the ApiManifest based plugins -public class Example83_ApiManifest(ITestOutputHelper output) : BaseTest(output) +public class ApiManifestBasedPlugins(ITestOutputHelper output) : BaseTest(output) { public static readonly IEnumerable s_parameters = [ diff --git a/dotnet/samples/Concepts/Plugins/Example13_ConversationSummaryPlugin.cs b/dotnet/samples/Concepts/Plugins/ConversationSummaryPlugin.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example13_ConversationSummaryPlugin.cs rename to dotnet/samples/Concepts/Plugins/ConversationSummaryPlugin.cs index fa29506d3d37..97bd901695d8 100644 --- a/dotnet/samples/Concepts/Plugins/Example13_ConversationSummaryPlugin.cs +++ b/dotnet/samples/Concepts/Plugins/ConversationSummaryPlugin.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Plugins.Core; using xRetry; using Xunit.Abstractions; namespace Examples; -public class Example13_ConversationSummaryPlugin(ITestOutputHelper output) : BaseTest(output) +public class ConversationSummaryPlugin(ITestOutputHelper output) : BaseTest(output) { private const string ChatTranscript = @" @@ -131,7 +129,7 @@ private async Task ConversationSummaryPluginAsync() WriteLine("======== SamplePlugins - Conversation Summary Plugin - Summarize ========"); Kernel kernel = InitializeKernel(); - KernelPlugin conversationSummaryPlugin = kernel.ImportPluginFromType(); + KernelPlugin conversationSummaryPlugin = kernel.ImportPluginFromType(); FunctionResult summary = await kernel.InvokeAsync( conversationSummaryPlugin["SummarizeConversation"], new() { ["input"] = ChatTranscript }); @@ -145,7 +143,7 @@ private async Task GetConversationActionItemsAsync() WriteLine("======== SamplePlugins - Conversation Summary Plugin - Action Items ========"); Kernel kernel = InitializeKernel(); - KernelPlugin conversationSummary = kernel.ImportPluginFromType(); + KernelPlugin conversationSummary = kernel.ImportPluginFromType(); FunctionResult summary = await kernel.InvokeAsync( conversationSummary["GetConversationActionItems"], new() { ["input"] = ChatTranscript }); @@ -159,7 +157,7 @@ private async Task GetConversationTopicsAsync() WriteLine("======== SamplePlugins - Conversation Summary Plugin - Topics ========"); Kernel kernel = InitializeKernel(); - KernelPlugin conversationSummary = kernel.ImportPluginFromType(); + KernelPlugin conversationSummary = kernel.ImportPluginFromType(); FunctionResult summary = await kernel.InvokeAsync( conversationSummary["GetConversationTopics"], new() { ["input"] = ChatTranscript }); diff --git a/dotnet/samples/Concepts/Plugins/Example22_OpenAIPlugin_AzureKeyVault.cs b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs similarity index 98% rename from dotnet/samples/Concepts/Plugins/Example22_OpenAIPlugin_AzureKeyVault.cs rename to dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs index 528a564c09f8..7bf1dcdc1023 100644 --- a/dotnet/samples/Concepts/Plugins/Example22_OpenAIPlugin_AzureKeyVault.cs +++ b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs @@ -1,24 +1,18 @@ // 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; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.OpenApi; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example22_OpenAIPlugin_AzureKeyVault(ITestOutputHelper output) : BaseTest(output) +public class CreatePluginFromOpenAI_AzureKeyVault(ITestOutputHelper output) : BaseTest(output) { private const string SecretName = "Foo"; private const string SecretValue = "Bar"; diff --git a/dotnet/samples/Concepts/Plugins/Example23_OpenAPIPlugin.cs b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Github.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example23_OpenAPIPlugin.cs rename to dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Github.cs index 954cd5c9f7ee..628d1482eb9c 100644 --- a/dotnet/samples/Concepts/Plugins/Example23_OpenAPIPlugin.cs +++ b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Github.cs @@ -1,12 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.IO; -using System.Net.Http; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.OpenApi; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -14,7 +9,7 @@ namespace Examples; /// /// Examples to show how to create plugins from OpenAPI specs. /// -public class Example23_OpenAPIPlugin(ITestOutputHelper output) : BaseTest(output) +public class CreatePluginFromOpenApiSpec_Github(ITestOutputHelper output) : BaseTest(output) { /// /// Example to show how to consume operation extensions and other metadata from an OpenAPI spec. diff --git a/dotnet/samples/Concepts/Plugins/Example24_OpenApiPlugin_Jira.cs b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example24_OpenApiPlugin_Jira.cs rename to dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs index ec0711db1316..c737e77199e0 100644 --- a/dotnet/samples/Concepts/Plugins/Example24_OpenApiPlugin_Jira.cs +++ b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs @@ -1,23 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; -using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.Json; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Identity.Client; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.OpenApi; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example24_OpenApiPlugin_Jira(ITestOutputHelper output) : BaseTest(output) +public class CreatePluginFromOpenApiSpec_Jira(ITestOutputHelper output) : BaseTest(output) { private static readonly JsonSerializerOptions s_jsonOptionsCache = new() { @@ -62,7 +55,7 @@ public async Task RunAsync() bool useLocalFile = true; if (useLocalFile) { - var apiPluginFile = "./../../../Plugins/JiraPlugin/openapi.json"; + var apiPluginFile = "./../../../../Plugins/JiraPlugin/openapi.json"; jiraFunctions = await kernel.ImportPluginFromOpenApiAsync( "jiraPlugin", apiPluginFile, diff --git a/dotnet/samples/Concepts/Plugins/Example69_MutableKernelPlugin.cs b/dotnet/samples/Concepts/Plugins/CustomMutablePlugin.cs similarity index 90% rename from dotnet/samples/Concepts/Plugins/Example69_MutableKernelPlugin.cs rename to dotnet/samples/Concepts/Plugins/CustomMutablePlugin.cs index c38ec2af6206..177e48e9ba9c 100644 --- a/dotnet/samples/Concepts/Plugins/Example69_MutableKernelPlugin.cs +++ b/dotnet/samples/Concepts/Plugins/CustomMutablePlugin.cs @@ -1,21 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; -// This example shows how to create a mutable . -public class Example69_MutableKernelPlugin(ITestOutputHelper output) : BaseTest(output) +/// +/// This example shows how to create a mutable . +/// +public class CustomMutablePlugin(ITestOutputHelper output) : BaseTest(output) { - /// - /// Show how to create a mutable . - /// [Fact] public async Task RunAsync() { diff --git a/dotnet/samples/Concepts/Plugins/Example10_DescribeAllPluginsAndFunctions.cs b/dotnet/samples/Concepts/Plugins/DescribeAllPluginsAndFunctions.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example10_DescribeAllPluginsAndFunctions.cs rename to dotnet/samples/Concepts/Plugins/DescribeAllPluginsAndFunctions.cs index b098c5468b2a..768bbaa1fce6 100644 --- a/dotnet/samples/Concepts/Plugins/Example10_DescribeAllPluginsAndFunctions.cs +++ b/dotnet/samples/Concepts/Plugins/DescribeAllPluginsAndFunctions.cs @@ -1,18 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System.IO; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Plugins.Core; using Plugins; -using RepoUtils; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example10_DescribeAllPluginsAndFunctions(ITestOutputHelper output) : BaseTest(output) +public class DescribeAllPluginsAndFunctions(ITestOutputHelper output) : BaseTest(output) { /// /// Print a list of all the functions imported into the kernel, including function descriptions, diff --git a/dotnet/samples/Concepts/Plugins/Example48_GroundednessChecks.cs b/dotnet/samples/Concepts/Plugins/GroundednessChecks.cs similarity index 98% rename from dotnet/samples/Concepts/Plugins/Example48_GroundednessChecks.cs rename to dotnet/samples/Concepts/Plugins/GroundednessChecks.cs index ecde8ebe71c0..ca58960658fa 100644 --- a/dotnet/samples/Concepts/Plugins/Example48_GroundednessChecks.cs +++ b/dotnet/samples/Concepts/Plugins/GroundednessChecks.cs @@ -1,19 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System.IO; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Planning.Handlebars; using Microsoft.SemanticKernel.Plugins.Core; -using RepoUtils; using xRetry; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example48_GroundednessChecks(ITestOutputHelper output) : BaseTest(output) +public class GroundednessChecks(ITestOutputHelper output) : BaseTest(output) { [RetryFact(typeof(HttpOperationException))] public async Task GroundednessCheckingAsync() diff --git a/dotnet/samples/Concepts/Plugins/Example35_GrpcPlugins.cs b/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs similarity index 96% rename from dotnet/samples/Concepts/Plugins/Example35_GrpcPlugins.cs rename to dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs index 57e368fc0d67..58fae656ec1d 100644 --- a/dotnet/samples/Concepts/Plugins/Example35_GrpcPlugins.cs +++ b/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs @@ -1,9 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Grpc; -using Xunit; using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/Plugins/Example21_OpenAIPlugins.cs b/dotnet/samples/Concepts/Plugins/OpenAIPlugins.cs similarity index 93% rename from dotnet/samples/Concepts/Plugins/Example21_OpenAIPlugins.cs rename to dotnet/samples/Concepts/Plugins/OpenAIPlugins.cs index b17f6647cc8b..95bcf0725a6a 100644 --- a/dotnet/samples/Concepts/Plugins/Example21_OpenAIPlugins.cs +++ b/dotnet/samples/Concepts/Plugins/OpenAIPlugins.cs @@ -1,16 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Net.Http; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.OpenApi; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example21_OpenAIPlugins(ITestOutputHelper output) : BaseTest(output) +public class OpenAIPlugins(ITestOutputHelper output) : BaseTest(output) { /// /// Generic template on how to call OpenAI plugins diff --git a/dotnet/samples/Concepts/PromptTemplates/Example63_ChatCompletionPrompts.cs b/dotnet/samples/Concepts/PromptTemplates/ChatCompletionPrompts.cs similarity index 93% rename from dotnet/samples/Concepts/PromptTemplates/Example63_ChatCompletionPrompts.cs rename to dotnet/samples/Concepts/PromptTemplates/ChatCompletionPrompts.cs index 1c365679cf7f..a3b67af936b1 100644 --- a/dotnet/samples/Concepts/PromptTemplates/Example63_ChatCompletionPrompts.cs +++ b/dotnet/samples/Concepts/PromptTemplates/ChatCompletionPrompts.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use chat completion standardized prompts. -public class Example63_ChatCompletionPrompts(ITestOutputHelper output) : BaseTest(output) +public class ChatCompletionPrompts(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/PromptTemplates/Example30_ChatWithPrompts.cs b/dotnet/samples/Concepts/PromptTemplates/ChatWithPrompts.cs similarity index 97% rename from dotnet/samples/Concepts/PromptTemplates/Example30_ChatWithPrompts.cs rename to dotnet/samples/Concepts/PromptTemplates/ChatWithPrompts.cs index 5060b4892900..abe197aeacc0 100644 --- a/dotnet/samples/Concepts/PromptTemplates/Example30_ChatWithPrompts.cs +++ b/dotnet/samples/Concepts/PromptTemplates/ChatWithPrompts.cs @@ -1,13 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Globalization; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Plugins.Core; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -35,7 +32,7 @@ namespace Examples; /// Out of scope and not in the example: if needed, one could go further and use a semantic /// function (with extra cost) asking AI to generate the text to send to the Chat model. /// -public class Example30_ChatWithPrompts(ITestOutputHelper output) : BaseTest(output) +public class ChatWithPrompts(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/PromptTemplates/Example64_MultiplePromptTemplates.cs b/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs similarity index 94% rename from dotnet/samples/Concepts/PromptTemplates/Example64_MultiplePromptTemplates.cs rename to dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs index c55bc70cba1e..1e1f4b0e64be 100644 --- a/dotnet/samples/Concepts/PromptTemplates/Example64_MultiplePromptTemplates.cs +++ b/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs @@ -1,16 +1,14 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.PromptTemplates.Handlebars; using xRetry; -using Xunit; using Xunit.Abstractions; namespace Examples; // This example shows how to use multiple prompt template formats. -public class Example64_MultiplePromptTemplates(ITestOutputHelper output) : BaseTest(output) +public class MultiplePromptTemplates(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to combine multiple prompt template factories. diff --git a/dotnet/samples/Concepts/PromptTemplates/Example27_PromptFunctionsUsingChatGPT.cs b/dotnet/samples/Concepts/PromptTemplates/PromptFunctionsWithChatGPT.cs similarity index 89% rename from dotnet/samples/Concepts/PromptTemplates/Example27_PromptFunctionsUsingChatGPT.cs rename to dotnet/samples/Concepts/PromptTemplates/PromptFunctionsWithChatGPT.cs index 041c64d8d39d..c52b90844906 100644 --- a/dotnet/samples/Concepts/PromptTemplates/Example27_PromptFunctionsUsingChatGPT.cs +++ b/dotnet/samples/Concepts/PromptTemplates/PromptFunctionsWithChatGPT.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -10,7 +8,7 @@ namespace Examples; /// /// This example shows how to use GPT3.5 Chat model for prompts and prompt functions. /// -public class Example27_PromptFunctionsUsingChatGPT(ITestOutputHelper output) : BaseTest(output) +public class PromptFunctionsWithChatGPT(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/PromptTemplates/Example06_TemplateLanguage.cs b/dotnet/samples/Concepts/PromptTemplates/TemplateLanguage.cs similarity index 95% rename from dotnet/samples/Concepts/PromptTemplates/Example06_TemplateLanguage.cs rename to dotnet/samples/Concepts/PromptTemplates/TemplateLanguage.cs index 92a5784ad236..243fc5c81bf8 100644 --- a/dotnet/samples/Concepts/PromptTemplates/Example06_TemplateLanguage.cs +++ b/dotnet/samples/Concepts/PromptTemplates/TemplateLanguage.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example06_TemplateLanguage(ITestOutputHelper output) : BaseTest(output) +public class TemplateLanguage(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to invoke a Method Function written in C# diff --git a/dotnet/samples/Concepts/RAG/Example80_FunctionCallingPlannerWithRAG.cs b/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs similarity index 95% rename from dotnet/samples/Concepts/RAG/Example80_FunctionCallingPlannerWithRAG.cs rename to dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs index 6889974684fd..70216900be03 100644 --- a/dotnet/samples/Concepts/RAG/Example80_FunctionCallingPlannerWithRAG.cs +++ b/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. using System.ComponentModel; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Planning; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example80_FunctionCallingPlannerWithRAG(ITestOutputHelper output) : BaseTest(output) +public class WithFunctionCallingStepwisePlanner(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/RAG/Example78_RAG.cs b/dotnet/samples/Concepts/RAG/WithPlugins.cs similarity index 90% rename from dotnet/samples/Concepts/RAG/Example78_RAG.cs rename to dotnet/samples/Concepts/RAG/WithPlugins.cs index 4de74d750130..b022c036f953 100644 --- a/dotnet/samples/Concepts/RAG/Example78_RAG.cs +++ b/dotnet/samples/Concepts/RAG/WithPlugins.cs @@ -1,22 +1,18 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.Net.Http.Headers; using System.Text.Json; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.Chroma; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Memory; -using Microsoft.SemanticKernel.Plugins.Memory; using Microsoft.SemanticKernel.Plugins.OpenApi; using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example78_RAG(ITestOutputHelper output) : BaseTest(output) +public class WithPlugins(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RAGWithCustomPluginAsync() @@ -33,7 +29,7 @@ public async Task RAGWithCustomPluginAsync() } /// - /// Shows how to use RAG pattern with . + /// Shows how to use RAG pattern with . /// [Fact(Skip = "Requires Chroma server up and running")] public async Task RAGWithTextMemoryPluginAsync() @@ -47,7 +43,7 @@ public async Task RAGWithTextMemoryPluginAsync() .AddOpenAIChatCompletion(TestConfiguration.OpenAI.ChatModelId, TestConfiguration.OpenAI.ApiKey) .Build(); - kernel.ImportPluginFromObject(new TextMemoryPlugin(memory)); + kernel.ImportPluginFromObject(new Microsoft.SemanticKernel.Plugins.Memory.TextMemoryPlugin(memory)); var result = await kernel.InvokePromptAsync("{{recall 'budget by year' collection='finances'}} What is my budget for 2024?"); diff --git a/dotnet/samples/Concepts/Resources/EmbeddedResource.cs b/dotnet/samples/Concepts/Resources/EmbeddedResource.cs index 44b49a7bd78f..831aa018a44c 100644 --- a/dotnet/samples/Concepts/Resources/EmbeddedResource.cs +++ b/dotnet/samples/Concepts/Resources/EmbeddedResource.cs @@ -1,10 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.IO; using System.Reflection; -using System.Threading.Tasks; -using RepoUtils; namespace Resources; @@ -27,13 +23,13 @@ internal static string Read(string fileName) // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. Assembly assembly = typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); + throw new ConfigurationNotFoundException($"[{s_namespace}] {fileName} assembly not found"); // Resources are mapped like types, using the namespace and appending "." (dot) and the file name var resourceName = $"{s_namespace}." + fileName; using Stream resource = assembly.GetManifestResourceStream(resourceName) ?? - throw new ConfigurationException($"{resourceName} resource not found"); + throw new ConfigurationNotFoundException($"{resourceName} resource not found"); // Return the resource content, in text format. using var reader = new StreamReader(resource); @@ -45,7 +41,7 @@ internal static string Read(string fileName) // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. Assembly assembly = typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); + throw new ConfigurationNotFoundException($"[{s_namespace}] {fileName} assembly not found"); // Resources are mapped like types, using the namespace and appending "." (dot) and the file name var resourceName = $"{s_namespace}." + fileName; diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/CalendarPlugin/apimanifest.json b/dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/CalendarPlugin/apimanifest.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/CalendarPlugin/apimanifest.json rename to dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/CalendarPlugin/apimanifest.json diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/ContactsPlugin/apimanifest.json b/dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/ContactsPlugin/apimanifest.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/ContactsPlugin/apimanifest.json rename to dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/ContactsPlugin/apimanifest.json diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/DriveItemPlugin/apimanifest.json b/dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/DriveItemPlugin/apimanifest.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/DriveItemPlugin/apimanifest.json rename to dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/DriveItemPlugin/apimanifest.json diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/MessagesPlugin/apimanifest.json b/dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/MessagesPlugin/apimanifest.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/MessagesPlugin/apimanifest.json rename to dotnet/samples/Concepts/Resources/Plugins/ApiManifestPlugins/MessagesPlugin/apimanifest.json diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs similarity index 91% rename from dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs rename to dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs index afb7d0a5cf55..65e44ab2b78b 100644 --- a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs +++ b/dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/ComplexParamsDictionaryPlugin.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; using System.ComponentModel; using System.Globalization; -using System.Linq; using System.Security.Cryptography; using System.Text.Json; using Microsoft.SemanticKernel; @@ -18,14 +15,14 @@ public sealed class ComplexParamsDictionaryPlugin { public const string PluginName = nameof(ComplexParamsDictionaryPlugin); - private readonly List _dictionary = - [ + private readonly List _dictionary = new() + { 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,10 +59,16 @@ 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(string word, string definition) +public sealed class DictionaryEntry { - public string Word { get; set; } = word; - public string Definition { get; set; } = 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; + } } /// diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs similarity index 97% rename from dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs rename to dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs index 7849a77d4a3c..1cfdcd20f4d9 100644 --- a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs +++ b/dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/StringParamsDictionaryPlugin.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using System.ComponentModel; -using System.Linq; using System.Security.Cryptography; using Microsoft.SemanticKernel; diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/openapi.json b/dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/openapi.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/DictionaryPlugin/openapi.json rename to dotnet/samples/Concepts/Resources/Plugins/DictionaryPlugin/openapi.json diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/EmailPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/EmailPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/EmailPlugin.cs rename to dotnet/samples/Concepts/Resources/Plugins/EmailPlugin.cs diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/JiraPlugin/README.md b/dotnet/samples/Concepts/Resources/Plugins/JiraPlugin/README.md similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/JiraPlugin/README.md rename to dotnet/samples/Concepts/Resources/Plugins/JiraPlugin/README.md diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/JiraPlugin/openapi.json b/dotnet/samples/Concepts/Resources/Plugins/JiraPlugin/openapi.json similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/JiraPlugin/openapi.json rename to dotnet/samples/Concepts/Resources/Plugins/JiraPlugin/openapi.json diff --git a/dotnet/samples/Concepts/AgentSyntax/Plugins/MenuPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs similarity index 96% rename from dotnet/samples/Concepts/AgentSyntax/Plugins/MenuPlugin.cs rename to dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs index e29627e047ad..ba74f786d90f 100644 --- a/dotnet/samples/Concepts/AgentSyntax/Plugins/MenuPlugin.cs +++ b/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs @@ -21,7 +21,7 @@ public string GetSpecials() [KernelFunction, Description("Provides the price of the requested menu item.")] public string GetItemPrice( [Description("The name of the menu item.")] - string menuItem) + string menuItem) { return "$9.99"; } diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/StaticTextPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/StaticTextPlugin.cs similarity index 100% rename from dotnet/samples/KernelSyntaxExamples/Plugins/StaticTextPlugin.cs rename to dotnet/samples/Concepts/Resources/Plugins/StaticTextPlugin.cs diff --git a/dotnet/samples/Concepts/Search/Example07_BingAndGooglePlugins.cs b/dotnet/samples/Concepts/Search/BingAndGooglePlugins.cs similarity index 98% rename from dotnet/samples/Concepts/Search/Example07_BingAndGooglePlugins.cs rename to dotnet/samples/Concepts/Search/BingAndGooglePlugins.cs index 6c6ec43e75b6..4b15697282b1 100644 --- a/dotnet/samples/Concepts/Search/Example07_BingAndGooglePlugins.cs +++ b/dotnet/samples/Concepts/Search/BingAndGooglePlugins.cs @@ -1,13 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Plugins.Web; using Microsoft.SemanticKernel.Plugins.Web.Bing; using Microsoft.SemanticKernel.Plugins.Web.Google; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -17,7 +14,7 @@ namespace Examples; /// you might want to import into your system, e.g. providing AI prompts with /// recent information, or for AI to generate recent information to display to users. /// -public class Example07_BingAndGooglePlugins(ITestOutputHelper output) : BaseTest(output) +public class BingAndGooglePlugins(ITestOutputHelper output) : BaseTest(output) { [Fact(Skip = "Setup Credentials")] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Search/Example84_AzureAISearchPlugin.cs b/dotnet/samples/Concepts/Search/MyAzureAISearchPlugin.cs similarity index 94% rename from dotnet/samples/Concepts/Search/Example84_AzureAISearchPlugin.cs rename to dotnet/samples/Concepts/Search/MyAzureAISearchPlugin.cs index 0289bf3c33f1..3c6dc27ab488 100644 --- a/dotnet/samples/Concepts/Search/Example84_AzureAISearchPlugin.cs +++ b/dotnet/samples/Concepts/Search/MyAzureAISearchPlugin.cs @@ -1,12 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Linq; using System.Text.Json; using System.Text.Json.Serialization; -using System.Threading; -using System.Threading.Tasks; using Azure; using Azure.Search.Documents; using Azure.Search.Documents.Indexes; @@ -14,12 +9,11 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Embeddings; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example84_AzureAISearchPlugin(ITestOutputHelper output) : BaseTest(output) +public class AzureAISearchPlugin(ITestOutputHelper output) : BaseTest(output) { /// /// Shows how to register Azure AI Search service as a plugin and work with custom index schema. @@ -47,7 +41,7 @@ public async Task AzureAISearchPluginAsync() kernelBuilder.AddOpenAIChatCompletion("gpt-4", TestConfiguration.OpenAI.ApiKey); // Register Azure AI Search Plugin - kernelBuilder.Plugins.AddFromType(); + kernelBuilder.Plugins.AddFromType(); // Create kernel var kernel = kernelBuilder.Build(); @@ -166,9 +160,9 @@ private sealed class AzureAISearchService(SearchIndexClient indexClient) : IAzur /// It uses to convert string query to vector. /// It uses to perform a request to Azure AI Search. /// - private sealed class AzureAISearchPlugin( + private sealed class MyAzureAISearchPlugin( ITextEmbeddingGenerationService textEmbeddingGenerationService, - Example84_AzureAISearchPlugin.IAzureAISearchService searchService) + Examples.AzureAISearchPlugin.IAzureAISearchService searchService) { private readonly ITextEmbeddingGenerationService _textEmbeddingGenerationService = textEmbeddingGenerationService; private readonly IAzureAISearchService _searchService = searchService; diff --git a/dotnet/samples/Concepts/Search/Example11_WebSearchQueries.cs b/dotnet/samples/Concepts/Search/WebSearchQueriesPlugin.cs similarity index 88% rename from dotnet/samples/Concepts/Search/Example11_WebSearchQueries.cs rename to dotnet/samples/Concepts/Search/WebSearchQueriesPlugin.cs index 9ed150a4b0c9..cc2da1099010 100644 --- a/dotnet/samples/Concepts/Search/Example11_WebSearchQueries.cs +++ b/dotnet/samples/Concepts/Search/WebSearchQueriesPlugin.cs @@ -1,14 +1,12 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Web; -using Xunit; using Xunit.Abstractions; namespace Examples; -public class Example11_WebSearchQueries(ITestOutputHelper output) : BaseTest(output) +public class WebSearchQueriesPlugin(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/LocalModels/Example16_CustomLLM.cs b/dotnet/samples/Concepts/TextGeneration/Custom_TextGenerationService.cs similarity index 95% rename from dotnet/samples/Concepts/LocalModels/Example16_CustomLLM.cs rename to dotnet/samples/Concepts/TextGeneration/Custom_TextGenerationService.cs index bbc53fbefeda..1d2bf1678460 100644 --- a/dotnet/samples/Concepts/LocalModels/Example16_CustomLLM.cs +++ b/dotnet/samples/Concepts/TextGeneration/Custom_TextGenerationService.cs @@ -1,20 +1,15 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; using System.Runtime.CompilerServices; -using System.Threading; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.TextGeneration; -using Xunit; using Xunit.Abstractions; namespace Examples; /** - * The following example shows how to plug a custom text generation model into SK. + * The following example shows how to plug a custom text generation service in SK. * * To do this, this example uses a text generation service stub (MyTextGenerationService) and * no actual model. @@ -28,7 +23,7 @@ namespace Examples; * * Refer to example 33 for streaming chat completion. */ -public class Example16_CustomLLM(ITestOutputHelper output) : BaseTest(output) +public class Custom_TextGenerationService(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task CustomTextGenerationWithKernelFunctionAsync() diff --git a/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs new file mode 100644 index 000000000000..fbc0ed4bbd78 --- /dev/null +++ b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs @@ -0,0 +1,103 @@ +// Copyright (c) Microsoft. All rights reserved. + +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.Connectors.HuggingFace; +using xRetry; +using Xunit.Abstractions; + +#pragma warning disable format // Format item can be simplified +#pragma warning disable CA1861 // Avoid constant arrays as arguments + +namespace Examples; + +// The following example shows how to use Semantic Kernel with HuggingFace API. +public class Example20_HuggingFace : BaseTest +{ + /// + /// This example uses HuggingFace Inference API to access hosted models. + /// More information here: + /// + [Fact] + public async Task RunInferenceApiExampleAsync() + { + WriteLine("\n======== HuggingFace Inference API example ========\n"); + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceTextGeneration( + model: TestConfiguration.HuggingFace.ModelId, + apiKey: TestConfiguration.HuggingFace.ApiKey) + .Build(); + + var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:"); + + var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" }); + + WriteLine(result.GetValue()); + } + + [RetryFact(typeof(HttpOperationException))] + public async Task RunStreamingExampleAsync() + { + WriteLine("\n======== HuggingFace zephyr-7b-beta streaming example ========\n"); + + const string Model = "HuggingFaceH4/zephyr-7b-beta"; + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceTextGeneration( + model: Model, + apiKey: TestConfiguration.HuggingFace.ApiKey) + .Build(); + + var settings = new HuggingFacePromptExecutionSettings { UseCache = false }; + + var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:", new HuggingFacePromptExecutionSettings + { + UseCache = false + }); + + await foreach (string text in kernel.InvokePromptStreamingAsync("Question: {{$input}}; Answer:", new(settings) { ["input"] = "What is New York?" })) + { + this.Write(text); + } + } + + /// + /// This example uses HuggingFace Llama 2 model and local HTTP server from Semantic Kernel repository. + /// How to setup local HTTP server: . + /// + /// Additional access is required to download Llama 2 model and run it locally. + /// How to get access: + /// 1. Visit and complete request access form. + /// 2. Visit and complete form "Access Llama 2 on Hugging Face". + /// Note: Your Hugging Face account email address MUST match the email you provide on the Meta website, or your request will not be approved. + /// + /// + [Fact(Skip = "Requires local model or Huggingface Pro subscription")] + public async Task RunLlamaExampleAsync() + { + WriteLine("\n======== HuggingFace Llama 2 example ========\n"); + + // HuggingFace Llama 2 model: https://huggingface.co/meta-llama/Llama-2-7b-hf + const string Model = "meta-llama/Llama-2-7b-hf"; + + // HuggingFace local HTTP server endpoint + // const string Endpoint = "http://localhost:5000/completions"; + + Kernel kernel = Kernel.CreateBuilder() + .AddHuggingFaceTextGeneration( + model: Model, + //endpoint: Endpoint, + apiKey: TestConfiguration.HuggingFace.ApiKey) + .Build(); + + var questionAnswerFunction = kernel.CreateFunctionFromPrompt("Question: {{$input}}; Answer:"); + + var result = await kernel.InvokeAsync(questionAnswerFunction, new() { ["input"] = "What is New York?" }); + + WriteLine(result.GetValue()); + } + + public Example20_HuggingFace(ITestOutputHelper output) : base(output) + { + } +} diff --git a/dotnet/samples/Concepts/TextGeneration/Example32_StreamingCompletion.cs b/dotnet/samples/Concepts/TextGeneration/OpenAI_TextGenerationStreaming.cs similarity index 87% rename from dotnet/samples/Concepts/TextGeneration/Example32_StreamingCompletion.cs rename to dotnet/samples/Concepts/TextGeneration/OpenAI_TextGenerationStreaming.cs index af284e67b3c5..c248f38c8698 100644 --- a/dotnet/samples/Concepts/TextGeneration/Example32_StreamingCompletion.cs +++ b/dotnet/samples/Concepts/TextGeneration/OpenAI_TextGenerationStreaming.cs @@ -1,15 +1,13 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.TextGeneration; -using Xunit; using Xunit.Abstractions; namespace Examples; /** - * The following example shows how to use Semantic Kernel with streaming text completion. + * The following example shows how to use Semantic Kernel with streaming text generation. * * This example will NOT work with regular chat completion models. It will only work with * text completion models. @@ -18,12 +16,12 @@ namespace Examples; * * Refer to example 33 for streaming chat completion. */ -public class Example32_StreamingCompletion(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_TextGenerationStreaming(ITestOutputHelper output) : BaseTest(output) { [Fact] public Task AzureOpenAITextGenerationStreamAsync() { - WriteLine("======== Azure OpenAI - Text Completion - Raw Streaming ========"); + WriteLine("======== Azure OpenAI - Text Generation - Raw Streaming ========"); var textGeneration = new AzureOpenAITextGenerationService( deploymentName: TestConfiguration.AzureOpenAI.DeploymentName, @@ -37,7 +35,7 @@ public Task AzureOpenAITextGenerationStreamAsync() [Fact] public Task OpenAITextGenerationStreamAsync() { - WriteLine("======== Open AI - Text Completion - Raw Streaming ========"); + WriteLine("======== Open AI - Text Generation - Raw Streaming ========"); var textGeneration = new OpenAITextGenerationService("gpt-3.5-turbo-instruct", TestConfiguration.OpenAI.ApiKey); diff --git a/dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs b/dotnet/samples/Concepts/TextToAudio/OpenAI_TextToAudio.cs similarity index 85% rename from dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs rename to dotnet/samples/Concepts/TextToAudio/OpenAI_TextToAudio.cs index 353399ba093f..e0fe272fa4e7 100644 --- a/dotnet/samples/Concepts/TextToAudio/Example82_Audio.cs +++ b/dotnet/samples/Concepts/TextToAudio/OpenAI_TextToAudio.cs @@ -1,13 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.AudioToText; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.TextToAudio; -using Resources; -using Xunit; using Xunit.Abstractions; namespace Examples; @@ -15,11 +10,9 @@ namespace Examples; /// /// Represents a class that demonstrates audio processing functionality. /// -public sealed class Example82_Audio(ITestOutputHelper output) : BaseTest(output) +public sealed class OpenAI_TextToAudio(ITestOutputHelper output) : BaseTest(output) { private const string TextToAudioModel = "tts-1"; - private const string AudioToTextModel = "whisper-1"; - private const string AudioFilename = "test_audio.wav"; [Fact(Skip = "Uncomment the line to write the audio file output before running this test.")] public async Task TextToAudioAsync() diff --git a/dotnet/samples/Concepts/TextToImage/Example18_DallE.cs b/dotnet/samples/Concepts/TextToImage/OpenAI_TextToImageDalle3.cs similarity index 98% rename from dotnet/samples/Concepts/TextToImage/Example18_DallE.cs rename to dotnet/samples/Concepts/TextToImage/OpenAI_TextToImageDalle3.cs index 36bf026ed24f..09932529906b 100644 --- a/dotnet/samples/Concepts/TextToImage/Example18_DallE.cs +++ b/dotnet/samples/Concepts/TextToImage/OpenAI_TextToImageDalle3.cs @@ -1,19 +1,16 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Http.Resilience; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.TextToImage; -using Xunit; using Xunit.Abstractions; namespace Examples; // The following example shows how to use Semantic Kernel with OpenAI DALL-E 2 to create images -public class Example18_DallE(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_TextToImageDalle3(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task OpenAIDallEAsync() diff --git a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj new file mode 100644 index 000000000000..8208021e8be8 --- /dev/null +++ b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj @@ -0,0 +1,49 @@ + + + + net8.0 + enable + enable + + false + true + + GettingStartedWithAgents + + + CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 + Library + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step1_Agent.cs b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs similarity index 96% rename from dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step1_Agent.cs rename to dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs index eb2826de82c9..4f26fcd3e6dd 100644 --- a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step1_Agent.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs @@ -1,10 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step2_Plugins.cs b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs similarity index 75% rename from dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step2_Plugins.cs rename to dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs index ea99b955ee04..5f591d8410af 100644 --- a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step2_Plugins.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; +using System.ComponentModel; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Plugins; -using Xunit; using Xunit.Abstractions; namespace GettingStarted; @@ -58,4 +55,26 @@ async Task InvokeAgentAsync(string input) } } } + + public sealed class MenuPlugin + { + [KernelFunction, Description("Provides a list of specials from the menu.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "Too smart")] + public string GetSpecials() + { + return @" +Special Soup: Clam Chowder +Special Salad: Cobb Salad +Special Drink: Chai Tea +"; + } + + [KernelFunction, Description("Provides the price of the requested menu item.")] + public string GetItemPrice( + [Description("The name of the menu item.")] + string menuItem) + { + return "$9.99"; + } + } } diff --git a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step3_Chat.cs b/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs similarity index 96% rename from dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step3_Chat.cs rename to dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs index 687f0101f473..0992a5bd97dd 100644 --- a/dotnet/samples/Concepts/AgentSyntax/Getting_Started/Step3_Chat.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs @@ -1,14 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; -using System.Threading; -using System.Threading.Tasks; -using Examples; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.Chat; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/KernelSyntaxExamples/BaseTest.cs b/dotnet/samples/KernelSyntaxExamples/BaseTest.cs deleted file mode 100644 index b2559c03ae6f..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/BaseTest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using RepoUtils; -using Xunit.Abstractions; - -namespace Examples; - -public abstract class BaseTest -{ - protected ITestOutputHelper Output { get; } - - protected ILoggerFactory LoggerFactory { get; } - - protected BaseTest(ITestOutputHelper output) - { - this.Output = output; - this.LoggerFactory = new XunitLogger(output); - - LoadUserSecrets(); - } - - private static void LoadUserSecrets() - { - IConfigurationRoot configRoot = new ConfigurationBuilder() - .AddJsonFile("appsettings.Development.json", true) - .AddEnvironmentVariables() - .AddUserSecrets() - .Build(); - - TestConfiguration.Initialize(configRoot); - } - - /// - /// This method can be substituted by Console.WriteLine when used in Console apps. - /// - /// Target object to write - protected void WriteLine(object? target = null) - { - this.Output.WriteLine(target ?? string.Empty); - } - - /// - /// Current interface ITestOutputHelper does not have a Write method. This extension method adds it to make it analogous to Console.Write when used in Console apps. - /// - /// Target object to write - protected void Write(object? target = null) - { - this.Output.WriteLine(target ?? string.Empty); - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/Example26_AADAuth.cs b/dotnet/samples/KernelSyntaxExamples/Example26_AADAuth.cs deleted file mode 100644 index 9c47490105a8..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Example26_AADAuth.cs +++ /dev/null @@ -1,66 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Threading.Tasks; -using Azure.Identity; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.ChatCompletion; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -/// -/// This example shows how to connect your app to Azure OpenAI using -/// Azure Active Directory(AAD) authentication, as opposed to API keys. -/// -/// The example uses , which you can configure to support -/// multiple authentication strategies: -/// -/// -Env vars present in Azure VMs -/// -Azure Managed Identities -/// -Shared tokens -/// -etc. -/// -public class Example26_AADAuth(ITestOutputHelper output) : BaseTest(output) -{ - [Fact(Skip = "Setup credentials")] - public async Task RunAsync() - { - WriteLine("======== SK with AAD Auth ========"); - - // Optional: choose which authentication to support - var authOptions = new DefaultAzureCredentialOptions - { - ExcludeEnvironmentCredential = true, - ExcludeManagedIdentityCredential = true, - ExcludeSharedTokenCacheCredential = true, - ExcludeAzureCliCredential = true, - ExcludeVisualStudioCredential = true, - ExcludeVisualStudioCodeCredential = true, - ExcludeInteractiveBrowserCredential = false, - ExcludeAzureDeveloperCliCredential = true, - ExcludeWorkloadIdentityCredential = true, - ExcludeAzurePowerShellCredential = true - }; - - Kernel kernel = Kernel.CreateBuilder() - // Add Azure OpenAI chat completion service using DefaultAzureCredential AAD auth - .AddAzureOpenAIChatCompletion( - deploymentName: TestConfiguration.AzureOpenAI.ChatDeploymentName, - endpoint: TestConfiguration.AzureOpenAI.Endpoint, - credentials: new DefaultAzureCredential(authOptions)) - .Build(); - - IChatCompletionService chatGPT = kernel.GetRequiredService(); - var chatHistory = new ChatHistory(); - - // User message - chatHistory.AddUserMessage("Tell me a joke about hourglasses"); - - // Bot reply - var reply = await chatGPT.GetChatMessageContentAsync(chatHistory); - WriteLine(reply); - - /* Output: Why did the hourglass go to the doctor? Because it was feeling a little run down! */ - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs b/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs deleted file mode 100644 index aa53585772f1..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Example74_FlowOrchestrator.cs +++ /dev/null @@ -1,284 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Diagnostics; -using System.Linq; -using System.Text.Json; -using System.Text.RegularExpressions; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Microsoft.Extensions.Logging; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.ChatCompletion; -using Microsoft.SemanticKernel.Connectors.OpenAI; -using Microsoft.SemanticKernel.Experimental.Orchestration; -using Microsoft.SemanticKernel.Memory; -using Microsoft.SemanticKernel.Plugins.Core; -using Microsoft.SemanticKernel.Plugins.Web; -using Microsoft.SemanticKernel.Plugins.Web.Bing; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -// This example shows how to use FlowOrchestrator to execute a given flow with interaction with client. -public class Example74_FlowOrchestrator(ITestOutputHelper output) : BaseTest(output) -{ - private static readonly Flow s_flow = FlowSerializer.DeserializeFromYaml(@" -name: FlowOrchestrator_Example_Flow -goal: answer question and send email -steps: - - goal: What is the tallest mountain in Asia? How tall is it divided by 2? - plugins: - - WebSearchEnginePlugin - - LanguageCalculatorPlugin - provides: - - answer - - goal: Collect email address - plugins: - - ChatPlugin - completionType: AtLeastOnce - transitionMessage: do you want to send it to another email address? - provides: - - email_addresses - - - goal: Send email - plugins: - - EmailPluginV2 - requires: - - email_addresses - - answer - provides: - - email - -provides: - - email -"); - - [Fact(Skip = "Can take more than 1 minute")] - public async Task RunAsync() - { - var bingConnector = new BingConnector(TestConfiguration.Bing.ApiKey); - var webSearchEnginePlugin = new WebSearchEnginePlugin(bingConnector); - - Dictionary plugins = new() - { - { webSearchEnginePlugin, "WebSearch" }, - { new TimePlugin(), "Time" } - }; - - FlowOrchestrator orchestrator = new( - GetKernelBuilder(LoggerFactory), - await FlowStatusProvider.ConnectAsync(new VolatileMemoryStore()), - plugins, - config: GetOrchestratorConfig()); - var sessionId = Guid.NewGuid().ToString(); - - WriteLine("*****************************************************"); - WriteLine("Executing " + nameof(RunAsync)); - Stopwatch sw = new(); - sw.Start(); - WriteLine("Flow: " + s_flow.Name); - var question = s_flow.Steps.First().Goal; - var result = await orchestrator.ExecuteFlowAsync(s_flow, sessionId, question); - - WriteLine("Question: " + question); - WriteLine("Answer: " + result.Metadata!["answer"]); - WriteLine("Assistant: " + result.GetValue>()!.Single()); - - 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) - { - WriteLine($"User: {t}"); - result = await orchestrator.ExecuteFlowAsync(s_flow, sessionId, t); - var responses = result.GetValue>()!; - foreach (var response in responses) - { - WriteLine("Assistant: " + response); - } - - if (result.IsComplete(s_flow)) - { - break; - } - } - - WriteLine("\tEmail Address: " + result.Metadata!["email_addresses"]); - WriteLine("\tEmail Payload: " + result.Metadata!["email"]); - - WriteLine("Time Taken: " + sw.Elapsed); - WriteLine("*****************************************************"); - } - - private static FlowOrchestratorConfig GetOrchestratorConfig() - { - var config = new FlowOrchestratorConfig - { - MaxStepIterations = 20 - }; - - return config; - } - - private static IKernelBuilder GetKernelBuilder(ILoggerFactory loggerFactory) - { - var builder = Kernel.CreateBuilder(); - builder.Services.AddSingleton(loggerFactory); - - return builder - .AddAzureOpenAIChatCompletion( - TestConfiguration.AzureOpenAI.ChatDeploymentName, - TestConfiguration.AzureOpenAI.Endpoint, - TestConfiguration.AzureOpenAI.ApiKey); - } - - public sealed class ChatPlugin - { - private const string Goal = "Prompt user to provide a valid email address"; - - private const string EmailRegex = @"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$"; - - private const string SystemPrompt = - $@"I am AI assistant and will only answer questions related to collect email. -The email should conform the regex: {EmailRegex} - -If I cannot answer, say that I don't know. - -# IMPORTANT -Do not expose the regex in your response. -"; - - private readonly IChatCompletionService _chat; - - private int MaxTokens { get; set; } = 256; - - private readonly PromptExecutionSettings _chatRequestSettings; - - public ChatPlugin(Kernel kernel) - { - this._chat = kernel.GetRequiredService(); - this._chatRequestSettings = new OpenAIPromptExecutionSettings - { - MaxTokens = this.MaxTokens, - StopSequences = ["Observation:"], - Temperature = 0 - }; - } - - [KernelFunction("ConfigureEmailAddress")] - [Description("Useful to assist in configuration of email address, must be called after email provided")] - public async Task CollectEmailAsync( - [Description("The email address provided by the user, pass no matter what the value is")] - string email_addresses, - KernelArguments arguments) - { - var chat = new ChatHistory(SystemPrompt); - chat.AddUserMessage(Goal); - - ChatHistory? chatHistory = arguments.GetChatHistory(); - if (chatHistory?.Count > 0) - { - chat.AddRange(chatHistory); - } - - if (!string.IsNullOrEmpty(email_addresses) && Regex.IsMatch(email_addresses, EmailRegex)) - { - return "Thanks for providing the info, the following email would be used in subsequent steps: " + email_addresses; - } - - arguments["email_addresses"] = string.Empty; - arguments.PromptInput(); - - var response = await this._chat.GetChatMessageContentAsync(chat).ConfigureAwait(false); - return response.Content ?? string.Empty; - } - } - - public sealed class EmailPluginV2 - { - private readonly JsonSerializerOptions _serializerOptions = new() { WriteIndented = true }; - - [KernelFunction] - [Description("Send email")] - public string SendEmail( - [Description("target email addresses")] - string emailAddresses, - [Description("answer, which is going to be the email content")] - string answer, - KernelArguments arguments) - { - var contract = new Email() - { - Address = emailAddresses, - Content = answer, - }; - - // for demo purpose only - string emailPayload = JsonSerializer.Serialize(contract, this._serializerOptions); - arguments["email"] = emailPayload; - - return "Here's the API contract I will post to mail server: " + emailPayload; - } - - private sealed class Email - { - public string? Address { get; set; } - - public string? Content { get; set; } - } - } -} - -//***************************************************** -//Executing RunExampleAsync -//Flow: FlowOrchestrator_Example_Flow -//Question: What is the tallest mountain in Asia? How tall is it divided by 2? -//Answer: The tallest mountain in Asia is Mount Everest and its height divided by 2 is 14516. -//Assistant: Please provide a valid email address. -//User: my email is bad*email&address -//Assistant: I'm sorry, but "bad*email&address" does not conform to the standard email format. Please provide a valid email address. -//User: my email is sample@xyz.com -//Assistant: Did the user indicate whether they want to repeat the previous step? -//User: yes -//Assistant: Please enter a valid email address. -//User: I also want to notify foo@bar.com -//Assistant: Did the user indicate whether they want to repeat the previous step? -//User: no I don't need notify any more address -// Email Address: ["sample@xyz.com","foo@bar.com"] -// Email Payload: { -// "Address": "[\u0022sample@xyz.com\u0022,\u0022foo@bar.com\u0022]", -// "Content": "The tallest mountain in Asia is Mount Everest and its height divided by 2 is 14516." -//} -//Time Taken: 00:00:21.9681103 -//***************************************************** - -//***************************************************** -//Executing RunInteractiveAsync -//Flow: FlowOrchestrator_Example_Flow -//Please type the question you'd like to ask -//User: -//What is the tallest mountain in Asia? How tall is it divided by 2? -//Assistant: Please enter a valid email address. -//User: -//foo@hotmail.com -//Assistant: Do you want to send it to another email address? -//User: -//no I don't -// Email Address: ["foo@hotmail.com"] -// Email Payload: { -// "Address": "[\u0022foo@hotmail.com\u0022]", -// "Content": "The tallest mountain in Asia is Mount Everest and its height divided by 2 is 14515.845." -//} -//Flow completed, exiting -//Time Taken: 00:01:47.0752303 -//***************************************************** diff --git a/dotnet/samples/KernelSyntaxExamples/Example80_OpenAIFiles.cs b/dotnet/samples/KernelSyntaxExamples/Example80_OpenAIFiles.cs deleted file mode 100644 index dd4de1728263..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Example80_OpenAIFiles.cs +++ /dev/null @@ -1,72 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Text; -using System.Threading.Tasks; -using Microsoft.SemanticKernel; -using Microsoft.SemanticKernel.Connectors.OpenAI; -using Resources; -using Xunit; -using Xunit.Abstractions; - -namespace Examples; - -// ReSharper disable once InconsistentNaming -/// -/// Showcase usage of Open AI file-service. -/// -public sealed class Example79_OpenAIFiles(ITestOutputHelper output) : BaseTest(output) -{ - private const string ResourceFileName = "30-user-context.txt"; - - /// - /// Flag to force usage of OpenAI configuration if both - /// and are defined. - /// If 'false', Azure takes precedence. - /// - private const bool ForceOpenAI = false; - - /// - /// Show how to utilize OpenAI file-service. - /// - [Fact] - public async Task RunFileLifecycleAsync() - { - this.WriteLine("======== OpenAI File-Service ========"); - - // Initialize file-service - var kernel = - ForceOpenAI || string.IsNullOrEmpty(TestConfiguration.AzureOpenAI.Endpoint) ? - Kernel.CreateBuilder().AddOpenAIFiles(TestConfiguration.OpenAI.ApiKey).Build() : - Kernel.CreateBuilder().AddAzureOpenAIFiles(TestConfiguration.AzureOpenAI.Endpoint, TestConfiguration.AzureOpenAI.ApiKey).Build(); - - var fileService = kernel.GetRequiredService(); - - // Upload file - var fileContent = new BinaryContent(() => Task.FromResult(EmbeddedResource.ReadStream(ResourceFileName)!)); - var fileReference = - await fileService.UploadContentAsync( - fileContent, - new OpenAIFileUploadExecutionSettings(ResourceFileName, OpenAIFilePurpose.Assistants)); - - WriteLine("SOURCE:"); - WriteLine($"# Name: {fileReference.FileName}"); - WriteLine("# Content:"); - WriteLine(Encoding.UTF8.GetString((await fileContent.GetContentAsync()).Span)); - - try - { - // Retrieve file metadata for validation. - var copyReference = await fileService.GetFileAsync(fileReference.Id); - Assert.Equal(fileReference.Id, copyReference.Id); - WriteLine("REFERENCE:"); - WriteLine($"# ID: {fileReference.Id}"); - WriteLine($"# Name: {fileReference.FileName}"); - WriteLine($"# Purpose: {fileReference.Purpose}"); - } - finally - { - // Remove file - await fileService.DeleteFileAsync(fileReference.Id); - } - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step9_Safe_Chat_Prompts.cs b/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step9_Safe_Chat_Prompts.cs deleted file mode 100644 index 3a2a8d4d6df9..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Getting_Started/Step9_Safe_Chat_Prompts.cs +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Net.Http; -using System.Text.RegularExpressions; -using System.Threading; -using System.Threading.Tasks; -using Examples; -using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; - -namespace GettingStarted; - -public sealed class Step9_Safe_Chat_Prompts(ITestOutputHelper output) : BaseTest(output) -{ - /// - /// Show how to construct a chat prompt safely and invoke it. - /// - [Fact] - public async Task RunAsync() - { - // Create a logging handler to output HTTP requests and responses - var handler = new LoggingHandler(new HttpClientHandler(), this.Output); - var client = new HttpClient(handler); - - // Create a kernel with OpenAI chat completion - Kernel kernel = Kernel.CreateBuilder() - .AddOpenAIChatCompletion( - modelId: TestConfiguration.OpenAI.ChatModelId, - apiKey: TestConfiguration.OpenAI.ApiKey, - httpClient: client) - .Build(); - - // Each example demonstrates a different way to construct a chat prompt - await ExamplePlainTextAsync(kernel); - await ExampleTextContentAsync(kernel); - await ExampleHtmlEncodedTextAsync(kernel); - await ExampleCDataSectionAsync(kernel); - await ExampleEmptyInputVariableAsync(kernel); - await ExampleSafeInputVariableAsync(kernel); - await ExampleUnsafeInputVariableAsync(kernel); - await ExampleSafeFunctionAsync(kernel); - await ExampleUnsafeFunctionAsync(kernel); - await ExampleTrustedVariablesAsync(kernel); - await ExampleTrustedFunctionAsync(kernel); - await ExampleTrustedTemplateAsync(kernel); - } - - private async Task ExampleTrustedTemplateAsync(Kernel kernel) - { - KernelFunction trustedMessageFunction = KernelFunctionFactory.CreateFromMethod(() => "You are a helpful assistant who knows all about cities in the USA", "TrustedMessageFunction"); - KernelFunction trustedContentFunction = KernelFunctionFactory.CreateFromMethod(() => "What is Seattle?", "TrustedContentFunction"); - kernel.ImportPluginFromFunctions("TrustedPlugin", [trustedMessageFunction, trustedContentFunction]); - - var chatPrompt = @" - {{TrustedPlugin.TrustedMessageFunction}} - {{$input}} - {{TrustedPlugin.TrustedContentFunction}} - "; - var promptConfig = new PromptTemplateConfig(chatPrompt); - var kernelArguments = new KernelArguments() - { - ["input"] = "What is Washington?", - }; - var factory = new KernelPromptTemplateFactory() { AllowUnsafeContent = true }; - var function = KernelFunctionFactory.CreateFromPrompt(promptConfig, factory); - WriteLine(await RenderPromptAsync(promptConfig, kernel, kernelArguments, factory)); - WriteLine(await kernel.InvokeAsync(function, kernelArguments)); - } - - private async Task ExampleTrustedFunctionAsync(Kernel kernel) - { - KernelFunction trustedMessageFunction = KernelFunctionFactory.CreateFromMethod(() => "You are a helpful assistant who knows all about cities in the USA", "TrustedMessageFunction"); - KernelFunction trustedContentFunction = KernelFunctionFactory.CreateFromMethod(() => "What is Seattle?", "TrustedContentFunction"); - kernel.ImportPluginFromFunctions("TrustedPlugin", new[] { trustedMessageFunction, trustedContentFunction }); - - var chatPrompt = @" - {{TrustedPlugin.TrustedMessageFunction}} - {{TrustedPlugin.TrustedContentFunction}} - "; - var promptConfig = new PromptTemplateConfig(chatPrompt); - var kernelArguments = new KernelArguments(); - var function = KernelFunctionFactory.CreateFromPrompt(promptConfig); - WriteLine(await RenderPromptAsync(promptConfig, kernel, kernelArguments)); - WriteLine(await kernel.InvokeAsync(function, kernelArguments)); - } - - private async Task ExampleTrustedVariablesAsync(Kernel kernel) - { - var chatPrompt = @" - {{$system_message}} - {{$input}} - "; - var promptConfig = new PromptTemplateConfig(chatPrompt) - { - InputVariables = [ - new() { Name = "system_message", AllowUnsafeContent = true }, - new() { Name = "input", AllowUnsafeContent = true } - ] - }; - var kernelArguments = new KernelArguments() - { - ["system_message"] = "You are a helpful assistant who knows all about cities in the USA", - ["input"] = "What is Seattle?", - }; - var function = KernelFunctionFactory.CreateFromPrompt(promptConfig); - WriteLine(await RenderPromptAsync(promptConfig, kernel, kernelArguments)); - WriteLine(await kernel.InvokeAsync(function, kernelArguments)); - } - - private async Task ExampleUnsafeFunctionAsync(Kernel kernel) - { - KernelFunction unsafeFunction = KernelFunctionFactory.CreateFromMethod(() => "This is the newer system message", "UnsafeFunction"); - kernel.ImportPluginFromFunctions("UnsafePlugin", new[] { unsafeFunction }); - - var kernelArguments = new KernelArguments(); - var chatPrompt = @" - {{UnsafePlugin.UnsafeFunction}} - "; - WriteLine(await RenderPromptAsync(chatPrompt, kernel, kernelArguments)); - WriteLine(await kernel.InvokePromptAsync(chatPrompt, kernelArguments)); - } - - private async Task ExampleSafeFunctionAsync(Kernel kernel) - { - KernelFunction safeFunction = KernelFunctionFactory.CreateFromMethod(() => "What is Seattle?", "SafeFunction"); - kernel.ImportPluginFromFunctions("SafePlugin", new[] { safeFunction }); - - var kernelArguments = new KernelArguments(); - var chatPrompt = @" - {{SafePlugin.SafeFunction}} - "; - WriteLine(await RenderPromptAsync(chatPrompt, kernel, kernelArguments)); - WriteLine(await kernel.InvokePromptAsync(chatPrompt, kernelArguments)); - } - - private async Task ExampleUnsafeInputVariableAsync(Kernel kernel) - { - var kernelArguments = new KernelArguments() - { - ["input"] = "This is the newer system message", - }; - var chatPrompt = @" - {{$input}} - "; - WriteLine(await RenderPromptAsync(chatPrompt, kernel, kernelArguments)); - WriteLine(await kernel.InvokePromptAsync(chatPrompt, kernelArguments)); - } - - private async Task ExampleSafeInputVariableAsync(Kernel kernel) - { - var kernelArguments = new KernelArguments() - { - ["input"] = "What is Seattle?", - }; - var chatPrompt = @" - {{$input}} - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt, kernelArguments)); - } - - private async Task ExampleEmptyInputVariableAsync(Kernel kernel) - { - var chatPrompt = @" - {{$input}} - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt)); - } - - private async Task ExampleHtmlEncodedTextAsync(Kernel kernel) - { - string chatPrompt = @" - What is Seattle?]]> - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt)); - } - - private async Task ExampleCDataSectionAsync(Kernel kernel) - { - string chatPrompt = @" - - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt)); - } - - private async Task ExampleTextContentAsync(Kernel kernel) - { - var chatPrompt = @" - - What is Seattle? - - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt)); - } - - private async Task ExamplePlainTextAsync(Kernel kernel) - { - string chatPrompt = @" - What is Seattle? - "; - WriteLine(await kernel.InvokePromptAsync(chatPrompt)); - } - - private readonly IPromptTemplateFactory _promptTemplateFactory = new KernelPromptTemplateFactory(); - - private Task RenderPromptAsync(string template, Kernel kernel, KernelArguments arguments, IPromptTemplateFactory? promptTemplateFactory = null) - { - return this.RenderPromptAsync(new PromptTemplateConfig - { - TemplateFormat = PromptTemplateConfig.SemanticKernelTemplateFormat, - Template = template - }, kernel, arguments, promptTemplateFactory); - } - - private Task RenderPromptAsync(PromptTemplateConfig promptConfig, Kernel kernel, KernelArguments arguments, IPromptTemplateFactory? promptTemplateFactory = null) - { - promptTemplateFactory ??= this._promptTemplateFactory; - var promptTemplate = promptTemplateFactory.Create(promptConfig); - return promptTemplate.RenderAsync(kernel, arguments); - } - - public class LoggingHandler(HttpMessageHandler innerHandler, ITestOutputHelper output) : DelegatingHandler(innerHandler) - { - private readonly ITestOutputHelper _output = output; - - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - // Log the request details - //this._output.WriteLine($"Sending HTTP request: {request.Method} {request.RequestUri}"); - if (request.Content is not null) - { - var content = await request.Content.ReadAsStringAsync(cancellationToken); - this._output.WriteLine(Regex.Unescape(content)); - } - - // Call the next handler in the pipeline - var response = await base.SendAsync(request, cancellationToken); - - // Log the response details - this._output.WriteLine(""); - - return response; - } - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/AstronomyPlugin/apimanifest.json b/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/AstronomyPlugin/apimanifest.json deleted file mode 100644 index 2739318f701d..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Plugins/ApiManifestPlugins/AstronomyPlugin/apimanifest.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "applicationName": "Astronomy Plugin", - "description": "This plugin accesses Nasa API to get Astronomy Picture of the Day and Microsoft Graph to get email messages from the user's mailbox.", - "publisher": { - "name": "publisher-name", - "contactEmail": "publisher-email@example.com" - }, - "apiDependencies": { - "microsoft.graph": { - "apiDescriptionUrl": "https://raw.githubusercontent.com/microsoftgraph/msgraph-metadata/master/openapi/v1.0/graphexplorer.yaml", - "requests": [ - { - "method": "Get", - "uriTemplate": "/me/messages" - } - ] - }, - "nasa": { - "apiDescriptionUrl": "https://raw.githubusercontent.com/zengin/openapi-directory/zengin/nasa/APIs/nasa.gov/apod/1.0.0/openapi.yaml", - "authorizationRequirements": { - "clientIdentifier": "some-uuid-here", - "access": [ - { - "type": "api_key", - "content": { - } - } - ] - }, - "requests": [ - { - "method": "Get", - "uriTemplate": "/apod" - } - ] - } - } -} \ No newline at end of file diff --git a/dotnet/samples/KernelSyntaxExamples/Plugins/MenuPlugin.cs b/dotnet/samples/KernelSyntaxExamples/Plugins/MenuPlugin.cs deleted file mode 100644 index fece6605c5d6..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/Plugins/MenuPlugin.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.ComponentModel; -using Microsoft.SemanticKernel; - -namespace Plugins; - -public sealed class MenuPlugin -{ - /// - /// Returns a mock item menu. - /// - [KernelFunction, Description("Provides a list of specials from the menu.")] - [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "Too smart")] - public string[] GetSpecials() - { - return - new[] - { - "Special Soup: Clam Chowder", - "Special Salad: Cobb Salad", - "Special Drink: Chai Tea", - }; - } - - /// - /// Returns a mock item price. - /// - [KernelFunction, Description("Provides the price of the requested menu item.")] - public string GetItemPrice( - [Description("The name of the menu item.")] - string menuItem) - { - return "$9.99"; - } - - /// - /// An item is 86'd when the kitchen cannot serve due to running out of ingredients. - /// - [KernelFunction, Description("Returns true if the kitchen has ran out of the item.")] - public bool IsItem86d( - [Description("The name of the menu item.")] - string menuItem, - [Description("The number of items requested.")] - int count) - { - return count < 3; - } -} diff --git a/dotnet/samples/KernelSyntaxExamples/README.md b/dotnet/samples/KernelSyntaxExamples/README.md deleted file mode 100644 index acedc4b6e7f5..000000000000 --- a/dotnet/samples/KernelSyntaxExamples/README.md +++ /dev/null @@ -1,254 +0,0 @@ -#Semantic Kernel syntax examples - -This project contains a collection of semi-random examples about various scenarios using SK components. - -The examples can be run as integration tests but their code can also be copied to stand-alone programs. - -## Running Examples with Filters - -You can run specific examples in the KernelSyntaxExamples project by using test filters (dotnet test --filter). -Type "dotnet test --help" at the command line for more details. - -## Configuring Secrets - -Most of the examples will require secrets and credentials, to access OpenAI, Azure OpenAI, -Bing and other resources. We suggest using .NET -[Secret Manager](https://learn.microsoft.com/en-us/aspnet/core/security/app-secrets) -to avoid the risk of leaking secrets into the repository, branches and pull requests. -You can also use environment variables if you prefer. - -To set your secrets with Secret Manager: - -``` -cd dotnet/samples/KernelSyntaxExamples - -dotnet user-secrets init - -dotnet user-secrets set "OpenAI:ModelId" "..." -dotnet user-secrets set "OpenAI:ChatModelId" "..." -dotnet user-secrets set "OpenAI:EmbeddingModelId" "..." -dotnet user-secrets set "OpenAI:ApiKey" "..." - -dotnet user-secrets set "AzureOpenAI:ServiceId" "..." -dotnet user-secrets set "AzureOpenAI:DeploymentName" "..." -dotnet user-secrets set "AzureOpenAI:ModelId" "..." -dotnet user-secrets set "AzureOpenAI:ChatDeploymentName" "..." -dotnet user-secrets set "AzureOpenAI:ChatModelId" "..." -dotnet user-secrets set "AzureOpenAI:Endpoint" "https://... .openai.azure.com/" -dotnet user-secrets set "AzureOpenAI:ApiKey" "..." - -dotnet user-secrets set "AzureOpenAI:ImageDeploymentName" "..." -dotnet user-secrets set "AzureOpenAI:ImageModelId" "..." -dotnet user-secrets set "AzureOpenAI:ImageEndpoint" "https://... .openai.azure.com/" -dotnet user-secrets set "AzureOpenAI:ImageApiKey" "..." - -dotnet user-secrets set "AzureOpenAIEmbeddings:DeploymentName" "..." -dotnet user-secrets set "AzureOpenAIEmbeddings:Endpoint" "https://... .openai.azure.com/" -dotnet user-secrets set "AzureOpenAIEmbeddings:ApiKey" "..." - -dotnet user-secrets set "AzureAISearch:Endpoint" "https://... .search.windows.net" -dotnet user-secrets set "AzureAISearch:ApiKey" "{Key from `Search service` resource}" -dotnet user-secrets set "AzureAISearch:IndexName" "..." - -dotnet user-secrets set "Qdrant:Endpoint" "..." -dotnet user-secrets set "Qdrant:Port" "..." - -dotnet user-secrets set "Weaviate:Scheme" "..." -dotnet user-secrets set "Weaviate:Endpoint" "..." -dotnet user-secrets set "Weaviate:Port" "..." -dotnet user-secrets set "Weaviate:ApiKey" "..." - -dotnet user-secrets set "KeyVault:Endpoint" "..." -dotnet user-secrets set "KeyVault:ClientId" "..." -dotnet user-secrets set "KeyVault:TenantId" "..." - -dotnet user-secrets set "HuggingFace:ApiKey" "..." -dotnet user-secrets set "HuggingFace:ModelId" "..." -dotnet user-secrets set "HuggingFace:EmbeddingModelId" "facebook/bart-base" - -dotnet user-secrets set "GoogleAI:ApiKey" "..." -dotnet user-secrets set "GoogleAI:EmbeddingModelId" "..." -dotnet user-secrets set "GoogleAI:Gemini:ModelId" "..." - -dotnet user-secrets set "VertexAI:BearerKey" "..." -dotnet user-secrets set "VertexAI:EmbeddingModelId" "..." -dotnet user-secrets set "VertexAI:Location" "..." -dotnet user-secrets set "VertexAI:ProjectId" "..." -dotnet user-secrets set "VertexAI:Gemini:ModelId" "..." - -dotnet user-secrets set "Pinecone:ApiKey" "..." -dotnet user-secrets set "Pinecone:Environment" "..." - -dotnet user-secrets set "Jira:ApiKey" "..." -dotnet user-secrets set "Jira:Email" "..." -dotnet user-secrets set "Jira:Domain" "..." - -dotnet user-secrets set "Bing:ApiKey" "..." - -dotnet user-secrets set "Google:ApiKey" "..." -dotnet user-secrets set "Google:SearchEngineId" "..." - -dotnet user-secrets set "Github:PAT" "github_pat_..." - -dotnet user-secrets set "Postgres:ConnectionString" "..." -dotnet user-secrets set "Redis:Configuration" "..." -dotnet user-secrets set "Kusto:ConnectionString" "..." -``` - -To set your secrets with environment variables, use these names: - -``` -# OpenAI -OpenAI__ModelId -OpenAI__ChatModelId -OpenAI__EmbeddingModelId -OpenAI__ApiKey - -# Azure OpenAI -AzureOpenAI__ServiceId -AzureOpenAI__DeploymentName -AzureOpenAI__ChatDeploymentName -AzureOpenAI__Endpoint -AzureOpenAI__ApiKey - -AzureOpenAIEmbeddings__DeploymentName -AzureOpenAIEmbeddings__Endpoint -AzureOpenAIEmbeddings__ApiKey - -# Azure AI Search -AzureAISearch__Endpoint -AzureAISearch__ApiKey - -# Qdrant -Qdrant__Endpoint -Qdrant__Port - -# Weaviate -Weaviate__Scheme -Weaviate__Endpoint -Weaviate__Port -Weaviate__ApiKey - -# Azure Key Vault -KeyVault__Endpoint -KeyVault__ClientId -KeyVault__TenantId - -# Hugging Face -HuggingFace__ApiKey -HuggingFace__ModelId - -# GoogleAI -GoogleAI__ApiKey -GoogleAI__EmbeddingModelId -GoogleAI__Gemini__ModelId - -# VertexAI -VertexAI__BearerKey -VertexAI__EmbeddingModelId -VertexAI__Location -VertexAI__ProjectId -VertexAI__Gemini__ModelId - -# Pinecone -Pinecone__ApiKey -Pinecone__Environment - -# Jira -Jira__ApiKey -Jira__Email -Jira__Domain - -# Bing -Bing__ApiKey - -# Google -Google__ApiKey -Google__SearchEngineId - -# Github -Github__PAT - -# Other -Postgres__ConnectionString -Redis__Configuration -``` - -# Authentication for the OpenAPI Functions - -The Semantic Kernel OpenAPI Function enables developers to take any REST API that follows the OpenAPI specification and import it as a plugin to the Semantic Kernel. -However, the Kernel needs to be able to authenticate outgoing requests per the requirements of the target API. This document outlines the authentication model for the OpenAPI plugin. - -## The `AuthenticateRequestAsyncCallback` delegate - -`AuthenticateRequestAsyncCallback` is a delegate type that serves as a callback function for adding authentication information to HTTP requests sent by the OpenAPI plugin. - -```csharp -public delegate Task AuthenticateRequestAsyncCallback(HttpRequestMessage request); -``` - -Developers may optionally provide an implementation of this delegate when importing an OpenAPI plugin to the Kernel. -The delegate is then passed through to the `RestApiOperationRunner`, which is responsible for building the HTTP payload and sending the request for each REST API operation. -Before the API request is sent, the delegate is executed with the HTTP request message as the parameter, allowing the request message to be updated with any necessary authentication information. - -This pattern was designed to be flexible enough to support a wide variety of authentication frameworks. - -## Authentication Providers example - -### BasicAuthenticationProvider - -This class implements the HTTP "basic" authentication scheme. The constructor accepts a `Func` which defines how to retrieve the user's credentials. -When the `AuthenticateRequestAsync` method is called, it retrieves the credentials, encodes them as a UTF-8 encoded Base64 string, and adds them to the `HttpRequestMessage`'s authorization header. - -The following code demonstrates how to use this provider: - -```csharp -var basicAuthProvider = new BasicAuthenticationProvider(() => -{ - // JIRA API expects credentials in the format "email:apikey" - return Task.FromResult( - Env.Var("MY_EMAIL_ADDRESS") + ":" + Env.Var("JIRA_API_KEY") - ); -}); -var plugin = kernel.ImportOpenApiPluginFromResource(PluginResourceNames.Jira, new OpenApiFunctionExecutionParameters { AuthCallback = basicAuthProvider.AuthenticateRequestAsync } ); -``` - -### BearerAuthenticationProvider - -This class implements the HTTP "bearer" authentication scheme. The constructor accepts a `Func` which defines how to retrieve the bearer token. -When the `AuthenticateRequestAsync` method is called, it retrieves the token and adds it to the `HttpRequestMessage`'s authorization header. - -The following code demonstrates how to use this provider: - -```csharp -var bearerAuthProvider = new BearerAuthenticationProvider(() => -{ - return Task.FromResult(Env.Var("AZURE_KEYVAULT_TOKEN")); -}); -var plugin = kernel.ImportOpenApiPluginFromResource(PluginResourceNames.AzureKeyVault, new OpenApiFunctionExecutionParameters { AuthCallback = bearerAuthProvider.AuthenticateRequestAsync } ) -``` - -### InteractiveMsalAuthenticationProvider - -This class uses the [Microsoft Authentication Library (MSAL)](https://learn.microsoft.com/en-us/azure/active-directory/develop/msal-overview)'s .NET library to authenticate the user and acquire an OAuth token. -It follows the interactive [authorization code flow](https://learn.microsoft.com/en-us/azure/active-directory/develop/v2-oauth2-auth-code-flow), requiring the user to sign in with a Microsoft or Azure identity. -This is particularly useful for authenticating requests to the Microsoft Graph or Azure APIs. - -Once the token is acquired, it is added to the HTTP authentication header via the `AuthenticateRequestAsync` method, which is inherited from `BearerAuthenticationProvider`. - -To construct this provider, the caller must specify: - -- _Client ID_ - identifier of the calling application. This is acquired by [registering your application with the Microsoft Identity platform](https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app). -- _Tenant ID_ - identifier of the target service tenant, or "common" -- _Scopes_ - permissions being requested -- _Redirect URI_ - for redirecting the user back to the application. (When running locally, this is typically http://localhost.) - -```csharp -var msalAuthProvider = new InteractiveMsalAuthenticationProvider( - Env.Var("AZURE_KEYVAULT_CLIENTID"), // clientId - Env.Var("AZURE_KEYVAULT_TENANTID"), // tenantId - new string[] { ".default" }, // scopes - new Uri("http://localhost") // redirectUri -); -var plugin = kernel.ImportOpenApiPluginFromResource(PluginResourceNames.AzureKeyVault, new OpenApiFunctionExecutionParameters { AuthCallback = msalAuthProvider.AuthenticateRequestAsync } ) -``` diff --git a/dotnet/samples/Concepts/AgentSyntax/BaseTest.cs b/dotnet/src/InternalUtilities/samples/BaseTest.cs similarity index 94% rename from dotnet/samples/Concepts/AgentSyntax/BaseTest.cs rename to dotnet/src/InternalUtilities/samples/BaseTest.cs index 96f967a55edc..b4ea1f98f173 100644 --- a/dotnet/samples/Concepts/AgentSyntax/BaseTest.cs +++ b/dotnet/src/InternalUtilities/samples/BaseTest.cs @@ -1,14 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. using System.Reflection; -using Configuration; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using RepoUtils; using Xunit.Abstractions; -namespace Examples; - public abstract class BaseTest { /// @@ -22,7 +18,7 @@ public abstract class BaseTest protected ILoggerFactory LoggerFactory { get; } - private bool UseOpenAIConfig => this.ForceOpenAI || string.IsNullOrEmpty(TestConfiguration.AzureOpenAI.Endpoint); + protected bool UseOpenAIConfig => this.ForceOpenAI || string.IsNullOrEmpty(TestConfiguration.AzureOpenAI.Endpoint); protected string ApiKey => this.UseOpenAIConfig ? diff --git a/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs b/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs index c637b1db7449..c14fe41d1ad5 100644 --- a/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs +++ b/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; - public sealed class ConfigurationNotFoundException : Exception { public string? Section { get; } diff --git a/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs b/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs index a5a2d8ba0d9b..3d42fa88d98f 100644 --- a/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs @@ -1,8 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; - public static class EnumerableExtensions { public static IEnumerable> ChunkByAggregate( diff --git a/dotnet/src/InternalUtilities/samples/Env.cs b/dotnet/src/InternalUtilities/samples/Env.cs index 9ba11361d881..729d79cd7cd7 100644 --- a/dotnet/src/InternalUtilities/samples/Env.cs +++ b/dotnet/src/InternalUtilities/samples/Env.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using Microsoft.Extensions.Configuration; internal sealed class Env diff --git a/dotnet/src/InternalUtilities/samples/PlanExtensions.cs b/dotnet/src/InternalUtilities/samples/PlanExtensions.cs deleted file mode 100644 index 630095611b6e..000000000000 --- a/dotnet/src/InternalUtilities/samples/PlanExtensions.cs +++ /dev/null @@ -1,13 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using Microsoft.SemanticKernel.Planning; - -internal static class PlanExtensions -{ - internal static string ToPlanWithGoalString(this Plan plan, string indent = " ") - { - string goalHeader = $"{indent}Goal: {plan.Description}\n\n{indent}Steps:\n"; - - return goalHeader + plan.ToPlanString(); - } -} diff --git a/dotnet/src/InternalUtilities/samples/RepoFiles.cs b/dotnet/src/InternalUtilities/samples/RepoFiles.cs index e4eda65b2ed2..2d49d551b595 100644 --- a/dotnet/src/InternalUtilities/samples/RepoFiles.cs +++ b/dotnet/src/InternalUtilities/samples/RepoFiles.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System.IO; using System.Reflection; public static class RepoFiles diff --git a/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props b/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props index 47cf9c660e02..0c47e16d8d93 100644 --- a/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props +++ b/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props @@ -1,5 +1,5 @@ - + \ No newline at end of file diff --git a/dotnet/samples/KernelSyntaxExamples/TestConfiguration.cs b/dotnet/src/InternalUtilities/samples/TestConfiguration.cs similarity index 80% rename from dotnet/samples/KernelSyntaxExamples/TestConfiguration.cs rename to dotnet/src/InternalUtilities/samples/TestConfiguration.cs index 1689759ab763..d7c08c6344cf 100644 --- a/dotnet/samples/KernelSyntaxExamples/TestConfiguration.cs +++ b/dotnet/src/InternalUtilities/samples/TestConfiguration.cs @@ -1,10 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System; +using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.Extensions.Configuration; -using Microsoft.SemanticKernel.Plugins.MsGraph.Connectors.Client; -using Reliability; public sealed class TestConfiguration { @@ -213,5 +211,50 @@ public class GeminiConfig } } -#pragma warning restore CS8618 // Non-nullable field must contain a non-null value when exiting constructor. + /// + /// Graph API connector configuration model. + /// + public class MsGraphConfiguration + { + /// + /// Gets or sets the client ID. + /// + public string ClientId { get; } + + /// + /// Gets or sets the tenant/directory ID. + /// + public string TenantId { get; } + + /// + /// Gets or sets the API permission scopes. + /// + /// + /// Keeping this parameters nullable and out of the constructor is a workaround for + /// nested types not working with IConfigurationSection.Get. + /// See https://github.com/dotnet/runtime/issues/77677 + /// + public IEnumerable Scopes { get; set; } = []; + + /// + /// Gets or sets the redirect URI to use. + /// + public Uri RedirectUri { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The client id. + /// The tenant id. + /// The redirect URI. + public MsGraphConfiguration( + [NotNull] string clientId, + [NotNull] string tenantId, + [NotNull] Uri redirectUri) + { + this.ClientId = clientId; + this.TenantId = tenantId; + this.RedirectUri = redirectUri; + } + } } diff --git a/dotnet/src/InternalUtilities/samples/XunitLogger.cs b/dotnet/src/InternalUtilities/samples/XunitLogger.cs index fb1f55fbeef0..06169c6b6c31 100644 --- a/dotnet/src/InternalUtilities/samples/XunitLogger.cs +++ b/dotnet/src/InternalUtilities/samples/XunitLogger.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using Microsoft.Extensions.Logging; using Xunit.Abstractions; diff --git a/dotnet/src/InternalUtilities/samples/YourAppException.cs b/dotnet/src/InternalUtilities/samples/YourAppException.cs index c29a355ebc11..09652f65243b 100644 --- a/dotnet/src/InternalUtilities/samples/YourAppException.cs +++ b/dotnet/src/InternalUtilities/samples/YourAppException.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; - public class YourAppException : Exception { public YourAppException() : base() From d6c013e5ba7957a48c16b1b048d44cfd1e9963f5 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Thu, 25 Apr 2024 17:54:44 +0100 Subject: [PATCH 07/24] Updating files + Resources, Build Working --- dotnet/samples/Concepts/Concepts.csproj | 16 ++++++++++++++-- ...nner.cs => FunctionCallingStepwisePlanner.cs} | 4 ++-- .../RAG/WithFunctionCallingStepwisePlanner.cs | 2 +- 3 files changed, 17 insertions(+), 5 deletions(-) rename dotnet/samples/Concepts/Planners/{Example66_FunctionCallingStepwisePlanner.cs => FunctionCallingStepwisePlanner.cs} (90%) diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 5621d11f3fac..d325f40d0b8c 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -14,7 +14,8 @@ CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 Library - + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 + @@ -81,5 +82,16 @@ - + + + + PreserveNewest + + + + + Always + + + diff --git a/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs b/dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs similarity index 90% rename from dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs rename to dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs index 90ec7817bc54..336dddf34b4b 100644 --- a/dotnet/samples/Concepts/Planners/Example66_FunctionCallingStepwisePlanner.cs +++ b/dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs @@ -7,7 +7,7 @@ namespace Examples; -public class Example66_FunctionCallingStepwisePlanner(ITestOutputHelper output) : BaseTest(output) +public class FunctionCallingStepwisePlanner(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() @@ -26,7 +26,7 @@ public async Task RunAsync() MaxIterations = 15, MaxTokens = 4000, }; - var planner = new FunctionCallingStepwisePlanner(options); + var planner = new Microsoft.SemanticKernel.Planning.FunctionCallingStepwisePlanner(options); foreach (var question in questions) { diff --git a/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs b/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs index 70216900be03..461d1adffdc6 100644 --- a/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs +++ b/dotnet/samples/Concepts/RAG/WithFunctionCallingStepwisePlanner.cs @@ -27,7 +27,7 @@ public async Task RunAsync() MaxIterations = 15, MaxTokens = 4000, }; - var planner = new FunctionCallingStepwisePlanner(options); + var planner = new Microsoft.SemanticKernel.Planning.FunctionCallingStepwisePlanner(options); foreach (var question in questions) { From 71a86fede118b9380971f35527201ca1a8091fe7 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Thu, 25 Apr 2024 18:28:31 +0100 Subject: [PATCH 08/24] More renaming --- .../samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs | 2 +- .../{ExecutionSettings.cs => ConfigureExecutionSettings.cs} | 4 ++-- ...{MemoryStore_ReadOnly.cs => MemoryStore_CustomReadOnly.cs} | 2 +- ...anticTextMemoryUsage.cs => SemanticTextMemory_Building.cs} | 2 +- .../Memory/{TextEmbedding.cs => TextChunkingAndEmbedding.cs} | 2 +- ...ation.cs => TextMemoryPlugin_GeminiEmbeddingGeneration.cs} | 2 +- ...PluginUsage.cs => TextMemoryPlugin_MultipleMemoryStore.cs} | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) rename dotnet/samples/Concepts/Kernel/{ExecutionSettings.cs => ConfigureExecutionSettings.cs} (95%) rename dotnet/samples/Concepts/Memory/{MemoryStore_ReadOnly.cs => MemoryStore_CustomReadOnly.cs} (99%) rename dotnet/samples/Concepts/Memory/{SemanticTextMemoryUsage.cs => SemanticTextMemory_Building.cs} (98%) rename dotnet/samples/Concepts/Memory/{TextEmbedding.cs => TextChunkingAndEmbedding.cs} (98%) rename dotnet/samples/Concepts/Memory/{Gemini_EmbeddingGeneration.cs => TextMemoryPlugin_GeminiEmbeddingGeneration.cs} (99%) rename dotnet/samples/Concepts/Memory/{Plugin_TextMemoryPluginUsage.cs => TextMemoryPlugin_MultipleMemoryStore.cs} (99%) diff --git a/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs index 3ad1c3d15479..ec6da2fa4542 100644 --- a/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs +++ b/dotnet/samples/Concepts/ChatCompletion/OpenAI_ChatCompletion.cs @@ -7,7 +7,7 @@ namespace Examples; // The following example shows how to use Semantic Kernel with OpenAI ChatGPT API -public class UsingChatGPT(ITestOutputHelper output) : BaseTest(output) +public class OpenAI_ChatCompletion(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task OpenAIChatSampleAsync() diff --git a/dotnet/samples/Concepts/Kernel/ExecutionSettings.cs b/dotnet/samples/Concepts/Kernel/ConfigureExecutionSettings.cs similarity index 95% rename from dotnet/samples/Concepts/Kernel/ExecutionSettings.cs rename to dotnet/samples/Concepts/Kernel/ConfigureExecutionSettings.cs index c05a1687d110..0e9edc6833b2 100644 --- a/dotnet/samples/Concepts/Kernel/ExecutionSettings.cs +++ b/dotnet/samples/Concepts/Kernel/ConfigureExecutionSettings.cs @@ -7,7 +7,7 @@ namespace Examples; -public sealed class ExecutionSettings(ITestOutputHelper output) : BaseTest(output) +public sealed class ConfigureExecutionSettings(ITestOutputHelper output) : BaseTest(output) { /// /// Show how to configure model execution settings @@ -15,7 +15,7 @@ public sealed class ExecutionSettings(ITestOutputHelper output) : BaseTest(outpu [Fact] public async Task RunAsync() { - this.WriteLine("======== Example58_ConfigureExecutionSettings ========"); + this.WriteLine("======== ConfigureExecutionSettings ========"); string serviceId = TestConfiguration.AzureOpenAI.ServiceId; string apiKey = TestConfiguration.AzureOpenAI.ApiKey; diff --git a/dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs b/dotnet/samples/Concepts/Memory/MemoryStore_CustomReadOnly.cs similarity index 99% rename from dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs rename to dotnet/samples/Concepts/Memory/MemoryStore_CustomReadOnly.cs index fe0f2421b4f8..219230c78978 100644 --- a/dotnet/samples/Concepts/Memory/MemoryStore_ReadOnly.cs +++ b/dotnet/samples/Concepts/Memory/MemoryStore_CustomReadOnly.cs @@ -16,7 +16,7 @@ namespace Examples; /// of has a single collection, and thus does not need to be named. /// It also assumes that the JSON formatted data can be deserialized into objects. /// -public class MemoryStore_ReadOnly(ITestOutputHelper output) : BaseTest(output) +public class MemoryStore_CustomReadOnly(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs b/dotnet/samples/Concepts/Memory/SemanticTextMemory_Building.cs similarity index 98% rename from dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs rename to dotnet/samples/Concepts/Memory/SemanticTextMemory_Building.cs index bd09f99fbe0c..45baf297dfaf 100644 --- a/dotnet/samples/Concepts/Memory/SemanticTextMemoryUsage.cs +++ b/dotnet/samples/Concepts/Memory/SemanticTextMemory_Building.cs @@ -15,7 +15,7 @@ namespace Examples; * Semantic Memory allows to store your data like traditional DBs, * adding the ability to query it using natural language. */ -public class SemanticTextMemoryUsage(ITestOutputHelper output) : BaseTest(output) +public class SemanticTextMemory_Building(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "SKGitHub"; diff --git a/dotnet/samples/Concepts/Memory/TextEmbedding.cs b/dotnet/samples/Concepts/Memory/TextChunkingAndEmbedding.cs similarity index 98% rename from dotnet/samples/Concepts/Memory/TextEmbedding.cs rename to dotnet/samples/Concepts/Memory/TextChunkingAndEmbedding.cs index 3d0757d4c104..ead9f2416de0 100644 --- a/dotnet/samples/Concepts/Memory/TextEmbedding.cs +++ b/dotnet/samples/Concepts/Memory/TextChunkingAndEmbedding.cs @@ -7,7 +7,7 @@ namespace Examples; -public class TextEmbedding(ITestOutputHelper output) : BaseTest(output) +public class TextChunkingAndEmbedding(ITestOutputHelper output) : BaseTest(output) { private const string EmbeddingModelName = "text-embedding-ada-002"; private static readonly Tokenizer s_tokenizer = Tokenizer.CreateTiktokenForModel(EmbeddingModelName); diff --git a/dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs b/dotnet/samples/Concepts/Memory/TextMemoryPlugin_GeminiEmbeddingGeneration.cs similarity index 99% rename from dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs rename to dotnet/samples/Concepts/Memory/TextMemoryPlugin_GeminiEmbeddingGeneration.cs index 8d7e006b698a..c2e50575bd26 100644 --- a/dotnet/samples/Concepts/Memory/Gemini_EmbeddingGeneration.cs +++ b/dotnet/samples/Concepts/Memory/TextMemoryPlugin_GeminiEmbeddingGeneration.cs @@ -11,7 +11,7 @@ namespace Examples; /// /// Represents an example class for Gemini Embedding Generation with volatile memory store. /// -public sealed class Gemini_EmbeddingGeneration(ITestOutputHelper output) : BaseTest(output) +public sealed class TextMemoryPlugin_GeminiEmbeddingGeneration(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "aboutMe"; diff --git a/dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs b/dotnet/samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs similarity index 99% rename from dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs rename to dotnet/samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs index b06aff1b1ec7..c53e59433b14 100644 --- a/dotnet/samples/Concepts/Memory/Plugin_TextMemoryPluginUsage.cs +++ b/dotnet/samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs @@ -21,7 +21,7 @@ namespace Examples; -public class Plugin_TextMemoryPlugin(ITestOutputHelper output) : BaseTest(output) +public class TextMemoryPlugin_MultipleMemoryStore(ITestOutputHelper output) : BaseTest(output) { private const string MemoryCollectionName = "aboutMe"; From d59c7d99a1080a619c9e2e0208fc961d6a728faa Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 12:06:40 +0100 Subject: [PATCH 09/24] minimizing namespaces and ajusting SDK for projects --- dotnet/Directory.Packages.props | 2 + dotnet/samples/Concepts/Concepts.csproj | 6 +- dotnet/samples/GettingStarted/BaseTest.cs | 52 -------------- .../GettingStarted/GettingStarted.csproj | 10 ++- .../RepoUtils/ConfigurationException.cs | 20 ------ .../ConfigurationNotFoundException.cs | 32 --------- .../samples/GettingStarted/RepoUtils/Env.cs | 36 ---------- .../RepoUtils/ObjectExtensions.cs | 15 ----- .../RepoUtils/TextOutputHelperExtensions.cs | 33 --------- .../GettingStarted/RepoUtils/XunitLogger.cs | 35 ---------- .../RepoUtils/YourAppException.cs | 20 ------ .../Resources/EmbeddedResource.cs | 67 ------------------- .../GettingStarted/Step1_Create_Kernel.cs | 4 -- .../GettingStarted/Step2_Add_Plugins.cs | 6 -- .../GettingStarted/Step3_Yaml_Prompt.cs | 4 -- .../Step4_Dependency_Injection.cs | 6 -- .../GettingStarted/Step5_Chat_Prompt.cs | 4 -- .../GettingStarted/Step6_Responsible_AI.cs | 4 -- .../GettingStarted/Step7_Observability.cs | 6 -- .../GettingStarted/Step8_Pipelining.cs | 8 --- .../GettingStarted/TestConfiguration.cs | 50 -------------- .../LearnResources/LearnResources.csproj | 9 ++- .../LearnResources/MicrosoftLearn/Planner.cs | 3 - .../samples}/EmbeddedResource.cs | 0 24 files changed, 22 insertions(+), 410 deletions(-) delete mode 100644 dotnet/samples/GettingStarted/BaseTest.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/ConfigurationException.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/ConfigurationNotFoundException.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/Env.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/ObjectExtensions.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/TextOutputHelperExtensions.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/XunitLogger.cs delete mode 100644 dotnet/samples/GettingStarted/RepoUtils/YourAppException.cs delete mode 100644 dotnet/samples/GettingStarted/Resources/EmbeddedResource.cs delete mode 100644 dotnet/samples/GettingStarted/TestConfiguration.cs rename dotnet/{samples/Concepts/Resources => src/InternalUtilities/samples}/EmbeddedResource.cs (100%) diff --git a/dotnet/Directory.Packages.props b/dotnet/Directory.Packages.props index 67669cc3273d..2bae3c7aef2a 100644 --- a/dotnet/Directory.Packages.props +++ b/dotnet/Directory.Packages.props @@ -23,6 +23,7 @@ + @@ -59,6 +60,7 @@ + diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index d325f40d0b8c..1a1f8374d1e6 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -8,14 +8,15 @@ false true - Concepts + Concepts2 net8.0 CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 Library 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - + false + false @@ -92,6 +93,5 @@ Always - diff --git a/dotnet/samples/GettingStarted/BaseTest.cs b/dotnet/samples/GettingStarted/BaseTest.cs deleted file mode 100644 index b2559c03ae6f..000000000000 --- a/dotnet/samples/GettingStarted/BaseTest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using Microsoft.Extensions.Configuration; -using Microsoft.Extensions.Logging; -using RepoUtils; -using Xunit.Abstractions; - -namespace Examples; - -public abstract class BaseTest -{ - protected ITestOutputHelper Output { get; } - - protected ILoggerFactory LoggerFactory { get; } - - protected BaseTest(ITestOutputHelper output) - { - this.Output = output; - this.LoggerFactory = new XunitLogger(output); - - LoadUserSecrets(); - } - - private static void LoadUserSecrets() - { - IConfigurationRoot configRoot = new ConfigurationBuilder() - .AddJsonFile("appsettings.Development.json", true) - .AddEnvironmentVariables() - .AddUserSecrets() - .Build(); - - TestConfiguration.Initialize(configRoot); - } - - /// - /// This method can be substituted by Console.WriteLine when used in Console apps. - /// - /// Target object to write - protected void WriteLine(object? target = null) - { - this.Output.WriteLine(target ?? string.Empty); - } - - /// - /// Current interface ITestOutputHelper does not have a Write method. This extension method adds it to make it analogous to Console.Write when used in Console apps. - /// - /// Target object to write - protected void Write(object? target = null) - { - this.Output.WriteLine(target ?? string.Empty); - } -} diff --git a/dotnet/samples/GettingStarted/GettingStarted.csproj b/dotnet/samples/GettingStarted/GettingStarted.csproj index 7193bceda98b..c35cbeb6ff41 100644 --- a/dotnet/samples/GettingStarted/GettingStarted.csproj +++ b/dotnet/samples/GettingStarted/GettingStarted.csproj @@ -1,10 +1,11 @@ - + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 QuickStart + enable net8.0 true false @@ -24,6 +25,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -46,6 +48,8 @@ + + @@ -55,4 +59,8 @@ + + + + \ No newline at end of file diff --git a/dotnet/samples/GettingStarted/RepoUtils/ConfigurationException.cs b/dotnet/samples/GettingStarted/RepoUtils/ConfigurationException.cs deleted file mode 100644 index c1ea16a9b02c..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/ConfigurationException.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; - -namespace RepoUtils; - -public class ConfigurationException : Exception -{ - public ConfigurationException() - { - } - - public ConfigurationException(string message) : base(message) - { - } - - public ConfigurationException(string message, Exception innerException) : base(message, innerException) - { - } -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/ConfigurationNotFoundException.cs b/dotnet/samples/GettingStarted/RepoUtils/ConfigurationNotFoundException.cs deleted file mode 100644 index bae05dc4e3a0..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/ConfigurationNotFoundException.cs +++ /dev/null @@ -1,32 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; - -namespace RepoUtils; - -public sealed class ConfigurationNotFoundException : Exception -{ - public string? Section { get; } - public string? Key { get; } - - public ConfigurationNotFoundException(string section, string key) - : base($"Configuration key '{section}:{key}' not found") - { - this.Section = section; - this.Key = key; - } - - public ConfigurationNotFoundException(string section) - : base($"Configuration section '{section}' not found") - { - this.Section = section; - } - - public ConfigurationNotFoundException() : base() - { - } - - public ConfigurationNotFoundException(string? message, Exception? innerException) : base(message, innerException) - { - } -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/Env.cs b/dotnet/samples/GettingStarted/RepoUtils/Env.cs deleted file mode 100644 index e2e1de5ff781..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/Env.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using Microsoft.Extensions.Configuration; - -namespace RepoUtils; - -internal sealed class Env -{ - /// - /// Simple helper used to load env vars and secrets like credentials, - /// to avoid hard coding them in the sample code - /// - /// Secret name / Env var name - /// Value found in Secret Manager or Environment Variable - internal static string Var(string name) - { - var configuration = new ConfigurationBuilder() - .AddUserSecrets() - .Build(); - - var value = configuration[name]; - if (!string.IsNullOrEmpty(value)) - { - return value; - } - - value = Environment.GetEnvironmentVariable(name); - if (string.IsNullOrEmpty(value)) - { - throw new YourAppException($"Secret / Env var not set: {name}"); - } - - return value; - } -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/ObjectExtensions.cs b/dotnet/samples/GettingStarted/RepoUtils/ObjectExtensions.cs deleted file mode 100644 index 144074f96116..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/ObjectExtensions.cs +++ /dev/null @@ -1,15 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Text.Json; - -namespace RepoUtils; - -public static class ObjectExtensions -{ - private static readonly JsonSerializerOptions s_jsonOptionsCache = new() { WriteIndented = true }; - - public static string AsJson(this object obj) - { - return JsonSerializer.Serialize(obj, s_jsonOptionsCache); - } -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/TextOutputHelperExtensions.cs b/dotnet/samples/GettingStarted/RepoUtils/TextOutputHelperExtensions.cs deleted file mode 100644 index 965afd76045c..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/TextOutputHelperExtensions.cs +++ /dev/null @@ -1,33 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using Xunit.Abstractions; - -namespace Examples; - -public static class TextOutputHelperExtensions -{ - public static void WriteLine(this ITestOutputHelper testOutputHelper, object target) - { - testOutputHelper.WriteLine(target.ToString()); - } - - public static void WriteLine(this ITestOutputHelper testOutputHelper) - { - testOutputHelper.WriteLine(string.Empty); - } - - public static void Write(this ITestOutputHelper testOutputHelper) - { - testOutputHelper.WriteLine(string.Empty); - } - - /// - /// Current interface ITestOutputHelper does not have a Write method. This extension method adds it to make it analogous to Console.Write when used in Console apps. - /// - /// TestOutputHelper - /// Target object to write - public static void Write(this ITestOutputHelper testOutputHelper, object target) - { - testOutputHelper.WriteLine(target.ToString()); - } -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/XunitLogger.cs b/dotnet/samples/GettingStarted/RepoUtils/XunitLogger.cs deleted file mode 100644 index 77575ac094c9..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/XunitLogger.cs +++ /dev/null @@ -1,35 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using Microsoft.Extensions.Logging; -using Xunit.Abstractions; - -namespace RepoUtils; - -/// -/// A logger that writes to the Xunit test output -/// -internal sealed class XunitLogger(ITestOutputHelper output) : ILoggerFactory, ILogger, IDisposable -{ - /// - public void Log(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func formatter) - => output.WriteLine(state?.ToString()); - - /// - public bool IsEnabled(LogLevel logLevel) => true; - - /// - public IDisposable BeginScope(TState state) where TState : notnull - => this; - - /// - public void Dispose() - { - // This class is marked as disposable to support the BeginScope method. - // However, there is no need to dispose anything. - } - - public ILogger CreateLogger(string categoryName) => this; - - public void AddProvider(ILoggerProvider provider) => throw new NotSupportedException(); -} diff --git a/dotnet/samples/GettingStarted/RepoUtils/YourAppException.cs b/dotnet/samples/GettingStarted/RepoUtils/YourAppException.cs deleted file mode 100644 index 28794dbb1b04..000000000000 --- a/dotnet/samples/GettingStarted/RepoUtils/YourAppException.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; - -namespace RepoUtils; - -public class YourAppException : Exception -{ - public YourAppException() : base() - { - } - - public YourAppException(string message) : base(message) - { - } - - public YourAppException(string message, Exception innerException) : base(message, innerException) - { - } -} diff --git a/dotnet/samples/GettingStarted/Resources/EmbeddedResource.cs b/dotnet/samples/GettingStarted/Resources/EmbeddedResource.cs deleted file mode 100644 index 44b49a7bd78f..000000000000 --- a/dotnet/samples/GettingStarted/Resources/EmbeddedResource.cs +++ /dev/null @@ -1,67 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.IO; -using System.Reflection; -using System.Threading.Tasks; -using RepoUtils; - -namespace Resources; - -/// -/// Resource helper to load resources embedded in the assembly. By default we embed only -/// text files, so the helper is limited to returning text. -/// -/// You can find information about embedded resources here: -/// * https://learn.microsoft.com/dotnet/core/extensions/create-resource-files -/// * https://learn.microsoft.com/dotnet/api/system.reflection.assembly.getmanifestresourcestream?view=net-7.0 -/// -/// To know which resources are embedded, check the csproj file. -/// -internal static class EmbeddedResource -{ - private static readonly string? s_namespace = typeof(EmbeddedResource).Namespace; - - internal static string Read(string fileName) - { - // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. - Assembly assembly = - typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); - - // Resources are mapped like types, using the namespace and appending "." (dot) and the file name - var resourceName = $"{s_namespace}." + fileName; - using Stream resource = - assembly.GetManifestResourceStream(resourceName) ?? - throw new ConfigurationException($"{resourceName} resource not found"); - - // Return the resource content, in text format. - using var reader = new StreamReader(resource); - return reader.ReadToEnd(); - } - - internal static Stream? ReadStream(string fileName) - { - // Get the current assembly. Note: this class is in the same assembly where the embedded resources are stored. - Assembly assembly = - typeof(EmbeddedResource).GetTypeInfo().Assembly ?? - throw new ConfigurationException($"[{s_namespace}] {fileName} assembly not found"); - - // Resources are mapped like types, using the namespace and appending "." (dot) and the file name - var resourceName = $"{s_namespace}." + fileName; - return assembly.GetManifestResourceStream(resourceName); - } - - internal static async Task> ReadAllAsync(string fileName) - { - await using Stream? resourceStream = ReadStream(fileName); - using var memoryStream = new MemoryStream(); - - // Copy the resource stream to the memory stream - await resourceStream!.CopyToAsync(memoryStream); - - // Convert the memory stream's buffer to ReadOnlyMemory - // Note: ToArray() creates a copy of the buffer, which is fine for converting to ReadOnlyMemory - return new ReadOnlyMemory(memoryStream.ToArray()); - } -} diff --git a/dotnet/samples/GettingStarted/Step1_Create_Kernel.cs b/dotnet/samples/GettingStarted/Step1_Create_Kernel.cs index 3ad56548b9d4..d6eaac6f7886 100644 --- a/dotnet/samples/GettingStarted/Step1_Create_Kernel.cs +++ b/dotnet/samples/GettingStarted/Step1_Create_Kernel.cs @@ -1,11 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step2_Add_Plugins.cs b/dotnet/samples/GettingStarted/Step2_Add_Plugins.cs index 5ff7e4d0aa47..c8abeb46b01b 100644 --- a/dotnet/samples/GettingStarted/Step2_Add_Plugins.cs +++ b/dotnet/samples/GettingStarted/Step2_Add_Plugins.cs @@ -1,16 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; -using System.Linq; using System.Text.Json.Serialization; -using System.Threading.Tasks; -using Examples; using Microsoft.OpenApi.Extensions; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step3_Yaml_Prompt.cs b/dotnet/samples/GettingStarted/Step3_Yaml_Prompt.cs index e3c06eb71807..e12acacdfdb0 100644 --- a/dotnet/samples/GettingStarted/Step3_Yaml_Prompt.cs +++ b/dotnet/samples/GettingStarted/Step3_Yaml_Prompt.cs @@ -1,12 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.PromptTemplates.Handlebars; using Resources; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step4_Dependency_Injection.cs b/dotnet/samples/GettingStarted/Step4_Dependency_Injection.cs index 28544e490b67..8028ecc5fa71 100644 --- a/dotnet/samples/GettingStarted/Step4_Dependency_Injection.cs +++ b/dotnet/samples/GettingStarted/Step4_Dependency_Injection.cs @@ -1,15 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; -using System.Threading.Tasks; -using Examples; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using RepoUtils; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step5_Chat_Prompt.cs b/dotnet/samples/GettingStarted/Step5_Chat_Prompt.cs index 4c3a1b002b51..d8b45173c085 100644 --- a/dotnet/samples/GettingStarted/Step5_Chat_Prompt.cs +++ b/dotnet/samples/GettingStarted/Step5_Chat_Prompt.cs @@ -1,10 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs b/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs index 7384722c0eea..5a0a9557b43e 100644 --- a/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs +++ b/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs @@ -1,11 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; -using Examples; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step7_Observability.cs b/dotnet/samples/GettingStarted/Step7_Observability.cs index 0010813b2c48..83826998b161 100644 --- a/dotnet/samples/GettingStarted/Step7_Observability.cs +++ b/dotnet/samples/GettingStarted/Step7_Observability.cs @@ -1,15 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; -using System.Threading.Tasks; -using Examples; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; -using RepoUtils; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/Step8_Pipelining.cs b/dotnet/samples/GettingStarted/Step8_Pipelining.cs index 9c7d26c8eb40..53d8528865cc 100644 --- a/dotnet/samples/GettingStarted/Step8_Pipelining.cs +++ b/dotnet/samples/GettingStarted/Step8_Pipelining.cs @@ -1,17 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Collections.Generic; using System.Globalization; -using System.Linq; -using System.Threading; -using System.Threading.Tasks; -using Examples; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStarted/TestConfiguration.cs b/dotnet/samples/GettingStarted/TestConfiguration.cs deleted file mode 100644 index 1ff9418fc991..000000000000 --- a/dotnet/samples/GettingStarted/TestConfiguration.cs +++ /dev/null @@ -1,50 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System; -using System.Runtime.CompilerServices; -using Microsoft.Extensions.Configuration; -using RepoUtils; - -public sealed class TestConfiguration -{ - private readonly IConfigurationRoot _configRoot; - private static TestConfiguration? s_instance; - - private TestConfiguration(IConfigurationRoot configRoot) - { - this._configRoot = configRoot; - } - - public static void Initialize(IConfigurationRoot configRoot) - { - s_instance = new TestConfiguration(configRoot); - } - - public static OpenAIConfig OpenAI => LoadSection(); - - private static T LoadSection([CallerMemberName] string? caller = null) - { - if (s_instance == null) - { - throw new InvalidOperationException( - "TestConfiguration must be initialized with a call to Initialize(IConfigurationRoot) before accessing configuration values."); - } - - if (string.IsNullOrEmpty(caller)) - { - throw new ArgumentNullException(nameof(caller)); - } - - return s_instance._configRoot.GetSection(caller).Get() ?? - throw new ConfigurationNotFoundException(section: caller); - } - -#pragma warning disable CS8618 // Non-nullable field must contain a non-null value when exiting constructor. - public class OpenAIConfig - { - public string ModelId { get; set; } - public string ChatModelId { get; set; } - public string EmbeddingModelId { get; set; } - public string ApiKey { get; set; } - } -} diff --git a/dotnet/samples/LearnResources/LearnResources.csproj b/dotnet/samples/LearnResources/LearnResources.csproj index a5cf2ee36005..9646f13bba38 100644 --- a/dotnet/samples/LearnResources/LearnResources.csproj +++ b/dotnet/samples/LearnResources/LearnResources.csproj @@ -1,4 +1,4 @@ - + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 @@ -7,6 +7,7 @@ net8.0 true + enable false CS8618,IDE0009,CA1051,CA1050,CA1707,CA2007,VSTHRD111,CS1591,RCS1110,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0101 @@ -29,6 +30,7 @@ + runtime; build; native; contentfiles; analyzers; buildtransitive all @@ -44,6 +46,7 @@ + @@ -62,4 +65,8 @@ Always + + + + \ No newline at end of file diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/Planner.cs b/dotnet/samples/LearnResources/MicrosoftLearn/Planner.cs index 1f88ec099165..9f527b76a771 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/Planner.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/Planner.cs @@ -1,14 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Plugins; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/Concepts/Resources/EmbeddedResource.cs b/dotnet/src/InternalUtilities/samples/EmbeddedResource.cs similarity index 100% rename from dotnet/samples/Concepts/Resources/EmbeddedResource.cs rename to dotnet/src/InternalUtilities/samples/EmbeddedResource.cs From f8c9bf07d39aa149cad352bf86bd00598003b083 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 12:21:57 +0100 Subject: [PATCH 10/24] Adding Folder for Sample utilities to improve visibility --- dotnet/samples/GettingStarted/GettingStarted.csproj | 1 + dotnet/samples/LearnResources/MicrosoftLearn/AIServices.cs | 3 --- dotnet/samples/LearnResources/MicrosoftLearn/BaseTest.cs | 2 -- .../LearnResources/MicrosoftLearn/ConfiguringPrompts.cs | 4 ---- .../LearnResources/MicrosoftLearn/CreatingFunctions.cs | 3 --- .../LearnResources/MicrosoftLearn/FunctionsWithinPrompts.cs | 5 ----- dotnet/samples/LearnResources/MicrosoftLearn/Plugin.cs | 4 ---- dotnet/samples/LearnResources/MicrosoftLearn/Prompts.cs | 3 --- .../LearnResources/MicrosoftLearn/SerializingPrompts.cs | 6 ------ dotnet/samples/LearnResources/MicrosoftLearn/Templates.cs | 5 ----- .../LearnResources/MicrosoftLearn/TestConfiguration.cs | 1 - .../samples/LearnResources/MicrosoftLearn/UsingTheKernel.cs | 3 --- dotnet/samples/LearnResources/Plugins/MathPlugin.cs | 1 - dotnet/samples/LearnResources/Plugins/MathSolver.cs | 1 - .../samples/{ => InternalUtilities}/BaseTest.cs | 0 .../ConfigurationNotFoundException.cs | 0 .../samples/{ => InternalUtilities}/EmbeddedResource.cs | 0 .../samples/{ => InternalUtilities}/EnumerableExtensions.cs | 0 .../samples/{ => InternalUtilities}/Env.cs | 0 .../samples/{ => InternalUtilities}/ObjectExtensions.cs | 0 .../samples/{ => InternalUtilities}/RepoFiles.cs | 0 .../{ => InternalUtilities}/SamplesInternalUtilities.props | 0 .../samples/{ => InternalUtilities}/TestConfiguration.cs | 0 .../{ => InternalUtilities}/TextOutputHelperExtensions.cs | 0 .../samples/{ => InternalUtilities}/XunitLogger.cs | 0 .../samples/{ => InternalUtilities}/YourAppException.cs | 0 26 files changed, 1 insertion(+), 41 deletions(-) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/BaseTest.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/ConfigurationNotFoundException.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/EmbeddedResource.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/EnumerableExtensions.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/Env.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/ObjectExtensions.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/RepoFiles.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/SamplesInternalUtilities.props (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/TestConfiguration.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/TextOutputHelperExtensions.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/XunitLogger.cs (100%) rename dotnet/src/InternalUtilities/samples/{ => InternalUtilities}/YourAppException.cs (100%) diff --git a/dotnet/samples/GettingStarted/GettingStarted.csproj b/dotnet/samples/GettingStarted/GettingStarted.csproj index c35cbeb6ff41..052b1b2d1898 100644 --- a/dotnet/samples/GettingStarted/GettingStarted.csproj +++ b/dotnet/samples/GettingStarted/GettingStarted.csproj @@ -48,6 +48,7 @@ + diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/AIServices.cs b/dotnet/samples/LearnResources/MicrosoftLearn/AIServices.cs index 1817350513e7..65a66229b0f8 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/AIServices.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/AIServices.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/BaseTest.cs b/dotnet/samples/LearnResources/MicrosoftLearn/BaseTest.cs index 738f065c70b7..5716e8cb2f0e 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/BaseTest.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/BaseTest.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; using Microsoft.Extensions.Configuration; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/ConfiguringPrompts.cs b/dotnet/samples/LearnResources/MicrosoftLearn/ConfiguringPrompts.cs index bce40826e44b..ef73d3c2b8f5 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/ConfiguringPrompts.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/ConfiguringPrompts.cs @@ -1,13 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Microsoft.SemanticKernel.Plugins.Core; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/CreatingFunctions.cs b/dotnet/samples/LearnResources/MicrosoftLearn/CreatingFunctions.cs index d18324f2c281..0379c58e3274 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/CreatingFunctions.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/CreatingFunctions.cs @@ -1,12 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; using Plugins; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/FunctionsWithinPrompts.cs b/dotnet/samples/LearnResources/MicrosoftLearn/FunctionsWithinPrompts.cs index 3292fb359ba7..bb7c34338f03 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/FunctionsWithinPrompts.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/FunctionsWithinPrompts.cs @@ -1,14 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Plugins.Core; using Microsoft.SemanticKernel.PromptTemplates.Handlebars; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/Plugin.cs b/dotnet/samples/LearnResources/MicrosoftLearn/Plugin.cs index 9888313a24d1..d68482a831ac 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/Plugin.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/Plugin.cs @@ -1,13 +1,9 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/Prompts.cs b/dotnet/samples/LearnResources/MicrosoftLearn/Prompts.cs index 3f32f698f8eb..29f89c037e8d 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/Prompts.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/Prompts.cs @@ -1,9 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/SerializingPrompts.cs b/dotnet/samples/LearnResources/MicrosoftLearn/SerializingPrompts.cs index b939b4c31890..5f0be6fa6289 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/SerializingPrompts.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/SerializingPrompts.cs @@ -1,16 +1,10 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.IO; -using System.Linq; using System.Reflection; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Plugins.Core; using Microsoft.SemanticKernel.PromptTemplates.Handlebars; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/Templates.cs b/dotnet/samples/LearnResources/MicrosoftLearn/Templates.cs index 2b3d90d3e37d..ae705e994a76 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/Templates.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/Templates.cs @@ -1,13 +1,8 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Collections.Generic; -using System.Linq; -using System.Threading.Tasks; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.PromptTemplates.Handlebars; -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/TestConfiguration.cs b/dotnet/samples/LearnResources/MicrosoftLearn/TestConfiguration.cs index 01108b8827dc..d6df5f215b4c 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/TestConfiguration.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/TestConfiguration.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.Runtime.CompilerServices; using Microsoft.Extensions.Configuration; diff --git a/dotnet/samples/LearnResources/MicrosoftLearn/UsingTheKernel.cs b/dotnet/samples/LearnResources/MicrosoftLearn/UsingTheKernel.cs index 99daa03023bb..400c5f29eb11 100644 --- a/dotnet/samples/LearnResources/MicrosoftLearn/UsingTheKernel.cs +++ b/dotnet/samples/LearnResources/MicrosoftLearn/UsingTheKernel.cs @@ -1,14 +1,11 @@ // Copyright (c) Microsoft. All rights reserved. -using System.Threading.Tasks; // using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Plugins.Core; // -using Xunit; -using Xunit.Abstractions; namespace Examples; diff --git a/dotnet/samples/LearnResources/Plugins/MathPlugin.cs b/dotnet/samples/LearnResources/Plugins/MathPlugin.cs index 101f03505d2a..a0b6bfa7c30a 100644 --- a/dotnet/samples/LearnResources/Plugins/MathPlugin.cs +++ b/dotnet/samples/LearnResources/Plugins/MathPlugin.cs @@ -1,6 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using System; using System.ComponentModel; using Microsoft.SemanticKernel; diff --git a/dotnet/samples/LearnResources/Plugins/MathSolver.cs b/dotnet/samples/LearnResources/Plugins/MathSolver.cs index 78454e2599cb..eb305c3f1928 100644 --- a/dotnet/samples/LearnResources/Plugins/MathSolver.cs +++ b/dotnet/samples/LearnResources/Plugins/MathSolver.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. using System.ComponentModel; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Planning.Handlebars; diff --git a/dotnet/src/InternalUtilities/samples/BaseTest.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/BaseTest.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs diff --git a/dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/ConfigurationNotFoundException.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/ConfigurationNotFoundException.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/ConfigurationNotFoundException.cs diff --git a/dotnet/src/InternalUtilities/samples/EmbeddedResource.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/EmbeddedResource.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/EmbeddedResource.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/EmbeddedResource.cs diff --git a/dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/EnumerableExtensions.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/EnumerableExtensions.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/EnumerableExtensions.cs diff --git a/dotnet/src/InternalUtilities/samples/Env.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/Env.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs diff --git a/dotnet/src/InternalUtilities/samples/ObjectExtensions.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/ObjectExtensions.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/ObjectExtensions.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/ObjectExtensions.cs diff --git a/dotnet/src/InternalUtilities/samples/RepoFiles.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/RepoFiles.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/RepoFiles.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/RepoFiles.cs diff --git a/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props b/dotnet/src/InternalUtilities/samples/InternalUtilities/SamplesInternalUtilities.props similarity index 100% rename from dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props rename to dotnet/src/InternalUtilities/samples/InternalUtilities/SamplesInternalUtilities.props diff --git a/dotnet/src/InternalUtilities/samples/TestConfiguration.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/TestConfiguration.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/TestConfiguration.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/TestConfiguration.cs diff --git a/dotnet/src/InternalUtilities/samples/TextOutputHelperExtensions.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/TextOutputHelperExtensions.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs diff --git a/dotnet/src/InternalUtilities/samples/XunitLogger.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/XunitLogger.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs diff --git a/dotnet/src/InternalUtilities/samples/YourAppException.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/YourAppException.cs similarity index 100% rename from dotnet/src/InternalUtilities/samples/YourAppException.cs rename to dotnet/src/InternalUtilities/samples/InternalUtilities/YourAppException.cs From a3dc27a04e36a40f6d0a7cde54ae90143cd6d7e3 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 12:24:59 +0100 Subject: [PATCH 11/24] Adjustments --- dotnet/samples/GettingStarted/GettingStarted.csproj | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/samples/GettingStarted/GettingStarted.csproj b/dotnet/samples/GettingStarted/GettingStarted.csproj index 052b1b2d1898..73e465f45ffd 100644 --- a/dotnet/samples/GettingStarted/GettingStarted.csproj +++ b/dotnet/samples/GettingStarted/GettingStarted.csproj @@ -3,7 +3,7 @@ 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - QuickStart + GettingStarted enable net8.0 From dd9bf2a8a51bc2d3d4f861501b8901312fd9aece Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 12:40:50 +0100 Subject: [PATCH 12/24] Typo fix --- .../Concepts/DependencyInjection/HttpClient_Resiliency.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs index d3053650e381..eb4e26c7cb48 100644 --- a/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs +++ b/dotnet/samples/Concepts/DependencyInjection/HttpClient_Resiliency.cs @@ -12,7 +12,7 @@ namespace Examples; public class HttpClient_Resiliency(ITestOutputHelper output) : BaseTest(output) { /// - /// Demostrates the usage of the HttpClientFactory with a custom resilience policy. + /// Demonstrates the usage of the HttpClientFactory with a custom resilience policy. /// [Fact] public async Task RunAsync() From 447bc75a7f310c4c7bdf4555f06a8ed6c249f9fd Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 14:42:39 +0100 Subject: [PATCH 13/24] Warning fix --- .../samples/Concepts/Agents/Legacy_Agents.cs | 4 +- dotnet/samples/Concepts/Filtering/Filters.cs | 1 + ...ner.cs => FunctionCallStepwisePlanning.cs} | 2 +- .../{Handlebars.cs => HandlebarsPlanning.cs} | 2 +- .../Resources/Plugins/LegacyMenuPlugin.cs | 75 +++++++++++++++++++ .../Concepts/Resources/Plugins/MenuPlugin.cs | 6 ++ .../GettingStarted/Step6_Responsible_AI.cs | 5 -- .../Memory/AzureCosmosDBMongoDB/DataHelper.cs | 4 +- ...OnnxTextEmbeddingGenerationServiceTests.cs | 16 ++-- .../samples/InternalUtilities/BaseTest.cs | 1 - .../samples/InternalUtilities/Env.cs | 2 + .../TextOutputHelperExtensions.cs | 2 - .../samples/InternalUtilities/XunitLogger.cs | 1 - .../SamplesInternalUtilities.props | 0 14 files changed, 98 insertions(+), 23 deletions(-) rename dotnet/samples/Concepts/Planners/{FunctionCallingStepwisePlanner.cs => FunctionCallStepwisePlanning.cs} (95%) rename dotnet/samples/Concepts/Planners/{Handlebars.cs => HandlebarsPlanning.cs} (99%) create mode 100644 dotnet/samples/Concepts/Resources/Plugins/LegacyMenuPlugin.cs rename dotnet/src/InternalUtilities/samples/{InternalUtilities => }/SamplesInternalUtilities.props (100%) diff --git a/dotnet/samples/Concepts/Agents/Legacy_Agents.cs b/dotnet/samples/Concepts/Agents/Legacy_Agents.cs index 699e96e0ac3a..b3c5f75e9c9a 100644 --- a/dotnet/samples/Concepts/Agents/Legacy_Agents.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_Agents.cs @@ -54,14 +54,14 @@ public async Task RunWithMethodFunctionsAsync() { WriteLine("======== Run:WithMethodFunctions ========"); - MenuPlugin menuApi = new(); + LegacyMenuPlugin menuApi = new(); KernelPlugin plugin = KernelPluginFactory.CreateFromObject(menuApi); // Call the common chat-loop await ChatAsync( "Agents.ToolAgent.yaml", // Defined under ./Resources/Agents plugin, - arguments: new() { { MenuPlugin.CorrelationIdArgument, 3.141592653 } }, + arguments: new() { { LegacyMenuPlugin.CorrelationIdArgument, 3.141592653 } }, "Hello", "What is the special soup?", "What is the special drink?", diff --git a/dotnet/samples/Concepts/Filtering/Filters.cs b/dotnet/samples/Concepts/Filtering/Filters.cs index 7ca46cf30527..906a91874836 100644 --- a/dotnet/samples/Concepts/Filtering/Filters.cs +++ b/dotnet/samples/Concepts/Filtering/Filters.cs @@ -2,6 +2,7 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Connectors.OpenAI; diff --git a/dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs b/dotnet/samples/Concepts/Planners/FunctionCallStepwisePlanning.cs similarity index 95% rename from dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs rename to dotnet/samples/Concepts/Planners/FunctionCallStepwisePlanning.cs index 960219969336..25bf9dec642d 100644 --- a/dotnet/samples/Concepts/Planners/FunctionCallingStepwisePlanner.cs +++ b/dotnet/samples/Concepts/Planners/FunctionCallStepwisePlanning.cs @@ -6,7 +6,7 @@ namespace Examples; -public class FunctionCallingStepwisePlanner(ITestOutputHelper output) : BaseTest(output) +public class FunctionCallStepwisePlanning(ITestOutputHelper output) : BaseTest(output) { [Fact] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Planners/Handlebars.cs b/dotnet/samples/Concepts/Planners/HandlebarsPlanning.cs similarity index 99% rename from dotnet/samples/Concepts/Planners/Handlebars.cs rename to dotnet/samples/Concepts/Planners/HandlebarsPlanning.cs index 747dab8a0279..479279e4497c 100644 --- a/dotnet/samples/Concepts/Planners/Handlebars.cs +++ b/dotnet/samples/Concepts/Planners/HandlebarsPlanning.cs @@ -11,7 +11,7 @@ namespace Examples; // This example shows how to use the Handlebars sequential planner. -public class Handlebars(ITestOutputHelper output) : BaseTest(output) +public class HandlebarsPlanning(ITestOutputHelper output) : BaseTest(output) { private static int s_sampleIndex; diff --git a/dotnet/samples/Concepts/Resources/Plugins/LegacyMenuPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/LegacyMenuPlugin.cs new file mode 100644 index 000000000000..7111e873cf4c --- /dev/null +++ b/dotnet/samples/Concepts/Resources/Plugins/LegacyMenuPlugin.cs @@ -0,0 +1,75 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.ComponentModel; +using Microsoft.SemanticKernel; + +namespace Plugins; + +public sealed class LegacyMenuPlugin +{ + public const string CorrelationIdArgument = "correlationId"; + + private readonly List _correlationIds = []; + + public IReadOnlyList CorrelationIds => this._correlationIds; + + /// + /// Returns a mock item menu. + /// + [KernelFunction, Description("Provides a list of specials from the menu.")] + [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "Too smart")] + public string[] GetSpecials(KernelArguments? arguments) + { + CaptureCorrelationId(arguments, nameof(GetSpecials)); + + return + [ + "Special Soup: Clam Chowder", + "Special Salad: Cobb Salad", + "Special Drink: Chai Tea", + ]; + } + + /// + /// Returns a mock item price. + /// + [KernelFunction, Description("Provides the price of the requested menu item.")] + public string GetItemPrice( + [Description("The name of the menu item.")] + string menuItem, + KernelArguments? arguments) + { + CaptureCorrelationId(arguments, nameof(GetItemPrice)); + + return "$9.99"; + } + + /// + /// An item is 86'd when the kitchen cannot serve due to running out of ingredients. + /// + [KernelFunction, Description("Returns true if the kitchen has ran out of the item.")] + public bool IsItem86d( + [Description("The name of the menu item.")] + string menuItem, + [Description("The number of items requested.")] + int count, + KernelArguments? arguments) + { + CaptureCorrelationId(arguments, nameof(IsItem86d)); + + return count < 3; + } + + private void CaptureCorrelationId(KernelArguments? arguments, string scope) + { + if (arguments?.TryGetValue(CorrelationIdArgument, out object? correlationId) ?? false) + { + string? correlationText = correlationId?.ToString(); + + if (!string.IsNullOrWhiteSpace(correlationText)) + { + this._correlationIds.Add($"{scope}:{correlationText}"); + } + } + } +} diff --git a/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs b/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs index ba74f786d90f..be82177eda5d 100644 --- a/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs +++ b/dotnet/samples/Concepts/Resources/Plugins/MenuPlugin.cs @@ -7,6 +7,12 @@ namespace Plugins; public sealed class MenuPlugin { + public const string CorrelationIdArgument = "correlationId"; + + private readonly List _correlationIds = []; + + public IReadOnlyList CorrelationIds => this._correlationIds; + [KernelFunction, Description("Provides a list of specials from the menu.")] [System.Diagnostics.CodeAnalysis.SuppressMessage("Design", "CA1024:Use properties where appropriate", Justification = "Too smart")] public string GetSpecials() diff --git a/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs b/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs index 8e5a36a48c91..5768761f6bbd 100644 --- a/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs +++ b/dotnet/samples/GettingStarted/Step6_Responsible_AI.cs @@ -1,12 +1,7 @@ // Copyright (c) Microsoft. All rights reserved. -using System; -using System.Threading.Tasks; -using Examples; using Microsoft.Extensions.DependencyInjection; using Microsoft.SemanticKernel; -using Xunit; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/src/IntegrationTests/Connectors/Memory/AzureCosmosDBMongoDB/DataHelper.cs b/dotnet/src/IntegrationTests/Connectors/Memory/AzureCosmosDBMongoDB/DataHelper.cs index 87546750ee9c..e7f708c19041 100644 --- a/dotnet/src/IntegrationTests/Connectors/Memory/AzureCosmosDBMongoDB/DataHelper.cs +++ b/dotnet/src/IntegrationTests/Connectors/Memory/AzureCosmosDBMongoDB/DataHelper.cs @@ -1,4 +1,4 @@ -// Copyright (c) Microsoft. All rights reserved. +// Copyright (c) Microsoft. All rights reserved. using System; using System.Linq; @@ -43,4 +43,4 @@ public static MemoryRecord[] CreateBatchRecords(int count) => private static DateTime GetDateTime() => new(TimeSpan.TicksPerMillisecond * (DateTime.Now.Ticks / TimeSpan.TicksPerMillisecond), DateTimeKind.Local); -} \ No newline at end of file +} diff --git a/dotnet/src/IntegrationTests/Connectors/Onnx/BertOnnxTextEmbeddingGenerationServiceTests.cs b/dotnet/src/IntegrationTests/Connectors/Onnx/BertOnnxTextEmbeddingGenerationServiceTests.cs index 2636feb44381..e2f7f006202c 100644 --- a/dotnet/src/IntegrationTests/Connectors/Onnx/BertOnnxTextEmbeddingGenerationServiceTests.cs +++ b/dotnet/src/IntegrationTests/Connectors/Onnx/BertOnnxTextEmbeddingGenerationServiceTests.cs @@ -1,18 +1,18 @@ // Copyright (c) Microsoft. All rights reserved. -using Microsoft.SemanticKernel.Embeddings; -using Microsoft.SemanticKernel; +using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Threading.Tasks; -using System; -using Xunit; -using System.Numerics.Tensors; -using Microsoft.SemanticKernel.Connectors.Onnx; -using System.Text; using System.Net.Http; +using System.Numerics.Tensors; using System.Security.Cryptography; +using System.Text; +using System.Threading.Tasks; +using Microsoft.SemanticKernel; +using Microsoft.SemanticKernel.Connectors.Onnx; +using Microsoft.SemanticKernel.Embeddings; +using Xunit; namespace SemanticKernel.IntegrationTests.Connectors.Onnx; diff --git a/dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs index b4ea1f98f173..b7a71d204011 100644 --- a/dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs +++ b/dotnet/src/InternalUtilities/samples/InternalUtilities/BaseTest.cs @@ -3,7 +3,6 @@ using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; using Microsoft.SemanticKernel; -using Xunit.Abstractions; public abstract class BaseTest { diff --git a/dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs index 729d79cd7cd7..5c2aa4b5a13e 100644 --- a/dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs +++ b/dotnet/src/InternalUtilities/samples/InternalUtilities/Env.cs @@ -2,6 +2,8 @@ using Microsoft.Extensions.Configuration; +#pragma warning disable CA1812 // Avoid uninstantiated internal classes + internal sealed class Env { /// diff --git a/dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs index cfb938a80fec..7f2ff7c3c8ad 100644 --- a/dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs +++ b/dotnet/src/InternalUtilities/samples/InternalUtilities/TextOutputHelperExtensions.cs @@ -1,7 +1,5 @@ // Copyright (c) Microsoft. All rights reserved. -using Xunit.Abstractions; - public static class TextOutputHelperExtensions { public static void WriteLine(this ITestOutputHelper testOutputHelper, object target) diff --git a/dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs b/dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs index 06169c6b6c31..ca2c22cd800a 100644 --- a/dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs +++ b/dotnet/src/InternalUtilities/samples/InternalUtilities/XunitLogger.cs @@ -1,7 +1,6 @@ // Copyright (c) Microsoft. All rights reserved. using Microsoft.Extensions.Logging; -using Xunit.Abstractions; /// /// A logger that writes to the Xunit test output diff --git a/dotnet/src/InternalUtilities/samples/InternalUtilities/SamplesInternalUtilities.props b/dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props similarity index 100% rename from dotnet/src/InternalUtilities/samples/InternalUtilities/SamplesInternalUtilities.props rename to dotnet/src/InternalUtilities/samples/SamplesInternalUtilities.props From e1bb8becfceff6a959cac39c5a09b5cd12b9b003 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 14:47:54 +0100 Subject: [PATCH 14/24] UnitTests passing all --- .../GettingStartedWithAgents/GettingStartedWithAgents.csproj | 2 ++ 1 file changed, 2 insertions(+) diff --git a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj index 8208021e8be8..9115b3f79287 100644 --- a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj +++ b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj @@ -30,6 +30,7 @@ + @@ -44,6 +45,7 @@ + From 58cd931b0f2311c9594d3f2c84ac7d09aa8577a3 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 15:34:54 +0100 Subject: [PATCH 15/24] Fix warnings and build --- dotnet/samples/GettingStarted/GettingStarted.csproj | 4 +--- .../GettingStartedWithAgents/GettingStartedWithAgents.csproj | 1 + dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs | 1 - dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs | 1 - dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs | 1 - dotnet/samples/LearnResources/LearnResources.csproj | 4 +--- 6 files changed, 3 insertions(+), 9 deletions(-) diff --git a/dotnet/samples/GettingStarted/GettingStarted.csproj b/dotnet/samples/GettingStarted/GettingStarted.csproj index 73e465f45ffd..496b1baf6e4b 100644 --- a/dotnet/samples/GettingStarted/GettingStarted.csproj +++ b/dotnet/samples/GettingStarted/GettingStarted.csproj @@ -1,7 +1,4 @@  - - 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - GettingStarted @@ -12,6 +9,7 @@ CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101 Library + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 diff --git a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj index 9115b3f79287..64c7a4e4653f 100644 --- a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj +++ b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj @@ -13,6 +13,7 @@ CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 Library + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 diff --git a/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs index 4f26fcd3e6dd..def6bb2ea74d 100644 --- a/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs @@ -2,7 +2,6 @@ using Microsoft.SemanticKernel; using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs index 5f591d8410af..a3c8551643bb 100644 --- a/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs @@ -4,7 +4,6 @@ using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.ChatCompletion; using Microsoft.SemanticKernel.Connectors.OpenAI; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs b/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs index 0992a5bd97dd..d5c90736fc79 100644 --- a/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step3_Chat.cs @@ -3,7 +3,6 @@ using Microsoft.SemanticKernel.Agents; using Microsoft.SemanticKernel.Agents.Chat; using Microsoft.SemanticKernel.ChatCompletion; -using Xunit.Abstractions; namespace GettingStarted; diff --git a/dotnet/samples/LearnResources/LearnResources.csproj b/dotnet/samples/LearnResources/LearnResources.csproj index 9646f13bba38..ed13bf32682e 100644 --- a/dotnet/samples/LearnResources/LearnResources.csproj +++ b/dotnet/samples/LearnResources/LearnResources.csproj @@ -1,7 +1,4 @@  - - 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - LearnResources @@ -12,6 +9,7 @@ CS8618,IDE0009,CA1051,CA1050,CA1707,CA2007,VSTHRD111,CS1591,RCS1110,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0101 Library + 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 From 7bfa869a29586ac2644ad3d823fbdf4e8752fd86 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 15:55:44 +0100 Subject: [PATCH 16/24] Fix AssemblyVersionName error --- dotnet/samples/Concepts/Concepts.csproj | 10 ++++------ .../GettingStartedWithAgents.csproj | 4 +--- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 43a1314a423f..40a0787a43ee 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -1,21 +1,19 @@  + Concepts + 1.0.0.0 + false + net8.0 enable enable - false true - - Concepts2 - - net8.0 CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 Library 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 - false false diff --git a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj index 64c7a4e4653f..0ac7baf6baf9 100644 --- a/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj +++ b/dotnet/samples/GettingStartedWithAgents/GettingStartedWithAgents.csproj @@ -1,14 +1,12 @@  + GettingStartedWithAgents net8.0 enable enable - false true - - GettingStartedWithAgents CS8618,IDE0009,CA1051,CA1050,CA1707,CA1054,CA2007,VSTHRD111,CS1591,RCS1110,RCS1243,CA5394,SKEXP0001,SKEXP0010,SKEXP0020,SKEXP0040,SKEXP0050,SKEXP0060,SKEXP0070,SKEXP0101,SKEXP0110 From 45247a3e9a87076f97ec42d9f77666bcaacdb9a3 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Fri, 26 Apr 2024 18:25:11 +0100 Subject: [PATCH 17/24] Adding Getting Started to VSCode launch options --- .vscode/launch.json | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index d512a2e56d8c..21bde253e9c3 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,6 +1,7 @@ { "version": "0.2.0", "configurations": [ + { // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes @@ -35,11 +36,18 @@ ] }, { - "name": "C#: HuggingFaceImageTextExample", + "name": "C#: HuggingFaceImageToText", "type": "dotnet", "request": "launch", - "projectPath": "${workspaceFolder}\\dotnet\\samples\\HuggingFaceImageTextExample\\HuggingFaceImageTextExample.csproj", - "launchConfigurationId": "TargetFramework=;HuggingFaceImageTextExample" + "projectPath": "${workspaceFolder}\\dotnet\\samples\\Demos\\HuggingFaceImageToText.csproj", + "launchConfigurationId": "TargetFramework=;HuggingFaceImageToText" + }, + { + "name": "C#: GettingStarted", + "type": "dotnet", + "request": "launch", + "projectPath": "${workspaceFolder}\\dotnet\\samples\\GettingStarted\\GettingStarted.csproj", + "launchConfigurationId": "TargetFramework=;GettingStarted" } ] } \ No newline at end of file From b777411ccdcb485da2bdcb340a094cd315e389a7 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Sat, 27 Apr 2024 07:59:23 +0100 Subject: [PATCH 18/24] Adding AssemblyInfo --- dotnet/samples/Concepts/Concepts.csproj | 1 + .../Concepts/Properties/AssemblyInfo.cs | 34 +++++++++++++++++++ 2 files changed, 35 insertions(+) create mode 100644 dotnet/samples/Concepts/Properties/AssemblyInfo.cs diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 40a0787a43ee..773a4473407e 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -3,6 +3,7 @@ Concepts 1.0.0.0 + 1.0.0.0 false net8.0 diff --git a/dotnet/samples/Concepts/Properties/AssemblyInfo.cs b/dotnet/samples/Concepts/Properties/AssemblyInfo.cs new file mode 100644 index 000000000000..109d37464884 --- /dev/null +++ b/dotnet/samples/Concepts/Properties/AssemblyInfo.cs @@ -0,0 +1,34 @@ +// Copyright (c) Microsoft. All rights reserved. + +using System.Reflection; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("Properties")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("Properties")] +[assembly: AssemblyCopyright("Copyright © 2024")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("7a06e178-6ef3-4d45-b427-3a5268d51913")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] From 122c80b771ce77ec1ad787db720540d8a8cf9685 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Sat, 27 Apr 2024 08:40:54 +0100 Subject: [PATCH 19/24] Fix Broken Links --- .vscode/launch.json | 19 +++++------- .vscode/tasks.json | 14 ++++----- .../0021-json-serializable-custom-types.md | 2 +- .../Concepts/Agents/Legacy_AgentAuthoring.cs | 4 +-- .../Kernel/CustomAIServiceSelector.cs | 2 +- .../CreatePluginFromOpenAI_AzureKeyVault.cs | 2 +- .../CreatePluginFromOpenApiSpec_Jira.cs | 2 +- .../Concepts/Plugins/ImportPluginFromGrpc.cs | 2 +- .../MultiplePromptTemplates.cs | 2 +- .../Concepts/Properties/AssemblyInfo.cs | 30 +++++-------------- dotnet/samples/Concepts/README.md | 2 +- .../HuggingFace_TextGeneration.cs | 6 +--- dotnet/samples/GettingStarted/README.md | 2 +- .../GettingStartedWithAgents/Step1_Agent.cs | 2 +- .../GettingStartedWithAgents/Step2_Plugins.cs | 2 +- dotnet/samples/README.md | 14 ++++----- .../Connectors.Memory.Chroma/README.md | 2 +- .../Connectors.Memory.Kusto/README.md | 2 +- .../Connectors.Memory.Milvus/README.md | 2 +- .../Connectors.Memory.MongoDB/README.md | 2 +- .../Connectors.Memory.Postgres/README.md | 2 +- .../Connectors.Memory.Redis/README.md | 2 +- .../Events/CancelKernelEventArgs.cs | 2 +- .../Events/FunctionInvokedEventArgs.cs | 2 +- .../Events/FunctionInvokingEventArgs.cs | 2 +- .../Events/KernelEventArgs.cs | 2 +- .../Events/PromptRenderedEventArgs.cs | 2 +- .../Events/PromptRenderingEventArgs.cs | 2 +- .../src/SemanticKernel.Abstractions/Kernel.cs | 16 +++++----- 29 files changed, 63 insertions(+), 84 deletions(-) diff --git a/.vscode/launch.json b/.vscode/launch.json index 21bde253e9c3..3e38b1ff0525 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -1,21 +1,20 @@ { "version": "0.2.0", "configurations": [ - { // Use IntelliSense to find out which attributes exist for C# debugging // Use hover for the description of the existing attributes // For further information visit https://github.com/OmniSharp/omnisharp-vscode/blob/master/debugger-launchjson.md - "name": ".NET Core Launch (dotnet-kernel-syntax-examples)", + "name": "C#: Concept Samples", "type": "coreclr", "request": "launch", - "preLaunchTask": "build (KernelSyntaxExamples)", + "preLaunchTask": "build (Concepts)", // If you have changed target frameworks, make sure to update the program path. - "program": "${workspaceFolder}/dotnet/samples/KernelSyntaxExamples/bin/Debug/net6.0/KernelSyntaxExamples.dll", + "program": "${workspaceFolder}/dotnet/samples/Concepts/bin/Debug/net6.0/Concepts.dll", "args": [ /*"example0"*/ ], - "cwd": "${workspaceFolder}/dotnet/samples/KernelSyntaxExamples", + "cwd": "${workspaceFolder}/dotnet/samples/Concepts", // For more information about the 'console' field, see https://aka.ms/VSCode-CS-LaunchJson-Console "console": "internalConsole", "stopAtEntry": false @@ -31,23 +30,21 @@ "type": "python", "request": "launch", "module": "pytest", - "args": [ - "${file}" - ] + "args": ["${file}"] }, { - "name": "C#: HuggingFaceImageToText", + "name": "C#: HuggingFaceImageToText Demo", "type": "dotnet", "request": "launch", "projectPath": "${workspaceFolder}\\dotnet\\samples\\Demos\\HuggingFaceImageToText.csproj", "launchConfigurationId": "TargetFramework=;HuggingFaceImageToText" }, { - "name": "C#: GettingStarted", + "name": "C#: GettingStarted Samples", "type": "dotnet", "request": "launch", "projectPath": "${workspaceFolder}\\dotnet\\samples\\GettingStarted\\GettingStarted.csproj", "launchConfigurationId": "TargetFramework=;GettingStarted" } ] -} \ No newline at end of file +} diff --git a/.vscode/tasks.json b/.vscode/tasks.json index 7993d689209a..91ff88105299 100644 --- a/.vscode/tasks.json +++ b/.vscode/tasks.json @@ -327,12 +327,12 @@ // **************** // Kernel Syntax Examples { - "label": "build (KernelSyntaxExamples)", + "label": "build (Concepts)", "command": "dotnet", "type": "process", "args": [ "build", - "${workspaceFolder}/dotnet/samples/KernelSyntaxExamples/KernelSyntaxExamples.csproj", + "${workspaceFolder}/dotnet/samples/Concepts/Concepts.csproj", "/property:GenerateFullPaths=true", "/consoleloggerparameters:NoSummary", "/property:DebugType=portable" @@ -341,26 +341,26 @@ "group": "build" }, { - "label": "watch (KernelSyntaxExamples)", + "label": "watch (Concepts)", "command": "dotnet", "type": "process", "args": [ "watch", "run", "--project", - "${workspaceFolder}/dotnet/samples/KernelSyntaxExamples/KernelSyntaxExamples.csproj" + "${workspaceFolder}/dotnet/samples/Concepts/Concepts.csproj" ], "problemMatcher": "$msCompile", "group": "build" }, { - "label": "run (KernelSyntaxExamples)", + "label": "run (Concepts)", "command": "dotnet", "type": "process", "args": [ "run", "--project", - "${workspaceFolder}/dotnet/samples/KernelSyntaxExamples/KernelSyntaxExamples.csproj", + "${workspaceFolder}/dotnet/samples/Concepts/Concepts.csproj", "${input:filter}" ], "problemMatcher": "$msCompile", @@ -370,7 +370,7 @@ "panel": "shared", "group": "PR-Validate" } - }, + } ], "inputs": [ { diff --git a/docs/decisions/0021-json-serializable-custom-types.md b/docs/decisions/0021-json-serializable-custom-types.md index d7a0072409a7..08e017db2060 100644 --- a/docs/decisions/0021-json-serializable-custom-types.md +++ b/docs/decisions/0021-json-serializable-custom-types.md @@ -15,7 +15,7 @@ This ADR aims to simplify the usage of custom types by allowing developers to us Standardizing on a JSON-serializable type is necessary to allow functions to be described using a JSON Schema within a planner's function manual. Using a JSON Schema to describe a function's input and output types will allow the planner to validate that the function is being used correctly. -Today, use of custom types within Semantic Kernel requires developers to implement a custom `TypeConverter` to convert to/from the string representation of the type. This is demonstrated in [Example60_AdvancedNativeFunctions](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/KernelSyntaxExamples/Example60_AdvancedNativeFunctions.cs#L202C44-L202C44) as seen below: +Today, use of custom types within Semantic Kernel requires developers to implement a custom `TypeConverter` to convert to/from the string representation of the type. This is demonstrated in [Functions/MethodFunctions_Advanced] as seen below: ```csharp [TypeConverter(typeof(MyCustomTypeConverter))] diff --git a/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs b/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs index 1e4aef5d341a..785fbb247148 100644 --- a/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs +++ b/dotnet/samples/Concepts/Agents/Legacy_AgentAuthoring.cs @@ -21,7 +21,7 @@ public class Legacy_AgentAuthoring(ITestOutputHelper output) : BaseTest(output) [Fact(Skip = "This test take more than 2 minutes to execute")] public async Task RunAgentAsync() { - WriteLine("======== Example73_AgentAuthoring ========"); + WriteLine($"======== {nameof(Legacy_AgentAuthoring)} ========"); try { // Initialize the agent with tools @@ -43,7 +43,7 @@ public async Task RunAgentAsync() [Fact(Skip = "This test take more than 2 minutes to execute")] public async Task RunAsPluginAsync() { - WriteLine("======== Example73_AgentAuthoring ========"); + WriteLine($"======== {nameof(Legacy_AgentAuthoring)} ========"); try { // Initialize the agent with tools diff --git a/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs b/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs index 1016f30d2fa2..bbba5274ccdd 100644 --- a/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs +++ b/dotnet/samples/Concepts/Kernel/CustomAIServiceSelector.cs @@ -16,7 +16,7 @@ public class CustomAIServiceSelector(ITestOutputHelper output) : BaseTest(output [Fact] public async Task RunAsync() { - WriteLine("======== Example62_CustomAIServiceSelector ========"); + WriteLine($"======== {nameof(CustomAIServiceSelector)} ========"); // Build a kernel with multiple chat completion services var builder = Kernel.CreateBuilder() diff --git a/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs index 37711fca767e..61d5a4bd394d 100644 --- a/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs +++ b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenAI_AzureKeyVault.cs @@ -33,7 +33,7 @@ public class CreatePluginFromOpenAI_AzureKeyVault(ITestOutputHelper output) : Ba /// dotnet user-secrets set "KeyVault:ClientId" "your_client_id" /// dotnet user-secrets set "KeyVault:ClientSecret" "your_secret" /// - /// 5. Replace your tenant ID with the "TENANT_ID" placeholder in dotnet/samples/KernelSyntaxExamples/Resources/22-ai-plugin.json + /// 5. Replace your tenant ID with the "TENANT_ID" placeholder in dotnet/samples/Concepts/Resources/22-ai-plugin.json /// [Fact(Skip = "Setup credentials")] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs index 2817dda10f92..cd632e4db33d 100644 --- a/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs +++ b/dotnet/samples/Concepts/Plugins/CreatePluginFromOpenApiSpec_Jira.cs @@ -31,7 +31,7 @@ public class CreatePluginFromOpenApiSpec_Jira(ITestOutputHelper output) : BaseTe /// 3. You can find your domain under the "Products" tab in your account management page. /// To go to your account management page, click on your profile picture in the top right corner of your Jira /// instance then select "Manage account". - /// 4. Configure the secrets as described by the ReadMe.md in the dotnet/samples/KernelSyntaxExamples folder. + /// 4. Configure the secrets as described by the ReadMe.md in the dotnet/samples/Concepts folder. /// [Fact(Skip = "Setup credentials")] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs b/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs index 91d5b6a3cb04..a924bf042386 100644 --- a/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs +++ b/dotnet/samples/Concepts/Plugins/ImportPluginFromGrpc.cs @@ -6,7 +6,7 @@ namespace Examples; // This example shows how to use gRPC plugins. -public class Example35_GrpcPlugins(ITestOutputHelper output) : BaseTest(output) +public class ImportPluginFromGrpc(ITestOutputHelper output) : BaseTest(output) { [Fact(Skip = "Setup crendentials")] public async Task RunAsync() diff --git a/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs b/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs index d19a74ea37c1..716a7777ef97 100644 --- a/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs +++ b/dotnet/samples/Concepts/PromptTemplates/MultiplePromptTemplates.cs @@ -17,7 +17,7 @@ public class MultiplePromptTemplates(ITestOutputHelper output) : BaseTest(output [InlineData("handlebars", "Hello AI, my name is {{name}}. What is the origin of my name?")] public Task RunAsync(string templateFormat, string prompt) { - WriteLine("======== Example64_MultiplePromptTemplates ========"); + WriteLine($"======== {nameof(MultiplePromptTemplates)} ========"); Kernel kernel = Kernel.CreateBuilder() .AddAzureOpenAIChatCompletion( diff --git a/dotnet/samples/Concepts/Properties/AssemblyInfo.cs b/dotnet/samples/Concepts/Properties/AssemblyInfo.cs index 109d37464884..f17c9f3e91ee 100644 --- a/dotnet/samples/Concepts/Properties/AssemblyInfo.cs +++ b/dotnet/samples/Concepts/Properties/AssemblyInfo.cs @@ -6,29 +6,15 @@ // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. -[assembly: AssemblyTitle("Properties")] -[assembly: AssemblyDescription("")] +[assembly: System.CLSCompliantAttribute(false)] +[assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("5ee045b0-aea3-4f08-8d31-32d1a6f8fed0")] +[assembly: AssemblyTitle("Concepts")] +[assembly: AssemblyDescription("Semantic Kernel Concepts Samples Project")] [assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("")] -[assembly: AssemblyProduct("Properties")] +[assembly: AssemblyCompany("Microsoft")] +[assembly: AssemblyProduct("Concepts")] [assembly: AssemblyCopyright("Copyright © 2024")] -[assembly: AssemblyTrademark("")] -[assembly: AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. -[assembly: ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM -[assembly: Guid("7a06e178-6ef3-4d45-b427-3a5268d51913")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] + +[assembly: ComVisible(false)] diff --git a/dotnet/samples/Concepts/README.md b/dotnet/samples/Concepts/README.md index feabf5dff1c5..63f4878727ea 100644 --- a/dotnet/samples/Concepts/README.md +++ b/dotnet/samples/Concepts/README.md @@ -22,4 +22,4 @@ This section contains code snippets that demonstrate the usage of Semantic Kerne | PromptTemplates | Using [`Templates`](https://github.com/microsoft/semantic-kernel/blob/main/dotnet/src/SemanticKernel.Abstractions/PromptTemplate/IPromptTemplate.cs) with parametrization for `Prompt` rendering | | RAG | Different ways of `RAG` (Retrieval-Augmented Generation) | | LocalModels | Using services against `LocalModels` to run models locally | -| Agents | Different ways of using [`Agents`](./AgentSyntax/README.md) | +| Agents | Different ways of using [`Agents`](./Agents/README.md) | diff --git a/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs index cef321943993..bfb7538db2c6 100644 --- a/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs +++ b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs @@ -10,7 +10,7 @@ namespace Examples; // The following example shows how to use Semantic Kernel with HuggingFace API. -public class Example20_HuggingFace : BaseTest +public class HuggingFace_TextGeneration(ITestOutputHelper helper) : BaseTest(helper) { /// /// This example uses HuggingFace Inference API to access hosted models. @@ -95,8 +95,4 @@ public async Task RunLlamaExampleAsync() WriteLine(result.GetValue()); } - - public Example20_HuggingFace(ITestOutputHelper output) : base(output) - { - } } diff --git a/dotnet/samples/GettingStarted/README.md b/dotnet/samples/GettingStarted/README.md index 300251e22dcb..e295461597e4 100644 --- a/dotnet/samples/GettingStarted/README.md +++ b/dotnet/samples/GettingStarted/README.md @@ -15,7 +15,7 @@ You can also use environment variables if you prefer. To set your secrets with Secret Manager: ``` -cd dotnet/samples/KernelSyntaxExamples +cd dotnet/samples/Concepts dotnet user-secrets init diff --git a/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs index def6bb2ea74d..475999d2f86a 100644 --- a/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step1_Agent.cs @@ -26,7 +26,7 @@ public async Task RunAsync() Kernel = this.CreateKernelWithChatCompletion(), }; - // Create a chat for agent interaction. For more, see: Example03_Chat. + /// Create a chat for agent interaction. For more, . AgentGroupChat chat = new(); // Respond to user input diff --git a/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs index a3c8551643bb..0661155ae7d2 100644 --- a/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs +++ b/dotnet/samples/GettingStartedWithAgents/Step2_Plugins.cs @@ -33,7 +33,7 @@ public async Task RunAsync() KernelPlugin plugin = KernelPluginFactory.CreateFromType(); agent.Kernel.Plugins.Add(plugin); - // Create a chat for agent interaction. For more, see: Example03_Chat. + /// Create a chat for agent interaction. For more, . AgentGroupChat chat = new(); // Respond to user input, invoking functions where appropriate. diff --git a/dotnet/samples/README.md b/dotnet/samples/README.md index 4b1b9d4c65c5..01e3f99e8667 100644 --- a/dotnet/samples/README.md +++ b/dotnet/samples/README.md @@ -1,9 +1,9 @@ ## Kernel Samples -| Type | Description | -| --------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | -| [`Getting Started`](./GettingStarted/README.md) | Take this step by step tutorial to get started with the Semantic Kernel and get introduced to the key concepts. | -| [`Concepts`](./Concepts/README.md) | This section contains focussed samples which illustrate all of the concepts included in the Semantic Kernel. | -| [`Demos`](./Demos/README.md) | Look here to find a sample which demonstrate how to use many of Semantic Kernel features. | -| [`LearnResources`](./LearnResources/README.md) | Code snippets that are related to online documentation sources like Microsoft Learn, DevBlogs and others | -| [`KernelSyntaxExamples`](./KernelSyntaxExamples/README.md) | ⚠️ Work in progress: Moving into `Concepts`. | +| Type | Description | +| ----------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | +| [`Getting Started`](./GettingStarted/README.md) | Take this step by step tutorial to get started with the Semantic Kernel and get introduced to the key concepts. | +| [`Concepts`](./Concepts/README.md) | This section contains focussed samples which illustrate all of the concepts included in the Semantic Kernel. | +| [`Demos`](./Demos/README.md) | Look here to find a sample which demonstrate how to use many of Semantic Kernel features. | +| [`LearnResources`](./LearnResources/README.md) | Code snippets that are related to online documentation sources like Microsoft Learn, DevBlogs and others | +| `KernelSyntaxExamples` | ⚠️ Work in progress: Moving into `Concepts`. | diff --git a/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md b/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md index 2d6e09fbca90..958adfc5aa2c 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md @@ -21,7 +21,7 @@ docker-compose up -d --build 3. Use Semantic Kernel with Chroma, using server local endpoint `http://localhost:8000`: - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp const string endpoint = "http://localhost:8000"; diff --git a/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md b/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md index e7685b1b0adb..17c4fdcadf8e 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md @@ -7,7 +7,7 @@ This connector uses [Azure Data Explorer (Kusto)](https://learn.microsoft.com/en 1. Create a cluster and database in Azure Data Explorer (Kusto) - see https://learn.microsoft.com/en-us/azure/data-explorer/create-cluster-and-database?tabs=free 2. To use Kusto as a semantic memory store, use the following code: - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp using Kusto.Data; diff --git a/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md b/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md index 8619aa4dc5ea..cf66a6801202 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md @@ -19,7 +19,7 @@ docker-compose up -d ``` 3. Use Semantic Kernel with Milvus, connecting to `localhost` with the default (gRPC) port of 1536: - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp using MilvusMemoryStore memoryStore = new("localhost"); diff --git a/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md b/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md index 74b3dc8c35c5..214c1e27fa35 100644 --- a/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md @@ -25,7 +25,7 @@ This connector uses [MongoDB Atlas Vector Search](https://www.mongodb.com/produc ``` 4. Create the MongoDB memory store - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp var connectionString = "MONGODB ATLAS CONNECTION STRING" diff --git a/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md b/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md index 4941821a3fe1..6218b1d0c06a 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md @@ -34,7 +34,7 @@ sk_demo=# CREATE EXTENSION vector; > Note, "Azure Cosmos DB for PostgreSQL" uses `SELECT CREATE_EXTENSION('vector');` to enable the extension. 3. To use Postgres as a semantic memory store: - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp NpgsqlDataSourceBuilder dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Port=5432;Database=sk_demo;User Id=postgres;Password=mysecretpassword"); diff --git a/dotnet/src/Connectors/Connectors.Memory.Redis/README.md b/dotnet/src/Connectors/Connectors.Memory.Redis/README.md index 62e7fb3ec031..2cd8adcc2733 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Redis/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Redis/README.md @@ -23,7 +23,7 @@ docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:la ``` 2. To use Redis as a semantic memory store: - > See [Example 14](../../../samples/KernelSyntaxExamples/Example14_SemanticMemory.cs) and [Example 15](../../../samples/KernelSyntaxExamples/Example15_TextMemoryPlugin.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp // ConnectionMultiplexer should be a singleton instance in your application, please consider to dispose of it when your application shuts down. diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/CancelKernelEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/CancelKernelEventArgs.cs index ed07decf7f27..5d268974e828 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/CancelKernelEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/CancelKernelEventArgs.cs @@ -9,7 +9,7 @@ namespace Microsoft.SemanticKernel; /// Provides an for cancelable operations related /// to -based operations. /// -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public abstract class CancelKernelEventArgs : KernelEventArgs { /// diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokedEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokedEventArgs.cs index 0317cb5cf860..de32ad666716 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokedEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokedEventArgs.cs @@ -7,7 +7,7 @@ namespace Microsoft.SemanticKernel; /// /// Provides a used in events just after a function is invoked. /// -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public sealed class FunctionInvokedEventArgs : CancelKernelEventArgs { /// diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokingEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokingEventArgs.cs index 99396a137bfe..803c9acc72fd 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokingEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/FunctionInvokingEventArgs.cs @@ -7,7 +7,7 @@ namespace Microsoft.SemanticKernel; /// /// Provides a used in events just before a function is invoked. /// -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public sealed class FunctionInvokingEventArgs : CancelKernelEventArgs { /// diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/KernelEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/KernelEventArgs.cs index 6c659dc53f33..d7bb3701232e 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/KernelEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/KernelEventArgs.cs @@ -6,7 +6,7 @@ namespace Microsoft.SemanticKernel; /// Provides an for operations related to -based operations. -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public abstract class KernelEventArgs : EventArgs { /// diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderedEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderedEventArgs.cs index 83f14a76aafd..373c8c1e0a01 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderedEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderedEventArgs.cs @@ -8,7 +8,7 @@ namespace Microsoft.SemanticKernel; /// /// Provides a used in events raised just after a prompt has been rendered. /// -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public sealed class PromptRenderedEventArgs : CancelKernelEventArgs { private string _renderedPrompt; diff --git a/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderingEventArgs.cs b/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderingEventArgs.cs index b808a6e8c293..2d86f989da98 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderingEventArgs.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Events/PromptRenderingEventArgs.cs @@ -7,7 +7,7 @@ namespace Microsoft.SemanticKernel; /// /// Provides a used in events raised just before a prompt is rendered. /// -[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] +[Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public sealed class PromptRenderingEventArgs : KernelEventArgs { /// diff --git a/dotnet/src/SemanticKernel.Abstractions/Kernel.cs b/dotnet/src/SemanticKernel.Abstractions/Kernel.cs index db70310000d5..abe569008c46 100644 --- a/dotnet/src/SemanticKernel.Abstractions/Kernel.cs +++ b/dotnet/src/SemanticKernel.Abstractions/Kernel.cs @@ -602,31 +602,31 @@ private static bool IsNotEmpty(IEnumerable enumerable) => /// Provides an event that's raised prior to a function's invocation. /// [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public event EventHandler? FunctionInvoking; /// /// Provides an event that's raised after a function's invocation. /// [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public event EventHandler? FunctionInvoked; /// /// Provides an event that's raised prior to a prompt being rendered. /// [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public event EventHandler? PromptRendering; /// /// Provides an event that's raised after a prompt is rendered. /// [EditorBrowsable(EditorBrowsableState.Never)] - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] public event EventHandler? PromptRendered; - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] internal FunctionInvokingEventArgs? OnFunctionInvoking(KernelFunction function, KernelArguments arguments) { FunctionInvokingEventArgs? eventArgs = null; @@ -639,7 +639,7 @@ private static bool IsNotEmpty(IEnumerable enumerable) => return eventArgs; } - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] internal FunctionInvokedEventArgs? OnFunctionInvoked(KernelFunction function, KernelArguments arguments, FunctionResult result) { FunctionInvokedEventArgs? eventArgs = null; @@ -652,7 +652,7 @@ private static bool IsNotEmpty(IEnumerable enumerable) => return eventArgs; } - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] internal PromptRenderingEventArgs? OnPromptRendering(KernelFunction function, KernelArguments arguments) { PromptRenderingEventArgs? eventArgs = null; @@ -665,7 +665,7 @@ private static bool IsNotEmpty(IEnumerable enumerable) => return eventArgs; } - [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/KernelSyntaxExamples/Getting_Started/Step7_Observability.cs of Semantic Kernel repository.")] + [Obsolete("Events are deprecated in favor of filters. Example in dotnet/samples/GettingStarted/Step7_Observability.cs of Semantic Kernel repository.")] internal PromptRenderedEventArgs? OnPromptRendered(KernelFunction function, KernelArguments arguments, string renderedPrompt) { PromptRenderedEventArgs? eventArgs = null; From cef1abc55ecc70f5fa9a1860ca21d8881c105dd1 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Sat, 27 Apr 2024 08:44:53 +0100 Subject: [PATCH 20/24] Memory Path Correction --- dotnet/src/Connectors/Connectors.Memory.Chroma/README.md | 2 +- dotnet/src/Connectors/Connectors.Memory.Kusto/README.md | 2 +- dotnet/src/Connectors/Connectors.Memory.Milvus/README.md | 2 +- dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md | 2 +- dotnet/src/Connectors/Connectors.Memory.Postgres/README.md | 2 +- dotnet/src/Connectors/Connectors.Memory.Redis/README.md | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md b/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md index 958adfc5aa2c..04d5e5526f10 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Chroma/README.md @@ -21,7 +21,7 @@ docker-compose up -d --build 3. Use Semantic Kernel with Chroma, using server local endpoint `http://localhost:8000`: - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp const string endpoint = "http://localhost:8000"; diff --git a/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md b/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md index 17c4fdcadf8e..f7c276c7e9c3 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Kusto/README.md @@ -7,7 +7,7 @@ This connector uses [Azure Data Explorer (Kusto)](https://learn.microsoft.com/en 1. Create a cluster and database in Azure Data Explorer (Kusto) - see https://learn.microsoft.com/en-us/azure/data-explorer/create-cluster-and-database?tabs=free 2. To use Kusto as a semantic memory store, use the following code: - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp using Kusto.Data; diff --git a/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md b/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md index cf66a6801202..b4d8e71d5a2c 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Milvus/README.md @@ -19,7 +19,7 @@ docker-compose up -d ``` 3. Use Semantic Kernel with Milvus, connecting to `localhost` with the default (gRPC) port of 1536: - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp using MilvusMemoryStore memoryStore = new("localhost"); diff --git a/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md b/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md index 214c1e27fa35..4a6ddcda3483 100644 --- a/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.MongoDB/README.md @@ -25,7 +25,7 @@ This connector uses [MongoDB Atlas Vector Search](https://www.mongodb.com/produc ``` 4. Create the MongoDB memory store - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp var connectionString = "MONGODB ATLAS CONNECTION STRING" diff --git a/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md b/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md index 6218b1d0c06a..35c80a45087a 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Postgres/README.md @@ -34,7 +34,7 @@ sk_demo=# CREATE EXTENSION vector; > Note, "Azure Cosmos DB for PostgreSQL" uses `SELECT CREATE_EXTENSION('vector');` to enable the extension. 3. To use Postgres as a semantic memory store: - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp NpgsqlDataSourceBuilder dataSourceBuilder = new NpgsqlDataSourceBuilder("Host=localhost;Port=5432;Database=sk_demo;User Id=postgres;Password=mysecretpassword"); diff --git a/dotnet/src/Connectors/Connectors.Memory.Redis/README.md b/dotnet/src/Connectors/Connectors.Memory.Redis/README.md index 2cd8adcc2733..3827e46918a4 100644 --- a/dotnet/src/Connectors/Connectors.Memory.Redis/README.md +++ b/dotnet/src/Connectors/Connectors.Memory.Redis/README.md @@ -23,7 +23,7 @@ docker run -d --name redis-stack-server -p 6379:6379 redis/redis-stack-server:la ``` 2. To use Redis as a semantic memory store: - > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. + > See [Example 14](../../../samples/Concepts/Memory/SemanticTextMemory_Building.cs) and [Example 15](../../../samples/Concepts/Memory/TextMemoryPlugin_MultipleMemoryStore.cs) for more memory usage examples with the kernel. ```csharp // ConnectionMultiplexer should be a singleton instance in your application, please consider to dispose of it when your application shuts down. From a55a0a892cc3f60b0c8777a6f41626c4f3cfae9e Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Mon, 29 Apr 2024 08:22:51 +0100 Subject: [PATCH 21/24] Removing AssemblyBuild error --- docs/decisions/0042-samples-restructure.md | 2 +- dotnet/samples/Concepts/Concepts.csproj | 2 +- .../Concepts/Properties/AssemblyInfo.cs | 20 ------------------- 3 files changed, 2 insertions(+), 22 deletions(-) delete mode 100644 dotnet/samples/Concepts/Properties/AssemblyInfo.cs diff --git a/docs/decisions/0042-samples-restructure.md b/docs/decisions/0042-samples-restructure.md index 2284aa040b30..6dcec8e934d5 100644 --- a/docs/decisions/0042-samples-restructure.md +++ b/docs/decisions/0042-samples-restructure.md @@ -37,7 +37,7 @@ informed: | Current Folder | Proposal | | ------------------------------------ | ------------------------------------------------------------------- | -| KernelSyntaxExamples/Getting_Started | Move into `Getting Started` | +| KernelSyntaxExamples/Getting_Started | Move into `GettingStarted` | | KernelSyntaxExamples/`Examples??_*` | Decompose into `Concepts` on multiple conceptual subfolders | | AgentSyntaxExamples | Decompose into `Concepts` on `Agents` specific subfolders. | | DocumentationExamples | Move into `LearnResources` subfolder and rename to `MicrosoftLearn` | diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 773a4473407e..19f220b60c97 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -4,7 +4,6 @@ Concepts 1.0.0.0 1.0.0.0 - false net8.0 enable @@ -16,6 +15,7 @@ Library 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 false + false diff --git a/dotnet/samples/Concepts/Properties/AssemblyInfo.cs b/dotnet/samples/Concepts/Properties/AssemblyInfo.cs deleted file mode 100644 index f17c9f3e91ee..000000000000 --- a/dotnet/samples/Concepts/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,20 +0,0 @@ -// Copyright (c) Microsoft. All rights reserved. - -using System.Reflection; -using System.Runtime.InteropServices; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -[assembly: System.CLSCompliantAttribute(false)] -[assembly: Microsoft.Extensions.Configuration.UserSecrets.UserSecretsIdAttribute("5ee045b0-aea3-4f08-8d31-32d1a6f8fed0")] -[assembly: AssemblyTitle("Concepts")] -[assembly: AssemblyDescription("Semantic Kernel Concepts Samples Project")] -[assembly: AssemblyConfiguration("")] -[assembly: AssemblyCompany("Microsoft")] -[assembly: AssemblyProduct("Concepts")] -[assembly: AssemblyCopyright("Copyright © 2024")] -[assembly: AssemblyVersion("1.0.0.0")] -[assembly: AssemblyFileVersion("1.0.0.0")] - -[assembly: ComVisible(false)] From 1bc4d6dfdda4080619a6e0846b3d6dc9f7283f7e Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Mon, 29 Apr 2024 11:54:05 +0100 Subject: [PATCH 22/24] Fix usings, removing versioning --- dotnet/samples/Concepts/Concepts.csproj | 18 ++++++++++++++---- .../HuggingFace_ChatCompletionWithTGI.cs | 6 +----- .../MultipleProviders_ChatCompletion.cs | 6 +----- .../Memory/HuggingFace_EmbeddingGeneration.cs | 6 +----- 4 files changed, 17 insertions(+), 19 deletions(-) diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 19f220b60c97..5b037561d1c1 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -2,11 +2,8 @@ Concepts - 1.0.0.0 - 1.0.0.0 net8.0 - enable enable false true @@ -15,7 +12,6 @@ Library 5ee045b0-aea3-4f08-8d31-32d1a6f8fed0 false - false @@ -83,6 +79,20 @@ + + + + + + + + + + + + + + diff --git a/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs b/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs index c404f4d52295..97bcfb1c07e2 100644 --- a/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs +++ b/dotnet/samples/Concepts/LocalModels/HuggingFace_ChatCompletionWithTGI.cs @@ -9,7 +9,7 @@ namespace Examples; // The following example shows how to use Semantic Kernel with HuggingFace API. -public class HuggingFace_ChatCompletionWithTGI : BaseTest +public class HuggingFace_ChatCompletionWithTGI(ITestOutputHelper output) : BaseTest(output) { /// /// Follow steps in to setup HuggingFace local Text Generation Inference HTTP server. @@ -86,8 +86,4 @@ public async Task RunTGI_StreamingChatCompletionAsync() Write(chatMessageChunk.Content); } } - - public HuggingFace_ChatCompletionWithTGI(ITestOutputHelper output) : base(output) - { - } } diff --git a/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs b/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs index b294f6003b5f..73dcecdb068c 100644 --- a/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs +++ b/dotnet/samples/Concepts/LocalModels/MultipleProviders_ChatCompletion.cs @@ -28,7 +28,7 @@ namespace Examples; /// 2. docker run -ti -p 8080:8080 localai/localai:v2.12.3-ffmpeg-core phi-2 /// 3. Run the LocalAI examples. /// -public class MultipleProviders_ChatCompletion : BaseTest +public class MultipleProviders_ChatCompletion(ITestOutputHelper output) : BaseTest(output) { [Theory(Skip = "Manual configuration needed")] [InlineData("LMStudio", "http://localhost:1234", "llama2")] // Setup Llama2 as the model in LM Studio UI and start the Message API Server on http://localhost:1234 @@ -92,8 +92,4 @@ Sign the mail as AI Assistant. this.WriteLine(word); }; } - - public MultipleProviders_ChatCompletion(ITestOutputHelper output) : base(output) - { - } } diff --git a/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs b/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs index 57ffeda8ce1e..d960d707cf46 100644 --- a/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs +++ b/dotnet/samples/Concepts/Memory/HuggingFace_EmbeddingGeneration.cs @@ -10,7 +10,7 @@ namespace Examples; // The following example shows how to use Semantic Kernel with HuggingFace API. -public class HuggingFace_EmbeddingGeneration : BaseTest +public class HuggingFace_EmbeddingGeneration(ITestOutputHelper output) : BaseTest(output) { [RetryFact(typeof(HttpOperationException))] public async Task RunInferenceApiEmbeddingAsync() @@ -30,8 +30,4 @@ public async Task RunInferenceApiEmbeddingAsync() this.WriteLine($"Generated {embeddings.Count} embeddings for the provided text"); } - - public HuggingFace_EmbeddingGeneration(ITestOutputHelper output) : base(output) - { - } } From 2bee5a9ba7e57d1e09d5874d12cb73ed200bf6f2 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Mon, 29 Apr 2024 12:09:31 +0100 Subject: [PATCH 23/24] Fix warnings --- dotnet/samples/Concepts/Concepts.csproj | 7 ------- 1 file changed, 7 deletions(-) diff --git a/dotnet/samples/Concepts/Concepts.csproj b/dotnet/samples/Concepts/Concepts.csproj index 5b037561d1c1..31be3a10499e 100644 --- a/dotnet/samples/Concepts/Concepts.csproj +++ b/dotnet/samples/Concepts/Concepts.csproj @@ -79,18 +79,11 @@ - - - - - - - From 5a6dbf4e1216aa7668500d86f5195e0ff53f0322 Mon Sep 17 00:00:00 2001 From: Roger Barreto <19890735+RogerBarreto@users.noreply.github.com> Date: Mon, 29 Apr 2024 12:33:08 +0100 Subject: [PATCH 24/24] Hugging Face Test update --- .../TextGeneration/HuggingFace_TextGeneration.cs | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs index bfb7538db2c6..49faef919bae 100644 --- a/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs +++ b/dotnet/samples/Concepts/TextGeneration/HuggingFace_TextGeneration.cs @@ -12,6 +12,7 @@ namespace Examples; // The following example shows how to use Semantic Kernel with HuggingFace API. public class HuggingFace_TextGeneration(ITestOutputHelper helper) : BaseTest(helper) { + private const string DefaultModel = "HuggingFaceH4/zephyr-7b-beta"; /// /// This example uses HuggingFace Inference API to access hosted models. /// More information here: @@ -23,7 +24,7 @@ public async Task RunInferenceApiExampleAsync() Kernel kernel = Kernel.CreateBuilder() .AddHuggingFaceTextGeneration( - model: TestConfiguration.HuggingFace.ModelId, + model: TestConfiguration.HuggingFace.ModelId ?? DefaultModel, apiKey: TestConfiguration.HuggingFace.ApiKey) .Build(); @@ -34,16 +35,22 @@ public async Task RunInferenceApiExampleAsync() WriteLine(result.GetValue()); } + /// + /// Some Hugging Face models support streaming responses, configure using the HuggingFace ModelId setting. + /// + /// + /// Tested with HuggingFaceH4/zephyr-7b-beta model. + /// [RetryFact(typeof(HttpOperationException))] public async Task RunStreamingExampleAsync() { - WriteLine("\n======== HuggingFace zephyr-7b-beta streaming example ========\n"); + string model = TestConfiguration.HuggingFace.ModelId ?? DefaultModel; - const string Model = "HuggingFaceH4/zephyr-7b-beta"; + WriteLine($"\n======== HuggingFace {model} streaming example ========\n"); Kernel kernel = Kernel.CreateBuilder() .AddHuggingFaceTextGeneration( - model: Model, + model: model, apiKey: TestConfiguration.HuggingFace.ApiKey) .Build();