-
Notifications
You must be signed in to change notification settings - Fork 1.7k
.NET: dotnet: Add hosted-agent User-Agent supplement to outgoing requests #5453
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
Merged
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
9027b5c
dotnet: Add hosted-agent User-Agent supplement to outgoing requests
8cecd7c
chore: update hosted UA format to foundry-hosting/agent-framework-dot…
e68ff12
Trying to get UA flowing, no luck yet.
516ea56
.NET: Polyfill MEAI OpenAIResponsesChatClient to add hosted-agent Use…
rogerbarreto 6610830
.NET: Address review feedback on hosted-agent User-Agent polyfill
rogerbarreto d3b9cfa
.NET: Drop null check from TryApplyUserAgent and its now-redundant test
rogerbarreto c64ba5f
.NET: Remove unused Microsoft.Shared.Diagnostics import in ServiceCol…
rogerbarreto 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
113 changes: 113 additions & 0 deletions
113
dotnet/src/Microsoft.Agents.AI.Foundry.Hosting/DelegatingResponsesClient.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,113 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.ClientModel; | ||
| using System.ClientModel.Primitives; | ||
| using System.Collections.Generic; | ||
| using System.Threading.Tasks; | ||
| using OpenAI; | ||
| using OpenAI.Responses; | ||
|
|
||
| #pragma warning disable OPENAI001, SCME0001 | ||
|
|
||
| namespace Microsoft.Agents.AI.Foundry.Hosting; | ||
|
|
||
| /// <summary> | ||
| /// A <see cref="ResponsesClient"/> subclass that delegates every protocol-level request to a | ||
| /// wrapped <see cref="ResponsesClient"/>. Before each call, a | ||
| /// <see cref="HostedAgentUserAgentPolicy"/> is added to the per-call | ||
| /// <see cref="RequestOptions"/> so the wrapped client's pipeline appends the hosted-agent | ||
| /// <c>User-Agent</c> segment on the wire. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The streaming overloads MEAI binds via reflection (<c>internal CreateResponseStreamingAsync(CreateResponseOptions, RequestOptions)</c> | ||
| /// and <c>internal GetResponseStreamingAsync(GetResponseOptions, RequestOptions)</c>) bottom out | ||
| /// in calls to the public-virtual non-streaming protocol overloads on <see langword="this"/>. Overriding those | ||
| /// non-streaming overloads is therefore sufficient to intercept both streaming and non-streaming traffic. | ||
| /// </para> | ||
| /// <para> | ||
| /// The base pipeline supplied to <see cref="ResponsesClient(ClientPipeline, OpenAIClientOptions)"/> | ||
| /// is a dummy pipeline whose terminal transport throws if invoked. Every override on this class | ||
| /// delegates to the inner client BEFORE any code path reaches <see cref="ResponsesClient.Pipeline"/>, so the dummy is | ||
| /// never expected to run; the throwing transport surfaces any unexpected escape route loudly. | ||
| /// </para> | ||
| /// </remarks> | ||
| internal sealed class DelegatingResponsesClient : ResponsesClient | ||
| { | ||
| private readonly ResponsesClient _inner; | ||
|
|
||
| public DelegatingResponsesClient(ResponsesClient inner) | ||
| : base(BuildDummyPipeline(), new OpenAIClientOptions { Endpoint = inner?.Endpoint }) | ||
| { | ||
| this._inner = inner ?? throw new ArgumentNullException(nameof(inner)); | ||
| } | ||
|
|
||
| public override async Task<ClientResult> CreateResponseAsync(BinaryContent content, RequestOptions? options = null) | ||
| => await this._inner.CreateResponseAsync(content, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult CreateResponse(BinaryContent content, RequestOptions? options = null) | ||
| => this._inner.CreateResponse(content, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> GetResponseAsync(string responseId, IEnumerable<IncludedResponseProperty>? include, bool? stream, int? startingAfter, bool? includeObfuscation, RequestOptions options) | ||
| => await this._inner.GetResponseAsync(responseId, include, stream, startingAfter, includeObfuscation, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult GetResponse(string responseId, IEnumerable<IncludedResponseProperty>? include, bool? stream, int? startingAfter, bool? includeObfuscation, RequestOptions options) | ||
| => this._inner.GetResponse(responseId, include, stream, startingAfter, includeObfuscation, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> DeleteResponseAsync(string responseId, RequestOptions options) | ||
| => await this._inner.DeleteResponseAsync(responseId, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult DeleteResponse(string responseId, RequestOptions options) | ||
| => this._inner.DeleteResponse(responseId, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> CancelResponseAsync(string responseId, RequestOptions options) | ||
| => await this._inner.CancelResponseAsync(responseId, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult CancelResponse(string responseId, RequestOptions options) | ||
| => this._inner.CancelResponse(responseId, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> GetInputTokenCountAsync(string contentType, BinaryContent content, RequestOptions? options = null) | ||
| => await this._inner.GetInputTokenCountAsync(contentType, content, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult GetInputTokenCount(string contentType, BinaryContent content, RequestOptions? options = null) | ||
| => this._inner.GetInputTokenCount(contentType, content, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> CompactResponseAsync(string contentType, BinaryContent content, RequestOptions? options = null) | ||
| => await this._inner.CompactResponseAsync(contentType, content, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult CompactResponse(string contentType, BinaryContent content, RequestOptions? options = null) | ||
| => this._inner.CompactResponse(contentType, content, AddUserAgentPolicy(options)); | ||
|
|
||
| public override async Task<ClientResult> GetResponseInputItemCollectionPageAsync(string responseId, int? limit, string order, string after, string before, RequestOptions options) | ||
| => await this._inner.GetResponseInputItemCollectionPageAsync(responseId, limit, order, after, before, AddUserAgentPolicy(options)).ConfigureAwait(false); | ||
|
|
||
| public override ClientResult GetResponseInputItemCollectionPage(string responseId, int? limit, string order, string after, string before, RequestOptions options) | ||
| => this._inner.GetResponseInputItemCollectionPage(responseId, limit, order, after, before, AddUserAgentPolicy(options)); | ||
|
|
||
| private static RequestOptions AddUserAgentPolicy(RequestOptions? options) | ||
| { | ||
| options ??= new RequestOptions(); | ||
| options.AddPolicy(HostedAgentUserAgentPolicy.Instance, PipelinePosition.PerCall); | ||
| return options; | ||
| } | ||
|
|
||
| private static ClientPipeline BuildDummyPipeline() | ||
| { | ||
| var options = new ClientPipelineOptions | ||
| { | ||
| Transport = new ThrowingTransport(), | ||
| }; | ||
| return ClientPipeline.Create(options, default, default, default); | ||
| } | ||
|
|
||
| private sealed class ThrowingTransport : PipelineTransport | ||
| { | ||
| private const string Message = | ||
| "DelegatingResponsesClient transport invoked bypassed the override-and-delegate design. This exception should be unreachable and should never be thrown following the correct usage of DelegatingResponsesClient."; | ||
|
|
||
| protected override PipelineMessage CreateMessageCore() => throw new InvalidOperationException(Message); | ||
| protected override void ProcessCore(PipelineMessage message) => throw new InvalidOperationException(Message); | ||
| protected override ValueTask ProcessCoreAsync(PipelineMessage message) => throw new InvalidOperationException(Message); | ||
| } | ||
| } | ||
84 changes: 84 additions & 0 deletions
84
dotnet/src/Microsoft.Agents.AI.Foundry.Hosting/HostedAgentUserAgentPolicy.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,84 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System.ClientModel.Primitives; | ||
| using System.Collections.Generic; | ||
| using System.Reflection; | ||
| using System.Threading.Tasks; | ||
|
|
||
| namespace Microsoft.Agents.AI.Foundry.Hosting; | ||
|
|
||
| /// <summary> | ||
| /// Pipeline policy that appends the hosted-agent <c>User-Agent</c> segment | ||
| /// (e.g. <c>"foundry-hosting/agent-framework-dotnet/{version}"</c>) to outgoing requests. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// <para> | ||
| /// The supplement value is computed once from the Microsoft.Agents.AI.Foundry.Hosting | ||
| /// assembly's informational version. The policy is idempotent on retries: if the segment | ||
| /// is already present in the <c>User-Agent</c> header, the policy does not append it again. | ||
| /// </para> | ||
| /// <para> | ||
| /// This policy is added at request time (per-call <see cref="PipelinePosition"/>) | ||
| /// by <see cref="DelegatingResponsesClient"/> when invoking the wrapped | ||
| /// <see cref="OpenAI.Responses.ResponsesClient"/>. It is only registered when an agent is | ||
| /// resolved by the Foundry hosting layer. | ||
| /// </para> | ||
| /// </remarks> | ||
| internal sealed class HostedAgentUserAgentPolicy : PipelinePolicy | ||
| { | ||
| public static HostedAgentUserAgentPolicy Instance { get; } = new HostedAgentUserAgentPolicy(); | ||
|
|
||
| private static readonly string s_supplementValue = CreateSupplementValue(); | ||
|
|
||
| public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex) | ||
| { | ||
| AppendHeader(message); | ||
| ProcessNext(message, pipeline, currentIndex); | ||
| } | ||
|
|
||
| public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex) | ||
| { | ||
| AppendHeader(message); | ||
| await ProcessNextAsync(message, pipeline, currentIndex).ConfigureAwait(false); | ||
| } | ||
|
|
||
| private static void AppendHeader(PipelineMessage message) | ||
| { | ||
| if (message.Request.Headers.TryGetValue("User-Agent", out var existing) && !string.IsNullOrEmpty(existing)) | ||
| { | ||
| // Guard against double-append on retries or when the policy | ||
| // is registered on multiple pipeline positions. | ||
| if (existing.Contains(s_supplementValue)) | ||
| { | ||
| return; | ||
| } | ||
|
|
||
| message.Request.Headers.Set("User-Agent", $"{existing} {s_supplementValue}"); | ||
| } | ||
| else | ||
| { | ||
| message.Request.Headers.Set("User-Agent", s_supplementValue); | ||
| } | ||
| } | ||
|
|
||
| private static string CreateSupplementValue() | ||
| { | ||
| const string Name = "foundry-hosting/agent-framework-dotnet"; | ||
|
|
||
| if (typeof(HostedAgentUserAgentPolicy).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion is string version) | ||
| { | ||
| int pos = version.IndexOf('+'); | ||
| if (pos >= 0) | ||
| { | ||
| version = version.Substring(0, pos); | ||
| } | ||
|
|
||
| if (version.Length > 0) | ||
| { | ||
| return $"{Name}/{version}"; | ||
| } | ||
| } | ||
|
|
||
| return Name; | ||
| } | ||
| } |
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
Oops, something went wrong.
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.