From 3e08a6f86b796dec3d47f13ead45514db8de23c7 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Sun, 25 Oct 2026 18:33:38 -0700 Subject: [PATCH 1/4] fix(chat): call Azure OpenAI v1 API with the OpenAI SDK, drop Azure.AI.OpenAI Chat on dev fails with HTTP 404 because AIChatService builds the Responses client by hand at {endpoint}/openai/deployments/{name}, a route the service does not have for Responses. Prod still runs the older SDK-built client (/openai/responses) and works, so the next prod deploy would break chat. Use the plain OpenAI SDK against the documented v1 route instead, as Microsoft's migration guidance recommends (Azure.AI.OpenAI has had no release since 2026-03-13): - Add AzureOpenAIV1Clients: Responses and embedding clients at {endpoint}/openai/v1, no api-version, deployment name as the model, Entra bearer auth (scope unchanged). - AIChatService and the embedding generator use it; remove the hand-built deployment URL, api-version policy and AzureOpenAIClient registration, plus two unused Semantic Kernel chat registrations. - Replace Microsoft.SemanticKernel with Microsoft.SemanticKernel.Core (the metapackage was the only source of Azure.AI.OpenAI) and drop the Azure.AI.OpenAI version. - Add tests pinning the request method, URL, auth header and model. --- Directory.Packages.props | 3 +- .../EssentialCSharp.Chat.Common.csproj | 2 +- .../Extensions/ServiceCollectionExtensions.cs | 26 +----- .../Services/AIChatService.cs | 81 +--------------- .../Services/AzureOpenAIV1Clients.cs | 74 +++++++++++++++ .../AzureOpenAIV1ClientsTests.cs | 93 +++++++++++++++++++ .../EssentialCSharp.Chat.csproj | 2 +- 7 files changed, 173 insertions(+), 108 deletions(-) create mode 100644 EssentialCSharp.Chat.Shared/Services/AzureOpenAIV1Clients.cs create mode 100644 EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs diff --git a/Directory.Packages.props b/Directory.Packages.props index 51ca5877..a98ed3cf 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -18,7 +18,6 @@ - @@ -41,7 +40,7 @@ - + diff --git a/EssentialCSharp.Chat.Shared/EssentialCSharp.Chat.Common.csproj b/EssentialCSharp.Chat.Shared/EssentialCSharp.Chat.Common.csproj index 83273b81..be145c61 100644 --- a/EssentialCSharp.Chat.Shared/EssentialCSharp.Chat.Common.csproj +++ b/EssentialCSharp.Chat.Shared/EssentialCSharp.Chat.Common.csproj @@ -7,7 +7,7 @@ - + diff --git a/EssentialCSharp.Chat.Shared/Extensions/ServiceCollectionExtensions.cs b/EssentialCSharp.Chat.Shared/Extensions/ServiceCollectionExtensions.cs index 60dc38f8..38f41425 100644 --- a/EssentialCSharp.Chat.Shared/Extensions/ServiceCollectionExtensions.cs +++ b/EssentialCSharp.Chat.Shared/Extensions/ServiceCollectionExtensions.cs @@ -1,4 +1,3 @@ -using Azure.AI.OpenAI; using Azure.Core; using Azure.Identity; using EssentialCSharp.Chat.Common.Models; @@ -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; @@ -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() - .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() diff --git a/EssentialCSharp.Chat.Shared/Services/AIChatService.cs b/EssentialCSharp.Chat.Shared/Services/AIChatService.cs index 1e815518..7a94f920 100644 --- a/EssentialCSharp.Chat.Shared/Services/AIChatService.cs +++ b/EssentialCSharp.Chat.Shared/Services/AIChatService.cs @@ -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 options, AISearchService searchService, TokenCredential credential, ILogger logger) - : this(options, searchService, CreateResponseClient(options.Value, credential), logger) + : this(options, searchService, AzureOpenAIV1Clients.CreateResponsesClient(options.Value.Endpoint, credential), logger) { } @@ -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. - } - - /// - /// 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. - /// - private sealed class ApiVersionPipelinePolicy(string apiVersion) : PipelinePolicy - { - public override void Process(PipelineMessage message, IReadOnlyList pipeline, int currentIndex) - { - AppendApiVersion(message); - ProcessNext(message, pipeline, currentIndex); - } - - public override async ValueTask ProcessAsync(PipelineMessage message, IReadOnlyList 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); - } - } - - /// - /// Bridges Azure.Core's into the System.ClientModel - /// abstraction used by . - /// - private sealed class AzureCogServicesTokenProvider(TokenCredential credential) : AuthenticationTokenProvider - { - public override GetTokenOptions CreateTokenOptions(IReadOnlyDictionary 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 GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken) - { - var token = await credential.GetTokenAsync(new TokenRequestContext([AzureCognitiveServicesScope]), cancellationToken); - return new AuthenticationToken(token.Token, "Bearer", token.ExpiresOn, null); - } - } - /// /// Gets a single chat completion response with all optional features /// diff --git a/EssentialCSharp.Chat.Shared/Services/AzureOpenAIV1Clients.cs b/EssentialCSharp.Chat.Shared/Services/AzureOpenAIV1Clients.cs new file mode 100644 index 00000000..4f2671cd --- /dev/null +++ b/EssentialCSharp.Chat.Shared/Services/AzureOpenAIV1Clients.cs @@ -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; + +/// +/// Builds plain OpenAI SDK clients for the Azure OpenAI v1 API ({endpoint}/openai/v1). +/// +/// +/// The v1 routes need no api-version and take the deployment name as the request's model +/// (there is no /deployments/{name} route for Responses). Authentication is Entra ID through +/// . This follows Microsoft's guidance to use the OpenAI package directly +/// instead of Azure.AI.OpenAI: https://learn.microsoft.com/azure/foundry/openai/api-version-lifecycle +/// +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); + + /// + /// Bridges Azure.Core's into the System.ClientModel + /// abstraction used by . + /// + private sealed class CredentialTokenProvider(TokenCredential credential) : AuthenticationTokenProvider + { + public override GetTokenOptions CreateTokenOptions(IReadOnlyDictionary 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 GetTokenAsync(GetTokenOptions options, CancellationToken cancellationToken) + { + AccessToken token = await credential.GetTokenAsync(new TokenRequestContext([TokenScope]), cancellationToken); + return new AuthenticationToken(token.Token, "Bearer", token.ExpiresOn, null); + } + } +} diff --git a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs new file mode 100644 index 00000000..ec75b37d --- /dev/null +++ b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs @@ -0,0 +1,93 @@ +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Net; +using System.Text; +using System.Text.Json; +using Azure.Core; +using EssentialCSharp.Chat.Common.Services; +using OpenAI.Responses; + +namespace EssentialCSharp.Chat.Tests; + +/// +/// Pins the exact requests sent to the Azure OpenAI v1 API. The live resource is private, so a wrong route +/// (for example /openai/deployments/{name}/responses, which 404s) is otherwise only found by a real chat. +/// +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.ThrowsAsync(async () => await client.CreateResponseAsync(options)); + + await Assert.That(handler.Method).IsEqualTo(HttpMethod.Post); + await Assert.That(handler.Uri!.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/responses"); + await Assert.That(handler.Uri.Query).IsEmpty(); + await Assert.That(handler.Authorization).IsEqualTo("Bearer test-token"); + await Assert.That(JsonDocument.Parse(handler.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.ThrowsAsync(async () => await client.GenerateEmbeddingAsync("hello")); + + await Assert.That(handler.Method).IsEqualTo(HttpMethod.Post); + await Assert.That(handler.Uri!.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/embeddings"); + await Assert.That(handler.Uri.Query).IsEmpty(); + await Assert.That(handler.Authorization).IsEqualTo("Bearer test-token"); + await Assert.That(JsonDocument.Parse(handler.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 GetTokenAsync(TokenRequestContext requestContext, CancellationToken cancellationToken) => + new(GetToken(requestContext, cancellationToken)); + } + + /// Records the first request and answers 404 so the SDK call throws without a real service. + private sealed class CapturingHandler : HttpMessageHandler + { + public HttpMethod? Method { get; private set; } + public Uri? Uri { get; private set; } + public string? Authorization { get; private set; } + public string? Body { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Method = request.Method; + Uri = request.RequestUri; + Authorization = request.Headers.Authorization?.ToString(); + Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); + return new HttpResponseMessage(HttpStatusCode.NotFound) + { + Content = new StringContent("{\"error\":{\"message\":\"Resource not found\"}}", Encoding.UTF8, "application/json") + }; + } + } +} diff --git a/EssentialCSharp.Chat/EssentialCSharp.Chat.csproj b/EssentialCSharp.Chat/EssentialCSharp.Chat.csproj index 33fc4920..e5665159 100644 --- a/EssentialCSharp.Chat/EssentialCSharp.Chat.csproj +++ b/EssentialCSharp.Chat/EssentialCSharp.Chat.csproj @@ -19,7 +19,7 @@ - + From 6e7caa4f806116eae970a5bca20aba1c2fc57a83 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Sun, 25 Oct 2026 22:50:16 -0700 Subject: [PATCH 2/4] test: capture the request in a non-null record instead of using null-forgiving operators --- .../AzureOpenAIV1ClientsTests.cs | 39 ++++++++++--------- 1 file changed, 21 insertions(+), 18 deletions(-) diff --git a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs index ec75b37d..22f660c9 100644 --- a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs +++ b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs @@ -36,11 +36,11 @@ public async Task ResponsesClient_PostsToV1ResponsesWithBearerTokenAndDeployment options.InputItems.Add(ResponseItem.CreateUserMessageItem("hello")); _ = await Assert.ThrowsAsync(async () => await client.CreateResponseAsync(options)); - await Assert.That(handler.Method).IsEqualTo(HttpMethod.Post); - await Assert.That(handler.Uri!.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/responses"); - await Assert.That(handler.Uri.Query).IsEmpty(); - await Assert.That(handler.Authorization).IsEqualTo("Bearer test-token"); - await Assert.That(JsonDocument.Parse(handler.Body!).RootElement.GetProperty("model").GetString()).IsEqualTo("web-chat"); + await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post); + await Assert.That(handler.Request.Uri.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/responses"); + await Assert.That(handler.Request.Uri.Query).IsEmpty(); + 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 } @@ -52,11 +52,11 @@ public async Task EmbeddingClient_PostsToV1EmbeddingsWithBearerTokenAndDeploymen _ = await Assert.ThrowsAsync(async () => await client.GenerateEmbeddingAsync("hello")); - await Assert.That(handler.Method).IsEqualTo(HttpMethod.Post); - await Assert.That(handler.Uri!.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/embeddings"); - await Assert.That(handler.Uri.Query).IsEmpty(); - await Assert.That(handler.Authorization).IsEqualTo("Bearer test-token"); - await Assert.That(JsonDocument.Parse(handler.Body!).RootElement.GetProperty("model").GetString()).IsEqualTo("embedding-model"); + await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post); + await Assert.That(handler.Request.Uri.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/embeddings"); + await Assert.That(handler.Request.Uri.Query).IsEmpty(); + 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)); @@ -73,21 +73,24 @@ public override ValueTask GetTokenAsync(TokenRequestContext request /// Records the first request and answers 404 so the SDK call throws without a real service. private sealed class CapturingHandler : HttpMessageHandler { - public HttpMethod? Method { get; private set; } - public Uri? Uri { get; private set; } - public string? Authorization { get; private set; } - public string? Body { get; private set; } + private CapturedRequest? _request; + + public CapturedRequest Request => _request + ?? throw new InvalidOperationException("The client under test never sent a request."); protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - Method = request.Method; - Uri = request.RequestUri; - Authorization = request.Headers.Authorization?.ToString(); - Body = request.Content is null ? null : await request.Content.ReadAsStringAsync(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 = new StringContent("{\"error\":{\"message\":\"Resource not found\"}}", Encoding.UTF8, "application/json") }; } } + + private sealed record CapturedRequest(HttpMethod Method, Uri Uri, string? Authorization, string Body); } From 11ee0523a938046c67f136afc6ffdabcae39df9b Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Sun, 25 Oct 2026 22:57:10 -0700 Subject: [PATCH 3/4] test: use TUnit exception chains, Assert.Multiple, and Uri equality in v1 client tests --- .../AzureOpenAIV1ClientsTests.cs | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs index 22f660c9..26c719ec 100644 --- a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs +++ b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs @@ -34,13 +34,16 @@ public async Task ResponsesClient_PostsToV1ResponsesWithBearerTokenAndDeployment CreateResponseOptions options = new() { Model = "web-chat" }; options.InputItems.Add(ResponseItem.CreateUserMessageItem("hello")); - _ = await Assert.ThrowsAsync(async () => await client.CreateResponseAsync(options)); + await Assert.That(async () => await client.CreateResponseAsync(options)).Throws(); - await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post); - await Assert.That(handler.Request.Uri.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/responses"); - await Assert.That(handler.Request.Uri.Query).IsEmpty(); - 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"); + 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 } @@ -50,13 +53,16 @@ public async Task EmbeddingClient_PostsToV1EmbeddingsWithBearerTokenAndDeploymen CapturingHandler handler = new(); var client = AzureOpenAIV1Clients.CreateEmbeddingClient(Endpoint, "embedding-model", new FakeCredential(), CreateTransport(handler)); - _ = await Assert.ThrowsAsync(async () => await client.GenerateEmbeddingAsync("hello")); + await Assert.That(async () => await client.GenerateEmbeddingAsync("hello")).Throws(); - await Assert.That(handler.Request.Method).IsEqualTo(HttpMethod.Post); - await Assert.That(handler.Request.Uri.GetLeftPart(UriPartial.Path)).IsEqualTo("https://example.cognitiveservices.azure.com/openai/v1/embeddings"); - await Assert.That(handler.Request.Uri.Query).IsEmpty(); - 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"); + 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)); From 347651ed5c6dbf4bd8d5bb0e07a9470e9df7e934 Mon Sep 17 00:00:00 2001 From: Benjamin Michaelis Date: Mon, 26 Oct 2026 13:37:00 -0700 Subject: [PATCH 4/4] test: build the stub 404 body with JsonContent.Create --- EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs index 26c719ec..a77ebc60 100644 --- a/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs +++ b/EssentialCSharp.Chat.Tests/AzureOpenAIV1ClientsTests.cs @@ -1,7 +1,7 @@ using System.ClientModel; using System.ClientModel.Primitives; using System.Net; -using System.Text; +using System.Net.Http.Json; using System.Text.Json; using Azure.Core; using EssentialCSharp.Chat.Common.Services; @@ -93,7 +93,7 @@ protected override async Task SendAsync(HttpRequestMessage request.Content is null ? string.Empty : await request.Content.ReadAsStringAsync(cancellationToken)); return new HttpResponseMessage(HttpStatusCode.NotFound) { - Content = new StringContent("{\"error\":{\"message\":\"Resource not found\"}}", Encoding.UTF8, "application/json") + Content = JsonContent.Create(new { error = new { message = "Resource not found" } }) }; } }