mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
* 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 #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 8015e00f5, before dotnet-1.0.0). No compat contract. Callers rename to AIProjectClientExtensions.
Rebase onto origin/main reconciliation: aad20c2b3 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.
371 lines
18 KiB
C#
371 lines
18 KiB
C#
// Copyright (c) Microsoft. All rights reserved.
|
|
|
|
using System;
|
|
using System.ClientModel;
|
|
using System.ClientModel.Primitives;
|
|
using System.Collections.Generic;
|
|
using System.Diagnostics.CodeAnalysis;
|
|
using System.Threading;
|
|
using System.Threading.Tasks;
|
|
using Azure.AI.Extensions.OpenAI;
|
|
using Azure.AI.Projects;
|
|
using Microsoft.Extensions.AI;
|
|
using Microsoft.Extensions.Logging;
|
|
using Microsoft.Shared.DiagnosticIds;
|
|
using Microsoft.Shared.Diagnostics;
|
|
|
|
namespace Microsoft.Agents.AI.Foundry;
|
|
|
|
/// <summary>
|
|
/// Provides an <see cref="AIAgent"/> that uses Microsoft Foundry for AI agent capabilities.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// <see cref="FoundryAgent"/> connects to a pre-configured server-side agent in Microsoft Foundry,
|
|
/// wrapping it as an <see cref="AIAgent"/> for use with Agent Framework. Unlike the direct
|
|
/// <c>AIProjectClient.AsAIAgent(model, instructions)</c> approach (which creates a local agent
|
|
/// backed by the Responses API without any server-side agent definition), <see cref="FoundryAgent"/>
|
|
/// works with agents that are managed and versioned in the Foundry service.
|
|
/// </para>
|
|
/// <para>
|
|
/// This class provides convenient access to Foundry-specific features such as server-side
|
|
/// conversation management via <see cref="CreateConversationSessionAsync(CancellationToken)"/>.
|
|
/// </para>
|
|
/// <para>
|
|
/// Instances can be created directly via public constructors or through
|
|
/// <c>AsAIAgent</c> extension methods on <see cref="AIProjectClient"/>.
|
|
/// </para>
|
|
/// </remarks>
|
|
[Experimental(DiagnosticIds.Experiments.AIOpenAIResponses)]
|
|
public sealed class FoundryAgent : DelegatingAIAgent
|
|
{
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="FoundryAgent"/> class using the direct Responses API path.
|
|
/// </summary>
|
|
/// <param name="projectEndpoint">The Microsoft Foundry project endpoint.</param>
|
|
/// <param name="credential">The authentication credential.</param>
|
|
/// <param name="model">The model deployment name.</param>
|
|
/// <param name="instructions">The instructions that guide the agent's behavior.</param>
|
|
/// <param name="clientOptions">Optional configuration options for the <see cref="AIProjectClient"/>.</param>
|
|
/// <param name="name">Optional name for the agent.</param>
|
|
/// <param name="description">Optional description for the agent.</param>
|
|
/// <param name="tools">Optional tools to use when interacting with the agent.</param>
|
|
/// <param name="clientFactory">Provides a way to customize the creation of the underlying <see cref="IChatClient"/>.</param>
|
|
/// <param name="loggerFactory">Optional logger factory for creating loggers used by the agent.</param>
|
|
/// <param name="services">Optional service provider for resolving dependencies required by AI functions.</param>
|
|
public FoundryAgent(
|
|
Uri projectEndpoint,
|
|
AuthenticationTokenProvider credential,
|
|
string model,
|
|
string instructions,
|
|
AIProjectClientOptions? clientOptions = null,
|
|
string? name = null,
|
|
string? description = null,
|
|
IList<AITool>? tools = null,
|
|
Func<IChatClient, IChatClient>? clientFactory = null,
|
|
ILoggerFactory? loggerFactory = null,
|
|
IServiceProvider? services = null)
|
|
: base(CreateInnerAgent(
|
|
CreateProjectClient(projectEndpoint, credential, clientOptions),
|
|
model, instructions, name, description, tools, clientFactory, loggerFactory, services,
|
|
out _))
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Initializes a new instance of the <see cref="FoundryAgent"/> class from an agent-specific endpoint.
|
|
/// </summary>
|
|
/// <param name="agentEndpoint">
|
|
/// The agent-specific endpoint URI. Must be of the shape
|
|
/// <c>https://<host>/.../projects/<project>/agents/<agentName>/endpoint/protocols/openai</c>.
|
|
/// </param>
|
|
/// <param name="credential">The authentication credential.</param>
|
|
/// <param name="clientOptions">
|
|
/// Optional configuration for the underlying <see cref="ProjectOpenAIClient"/>. When supplied:
|
|
/// <list type="bullet">
|
|
/// <item><description>The instance is passed through to the per-agent client; pipeline policies added via <c>AddPolicy(...)</c> on it execute on the per-agent traffic.</description></item>
|
|
/// <item><description><c>Endpoint</c> and <see cref="ProjectOpenAIClientOptions.AgentName"/> are owned by this constructor and are overwritten with values derived from <paramref name="agentEndpoint"/>; any caller value is replaced.</description></item>
|
|
/// <item><description>For the project-level conversations client a separate fresh options bag is built that copies only <see cref="ClientPipelineOptions.RetryPolicy"/>, <see cref="ClientPipelineOptions.NetworkTimeout"/>, <see cref="ClientPipelineOptions.Transport"/>, and <c>UserAgentApplicationId</c>; pipeline policies added via <c>AddPolicy(...)</c> do <strong>not</strong> propagate to the conversations pipeline.</description></item>
|
|
/// </list>
|
|
/// </param>
|
|
/// <param name="tools">Optional tools to use when interacting with the agent.</param>
|
|
/// <param name="clientFactory">Provides a way to customize the creation of the underlying <see cref="IChatClient"/>.</param>
|
|
/// <param name="services">Optional service provider for resolving dependencies required by AI functions.</param>
|
|
/// <exception cref="ArgumentNullException"><paramref name="agentEndpoint"/> or <paramref name="credential"/> is null.</exception>
|
|
/// <exception cref="ArgumentException"><paramref name="agentEndpoint"/> does not match the expected agent-endpoint shape.</exception>
|
|
/// <remarks>
|
|
/// This is the lightweight constructor for invoking an existing Foundry hosted agent when the
|
|
/// caller already has the per-agent endpoint URL. It populates <see cref="ChatClientAgentOptions.Id"/>
|
|
/// and <see cref="ChatClientAgentOptions.Name"/> from the agent name parsed out of the endpoint
|
|
/// path; <c>Description</c>, <c>Instructions</c>, <c>Temperature</c>, and <c>TopP</c> are not
|
|
/// populated. Callers that need those fields hydrated from server-side state should use
|
|
/// <c>AIProjectClient.AsAIAgent(ProjectsAgentVersion)</c> or
|
|
/// <c>AIProjectClient.AsAIAgent(ProjectsAgentRecord)</c> instead.
|
|
/// </remarks>
|
|
public FoundryAgent(
|
|
Uri agentEndpoint,
|
|
AuthenticationTokenProvider credential,
|
|
ProjectOpenAIClientOptions? clientOptions = null,
|
|
IList<AITool>? tools = null,
|
|
Func<IChatClient, IChatClient>? clientFactory = null,
|
|
IServiceProvider? services = null)
|
|
: base(CreateInnerAgentFromAgentEndpoint(agentEndpoint, credential, clientOptions, tools, clientFactory, services))
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Internal constructor used by the <c>AsAIAgent(this AIProjectClient, Uri, ...)</c>
|
|
/// extension where the caller already has an <see cref="AIProjectClient"/> and the agent
|
|
/// endpoint URI. Reuses the supplied client's pipeline (no new credential or transport is
|
|
/// stamped) and surfaces the agent through a <see cref="FoundryChatClient"/> just like the
|
|
/// public agent-endpoint ctor.
|
|
/// </summary>
|
|
internal FoundryAgent(
|
|
AIProjectClient aiProjectClient,
|
|
Uri agentEndpoint,
|
|
IList<AITool>? tools = null,
|
|
Func<IChatClient, IChatClient>? clientFactory = null,
|
|
IServiceProvider? services = null)
|
|
: base(CreateInnerAgentFromAgentEndpointReusingProjectClient(aiProjectClient, agentEndpoint, tools, clientFactory, services))
|
|
{
|
|
}
|
|
|
|
/// <summary>
|
|
/// Internal constructor used by <c>AsAIAgent</c> extension methods that already have a
|
|
/// configured <see cref="ChatClientAgent"/>. The inner agent already routes through a
|
|
/// <see cref="FoundryChatClient"/> whose <c>GetService<AIProjectClient>()</c> surfaces
|
|
/// the project client to downstream callers, so the agent does not also need a private
|
|
/// <see cref="AIProjectClient"/> reference here.
|
|
/// </summary>
|
|
internal FoundryAgent(ChatClientAgent innerAgent)
|
|
: base(WireClientHeaders(Throw.IfNull(innerAgent)))
|
|
{
|
|
}
|
|
|
|
#region Convenience methods
|
|
|
|
/// <summary>
|
|
/// Creates a new agent session instance using an existing conversation identifier to continue that conversation.
|
|
/// </summary>
|
|
/// <param name="conversationId">The identifier of an existing conversation to continue.</param>
|
|
/// <param name="cancellationToken">The <see cref="CancellationToken"/> to monitor for cancellation requests.</param>
|
|
/// <returns>
|
|
/// A value task representing the asynchronous operation. The task result contains a new <see cref="AgentSession"/> instance configured to work with the specified conversation.
|
|
/// </returns>
|
|
/// <remarks>
|
|
/// <para>
|
|
/// This method creates an <see cref="AgentSession"/> that relies on server-side chat history storage, where the chat history
|
|
/// is maintained by the underlying AI service rather than by a local <see cref="ChatHistoryProvider"/>.
|
|
/// </para>
|
|
/// <para>
|
|
/// Agent sessions created with this method will only work with <see cref="FoundryAgent"/>
|
|
/// instances that support server-side conversation storage through their underlying <see cref="IChatClient"/>.
|
|
/// </para>
|
|
/// </remarks>
|
|
public ValueTask<AgentSession> CreateSessionAsync(string conversationId, CancellationToken cancellationToken = default)
|
|
=> this.GetInnerChatClientAgent().CreateSessionAsync(conversationId, cancellationToken);
|
|
|
|
/// <summary>
|
|
/// Creates a server-side conversation session that appears in the Foundry Project UI.
|
|
/// </summary>
|
|
/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>
|
|
/// <returns>A <see cref="ChatClientAgentSession"/> linked to the newly created server-side conversation.</returns>
|
|
public async Task<ChatClientAgentSession> CreateConversationSessionAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
// The inner FoundryChatClient surfaces an AIProjectClient via GetService for all
|
|
// three construction modes (Plan #2 Agent Endpoint mode materialization). Resolve it through the
|
|
// delegating chain at call time instead of caching a private reference on this agent.
|
|
var aiProjectClient = this.GetService<AIProjectClient>()
|
|
?? throw new InvalidOperationException(
|
|
"FoundryAgent inner chain does not expose an AIProjectClient; cannot create a project-level conversation session.");
|
|
var conversationsClient = aiProjectClient.GetProjectOpenAIClient().GetProjectConversationsClient();
|
|
|
|
var conversation = (await conversationsClient.CreateProjectConversationAsync(options: null, cancellationToken).ConfigureAwait(false)).Value;
|
|
|
|
return (ChatClientAgentSession)await this.GetInnerChatClientAgent().CreateSessionAsync(conversation.Id, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
/// <summary>Walks the delegating chain to find the inner <see cref="ChatClientAgent"/>.</summary>
|
|
private ChatClientAgent GetInnerChatClientAgent() =>
|
|
this.GetService<ChatClientAgent>()
|
|
?? throw new InvalidOperationException("FoundryAgent inner chain does not contain a ChatClientAgent.");
|
|
|
|
#endregion
|
|
|
|
#region Private helpers
|
|
|
|
private static AIAgent CreateInnerAgent(
|
|
AIProjectClient aiProjectClient,
|
|
string model, string instructions,
|
|
string? name, string? description,
|
|
IList<AITool>? tools,
|
|
Func<IChatClient, IChatClient>? clientFactory,
|
|
ILoggerFactory? loggerFactory,
|
|
IServiceProvider? services,
|
|
out AIProjectClient outClient)
|
|
{
|
|
Throw.IfNullOrWhitespace(model);
|
|
Throw.IfNullOrWhitespace(instructions);
|
|
|
|
outClient = aiProjectClient;
|
|
|
|
ChatClientAgentOptions options = new()
|
|
{
|
|
Name = name,
|
|
Description = description,
|
|
ChatOptions = new ChatOptions
|
|
{
|
|
ModelId = model,
|
|
Instructions = instructions,
|
|
Tools = tools,
|
|
},
|
|
};
|
|
|
|
return CreateResponsesChatClientAgent(aiProjectClient, options, clientFactory, loggerFactory, services);
|
|
}
|
|
|
|
private static AIAgent CreateResponsesChatClientAgent(
|
|
AIProjectClient aiProjectClient,
|
|
ChatClientAgentOptions agentOptions,
|
|
Func<IChatClient, IChatClient>? clientFactory,
|
|
ILoggerFactory? loggerFactory,
|
|
IServiceProvider? services)
|
|
{
|
|
Throw.IfNull(aiProjectClient);
|
|
Throw.IfNull(agentOptions);
|
|
Throw.IfNull(agentOptions.ChatOptions);
|
|
Throw.IfNullOrWhitespace(agentOptions.ChatOptions.ModelId);
|
|
|
|
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentOptions.ChatOptions.ModelId);
|
|
|
|
if (clientFactory is not null)
|
|
{
|
|
chatClient = clientFactory(chatClient);
|
|
}
|
|
|
|
return WireClientHeaders(new ChatClientAgent(chatClient, agentOptions, loggerFactory, services));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Registers <see cref="ClientHeadersPolicy"/> on the agent's underlying chat client (if it
|
|
/// exposes <see cref="OpenAIRequestPolicies"/>) and wraps the agent in a
|
|
/// <see cref="ClientHeadersAgent"/> so per-call <c>x-client-*</c> headers stamped via
|
|
/// <see cref="ClientHeadersExtensions.WithClientHeader(ChatOptions, string, string)"/> reach
|
|
/// the wire. Idempotent: if the chain already contains a <see cref="ClientHeadersAgent"/>,
|
|
/// the original instance is returned unchanged.
|
|
/// </summary>
|
|
private static AIAgent WireClientHeaders(ChatClientAgent innerAgent)
|
|
{
|
|
if (innerAgent.GetService<ClientHeadersAgent>() is not null)
|
|
{
|
|
return innerAgent;
|
|
}
|
|
|
|
if (innerAgent.ChatClient.GetService<OpenAIRequestPolicies>() is { } policies)
|
|
{
|
|
OpenAIRequestPoliciesReflection.AddPolicyIfMissing(
|
|
policies,
|
|
ClientHeadersPolicy.Instance,
|
|
PipelinePosition.PerCall);
|
|
}
|
|
|
|
return new ClientHeadersAgent(innerAgent);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Builds the inner <see cref="ChatClientAgent"/> for the agent-endpoint constructor. The
|
|
/// per-agent <see cref="ProjectOpenAIClient"/> shape and URL parsing are owned by
|
|
/// <see cref="FoundryChatClient"/>; we just construct it in the Agent Endpoint mode (Mode 3)
|
|
/// and pass the inner chat client through any caller-provided <paramref name="clientFactory"/>.
|
|
/// </summary>
|
|
private static AIAgent CreateInnerAgentFromAgentEndpoint(
|
|
Uri agentEndpoint,
|
|
AuthenticationTokenProvider credential,
|
|
ProjectOpenAIClientOptions? clientOptions,
|
|
IList<AITool>? tools,
|
|
Func<IChatClient, IChatClient>? clientFactory,
|
|
IServiceProvider? services)
|
|
{
|
|
Throw.IfNull(agentEndpoint);
|
|
Throw.IfNull(credential);
|
|
|
|
IChatClient chatClient = new FoundryChatClient(agentEndpoint, credential, clientOptions);
|
|
var agentName = ((FoundryChatClient)chatClient).AgentName!;
|
|
|
|
if (clientFactory is not null)
|
|
{
|
|
chatClient = clientFactory(chatClient);
|
|
}
|
|
|
|
ChatClientAgentOptions agentOptions = new()
|
|
{
|
|
Id = agentName,
|
|
Name = agentName,
|
|
ChatOptions = new() { Tools = tools },
|
|
};
|
|
|
|
return WireClientHeaders(new ChatClientAgent(chatClient, agentOptions, services: services));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Variant of <see cref="CreateInnerAgentFromAgentEndpoint"/> that reuses an existing
|
|
/// <see cref="AIProjectClient"/>'s pipeline instead of stamping a fresh credential. Used by
|
|
/// the <c>AsAIAgent(AIProjectClient, Uri agentEndpoint, ...)</c> extension overload.
|
|
/// </summary>
|
|
private static AIAgent CreateInnerAgentFromAgentEndpointReusingProjectClient(
|
|
AIProjectClient aiProjectClient,
|
|
Uri agentEndpoint,
|
|
IList<AITool>? tools,
|
|
Func<IChatClient, IChatClient>? clientFactory,
|
|
IServiceProvider? services)
|
|
{
|
|
Throw.IfNull(aiProjectClient);
|
|
Throw.IfNull(agentEndpoint);
|
|
|
|
IChatClient chatClient = new FoundryChatClient(aiProjectClient, agentEndpoint, clientOptions: null);
|
|
var agentName = ((FoundryChatClient)chatClient).AgentName!;
|
|
|
|
if (clientFactory is not null)
|
|
{
|
|
chatClient = clientFactory(chatClient);
|
|
}
|
|
|
|
ChatClientAgentOptions agentOptions = new()
|
|
{
|
|
Id = agentName,
|
|
Name = agentName,
|
|
ChatOptions = new() { Tools = tools },
|
|
};
|
|
|
|
return WireClientHeaders(new ChatClientAgent(chatClient, agentOptions, services: services));
|
|
}
|
|
|
|
/// <summary>
|
|
/// Parses an agent endpoint URI. Delegates to <see cref="FoundryChatClient.ParseAgentEndpoint(Uri)"/>
|
|
/// so the chat client and the agent share a single source of truth for the URL shape.
|
|
/// </summary>
|
|
internal static (string AgentName, Uri ProjectRoot) ParseAgentEndpoint(Uri agentEndpoint)
|
|
=> FoundryChatClient.ParseAgentEndpoint(agentEndpoint);
|
|
|
|
/// <summary>
|
|
/// Parses an agent endpoint URI of shape
|
|
/// <c>https://<host>/.../projects/<project>/agents/<agentName>/endpoint/protocols/openai</c>
|
|
/// and returns the agent name and the derived project-root URI.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Single source of truth for both agent-name extraction and project-root derivation.
|
|
/// Tolerates trailing slash, casing variants on <c>/agents/</c> and the suffix segment, and
|
|
/// strips query string and fragment. Throws <see cref="ArgumentException"/> for inputs that
|
|
/// do not match the expected shape.
|
|
/// </remarks>
|
|
private static AIProjectClient CreateProjectClient(Uri endpoint, AuthenticationTokenProvider credential, AIProjectClientOptions? clientOptions = null)
|
|
{
|
|
Throw.IfNull(endpoint);
|
|
Throw.IfNull(credential);
|
|
|
|
return new AIProjectClient(endpoint, credential, clientOptions ?? new AIProjectClientOptions());
|
|
}
|
|
|
|
#endregion
|
|
}
|