Skip to content

Commit a12cc38

Browse files
authored
.NET: Promote FoundryChatClient to public, add file/vector-store helpers and ToPromptAgentAsync converter (microsoft#5940)
* Consolidate Foundry chat client decorators into FoundryChatClient - Replace AzureAIProjectChatClient and AzureAIProjectResponsesChatClient with a single internal sealed FoundryChatClient that covers three modes (pure responses, server-side agent reference, hosted agent endpoint). - Rename AzureAIProjectChatClientExtensions to AIProjectClientExtensions to reflect that it extends AIProjectClient. - All four AsAIAgent extension overloads and both FoundryAgent constructors now construct FoundryChatClient internally so the microsoft.foundry telemetry tag is uniform across paths. - Introduce AgentFrameworkUserAgentPolicy that stamps agent-framework-dotnet/{version} on outbound requests, mirroring the Python agent-framework-python/{version} contract. - Delete the Foundry-local MeaiUserAgentPolicy duplicate; rely on MEAI 10.5.1 to stamp MEAI/{version} automatically. - HostedAgentUserAgentPolicy keeps the combined foundry-hosting/agent-framework-dotnet/{version} segment (Python parity) and upgrades the bare segment in place to avoid duplication. - Tests reorganized: FoundryChatClientTests, AIProjectClientExtensionsTests, AgentFrameworkUserAgentPolicyTests, MeaiAutoUserAgentVerificationTests, plus in-place upgrade unit tests in HostedOutboundUserAgentTests. * Promote FoundryChatClient to public; add file/vector-store helpers and ToPromptAgentAsync converter - Promote FoundryChatClient from internal sealed to public sealed for Python parity, so .NET developers can hold and pass a FoundryChatClient directly the way Python developers do. - Mode 3 (hosted agent endpoint) now materializes an AIProjectClient from the parsed project root, making GetService<AIProjectClient>() non-null across all three construction modes. This eliminates the per-mode asymmetry that previously hid project-level helpers from agents constructed via an agent endpoint URL. - Add four new instance methods on FoundryChatClient mirroring Python's spec: UploadFileAsync, DeleteFileAsync, CreateVectorStoreAsync (bundles upload + create + wait), DeleteVectorStoreAsync. Single overload each, path-only inputs to start; additional overloads can be added later without breaking callers. All are Experimental, consistent with the rest of the Foundry package. - Add ToPromptAgentAsync extension methods on ChatClientAgent and FoundryAgent for the agent-to-prompt-agent converter described in the Foundry spec. Mode 1 (responses API) synthesizes a DeclarativeAgentDefinition from the agent's ChatOptions; mode 2 (server-side agent reference, version, or record) returns the cached or freshly fetched Definition; mode 3 throws InvalidOperationException because no local definition exists to convert. - Strict AITool to ResponseTool mapping for mode 1: AIFunction becomes CreateFunctionTool with the function's JSON schema; AITool instances that wrap a ResponseTool unwrap via GetService(typeof(ResponseTool)); anything else throws InvalidOperationException naming the offending tool type. Matches the Python spec's unsupported-tools-raise-ValueError contract. - New unit tests: FoundryChatClientVectorStoreTests (22 tests covering all four helpers across the three FoundryChatClient construction modes plus validation and cancellation), FoundryPromptAgentConverterTests (16 tests covering both extension entry points across mode 1 synthesis, mode 2 cached and fetched paths, all failure modes, and a Python-parity guard asserting both extensions produce equivalent definitions for equivalent inputs), plus four new tests in FoundryChatClientTests for the mode 3 AIProjectClient materialization. * Stop building duplicate ProjectOpenAIClient in FoundryAgent agent-endpoint ctor After Plan #2's mode-3 AIProjectClient materialization, the inner FoundryChatClient already exposes a project-level AIProjectClient (via GetService) that internally provides the project-level ProjectOpenAIClient via GetProjectOpenAIClient(). FoundryAgent's agent-endpoint constructor was still independently constructing a second project-level ProjectOpenAIClient via the now-redundant CreateProjectLevelOpenAIClientFromAgentEndpoint helper — two handles to the same logical resource. Refactor: the agent-endpoint constructor now reads the inner FoundryChatClient's materialized AIProjectClient via base.GetService(typeof(AIProjectClient)) and derives the project-level ProjectOpenAIClient from it. The dead helper on both FoundryAgent (private static wrapper) and FoundryChatClient (the actual implementation) is removed. The user-supplied per-agent ClientPipelineOptions primitives (Transport, RetryPolicy, NetworkTimeout, UserAgentApplicationId) are propagated into the materialized AIProjectClientOptions so test-injected transports and explicit retry / timeout / user-agent settings reach the project-level pipeline — preserving the behavior the dead helper used to provide. Updated AgentEndpointConstructor_GetServiceAIProjectClient_ReturnsNull to its now-correct counterpart AgentEndpointConstructor_GetServiceAIProjectClient_ReturnsNonNull, since after Plan #2 the agent-endpoint ctor surfaces a non-null AIProjectClient (per user direction in Plan #2 Q2). * Strip duplicated AIProjectClient/ProjectOpenAIClient state from FoundryAgent Both _aiProjectClient and _projectOpenAIClient fields on FoundryAgent were redundant: - _aiProjectClient: FoundryAgent's GetService<AIProjectClient> override returned this field, but DelegatingAIAgent.GetService → ChatClientAgent.GetService → FoundryChatClient.GetService<AIProjectClient> already returns the same instance through the delegating chain. Field + override are pure duplication. - _projectOpenAIClient: only used by FoundryAgent's own GetService<ProjectOpenAIClient> override and by CreateConversationSessionAsync. Per user direction, ProjectOpenAIClient is no longer exposed via GetService on either FoundryChatClient or FoundryAgent — callers retrieve it from the AIProjectClient themselves (aiProjectClient.GetProjectOpenAIClient()) the same way the framework does internally. This eliminates the mode-3 asymmetry where the chat client's stored ProjectOpenAIClient was per-agent (URL /agents/{name}/endpoint/protocols/openai) while the agent's was project-level. Refactor: - Delete both fields on FoundryAgent and the GetService override. - Delete the ProjectOpenAIClient branch from FoundryChatClient.GetService. - CreateConversationSessionAsync now resolves AIProjectClient at call time via this.GetService<AIProjectClient>() and derives the conversations client from it. - Update FoundryChatClient tests that asserted on GetService<ProjectOpenAIClient> to assert Null (deliberate removal). - Update FoundryAgent tests AgentEndpointConstructor_GetServiceProjectOpenAIClient_ReturnsNonNull and ProjectEndpointConstructor_GetServiceProjectOpenAIClient_ReturnsNonNull to ...ReturnsNull, and rewrite AgentEndpointConstructor_PropagatesUserAgentApplicationId_ToProjectLevelClient to look up AIProjectClient instead. No production code (only tests) referenced GetService<ProjectOpenAIClient>, so this is a safe surface reduction. Net: 30 insertions, 61 deletions; FoundryAgent shrinks to a pure delegator with only the two convenience methods (CreateSessionAsync, CreateConversationSessionAsync) on top of the delegating chain. * Rename FoundryChatClient.HostedAgentName to AgentName and populate it for mode 2 The previous name implied a mode 3 only property tied to the hosted-agent endpoint URL. Today only hosted endpoints surface this name, but conceptually an agent name exists for every server-side agent the client talks to. Renaming to AgentName makes the property general-purpose and ready for future modes where the same chat client may target other server-side agent shapes that are not necessarily 'hosted'. Mode 2 (server-side agent reference) now mirrors AgentReference.Name into AgentName so callers have a uniform handle regardless of construction mode: * Mode 1 (pure responses): AgentName is null. There is no agent. * Mode 2 (AgentReference): AgentName == AgentReference.Name. * Mode 3 (agent endpoint URL): AgentName is parsed from the URL segment as before. Converter discriminator update: FoundryPromptAgentConverter previously used 'HostedAgentName is not null' to detect mode 3 and reject it. Now that mode 2 also populates AgentName, the mode 3 guard moves to the end of the resolution chain and uses the unambiguous 'AgentName is set AND no AgentReference exists' test. The user-visible error message and behavior are preserved. Dead-state cleanup spotted during format verify: * IDE0052 surfaced that FoundryChatClient._projectOpenAIClient is never read since the prior refactor stopped exposing ProjectOpenAIClient via GetService and rewired CreateConversationSessionAsync to resolve the AIProjectClient through the delegating chain. The field is deleted and its three ctor assignments removed. * HostedAgentEndpointInner.PerAgentClient only existed to plumb the per-agent ProjectOpenAIClient into that now-deleted field, so the property and its ctor parameter are removed. The local 'perAgentClient' variable inside BuildHostedAgentEndpointInner is still needed to derive the inner IChatClient, but no longer escapes the helper. Tests: * Mode1_PureResponses_ReturnsNullForAgentSpecificServices now also asserts AgentName is null. * New Mode2_AgentReference_PopulatesAgentNameFromAgentReference asserts the mode 2 mirror. * Mode3_HostedAgentEndpoint_ParsesAgentNameFromUrl renamed assertion target HostedAgentName to AgentName. Verification: 335/335 net10.0, 273/273 net472 Foundry unit; 229/229 Foundry.Hosting unit; format-verify (WSL2 + Docker mcr.microsoft.com/dotnet/sdk:10.0) clean on Microsoft.Agents.AI.Foundry. * Adopt canonical mode names: Responses Agent, Prompt Agent, Agent Endpoint Three FoundryChatClient construction modes now have one canonical noun used everywhere. * Responses Agent (Mode 1): inline ChatClientAgent, project-level Responses API, no server-side def. * Prompt Agent (Mode 2): server-side ProjectsAgentDefinition invoked by AgentReference. * Agent Endpoint (Mode 3): per-agent URL /agents/{name}/endpoint/protocols/openai. Hosted-or-not. 'Hosted' stays the kind of agent (Microsoft.Agents.AI.Foundry.Hosting). Not synonym of Mode 3. Rings: 1. XML docs + error messages use canonical names. en-GB to en-US: centralises, synthesise. 2. HostedAgentEndpointInner -> AgentEndpointInner, BuildHostedAgentEndpointInner -> BuildAgentEndpointInner. 3. Tests: Mode1_PureResponses_* -> Mode1_ResponsesAgent_*, Mode2_AgentReference_* -> Mode2_PromptAgent_*, Mode3_HostedAgentEndpoint_* -> Mode3_AgentEndpoint_*. Pure rename. No behavior change. 335/335 net10 + 273/273 net472 unit, format clean. * Address PR microsoft#5940 design feedback (Q-A through Q-F) Q-A: poll vector store til status leaves InProgress before return. Exp backoff 250ms-2s. Honor cancel. Q-B: try/catch upload loop. Mid-fail = best-effort DeleteFileAsync on already-uploaded ids. Swallow cleanup errors. Q-C: pinned AgentReference.Version uses GetAgentVersionAsync. Empty/whitespace/'latest' = GetLatest path. Q-D: HostedAgentUserAgentPolicy detects existing combined 'foundry-hosting/...' segment. No double prefix. Q-E: mode-3 vector-store test uses fake transport. No DNS to example.com. Q-F: no shim. Class always [Experimental] (since 8015e00, before dotnet-1.0.0). No compat contract. Callers rename to AIProjectClientExtensions. Rebase onto origin/main reconciliation: aad20c2 added public AsAIAgent(this AIProjectClient, Uri agentEndpoint, ...) extension that calls an internal FoundryAgent(AIProjectClient, Uri, ...) ctor. Reintroduced that ctor + a new FoundryChatClient(AIProjectClient, Uri, ProjectOpenAIClientOptions?) overload that reuses the supplied AIProjectClient's pipeline (via GetProjectResponsesClientForAgentEndpoint) instead of stamping a fresh credential. Verified: 346/346 net10 + 284/284 net472 Foundry unit, 230/230 Foundry.Hosting unit, format clean. * Add FoundryAgent helper extensions: UploadFile/DeleteFile/CreateVectorStore/DeleteVectorStore 4 thin forwarders on FoundryAgent that route to the inner FoundryChatClient's helpers via agent.GetService<FoundryChatClient>().X(). Live in existing FoundryAgentExtensions.cs alongside ToPromptAgentAsync. Throws InvalidOperationException when agent does not expose a FoundryChatClient via GetService (same pattern as ToPromptAgentAsync). Unit tests: FoundryAgentExtensionsTests covers all 4 forwarders + null-agent ArgumentNullException for each. 8 new tests, 354/354 net10 + 292/292 net472. Integration tests: parallel FoundryAgentExtensionsTests under Foundry.IntegrationTests mirrors the existing CreateAgent_CreatesAgentWithVectorStoresAsync shape (upload -> create vector store -> FileSearch tool answers question -> cleanup), but routes every helper call through the new FoundryAgent extensions. 4 new IT tests, all verified pass live against the real Foundry project (12-30s each). Skipped by default like the existing vector-store IT. * Address Sergey's PR review comments #1 (FoundryAgent.cs:139): drop unused aiProjectClient param from internal FoundryAgent(AIProjectClient, ChatClientAgent) ctor. Was discarded after null-check. Inner FoundryChatClient already surfaces AIProjectClient via GetService. 3 call sites in AIProjectClientExtensions updated. #2 (FoundryChatClient.cs:376): add pollingTimeout param to CreateVectorStoreAsync. Defaults to 5 min, configurable, Timeout.InfiniteTimeSpan disables. Throws TimeoutException with vector store id and elapsed seconds when bound exceeded. CancellationToken still wins. New unit test PollingTimeout_ThrowsTimeoutExceptionAsync. FoundryAgentExtensions forwarder updated to plumb the new param. Verified: 355/355 net10 + 293/293 net472 Foundry unit, 230/230 Foundry.Hosting unit, format clean.
1 parent 47f5c33 commit a12cc38

24 files changed

Lines changed: 3981 additions & 832 deletions

dotnet/src/Microsoft.Agents.AI.Foundry.Hosting/HostedAgentUserAgentPolicy.cs

Lines changed: 60 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
// Copyright (c) Microsoft. All rights reserved.
22

3+
using System;
34
using System.ClientModel.Primitives;
45
using System.Collections.Generic;
56
using System.Reflection;
@@ -9,8 +10,11 @@
910
namespace Microsoft.Agents.AI.Foundry.Hosting;
1011

1112
/// <summary>
12-
/// Pipeline policy that appends the hosted-agent <c>User-Agent</c> segment
13-
/// (e.g. <c>"foundry-hosting/agent-framework-dotnet/{version}"</c>) to outgoing requests.
13+
/// Pipeline policy that emits the hosted-agent <c>User-Agent</c> segment
14+
/// (<c>"foundry-hosting/agent-framework-dotnet/{version}"</c>), matching Python's hosted
15+
/// contract (<c>foundry-hosting/agent-framework-python/{version}</c>, see
16+
/// <c>python/packages/core/agent_framework/_telemetry.py</c>: the hosted prefix is joined
17+
/// with the base agent-framework segment into a single combined User-Agent value).
1418
/// </summary>
1519
/// <remarks>
1620
/// <para>
@@ -19,6 +23,12 @@ namespace Microsoft.Agents.AI.Foundry.Hosting;
1923
/// is already present in the <c>User-Agent</c> header, the policy does not append it again.
2024
/// </para>
2125
/// <para>
26+
/// When a bare <c>agent-framework-dotnet/{version}</c> segment is already present (stamped by
27+
/// the framework-wide <c>AgentFrameworkUserAgentPolicy</c> registered by
28+
/// <c>FoundryChatClient</c>), this policy <em>replaces</em> that segment with the combined
29+
/// hosted form so the wire never carries both forms simultaneously, preserving Python parity.
30+
/// </para>
31+
/// <para>
2232
/// This policy is added at hosted-agent resolution time via the MEAI 10.5.1
2333
/// <see cref="OpenAIRequestPolicies"/> hook on the agent's underlying chat client. It is only
2434
/// registered when an agent is resolved by the Foundry hosting layer.
@@ -30,6 +40,12 @@ internal sealed class HostedAgentUserAgentPolicy : PipelinePolicy
3040

3141
private static readonly string s_supplementValue = CreateSupplementValue();
3242

43+
/// <summary>Bare segment stamped by <c>AgentFrameworkUserAgentPolicy</c> in the non-hosted scenario; this policy upgrades it in-place when both run.</summary>
44+
private const string BareAgentFrameworkPrefix = "agent-framework-dotnet/";
45+
46+
/// <summary>Combined hosted segment that this policy emits. Recognized in-place so callers whose pipelines already carry a (possibly different-version) combined segment get it replaced rather than double-prefixed (Q-D fix).</summary>
47+
private const string CombinedHostedPrefix = "foundry-hosting/agent-framework-dotnet/";
48+
3349
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
3450
{
3551
AppendHeader(message);
@@ -46,10 +62,49 @@ private static void AppendHeader(PipelineMessage message)
4662
{
4763
if (message.Request.Headers.TryGetValue("User-Agent", out var existing) && !string.IsNullOrEmpty(existing))
4864
{
49-
// Guard against double-append on retries or when the policy
50-
// is registered on multiple pipeline positions.
51-
if (existing.Contains(s_supplementValue))
65+
// Guard against double-append on retries or when the policy is registered on
66+
// multiple pipeline positions.
67+
if (existing!.Contains(s_supplementValue))
68+
{
69+
return;
70+
}
71+
72+
// Combined-form check first: if the caller's pipeline already has
73+
// `foundry-hosting/agent-framework-dotnet/{version}` (with a version that differs
74+
// from ours — otherwise the .Contains above would have returned early), replace the
75+
// entire combined span in place. Without this, the bare-prefix search below would
76+
// match `agent-framework-dotnet/` *inside* the combined segment and produce a
77+
// malformed `foundry-hosting/foundry-hosting/agent-framework-dotnet/...` value.
78+
var combinedIdx = existing.IndexOf(CombinedHostedPrefix, StringComparison.Ordinal);
79+
if (combinedIdx >= 0)
5280
{
81+
var combinedEnd = existing.IndexOf(' ', combinedIdx);
82+
if (combinedEnd < 0)
83+
{
84+
combinedEnd = existing.Length;
85+
}
86+
87+
var replacedCombined = string.Concat(existing.AsSpan(0, combinedIdx), s_supplementValue.AsSpan(), existing.AsSpan(combinedEnd));
88+
message.Request.Headers.Set("User-Agent", replacedCombined);
89+
return;
90+
}
91+
92+
// If the bare agent-framework segment is present (stamped by
93+
// AgentFrameworkUserAgentPolicy when not hosted), upgrade it in place to the
94+
// combined hosted form so the wire never carries both segments simultaneously.
95+
// Mirrors Python where get_user_agent() returns a single combined string when the
96+
// hosted prefix is registered.
97+
var idx = existing.IndexOf(BareAgentFrameworkPrefix, StringComparison.Ordinal);
98+
if (idx >= 0)
99+
{
100+
var end = existing.IndexOf(' ', idx);
101+
if (end < 0)
102+
{
103+
end = existing.Length;
104+
}
105+
106+
var replaced = string.Concat(existing.AsSpan(0, idx), s_supplementValue.AsSpan(), existing.AsSpan(end));
107+
message.Request.Headers.Set("User-Agent", replaced);
53108
return;
54109
}
55110

dotnet/src/Microsoft.Agents.AI.Foundry/AzureAIProjectChatClientExtensions.cs renamed to dotnet/src/Microsoft.Agents.AI.Foundry/AIProjectClientExtensions.cs

Lines changed: 8 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ namespace Azure.AI.Projects;
2323
/// Provides extension methods for <see cref="AIProjectClient"/>.
2424
/// </summary>
2525
[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)]
26-
public static partial class AzureAIProjectChatClientExtensions
26+
public static partial class AIProjectClientExtensions
2727
{
2828
/// <summary>
2929
/// Uses an existing server side agent, wrapped as a <see cref="ChatClientAgent"/> using the provided <see cref="AIProjectClient"/> and <see cref="AgentReference"/>.
@@ -63,7 +63,7 @@ public static FoundryAgent AsAIAgent(
6363
clientFactory,
6464
services);
6565

66-
return new FoundryAgent(aiProjectClient, innerAgent);
66+
return new FoundryAgent(innerAgent);
6767
}
6868

6969
/// <summary>
@@ -132,7 +132,7 @@ public static FoundryAgent AsAIAgent(
132132
!allowDeclarativeMode,
133133
services);
134134

135-
return new FoundryAgent(aiProjectClient, innerAgent);
135+
return new FoundryAgent(innerAgent);
136136
}
137137

138138
/// <summary>
@@ -165,7 +165,7 @@ public static FoundryAgent AsAIAgent(
165165
!allowDeclarativeMode,
166166
services);
167167

168-
return new FoundryAgent(aiProjectClient, innerAgent);
168+
return new FoundryAgent(innerAgent);
169169
}
170170

171171
/// <summary>
@@ -246,7 +246,7 @@ private static ChatClientAgent CreateChatClientAgent(
246246
Func<IChatClient, IChatClient>? clientFactory,
247247
IServiceProvider? services)
248248
{
249-
IChatClient chatClient = new AzureAIProjectChatClient(aiProjectClient, agentVersion, agentOptions.ChatOptions);
249+
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentVersion, agentOptions.ChatOptions);
250250

251251
if (clientFactory is not null)
252252
{
@@ -268,10 +268,7 @@ private static ChatClientAgent CreateResponsesChatClientAgent(
268268
Throw.IfNull(agentOptions.ChatOptions);
269269
Throw.IfNullOrWhitespace(agentOptions.ChatOptions.ModelId);
270270

271-
IChatClient chatClient = aiProjectClient
272-
.GetProjectOpenAIClient()
273-
.GetResponsesClient()
274-
.AsIChatClient(agentOptions.ChatOptions.ModelId);
271+
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentOptions.ChatOptions.ModelId);
275272

276273
if (clientFactory is not null)
277274
{
@@ -298,7 +295,7 @@ private static ChatClientAgent AsChatClientAgent(
298295
Func<IChatClient, IChatClient>? clientFactory,
299296
IServiceProvider? services)
300297
{
301-
IChatClient chatClient = new AzureAIProjectChatClient(aiProjectClient, agentRecord, agentOptions.ChatOptions);
298+
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentRecord, agentOptions.ChatOptions);
302299

303300
if (clientFactory is not null)
304301
{
@@ -316,7 +313,7 @@ private static ChatClientAgent AsChatClientAgent(
316313
Func<IChatClient, IChatClient>? clientFactory,
317314
IServiceProvider? services)
318315
{
319-
IChatClient chatClient = new AzureAIProjectChatClient(aiProjectClient, agentReference, defaultModelId: null, agentOptions.ChatOptions);
316+
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentReference, defaultModelId: null, agentOptions.ChatOptions);
320317

321318
if (clientFactory is not null)
322319
{
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
// Copyright (c) Microsoft. All rights reserved.
2+
3+
using System.ClientModel.Primitives;
4+
using System.Collections.Generic;
5+
using System.Reflection;
6+
using System.Threading.Tasks;
7+
8+
namespace Microsoft.Agents.AI.Foundry;
9+
10+
/// <summary>
11+
/// Framework-wide pipeline policy that appends the <c>agent-framework-dotnet/{version}</c>
12+
/// segment to outgoing <c>User-Agent</c> headers, mirroring the
13+
/// <c>agent-framework-python/{version}</c> contract used by every Python provider package.
14+
/// </summary>
15+
/// <remarks>
16+
/// <para>
17+
/// The segment value is computed once from the <c>Microsoft.Agents.AI.Foundry</c> assembly's
18+
/// <see cref="AssemblyInformationalVersionAttribute"/>. The policy is idempotent on retries: if
19+
/// the segment is already present in the <c>User-Agent</c> header, the policy does not append
20+
/// it again.
21+
/// </para>
22+
/// <para>
23+
/// The policy is registered by <c>FoundryChatClient</c> on the underlying chat client's
24+
/// <c>OpenAIRequestPolicies</c> hook so every outbound Foundry call carries the segment. The
25+
/// policy is currently colocated with the Foundry package; it is expected to migrate to a
26+
/// framework-wide location (such as <c>Microsoft.Agents.AI</c>) once another provider package
27+
/// adopts the same User-Agent contract.
28+
/// </para>
29+
/// </remarks>
30+
internal sealed class AgentFrameworkUserAgentPolicy : PipelinePolicy
31+
{
32+
/// <summary>Gets the singleton policy instance.</summary>
33+
public static AgentFrameworkUserAgentPolicy Instance { get; } = new AgentFrameworkUserAgentPolicy();
34+
35+
private static readonly string s_segmentValue = CreateSegmentValue();
36+
37+
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
38+
{
39+
AppendHeader(message);
40+
ProcessNext(message, pipeline, currentIndex);
41+
}
42+
43+
public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
44+
{
45+
AppendHeader(message);
46+
await ProcessNextAsync(message, pipeline, currentIndex).ConfigureAwait(false);
47+
}
48+
49+
private static void AppendHeader(PipelineMessage message)
50+
{
51+
if (message.Request.Headers.TryGetValue("User-Agent", out var existing) && !string.IsNullOrEmpty(existing))
52+
{
53+
// Guard against double-append on retries or when the policy
54+
// is registered on multiple pipeline positions.
55+
if (existing!.Contains(s_segmentValue))
56+
{
57+
return;
58+
}
59+
60+
message.Request.Headers.Set("User-Agent", $"{existing} {s_segmentValue}");
61+
}
62+
else
63+
{
64+
message.Request.Headers.Set("User-Agent", s_segmentValue);
65+
}
66+
}
67+
68+
private static string CreateSegmentValue()
69+
{
70+
const string Name = "agent-framework-dotnet";
71+
72+
if (typeof(AgentFrameworkUserAgentPolicy).Assembly.GetCustomAttribute<AssemblyInformationalVersionAttribute>()?.InformationalVersion is string version)
73+
{
74+
int pos = version.IndexOf('+');
75+
if (pos >= 0)
76+
{
77+
version = version.Substring(0, pos);
78+
}
79+
80+
if (version.Length > 0)
81+
{
82+
return $"{Name}/{version}";
83+
}
84+
}
85+
86+
return Name;
87+
}
88+
}

0 commit comments

Comments
 (0)