-
Notifications
You must be signed in to change notification settings - Fork 2.1k
.NET: Add AIClient HTTP Traffic Tracing sample with logging capabilities #3053
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Vijay-Nirmal
wants to merge
10
commits into
microsoft:main
from
Vijay-Nirmal:sample/632-AIClientHttpTrafficTracing
Closed
Changes from 2 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
604777e
Add AIClient HTTP Traffic Tracing sample with logging capabilities
Vijay-Nirmal 46c6c84
Refactor AIClient pirate assistant interaction by removing unnecessar…
Vijay-Nirmal 2e86496
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal e019278
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal 45a487a
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal a5459db
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal 3092b0e
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal 0ce9f50
Update dotnet/samples/GettingStarted/Observability/AIClientHttpTraffi…
Vijay-Nirmal 71b6a2c
Fixed copilot review comments
Vijay-Nirmal 340941f
Merge branch 'main' into sample/632-AIClientHttpTrafficTracing
Vijay-Nirmal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
22 changes: 22 additions & 0 deletions
22
...GettingStarted/Observability/AIClientHttpTrafficTracing/AIClientHttpTrafficTracing.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,22 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
|
|
||
| <PropertyGroup> | ||
| <OutputType>Exe</OutputType> | ||
| <TargetFramework>net10.0</TargetFramework> | ||
| <ImplicitUsings>enable</ImplicitUsings> | ||
| <Nullable>enable</Nullable> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Azure.AI.OpenAI" /> | ||
| <PackageReference Include="Azure.Identity" /> | ||
| <PackageReference Include="Microsoft.Extensions.AI.OpenAI" /> | ||
| <PackageReference Include="Microsoft.Extensions.Logging.Console" /> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI.OpenAI\Microsoft.Agents.AI.OpenAI.csproj" /> | ||
| <ProjectReference Include="..\..\..\..\src\Microsoft.Agents.AI\Microsoft.Agents.AI.csproj" /> | ||
| </ItemGroup> | ||
|
|
||
| </Project> | ||
75 changes: 75 additions & 0 deletions
75
dotnet/samples/GettingStarted/Observability/AIClientHttpTrafficTracing/Program.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
|
Vijay-Nirmal marked this conversation as resolved.
|
||
| using System.ClientModel.Primitives; | ||
| using Azure.AI.OpenAI; | ||
| using Azure.Identity; | ||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| var endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT environment variable is not set."); | ||
| var deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
|
|
||
| var services = new ServiceCollection(); | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
| services.AddLogging(loggingBuilder => | ||
| { | ||
| loggingBuilder.AddConsole(); | ||
| loggingBuilder.AddFilter("System.ClientModel.Primitives.MessageLoggingPolicy", LogLevel.Debug); // For Request and Response body logging we need to set Debug level | ||
| /* If uses in ASP.NET Core, with appsettings then this can be configured in appsettings.json as: | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning" | ||
| "System.ClientModel.Primitives.MessageLoggingPolicy"": "Debug" | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
| } | ||
| } | ||
| } | ||
| */ | ||
| }); | ||
|
|
||
| services.AddChatClient(provider => | ||
| { | ||
| var clientLoggingOptions = new ClientLoggingOptions | ||
| { | ||
| EnableLogging = true, // Enable logging overall | ||
| EnableMessageContentLogging = true, // Enable request and response body logging | ||
| MessageContentSizeLimit = 5000, // Limit size of logged content. If Null or Not set, then default value will be 4 * 1024 characters | ||
| EnableMessageLogging = true, // Logging the Request and Response Url and Header information. If Null or Not set, then default value will be true | ||
| LoggerFactory = provider.GetRequiredService<ILoggerFactory>() | ||
| }; | ||
| clientLoggingOptions.AllowedHeaderNames.Add("Authorization"); // Logging sensitive header information, by default values will be REDACTED | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
|
|
||
| /* Switch to OpenAI Compatible SDK using below code | ||
| var clientOptions = new OpenAIClientOptions() | ||
| { | ||
| Endpoint = new Uri("https://endpoint"), | ||
| ClientLoggingOptions = clientLoggingOptions | ||
| }; | ||
| new OpenAIClient(new ApiKeyCredential("<apiKey/accessKey>"), clientOptions) | ||
| .GetChatClient("modelName") | ||
| .AsIChatClient(); | ||
| */ | ||
|
|
||
| return new AzureOpenAIClient(new Uri(endpoint), new AzureCliCredential(), new AzureOpenAIClientOptions() // Use OpenAIClientOptions of OpenAIClient, similar options for other clients | ||
| { | ||
| ClientLoggingOptions = clientLoggingOptions | ||
| }) | ||
| .GetChatClient(deploymentName) | ||
| .AsIChatClient(); | ||
| }); | ||
|
|
||
| var serviceProvider = services.BuildServiceProvider(); | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
|
|
||
| var chatClient = serviceProvider.GetRequiredService<IChatClient>(); | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
| var pirateAssistant = chatClient.CreateAIAgent("You are a pirate assistant. Answer questions in short pirate speak."); | ||
|
|
||
|
Vijay-Nirmal marked this conversation as resolved.
|
||
| var userInput = "Who are you?"; | ||
| Console.WriteLine($"You: {userInput}\n"); | ||
|
Vijay-Nirmal marked this conversation as resolved.
|
||
| var response = await pirateAssistant.RunAsync(userInput); | ||
| Console.WriteLine($"\nPirate Assistant: {response}"); | ||
|
|
||
|
Vijay-Nirmal marked this conversation as resolved.
|
||
| /*await foreach (var item in pirateAssistant.RunStreamingAsync(userInput)) // For Streaming responses (RunStreamingAsync), there will be multiple log entries | ||
| { | ||
| Console.Write(item); | ||
| }*/ | ||
78 changes: 78 additions & 0 deletions
78
dotnet/samples/GettingStarted/Observability/AIClientHttpTrafficTracing/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,78 @@ | ||
| # AIClient HTTP Traffic Tracing | ||
|
|
||
| This sample shows how to enable **HTTP request/response logging** for LLM calls (including request/response bodies) for any `AIClient`. | ||
|
|
||
| It uses the `ClientLoggingOptions` pipeline to print HTTP details to the `ILogger` so you can troubleshoot prompts, headers, and responses. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| - Azure CLI login (this sample uses `AzureCliCredential`): | ||
| - `az login` | ||
| - Environment variables: | ||
| - `AZURE_OPENAI_ENDPOINT` (e.g. `https://{resource-name}.openai.azure.com/`) | ||
| - `AZURE_OPENAI_DEPLOYMENT_NAME` (optional; defaults to `gpt-4o-mini`) | ||
|
|
||
| Switch to OpenAI Compatible SDK using below code | ||
| ```csharp | ||
| var clientOptions = new OpenAIClientOptions() | ||
| { | ||
| Endpoint = new Uri("https://endpoint"), | ||
| ClientLoggingOptions = clientLoggingOptions | ||
| }; | ||
| new OpenAIClient(new ApiKeyCredential("<apiKey/accessKey>"), clientOptions) | ||
| .GetChatClient("modelName") | ||
| .AsIChatClient(); | ||
| ``` | ||
|
|
||
| ## Run | ||
|
|
||
| From the repo root: | ||
|
|
||
| ```powershell | ||
| cd samples\GettingStarted\Observability\AIClientHttpTrafficTracing | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
| dotnet run | ||
| ``` | ||
|
|
||
| ## Enable HTTP traffic logging | ||
|
|
||
| This sample enables logging in two places: | ||
|
|
||
| 1. **Enable HTTP logging on the client** | ||
|
|
||
| In [Program.cs](Program.cs), the sample configures: | ||
|
|
||
| - `ClientLoggingOptions.EnableLogging = true` | ||
| - `ClientLoggingOptions.EnableMessageLogging = true` (URL + headers + query parameters) | ||
| - `ClientLoggingOptions.EnableMessageContentLogging = true` (request/response bodies) | ||
| - `ClientLoggingOptions.MessageContentSizeLimit` to cap how much body content is written | ||
|
|
||
| `ClientLoggingOptions` is a common pattern across SDK clients that expose these options (for example, via a `ClientLoggingOptions` property on client options like `AzureOpenAIClientOptions`). | ||
|
|
||
| 2. **Raise the log level to `Debug` only if you want request/response bodies** | ||
|
|
||
| URL/headers/query parameter logging (step 1) is normally available at `Information` level and step 2 is not needed. | ||
|
|
||
| Request/response *body* logging is emitted at `Debug` level by the underlying message logging policy. The sample sets: | ||
|
|
||
| - `System.ClientModel.Primitives.MessageLoggingPolicy` → `Debug` | ||
|
|
||
| ## Security notes | ||
|
|
||
| - Logging bodies can include sensitive prompt/response data. Use only in dev/test. | ||
| - Headers like `Authorization` are **redacted by default**. The sample shows how to allow logging a sensitive header via `clientLoggingOptions.AllowedHeaderNames.Add("Authorization")` — avoid doing this unless you really need it. | ||
|
Vijay-Nirmal marked this conversation as resolved.
Outdated
|
||
|
|
||
| ## Using ASP.NET Core configuration | ||
|
|
||
| If you’re using ASP.NET Core, you can set the log level in `appsettings.json` instead of calling `AddFilter`, for example: | ||
|
|
||
| ```json | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning", | ||
| "System.ClientModel.Primitives.MessageLoggingPolicy": "Debug" | ||
| } | ||
| } | ||
| } | ||
| ``` | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.