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
3 changes: 1 addition & 2 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
<PackageVersion Include="AspNet.Security.OAuth.GitHub" Version="10.0.0" />
<PackageVersion Include="Azure.Extensions.AspNetCore.Configuration.Secrets" Version="1.5.2" />
<PackageVersion Include="Azure.Identity" Version="1.21.0" />
<PackageVersion Include="Azure.AI.OpenAI" Version="2.9.0-beta.1" />
<PackageVersion Include="Azure.Monitor.OpenTelemetry.AspNetCore" Version="1.6.0" />
<!-- TODO: update to stable release when Azure.Monitor.OpenTelemetry.Profiler reaches GA -->
<PackageVersion Include="Azure.Monitor.OpenTelemetry.Profiler" Version="1.0.1-beta.7" />
Expand All @@ -41,7 +40,7 @@
<PackageVersion Include="Microsoft.EntityFrameworkCore.SqlServer" Version="10.0.13" />
<PackageVersion Include="Microsoft.EntityFrameworkCore.Tools" Version="10.0.13" />
<PackageVersion Include="Microsoft.Extensions.Http.Resilience" Version="10.11.0" />
<PackageVersion Include="Microsoft.SemanticKernel" Version="1.81.0" />
<PackageVersion Include="Microsoft.SemanticKernel.Core" Version="1.81.0" />
<PackageVersion Include="CommunityToolkit.VectorData.PgVector" Version="1.0.1" />
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.402" />
<!-- Pin to patched versions; NuGet.Protocol 6.12.5+ fixes GHSA-g4vj-cjjj-v7hg (pulled in by Microsoft.VisualStudio.Web.CodeGeneration.Design) -->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
<ItemGroup>
<PackageReference Include="Azure.Identity" />
<PackageReference Include="Microsoft.Extensions.AI.OpenAI" />
<PackageReference Include="Microsoft.SemanticKernel" />
<PackageReference Include="Microsoft.SemanticKernel.Core" />
<PackageReference Include="CommunityToolkit.VectorData.PgVector" />
<PackageReference Include="Microsoft.Extensions.Http.Resilience" />
<PackageReference Include="ModelContextProtocol" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
using Azure.AI.OpenAI;
using Azure.Core;
using Azure.Identity;
using EssentialCSharp.Chat.Common.Models;
Expand All @@ -7,7 +6,6 @@
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Microsoft.SemanticKernel;
using Npgsql;

namespace EssentialCSharp.Chat.Common.Extensions;
Expand Down Expand Up @@ -40,37 +38,17 @@ public static IServiceCollection AddAzureOpenAIServices(
throw new InvalidOperationException("AIOptions.Endpoint is required.");
}

var endpoint = new Uri(aiOptions.Endpoint);

// Register Azure OpenAI services with Managed Identity authentication
#pragma warning disable SKEXP0010 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed.
services.AddAzureOpenAIChatClient(
aiOptions.ChatDeploymentName,
endpoint.ToString(),
credential);

services.AddSingleton(provider =>
new AzureOpenAIClient(endpoint, credential));

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

services.AddAzureOpenAIChatCompletion(
aiOptions.ChatDeploymentName,
aiOptions.Endpoint,
credential);

// Add PostgreSQL vector store with managed identity support
services.AddPostgresVectorStoreWithManagedIdentity(postgresConnectionString, credential);

services.AddEmbeddingGenerator(sp =>
sp.GetRequiredService<AzureOpenAIClient>()
.GetEmbeddingClient(aiOptions.VectorGenerationDeploymentName)
AzureOpenAIV1Clients.CreateEmbeddingClient(aiOptions.Endpoint, aiOptions.VectorGenerationDeploymentName, credential)
.AsIEmbeddingGenerator())
.UseLogging()
.UseOpenTelemetry();
#pragma warning restore SKEXP0010

// Ensure options are available even when caller provides AIOptions directly.
services.AddOptions<EmbeddingRetryOptions>()
Expand Down
81 changes: 1 addition & 80 deletions EssentialCSharp.Chat.Shared/Services/AIChatService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,8 @@ public partial class AIChatService : IChatCompletionService
public bool IsAvailable => true;
public bool SupportsContextualSearch => true;

// 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)
: this(options, searchService, CreateResponseClient(options.Value, credential), logger)
: this(options, searchService, AzureOpenAIV1Clients.CreateResponsesClient(options.Value.Endpoint, credential), logger)
{
}

Expand All @@ -61,75 +51,6 @@ public AIChatService(
_ResponseClient = responseClient;
}

#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 static ResponsesClient CreateResponseClient(AIOptions options, TokenCredential credential)
{
// 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);
return 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
74 changes: 74 additions & 0 deletions EssentialCSharp.Chat.Shared/Services/AzureOpenAIV1Clients.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using Azure.Core;
using OpenAI;
using OpenAI.Embeddings;
using OpenAI.Responses;
using System.ClientModel;
using System.ClientModel.Primitives;

namespace EssentialCSharp.Chat.Common.Services;

/// <summary>
/// Builds plain OpenAI SDK clients for the Azure OpenAI v1 API (<c>{endpoint}/openai/v1</c>).
/// </summary>
/// <remarks>
/// The v1 routes need no <c>api-version</c> and take the deployment name as the request's <c>model</c>
/// (there is no <c>/deployments/{name}</c> route for Responses). Authentication is Entra ID through
/// <see cref="TokenCredential"/>. This follows Microsoft's guidance to use the <c>OpenAI</c> package directly
/// instead of <c>Azure.AI.OpenAI</c>: https://learn.microsoft.com/azure/foundry/openai/api-version-lifecycle
/// </remarks>
public static class AzureOpenAIV1Clients
{
// The scope the existing resource has been called with so far; keep it until the v1 route is verified with another.
private const string TokenScope = "https://cognitiveservices.azure.com/.default";

public static Uri GetV1Endpoint(string endpoint) => new($"{endpoint.TrimEnd('/')}/openai/v1");

#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.
public static ResponsesClient CreateResponsesClient(string endpoint, TokenCredential credential, PipelineTransport? transport = null)
{
ResponsesClientOptions options = new() { Endpoint = GetV1Endpoint(endpoint) };
if (transport is not null)
{
options.Transport = transport;
}

return new ResponsesClient(CreateBearerPolicy(credential), options);
}

public static EmbeddingClient CreateEmbeddingClient(string endpoint, string deploymentName, TokenCredential credential, PipelineTransport? transport = null)
{
OpenAIClientOptions options = new() { Endpoint = GetV1Endpoint(endpoint) };
if (transport is not null)
{
options.Transport = transport;
}

return new EmbeddingClient(deploymentName, CreateBearerPolicy(credential), options);
}
#pragma warning restore OPENAI001

private static BearerTokenPolicy CreateBearerPolicy(TokenCredential credential) =>
new(new CredentialTokenProvider(credential), TokenScope);

/// <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 CredentialTokenProvider(TokenCredential credential) : AuthenticationTokenProvider
{
public override GetTokenOptions CreateTokenOptions(IReadOnlyDictionary<string, object> context)
=> new(context);

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

public override async ValueTask<AuthenticationToken> GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken)
{
AccessToken token = await credential.GetTokenAsync(new TokenRequestContext([TokenScope]), cancellationToken);
return new AuthenticationToken(token.Token, "Bearer", token.ExpiresOn, null);
}
}
}
102 changes: 102 additions & 0 deletions EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
using System.ClientModel;
using System.ClientModel.Primitives;
using System.Net;
using System.Net.Http.Json;
using System.Text.Json;
using Azure.Core;
using EssentialCSharp.Chat.Common.Services;
using OpenAI.Responses;

namespace EssentialCSharp.Chat.Tests;

/// <summary>
/// Pins the exact requests sent to the Azure OpenAI v1 API. The live resource is private, so a wrong route
/// (for example <c>/openai/deployments/{name}/responses</c>, which 404s) is otherwise only found by a real chat.
/// </summary>
public class AzureOpenAIV1ClientsTests
{
private const string Endpoint = "https://example.cognitiveservices.azure.com/";

[Test]
[Arguments("https://example.cognitiveservices.azure.com/", "https://example.cognitiveservices.azure.com/openai/v1")]
[Arguments("https://example.cognitiveservices.azure.com", "https://example.cognitiveservices.azure.com/openai/v1")]
public async Task GetV1Endpoint_AppendsOpenAiV1(string endpoint, string expected)
{
await Assert.That(AzureOpenAIV1Clients.GetV1Endpoint(endpoint).ToString()).IsEqualTo(expected);
}

[Test]
public async Task ResponsesClient_PostsToV1ResponsesWithBearerTokenAndDeploymentAsModel()
{
#pragma warning disable OPENAI001 // Responses API types are experimental in the OpenAI SDK.
CapturingHandler handler = new();
ResponsesClient client = AzureOpenAIV1Clients.CreateResponsesClient(Endpoint, new FakeCredential(), CreateTransport(handler));

CreateResponseOptions options = new() { Model = "web-chat" };
options.InputItems.Add(ResponseItem.CreateUserMessageItem("hello"));
await Assert.That(async () => await client.CreateResponseAsync(options)).Throws<ClientResultException>();

using (Assert.Multiple())
{
await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post);
// Uri equality includes the query string, so this also proves no api-version is appended.
await Assert.That(handler.Request.Uri).IsEqualTo(new Uri("https://example.cognitiveservices.azure.com/openai/v1/responses"));
await Assert.That(handler.Request.Authorization).IsEqualTo("Bearer test-token");
await Assert.That(JsonDocument.Parse(handler.Request.Body).RootElement.GetProperty("model").GetString()).IsEqualTo("web-chat");
}
#pragma warning restore OPENAI001
}

[Test]
public async Task EmbeddingClient_PostsToV1EmbeddingsWithBearerTokenAndDeploymentAsModel()
{
CapturingHandler handler = new();
var client = AzureOpenAIV1Clients.CreateEmbeddingClient(Endpoint, "embedding-model", new FakeCredential(), CreateTransport(handler));

await Assert.That(async () => await client.GenerateEmbeddingAsync("hello")).Throws<ClientResultException>();

using (Assert.Multiple())
{
await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post);
// Uri equality includes the query string, so this also proves no api-version is appended.
await Assert.That(handler.Request.Uri).IsEqualTo(new Uri("https://example.cognitiveservices.azure.com/openai/v1/embeddings"));
await Assert.That(handler.Request.Authorization).IsEqualTo("Bearer test-token");
await Assert.That(JsonDocument.Parse(handler.Request.Body).RootElement.GetProperty("model").GetString()).IsEqualTo("embedding-model");
}
}

private static HttpClientPipelineTransport CreateTransport(CapturingHandler handler) => new(new HttpClient(handler));

private sealed class FakeCredential : TokenCredential
{
public override AccessToken GetToken(TokenRequestContext requestContext, CancellationToken cancellationToken) =>
new("test-token", DateTimeOffset.UtcNow.AddHours(1));

public override ValueTask<AccessToken> GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) =>
new(GetToken(requestContext, cancellationToken));
}

/// <summary>Records the first request and answers 404 so the SDK call throws without a real service.</summary>
private sealed class CapturingHandler : HttpMessageHandler
{
private CapturedRequest? _request;

public CapturedRequest Request => _request
?? throw new InvalidOperationException("The client under test never sent a request.");

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
_request = new CapturedRequest(
request.Method,
request.RequestUri ?? throw new InvalidOperationException("The request has no URI."),
request.Headers.Authorization?.ToString(),
request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken));
return new HttpResponseMessage(HttpStatusCode.NotFound)
{
Content = JsonContent.Create(new { error = new { message = "Resource not found" } })
};
}
}

private sealed record CapturedRequest(HttpMethod Method, Uri Uri, string? Authorization, string Body);
}
2 changes: 1 addition & 1 deletion EssentialCSharp.Chat/EssentialCSharp.Chat.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@

<ItemGroup>
<PackageReference Include="Azure.Extensions.AspNetCore.Configuration.Secrets" />
<PackageReference Include="Microsoft.SemanticKernel" />
<PackageReference Include="Microsoft.SemanticKernel.Core" />
<PackageReference Include="CommunityToolkit.VectorData.PgVector" />
<PackageReference Include="ModelContextProtocol" />
<PackageReference Include="IntelliTect.Multitool" />
Expand Down
Loading