diff --git a/ChatApp.WebApi/Program.cs b/ChatApp.WebApi/Program.cs index 04f1161..c32a80e 100644 --- a/ChatApp.WebApi/Program.cs +++ b/ChatApp.WebApi/Program.cs @@ -3,7 +3,7 @@ using System.Text.Json; using System.Text.Json.Serialization; - +using ChatApp.WebApi; using ChatApp.WebApi.Interfaces; using ChatApp.WebApi.Model; using ChatApp.WebApi.Services; @@ -11,6 +11,7 @@ var builder = WebApplication.CreateBuilder(args); builder.AddServiceDefaults(); +builder.AddSemanticKernelTelemetry(); builder.AddAzureOpenAIClient("openAi"); diff --git a/ChatApp.WebApi/SemanticKernelTelemetryExtensions.cs b/ChatApp.WebApi/SemanticKernelTelemetryExtensions.cs new file mode 100644 index 0000000..57e48e2 --- /dev/null +++ b/ChatApp.WebApi/SemanticKernelTelemetryExtensions.cs @@ -0,0 +1,43 @@ +using OpenTelemetry.Metrics; +using OpenTelemetry.Trace; + +namespace ChatApp.WebApi +{ + // Adds OpenTelemetry support for the Semantic Kernel. + // As the semantic conventions for gen_ai telemetry are still experimental, + // it needs to be enabled with an App Context switch. + // Sensitive mode will add the chat messages to the telemetry, which is useful + // for debugging but should not be used in production. + // For more details see https://github.com/microsoft/semantic-kernel/blob/main/dotnet/samples/Demos/TelemetryWithAppInsights/README.md + + public static class SemanticKernelTelemetryExtensions + { + public static IHostApplicationBuilder AddSemanticKernelTelemetry(this IHostApplicationBuilder builder) + { + if (builder.Environment.IsDevelopment()) + { + AppContext.SetSwitch("Microsoft.SemanticKernel.Experimental.GenAI.EnableOTelDiagnosticsSensitive", true); + } + else + { + AppContext.SetSwitch("Microsoft.SemanticKernel.Experimental.GenAI.EnableOTelDiagnostics", true); + } + + + builder.Services.AddOpenTelemetry() + .WithMetrics(metrics => + { + metrics.AddMeter("Microsoft.SemanticKernel*") + .AddMeter("Azure.*"); + }) + .WithTracing(tracing => + { + tracing.AddSource("Microsoft.SemanticKernel.*") + .AddSource("Azure.*") + .AddSource("Microsoft.ML.*"); + }); + + return builder; + } + } +}