Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
<PackageVersion Include="NuGet.Protocol" Version="7.9.0" />
<PackageVersion Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.23.0" />
<PackageVersion Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="10.0.2" />
<PackageVersion Include="Microsoft.Extensions.AI.OpenAI" Version="10.5.0" />
<PackageVersion Include="Microsoft.Extensions.AI.OpenAI" Version="10.9.0" />
<PackageVersion Include="ModelContextProtocol" Version="2.1.0" />
<PackageVersion Include="ModelContextProtocol.AspNetCore" Version="2.1.0" />
<PackageVersion Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.11" />
Expand All @@ -64,7 +64,7 @@
<PackageVersion Include="System.ClientModel" Version="1.15.0" />
<PackageVersion Include="Newtonsoft.Json" Version="13.0.4" />
<PackageVersion Include="Octokit" Version="14.0.0" />
<PackageVersion Include="OpenAI" Version="2.10.0" />
<PackageVersion Include="OpenAI" Version="2.12.0" />
<PackageVersion Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.17.0" />
<PackageVersion Include="OpenTelemetry.Extensions.Hosting" Version="1.17.0" />
<PackageVersion Include="OpenTelemetry.Instrumentation.AspNetCore" Version="1.17.0" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ public static IServiceCollection AddAzureOpenAIServices(
services.AddSingleton(provider =>
new AzureOpenAIClient(endpoint, credential));

// Register the resolved credential so AIChatService can build its ResponsesClient
// directly, bypassing the binary-incompatible AzureOpenAIClient.GetResponsesClient().
services.AddSingleton(credential);

services.AddAzureOpenAIChatCompletion(
aiOptions.ChatDeploymentName,
aiOptions.Endpoint,
Expand Down
83 changes: 76 additions & 7 deletions EssentialCSharp.Chat.Shared/Services/AIChatService.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
using Azure.AI.OpenAI;
using Azure.Core;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol;
using OpenAI.Responses;
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Collections.Frozen;

namespace EssentialCSharp.Chat.Common.Services;
Expand All @@ -15,7 +16,6 @@ namespace EssentialCSharp.Chat.Common.Services;
public partial class AIChatService : IChatCompletionService
{
private readonly AIOptions _Options;
private readonly AzureOpenAIClient _AzureClient;
#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
private readonly ResponsesClient _ResponseClient;
#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
Expand All @@ -25,21 +25,90 @@ public partial class AIChatService : IChatCompletionService
public bool IsAvailable => true;
public bool SupportsContextualSearch => true;

public AIChatService(IOptions<AIOptions> options, AISearchService searchService, AzureOpenAIClient azureClient, ILogger<AIChatService> logger)
// The scope required for Azure OpenAI token auth via managed identity.
private const string AzureCognitiveServicesScope = "https://cognitiveservices.azure.com/.default";

// The Azure OpenAI REST API version used by Azure.AI.OpenAI 2.9.0-beta.1.
// AzureOpenAIClient.GetResponsesClient() is binary-incompatible with OpenAI 2.12.0
// because OpenAI changed the ResponsesClient constructor from (ClientPipeline, OpenAIClientOptions)
// to (ClientPipeline, ResponsesClientOptions). Until Azure.AI.OpenAI ships an update that
// supports OpenAI 2.12+, we construct ResponsesClient directly using BearerTokenPolicy.
private const string AzureApiVersion = "2025-04-01-preview";

public AIChatService(IOptions<AIOptions> options, AISearchService searchService, TokenCredential credential, ILogger<AIChatService> logger)
{
_Options = options.Value;
_SearchService = searchService;
_Logger = logger;
_AllowedMcpTools = _Options.AllowedMcpTools.ToFrozenSet(StringComparer.Ordinal);

// Initialize Azure OpenAI client and get the Response Client from it
_AzureClient = azureClient;

#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
_ResponseClient = _AzureClient.GetResponsesClient();
// Build an Azure-authenticated ResponsesClient directly, targeting the deployment endpoint.
// The endpoint is: {AzureEndpoint}/openai/deployments/{ChatDeploymentName}
// ResponsesClient appends "/responses" to produce the full Azure REST path.
var deploymentEndpoint = new Uri(
$"{_Options.Endpoint.TrimEnd('/')}/openai/deployments/{_Options.ChatDeploymentName}");

var responsesOptions = new ResponsesClientOptions { Endpoint = deploymentEndpoint };
responsesOptions.AddPolicy(new ApiVersionPipelinePolicy(AzureApiVersion), PipelinePosition.PerCall);

var tokenProvider = new AzureCogServicesTokenProvider(credential);
var bearerPolicy = new BearerTokenPolicy(tokenProvider, AzureCognitiveServicesScope);
_ResponseClient = new ResponsesClient(bearerPolicy, responsesOptions);
#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
}

/// <summary>
/// Adds the Azure api-version query parameter to every outgoing request.
/// Required because the base ResponsesClient does not know the Azure API version;
/// that concern was previously handled internally by AzureResponsesClient.
/// </summary>
private sealed class ApiVersionPipelinePolicy(string apiVersion) : PipelinePolicy
{
public override void Process(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
AppendApiVersion(message);
ProcessNext(message, pipeline, currentIndex);
}

public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList<PipelinePolicy> pipeline, int currentIndex)
{
AppendApiVersion(message);
await ProcessNextAsync(message, pipeline, currentIndex);
}

private void AppendApiVersion(PipelineMessage message)
{
var uri = message.Request.Uri?.ToString();
if (uri is null || uri.Contains("api-version", StringComparison.OrdinalIgnoreCase))
return;
var separator = uri.Contains('?') ? '&' : '?';
message.Request.Uri = new Uri(uri + separator + "api-version=" + apiVersion);
}
}

/// <summary>
/// Bridges Azure.Core's <see cref="TokenCredential"/> into the System.ClientModel
/// <see cref="AuthenticationTokenProvider"/> abstraction used by <see cref="BearerTokenPolicy"/>.
/// </summary>
private sealed class AzureCogServicesTokenProvider(TokenCredential credential) : AuthenticationTokenProvider
{
public override GetTokenOptions CreateTokenOptions(IReadOnlyDictionary<string, object> context)
=> new(context);

public override AuthenticationToken GetToken(GetTokenOptions options, CancellationToken cancellationToken)
{
var token = credential.GetToken(new TokenRequestContext([AzureCognitiveServicesScope]), cancellationToken);
return new AuthenticationToken(token.Token, "Bearer", token.ExpiresOn, null);
}

public override async ValueTask<AuthenticationToken> GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken)
{
var token = await credential.GetTokenAsync(new TokenRequestContext([AzureCognitiveServicesScope]), cancellationToken);
return new AuthenticationToken(token.Token, "Bearer", token.ExpiresOn, null);
}
}

/// <summary>
/// Gets a single chat completion response with all optional features
/// </summary>
Expand Down