-
Notifications
You must be signed in to change notification settings - Fork 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
Open
Vijay-Nirmal
wants to merge
9
commits into
microsoft:main
Choose a base branch
from
Vijay-Nirmal:sample/632-AIClientHttpTrafficTracing
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
9 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 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> | ||
| <TargetFrameworks>net10.0</TargetFrameworks> | ||
| <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> |
81 changes: 81 additions & 0 deletions
81
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,81 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| // This sample shows how to enable **HTTP request/response logging** for LLM calls (including request/response bodies) for any `AIClient`. | ||
|
|
||
| using System.ClientModel.Primitives; | ||
| using Azure.AI.OpenAI; | ||
| using Azure.Identity; | ||
| using Microsoft.Agents.AI; | ||
| using Microsoft.Extensions.AI; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| string endpoint = Environment.GetEnvironmentVariable("AZURE_OPENAI_ENDPOINT") ?? throw new InvalidOperationException("AZURE_OPENAI_ENDPOINT environment variable is not set."); | ||
| string deploymentName = Environment.GetEnvironmentVariable("AZURE_OPENAI_DEPLOYMENT_NAME") ?? "gpt-4o-mini"; | ||
|
|
||
| ServiceCollection services = new(); | ||
| 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 used in ASP.NET Core, with appsettings then this can be configured in appsettings.json as: | ||
| { | ||
| "Logging": { | ||
| "LogLevel": { | ||
| "Default": "Information", | ||
| "Microsoft.AspNetCore": "Warning", | ||
| "System.ClientModel.Primitives.MessageLoggingPolicy": "Debug" | ||
| } | ||
| } | ||
| } | ||
| */ | ||
| }); | ||
|
|
||
| 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>() | ||
| }; | ||
| // WARNING: Do NOT log sensitive headers such as "Authorization" in production or shared environments. | ||
| // By default, sensitive headers are REDACTED. The following example shows how to override this behavior | ||
| // for controlled, non-production testing only. | ||
| clientLoggingOptions.AllowedHeaderNames.Add("Authorization"); | ||
|
|
||
| /* 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(); | ||
| }); | ||
|
|
||
| ServiceProvider serviceProvider = services.BuildServiceProvider(); | ||
|
|
||
| IChatClient chatClient = serviceProvider.GetRequiredService<IChatClient>(); | ||
| ChatClientAgent pirateAssistant = chatClient.CreateAIAgent("You are a pirate assistant. Answer questions in short pirate speak."); | ||
|
|
||
Vijay-Nirmal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| string userInput = "Who are you?"; | ||
| Console.WriteLine($"You: {userInput}\n"); | ||
Vijay-Nirmal marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| AgentRunResponse response = await pirateAssistant.RunAsync(userInput); | ||
| Console.WriteLine($"\nPirate Assistant: {response}"); | ||
|
|
||
Vijay-Nirmal marked this conversation as resolved.
Show resolved
Hide 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 | ||
| 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**. While it is technically possible to allow logging a sensitive header (for example, via `clientLoggingOptions.AllowedHeaderNames.Add("Authorization")`), **do not enable this in production or long-lived environments**. If you must temporarily log such headers for debugging, do so only in tightly controlled, short-lived sessions, treat the logs as secrets, and securely delete them immediately after use. | ||
|
|
||
| ## 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.