chore: import upstream snapshot with attribution
dotnet-build-and-test / dotnet-test-functions (push) Has been cancelled
dotnet-build-and-test / paths-filter (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Debug, windows-latest, net9.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, ubuntu-latest, net8.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-build (Release, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, ubuntu-latest, net10.0) (push) Has been cancelled
dotnet-build-and-test / dotnet-test (Release, integration, true, windows-latest, net472) (push) Has been cancelled
dotnet-build-and-test / dotnet-foundry-hosted-it (push) Has been cancelled
dotnet-build-and-test / dotnet-build-and-test-check (push) Has been cancelled
dotnet-build-and-test / Integration Test Report (push) Has been cancelled
CodeQL / Analyze (csharp) (push) Has been cancelled
CodeQL / Analyze (python) (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:39:25 +08:00
commit db620d33df
5151 changed files with 925932 additions and 0 deletions
@@ -0,0 +1,375 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using OpenAI.Responses;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
using ChatRole = Microsoft.Extensions.AI.ChatRole;
using OpenAIChatMessage = OpenAI.Chat.ChatMessage;
using TextContent = Microsoft.Extensions.AI.TextContent;
namespace Microsoft.Agents.AI.OpenAI.UnitTests.Extensions;
/// <summary>
/// Unit tests for the <see cref="AIAgentWithOpenAIExtensions"/> class.
/// </summary>
public sealed class AIAgentWithOpenAIExtensionsTests
{
/// <summary>
/// Verify that RunAsync throws ArgumentNullException when agent is null.
/// </summary>
[Fact]
public async Task RunAsync_WithNullAgent_ThrowsArgumentNullExceptionAsync()
{
// Arrange
AIAgent? agent = null;
var messages = new List<OpenAIChatMessage>
{
OpenAIChatMessage.CreateUserMessage("Test message")
};
// Act & Assert
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => agent!.RunAsync(messages));
Assert.Equal("agent", exception.ParamName);
}
/// <summary>
/// Verify that RunAsync throws ArgumentNullException when messages is null.
/// </summary>
[Fact]
public async Task RunAsync_WithNullMessages_ThrowsArgumentNullExceptionAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
IEnumerable<OpenAIChatMessage>? messages = null;
// Act & Assert
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => mockAgent.Object.RunAsync(messages!));
Assert.Equal("messages", exception.ParamName);
}
/// <summary>
/// Verify that the RunAsync extension method calls the underlying agent's RunAsync with converted messages and parameters.
/// </summary>
[Fact]
public async Task RunAsync_CallsUnderlyingAgentAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
var mockSession = new Mock<AgentSession>();
var options = new AgentRunOptions();
var cancellationToken = new CancellationToken(false);
const string TestMessageText = "Hello, assistant!";
const string ResponseText = "This is the assistant's response.";
var openAiMessages = new List<OpenAIChatMessage>
{
OpenAIChatMessage.CreateUserMessage(TestMessageText)
};
var responseMessage = new ChatMessage(ChatRole.Assistant, [new TextContent(ResponseText)]);
mockAgent
.Protected()
.Setup<Task<AgentResponse>>("RunCoreAsync",
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
ItExpr.IsAny<AgentSession?>(),
ItExpr.IsAny<AgentRunOptions?>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new AgentResponse([responseMessage]));
// Act
var result = await mockAgent.Object.RunAsync(openAiMessages, mockSession.Object, options, cancellationToken);
// Assert
mockAgent.Protected()
.Verify("RunCoreAsync",
Times.Once(),
ItExpr.Is<IEnumerable<ChatMessage>>(msgs =>
msgs.ToList().Count == 1 &&
msgs.ToList()[0].Text == TestMessageText),
mockSession.Object,
options,
cancellationToken
);
Assert.NotNull(result);
Assert.NotEmpty(result.Content);
Assert.Equal(ResponseText, result.Content.Last().Text);
}
/// <summary>
/// Verify that RunStreamingAsync throws ArgumentNullException when agent is null.
/// </summary>
[Fact]
public void RunStreamingAsync_WithNullAgent_ThrowsArgumentNullException()
{
// Arrange
AIAgent? agent = null;
var messages = new List<OpenAIChatMessage>
{
OpenAIChatMessage.CreateUserMessage("Test message")
};
// Act & Assert
Assert.Throws<ArgumentNullException>(
"agent",
() => agent!.RunStreamingAsync(messages));
}
/// <summary>
/// Verify that RunStreamingAsync throws ArgumentNullException when messages is null.
/// </summary>
[Fact]
public void RunStreamingAsync_WithNullMessages_ThrowsArgumentNullException()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
IEnumerable<OpenAIChatMessage>? messages = null;
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(
() => mockAgent.Object.RunStreamingAsync(messages!));
Assert.Equal("messages", exception.ParamName);
}
/// <summary>
/// Verify that the RunStreamingAsync extension method calls the underlying agent's RunStreamingAsync with converted messages and parameters.
/// </summary>
[Fact]
public async Task RunStreamingAsync_CallsUnderlyingAgentAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
var mockSession = new Mock<AgentSession>();
var options = new AgentRunOptions();
var cancellationToken = new CancellationToken(false);
const string TestMessageText = "Hello, assistant!";
const string ResponseText1 = "This is ";
const string ResponseText2 = "the assistant's response.";
var openAiMessages = new List<OpenAIChatMessage>
{
OpenAIChatMessage.CreateUserMessage(TestMessageText)
};
var responseUpdates = new List<AgentResponseUpdate>
{
new(ChatRole.Assistant, ResponseText1),
new(ChatRole.Assistant, ResponseText2)
};
mockAgent
.Protected()
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
ItExpr.IsAny<AgentSession?>(),
ItExpr.IsAny<AgentRunOptions?>(),
ItExpr.IsAny<CancellationToken>())
.Returns(ToAsyncEnumerableAsync(responseUpdates));
// Act
var result = mockAgent.Object.RunStreamingAsync(openAiMessages, mockSession.Object, options, cancellationToken);
var updateCount = 0;
await foreach (var update in result)
{
updateCount++;
}
// Assert
mockAgent.Protected()
.Verify("RunCoreStreamingAsync",
Times.Once(),
ItExpr.Is<IEnumerable<ChatMessage>>(msgs =>
msgs.ToList().Count == 1 &&
msgs.ToList()[0].Text == TestMessageText),
mockSession.Object,
options,
cancellationToken
);
Assert.True(updateCount > 0, "Expected at least one streaming update");
}
/// <summary>
/// Helper method to convert a list of AgentResponseUpdate to an async enumerable.
/// </summary>
private static async IAsyncEnumerable<AgentResponseUpdate> ToAsyncEnumerableAsync(IEnumerable<AgentResponseUpdate> updates)
{
foreach (var update in updates)
{
yield return await Task.FromResult(update);
}
}
#region ResponseItem overload tests
/// <summary>
/// Verify that RunAsync with ResponseItem throws ArgumentNullException when agent is null.
/// </summary>
[Fact]
public async Task RunAsync_ResponseItem_WithNullAgent_ThrowsArgumentNullExceptionAsync()
{
// Arrange
AIAgent? agent = null;
IEnumerable<ResponseItem> messages = [ResponseItem.CreateUserMessageItem("Test message")];
// Act & Assert
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => agent!.RunAsync(messages));
Assert.Equal("agent", exception.ParamName);
}
/// <summary>
/// Verify that RunAsync with ResponseItem throws ArgumentNullException when messages is null.
/// </summary>
[Fact]
public async Task RunAsync_ResponseItem_WithNullMessages_ThrowsArgumentNullExceptionAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
IEnumerable<ResponseItem>? messages = null;
// Act & Assert
var exception = await Assert.ThrowsAsync<ArgumentNullException>(
() => mockAgent.Object.RunAsync(messages!));
Assert.Equal("messages", exception.ParamName);
}
/// <summary>
/// Verify that the RunAsync with ResponseItem extension method calls the underlying agent's RunAsync with converted messages and parameters.
/// </summary>
[Fact]
public async Task RunAsync_ResponseItem_CallsUnderlyingAgentAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
var mockSession = new Mock<AgentSession>();
var options = new AgentRunOptions();
var cancellationToken = new CancellationToken(false);
const string TestMessageText = "Hello, assistant!";
const string ResponseText = "This is the assistant's response.";
IEnumerable<ResponseItem> responseItemMessages = [ResponseItem.CreateUserMessageItem(TestMessageText)];
var responseMessage = new ChatMessage(ChatRole.Assistant, [new TextContent(ResponseText)]);
mockAgent
.Protected()
.Setup<Task<AgentResponse>>("RunCoreAsync",
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
ItExpr.IsAny<AgentSession?>(),
ItExpr.IsAny<AgentRunOptions?>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new AgentResponse([responseMessage]));
// Act
ResponseResult result = await mockAgent.Object.RunAsync(responseItemMessages, mockSession.Object, options, cancellationToken);
// Assert
mockAgent.Protected()
.Verify("RunCoreAsync",
Times.Once(),
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
mockSession.Object,
options,
cancellationToken
);
Assert.NotNull(result);
}
/// <summary>
/// Verify that RunStreamingAsync with ResponseItem throws ArgumentNullException when agent is null.
/// </summary>
[Fact]
public void RunStreamingAsync_ResponseItem_WithNullAgent_ThrowsArgumentNullException()
{
// Arrange
AIAgent? agent = null;
IEnumerable<ResponseItem> messages = [ResponseItem.CreateUserMessageItem("Test message")];
// Act & Assert
Assert.Throws<ArgumentNullException>(
"agent",
() => agent!.RunStreamingAsync(messages));
}
/// <summary>
/// Verify that RunStreamingAsync with ResponseItem throws ArgumentNullException when messages is null.
/// </summary>
[Fact]
public void RunStreamingAsync_ResponseItem_WithNullMessages_ThrowsArgumentNullException()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
IEnumerable<ResponseItem>? messages = null;
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(
() => mockAgent.Object.RunStreamingAsync(messages!));
Assert.Equal("messages", exception.ParamName);
}
/// <summary>
/// Verify that the RunStreamingAsync with ResponseItem extension method calls the underlying agent's RunStreamingAsync with converted messages and parameters.
/// </summary>
[Fact]
public async Task RunStreamingAsync_ResponseItem_CallsUnderlyingAgentAsync()
{
// Arrange
var mockAgent = new Mock<AIAgent>();
var mockSession = new Mock<AgentSession>();
var options = new AgentRunOptions();
var cancellationToken = new CancellationToken(false);
const string TestMessageText = "Hello, assistant!";
const string ResponseText1 = "This is ";
const string ResponseText2 = "the assistant's response.";
IEnumerable<ResponseItem> responseItemMessages = [ResponseItem.CreateUserMessageItem(TestMessageText)];
var responseUpdates = new List<AgentResponseUpdate>
{
new(ChatRole.Assistant, ResponseText1),
new(ChatRole.Assistant, ResponseText2)
};
mockAgent
.Protected()
.Setup<IAsyncEnumerable<AgentResponseUpdate>>("RunCoreStreamingAsync",
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
ItExpr.IsAny<AgentSession?>(),
ItExpr.IsAny<AgentRunOptions?>(),
ItExpr.IsAny<CancellationToken>())
.Returns(ToAsyncEnumerableAsync(responseUpdates));
// Act
var result = mockAgent.Object.RunStreamingAsync(responseItemMessages, mockSession.Object, options, cancellationToken);
var updateCount = 0;
await foreach (var update in result)
{
updateCount++;
}
// Assert
mockAgent.Protected()
.Verify("RunCoreStreamingAsync",
Times.Once(),
ItExpr.IsAny<IEnumerable<ChatMessage>>(),
mockSession.Object,
options,
cancellationToken
);
}
#endregion
}
@@ -0,0 +1,142 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using OpenAI.Chat;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
using ChatRole = Microsoft.Extensions.AI.ChatRole;
using TextContent = Microsoft.Extensions.AI.TextContent;
namespace Microsoft.Agents.AI.OpenAI.UnitTests.Extensions;
/// <summary>
/// Unit tests for the AgentResponseExtensions class that provides OpenAI extension methods.
/// </summary>
public sealed class AgentResponseExtensionsTests
{
/// <summary>
/// Verify that AsOpenAIChatCompletion throws ArgumentNullException when response is null.
/// </summary>
[Fact]
public void AsOpenAIChatCompletion_WithNullResponse_ThrowsArgumentNullException()
{
// Arrange
AgentResponse? response = null;
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(
() => response!.AsOpenAIChatCompletion());
Assert.Equal("response", exception.ParamName);
}
/// <summary>
/// Verify that AsOpenAIChatCompletion returns the RawRepresentation when it is a ChatCompletion.
/// </summary>
[Fact]
public void AsOpenAIChatCompletion_WithChatCompletionRawRepresentation_ReturnsChatCompletion()
{
// Arrange
ChatCompletion chatCompletion = ModelReaderWriterHelper.CreateChatCompletion("assistant_id", "Hello");
var responseMessage = new ChatMessage(ChatRole.Assistant, [new TextContent("Hello")]);
var agentResponse = new AgentResponse([responseMessage])
{
RawRepresentation = chatCompletion
};
// Act
ChatCompletion result = agentResponse.AsOpenAIChatCompletion();
// Assert
Assert.NotNull(result);
Assert.Same(chatCompletion, result);
}
/// <summary>
/// Verify that AsOpenAIChatCompletion converts a ChatResponse when RawRepresentation is not a ChatCompletion.
/// </summary>
[Fact]
public void AsOpenAIChatCompletion_WithNonChatCompletionRawRepresentation_ConvertsChatResponse()
{
// Arrange
const string ResponseText = "This is a test response.";
var responseMessage = new ChatMessage(ChatRole.Assistant, [new TextContent(ResponseText)]);
var agentResponse = new AgentResponse([responseMessage]);
// Act
ChatCompletion result = agentResponse.AsOpenAIChatCompletion();
// Assert
Assert.NotNull(result);
Assert.Single(result.Content);
Assert.Equal(ResponseText, result.Content[0].Text);
}
/// <summary>
/// Verify that AsOpenAIResponse throws ArgumentNullException when response is null.
/// </summary>
[Fact]
public void AsOpenAIResponse_WithNullResponse_ThrowsArgumentNullException()
{
// Arrange
AgentResponse? response = null;
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(
() => response!.AsOpenAIResponse());
Assert.Equal("response", exception.ParamName);
}
/// <summary>
/// Verify that AsOpenAIResponse converts a ChatResponse when RawRepresentation is not a ResponseResult.
/// </summary>
[Fact]
public void AsOpenAIResponse_WithNonResponseResultRawRepresentation_ConvertsChatResponse()
{
// Arrange
const string ResponseText = "This is a test response.";
var responseMessage = new ChatMessage(ChatRole.Assistant, [new TextContent(ResponseText)]);
var agentResponse = new AgentResponse([responseMessage]);
// Act
var result = agentResponse.AsOpenAIResponse();
// Assert
Assert.NotNull(result);
}
}
/// <summary>
/// Helper class for creating OpenAI model objects using ModelReaderWriter.
/// </summary>
internal static class ModelReaderWriterHelper
{
public static ChatCompletion CreateChatCompletion(string id, string contentText)
{
string json = $$"""
{
"id": "{{id}}",
"object": "chat.completion",
"created": 1700000000,
"model": "gpt-4",
"choices": [
{
"index": 0,
"message": {
"role": "assistant",
"content": "{{contentText}}"
},
"finish_reason": "stop"
}
],
"usage": {
"prompt_tokens": 10,
"completion_tokens": 10,
"total_tokens": 20
}
}
""";
return System.ClientModel.Primitives.ModelReaderWriter.Read<ChatCompletion>(BinaryData.FromString(json))!;
}
}
@@ -0,0 +1,228 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OpenAI.Chat;
using ChatMessage = Microsoft.Extensions.AI.ChatMessage;
using OpenAIChatClient = OpenAI.Chat.ChatClient;
namespace Microsoft.Agents.AI.OpenAI.UnitTests.Extensions;
/// <summary>
/// Unit tests for the <see cref="OpenAIChatClientExtensions"/> class.
/// </summary>
public sealed class OpenAIChatClientExtensionsTests
{
/// <summary>
/// Test custom chat client that can be used to verify clientFactory functionality.
/// </summary>
private sealed class TestChatClient : IChatClient
{
private readonly IChatClient _innerClient;
public TestChatClient(IChatClient innerClient)
{
this._innerClient = innerClient;
}
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
=> this._innerClient.GetResponseAsync(messages, options, cancellationToken);
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var update in this._innerClient.GetStreamingResponseAsync(messages, options, cancellationToken))
{
yield return update;
}
}
public object? GetService(Type serviceType, object? serviceKey = null)
{
// Return this instance when requested
if (serviceType == typeof(TestChatClient))
{
return this;
}
return this._innerClient.GetService(serviceType, serviceKey);
}
public void Dispose() => this._innerClient.Dispose();
}
/// <summary>
/// Creates a test ChatClient implementation for testing.
/// </summary>
private sealed class TestOpenAIChatClient : OpenAIChatClient
{
public TestOpenAIChatClient()
{
}
}
/// <summary>
/// Verify that CreateAIAgent with clientFactory parameter correctly applies the factory.
/// </summary>
[Fact]
public void CreateAIAgent_WithClientFactory_AppliesFactoryCorrectly()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
var testChatClient = new TestChatClient(chatClient.AsIChatClient());
// Act
var agent = chatClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
description: "Test description",
clientFactory: (innerClient) => testChatClient);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
Assert.Equal("Test description", agent.Description);
// Verify that the custom chat client can be retrieved from the agent's service collection
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.NotNull(retrievedTestClient);
Assert.Same(testChatClient, retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent with clientFactory using AsBuilder pattern works correctly.
/// </summary>
[Fact]
public void CreateAIAgent_WithClientFactoryUsingAsBuilder_AppliesFactoryCorrectly()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
TestChatClient? testChatClient = null;
// Act
var agent = chatClient.AsAIAgent(
instructions: "Test instructions",
clientFactory: (innerClient) =>
innerClient.AsBuilder().Use((innerClient) => testChatClient = new TestChatClient(innerClient)).Build());
// Assert
Assert.NotNull(agent);
// Verify that the custom chat client can be retrieved from the agent's service collection
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.NotNull(retrievedTestClient);
Assert.Same(testChatClient, retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent with options and clientFactory parameter correctly applies the factory.
/// </summary>
[Fact]
public void CreateAIAgent_WithOptionsAndClientFactory_AppliesFactoryCorrectly()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
var testChatClient = new TestChatClient(chatClient.AsIChatClient());
var options = new ChatClientAgentOptions
{
Name = "Test Agent",
Description = "Test description",
ChatOptions = new() { Instructions = "Test instructions" }
};
// Act
var agent = chatClient.AsAIAgent(
options,
clientFactory: (innerClient) => testChatClient);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
Assert.Equal("Test description", agent.Description);
// Verify that the custom chat client can be retrieved from the agent's service collection
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.NotNull(retrievedTestClient);
Assert.Same(testChatClient, retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent without clientFactory works normally.
/// </summary>
[Fact]
public void CreateAIAgent_WithoutClientFactory_WorksNormally()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
// Act
var agent = chatClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent");
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
// Verify that no TestChatClient is available since no factory was provided
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.Null(retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent with null clientFactory works normally.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullClientFactory_WorksNormally()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
// Act
var agent = chatClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
clientFactory: null);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
// Verify that no TestChatClient is available since no factory was provided
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.Null(retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent throws ArgumentNullException when client is null.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullClient_ThrowsArgumentNullException()
{
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(() =>
((OpenAIChatClient)null!).AsAIAgent());
Assert.Equal("client", exception.ParamName);
}
/// <summary>
/// Verify that CreateAIAgent with options throws ArgumentNullException when options is null.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullOptions_ThrowsArgumentNullException()
{
// Arrange
var chatClient = new TestOpenAIChatClient();
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(() =>
chatClient.AsAIAgent((ChatClientAgentOptions)null!));
Assert.Equal("options", exception.ParamName);
}
}
@@ -0,0 +1,488 @@
// Copyright (c) Microsoft. All rights reserved.
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.AI;
using OpenAI.Responses;
namespace Microsoft.Agents.AI.OpenAI.UnitTests.Extensions;
/// <summary>
/// Unit tests for the <see cref="OpenAIResponseClientExtensions"/> class.
/// </summary>
public sealed class OpenAIResponseClientExtensionsTests
{
/// <summary>
/// Test custom chat client that can be used to verify clientFactory functionality.
/// </summary>
private sealed class TestChatClient : IChatClient
{
private readonly IChatClient _innerClient;
public TestChatClient(IChatClient innerClient)
{
this._innerClient = innerClient;
}
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
=> this._innerClient.GetResponseAsync(messages, options, cancellationToken);
public async IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(
IEnumerable<ChatMessage> messages, ChatOptions? options = null, [EnumeratorCancellation] CancellationToken cancellationToken = default)
{
await foreach (var update in this._innerClient.GetStreamingResponseAsync(messages, options, cancellationToken))
{
yield return update;
}
}
public object? GetService(Type serviceType, object? serviceKey = null)
{
// Return this instance when requested
if (serviceType == typeof(TestChatClient))
{
return this;
}
return this._innerClient.GetService(serviceType, serviceKey);
}
public void Dispose() => this._innerClient.Dispose();
}
/// <summary>
/// Creates a test ResponsesClient implementation for testing.
/// </summary>
private sealed class TestOpenAIResponseClient : ResponsesClient
{
public TestOpenAIResponseClient()
{
}
}
/// <summary>
/// Verify that CreateAIAgent with clientFactory parameter correctly applies the factory.
/// </summary>
[Fact]
public void CreateAIAgent_WithClientFactory_AppliesFactoryCorrectly()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var testChatClient = new TestChatClient(responseClient.AsIChatClient());
// Act
var agent = responseClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
description: "Test description",
clientFactory: (innerClient) => testChatClient);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
Assert.Equal("Test description", agent.Description);
// Verify that the custom chat client can be retrieved from the agent's service collection
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.NotNull(retrievedTestClient);
Assert.Same(testChatClient, retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent without clientFactory works normally.
/// </summary>
[Fact]
public void CreateAIAgent_WithoutClientFactory_WorksNormally()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var agent = responseClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent");
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
// Verify that no TestChatClient is available since no factory was provided
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.Null(retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent with null clientFactory works normally.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullClientFactory_WorksNormally()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var agent = responseClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
clientFactory: null);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
// Verify that no TestChatClient is available since no factory was provided
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.Null(retrievedTestClient);
}
/// <summary>
/// Verify that CreateAIAgent throws ArgumentNullException when client is null.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullClient_ThrowsArgumentNullException()
{
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(() =>
((ResponsesClient)null!).AsAIAgent());
Assert.Equal("client", exception.ParamName);
}
/// <summary>
/// Verify that CreateAIAgent with options throws ArgumentNullException when options is null.
/// </summary>
[Fact]
public void CreateAIAgent_WithNullOptions_ThrowsArgumentNullException()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(() =>
responseClient.AsAIAgent((ChatClientAgentOptions)null!));
Assert.Equal("options", exception.ParamName);
}
/// <summary>
/// Verify that CreateAIAgent with services parameter correctly passes it through to the ChatClientAgent.
/// </summary>
[Fact]
public void CreateAIAgent_WithServices_PassesServicesToAgent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var serviceProvider = new TestServiceProvider();
// Act
var agent = responseClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
services: serviceProvider);
// Assert
Assert.NotNull(agent);
// Verify the IServiceProvider was passed through to the FunctionInvokingChatClient
var chatClient = agent.GetService<IChatClient>();
Assert.NotNull(chatClient);
var functionInvokingClient = chatClient.GetService<FunctionInvokingChatClient>();
Assert.NotNull(functionInvokingClient);
Assert.Same(serviceProvider, GetFunctionInvocationServices(functionInvokingClient));
}
/// <summary>
/// Verify that CreateAIAgent with options and services parameter correctly passes it through to the ChatClientAgent.
/// </summary>
[Fact]
public void CreateAIAgent_WithOptionsAndServices_PassesServicesToAgent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var serviceProvider = new TestServiceProvider();
var options = new ChatClientAgentOptions
{
Name = "Test Agent",
ChatOptions = new() { Instructions = "Test instructions" }
};
// Act
var agent = responseClient.AsAIAgent(options, services: serviceProvider);
// Assert
Assert.NotNull(agent);
Assert.Equal("Test Agent", agent.Name);
// Verify the IServiceProvider was passed through to the FunctionInvokingChatClient
var chatClient = agent.GetService<IChatClient>();
Assert.NotNull(chatClient);
var functionInvokingClient = chatClient.GetService<FunctionInvokingChatClient>();
Assert.NotNull(functionInvokingClient);
Assert.Same(serviceProvider, GetFunctionInvocationServices(functionInvokingClient));
}
/// <summary>
/// Verify that CreateAIAgent with both clientFactory and services works correctly.
/// </summary>
[Fact]
public void CreateAIAgent_WithClientFactoryAndServices_AppliesBothCorrectly()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var serviceProvider = new TestServiceProvider();
var testChatClient = new TestChatClient(responseClient.AsIChatClient());
// Act
var agent = responseClient.AsAIAgent(
instructions: "Test instructions",
name: "Test Agent",
clientFactory: (innerClient) => testChatClient,
services: serviceProvider);
// Assert
Assert.NotNull(agent);
// Verify the custom chat client was applied
var retrievedTestClient = agent.GetService<TestChatClient>();
Assert.NotNull(retrievedTestClient);
Assert.Same(testChatClient, retrievedTestClient);
// Verify the IServiceProvider was passed through
var chatClient = agent.GetService<IChatClient>();
Assert.NotNull(chatClient);
var functionInvokingClient = chatClient.GetService<FunctionInvokingChatClient>();
Assert.NotNull(functionInvokingClient);
Assert.Same(serviceProvider, GetFunctionInvocationServices(functionInvokingClient));
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled throws ArgumentNullException when client is null.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_WithNullClient_ThrowsArgumentNullException()
{
// Act & Assert
var exception = Assert.Throws<ArgumentNullException>(() =>
((ResponsesClient)null!).AsIChatClientWithStoredOutputDisabled());
Assert.Equal("responseClient", exception.ParamName);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled wraps the original ResponsesClient,
/// which remains accessible via the service chain.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_InnerResponsesClientIsAccessible()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled();
// Assert - the inner ResponsesClient should be accessible via GetService
var innerClient = chatClient.GetService<ResponsesClient>();
Assert.NotNull(innerClient);
Assert.Same(responseClient, innerClient);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled with includeReasoningEncryptedContent false
/// wraps the original ResponsesClient, which remains accessible via the service chain.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_WithIncludeReasoningFalse_InnerResponsesClientIsAccessible()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled(includeReasoningEncryptedContent: false);
// Assert - the inner ResponsesClient should be accessible via GetService
var innerClient = chatClient.GetService<ResponsesClient>();
Assert.NotNull(innerClient);
Assert.Same(responseClient, innerClient);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled with default parameter (includeReasoningEncryptedContent = true)
/// configures StoredOutputEnabled to false and includes ReasoningEncryptedContent in IncludedProperties.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_Default_ConfiguresStoredOutputDisabledWithReasoningEncryptedContent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled();
// Assert
var createResponseOptions = GetCreateResponseOptionsFromPipeline(chatClient);
Assert.NotNull(createResponseOptions);
Assert.False(createResponseOptions.StoredOutputEnabled);
Assert.Contains(IncludedResponseProperty.ReasoningEncryptedContent, createResponseOptions.IncludedProperties);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled with includeReasoningEncryptedContent explicitly set to true
/// configures StoredOutputEnabled to false and includes ReasoningEncryptedContent in IncludedProperties.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_WithIncludeReasoningTrue_ConfiguresStoredOutputDisabledWithReasoningEncryptedContent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled(includeReasoningEncryptedContent: true);
// Assert
var createResponseOptions = GetCreateResponseOptionsFromPipeline(chatClient);
Assert.NotNull(createResponseOptions);
Assert.False(createResponseOptions.StoredOutputEnabled);
Assert.Contains(IncludedResponseProperty.ReasoningEncryptedContent, createResponseOptions.IncludedProperties);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled with includeReasoningEncryptedContent set to false
/// configures StoredOutputEnabled to false and does not include ReasoningEncryptedContent in IncludedProperties.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_WithIncludeReasoningFalse_ConfiguresStoredOutputDisabledWithoutReasoningEncryptedContent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
// Act
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled(includeReasoningEncryptedContent: false);
// Assert
var createResponseOptions = GetCreateResponseOptionsFromPipeline(chatClient);
Assert.NotNull(createResponseOptions);
Assert.False(createResponseOptions.StoredOutputEnabled);
Assert.DoesNotContain(IncludedResponseProperty.ReasoningEncryptedContent, createResponseOptions.IncludedProperties);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled preserves an existing RawRepresentationFactory
/// set on ChatOptions, augmenting it with StoredOutputEnabled and ReasoningEncryptedContent
/// rather than replacing it.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_PreservesExistingRawRepresentationFactory()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled();
// Simulate a caller setting their own RawRepresentationFactory on ChatOptions
// (e.g., to add WebSearchCallActionSources).
var options = new ChatOptions
{
RawRepresentationFactory = _ => new CreateResponseOptions
{
IncludedProperties = { IncludedResponseProperty.WebSearchCallActionSources },
},
};
// Act
var createResponseOptions = GetCreateResponseOptionsFromPipeline(chatClient, options);
// Assert
Assert.NotNull(createResponseOptions);
Assert.False(createResponseOptions.StoredOutputEnabled);
Assert.Contains(IncludedResponseProperty.ReasoningEncryptedContent, createResponseOptions.IncludedProperties);
Assert.Contains(IncludedResponseProperty.WebSearchCallActionSources, createResponseOptions.IncludedProperties);
}
/// <summary>
/// Verify that AsIChatClientWithStoredOutputDisabled does not duplicate ReasoningEncryptedContent
/// when the existing factory already includes it.
/// </summary>
[Fact]
public void AsIChatClientWithStoredOutputDisabled_DoesNotDuplicateReasoningEncryptedContent()
{
// Arrange
var responseClient = new TestOpenAIResponseClient();
var chatClient = responseClient.AsIChatClientWithStoredOutputDisabled();
// Simulate a caller that already includes ReasoningEncryptedContent
var options = new ChatOptions
{
RawRepresentationFactory = _ => new CreateResponseOptions
{
IncludedProperties = { IncludedResponseProperty.ReasoningEncryptedContent },
},
};
// Act
var createResponseOptions = GetCreateResponseOptionsFromPipeline(chatClient, options);
// Assert - ReasoningEncryptedContent should appear exactly once
Assert.NotNull(createResponseOptions);
int count = 0;
foreach (var prop in createResponseOptions.IncludedProperties)
{
if (prop == IncludedResponseProperty.ReasoningEncryptedContent)
{
count++;
}
}
Assert.Equal(1, count);
}
/// <summary>
/// A simple test IServiceProvider implementation for testing.
/// </summary>
private sealed class TestServiceProvider : IServiceProvider
{
public object? GetService(Type serviceType) => null;
}
/// <summary>
/// Uses reflection to access the FunctionInvocationServices property which is not public.
/// </summary>
private static IServiceProvider? GetFunctionInvocationServices(FunctionInvokingChatClient client)
{
var property = typeof(FunctionInvokingChatClient).GetProperty(
"FunctionInvocationServices",
BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
return property?.GetValue(client) as IServiceProvider;
}
/// <summary>
/// Extracts the <see cref="CreateResponseOptions"/> produced by the ConfigureOptions pipeline
/// by using reflection to access the configure action and invoking it on a test <see cref="ChatOptions"/>.
/// </summary>
private static CreateResponseOptions? GetCreateResponseOptionsFromPipeline(IChatClient chatClient)
{
return GetCreateResponseOptionsFromPipeline(chatClient, new ChatOptions());
}
/// <summary>
/// Overload that runs the configure action on caller-supplied <see cref="ChatOptions"/>,
/// useful for testing that existing factories are preserved.
/// </summary>
private static CreateResponseOptions? GetCreateResponseOptionsFromPipeline(IChatClient chatClient, ChatOptions options)
{
// The ConfigureOptionsChatClient stores the configure action in a private field.
var configureField = chatClient.GetType().GetField("_configureOptions", BindingFlags.NonPublic | BindingFlags.Instance);
Assert.NotNull(configureField);
var configureAction = configureField.GetValue(chatClient) as Action<ChatOptions>;
Assert.NotNull(configureAction);
configureAction(options);
Assert.NotNull(options.RawRepresentationFactory);
return options.RawRepresentationFactory(chatClient) as CreateResponseOptions;
}
}