mirror of
https://github.com/microsoft/agent-framework.git
synced 2026-06-16 21:04:09 +08:00
Python: [Feature Branch] Merge from main to Azure AI branch (#2111)
* Do not build DevUI assets during .NET project build (#2010) * .NET: Add unit tests for declarative executor SetMultipleVariables (#2016) * Add unit tests for create conversation executor * Update indentation and comment typo. * Added unit tests for declarative executor SetMultipleVariablesExecutor * Updated comments and syntactic sugar * Python: DevUI: Use metadata.entity_id instead of model field (#1984) * DevUI: Use metadata.entity_id for agent/workflow name instead of model field * OpenAI Responses: add explicit request validation * Review feedback * .NET: DevUI - Do not automatically add/map OpenAI services/endpoints (#2014) * Don't add OpenAIResponses as part of Dev UI You should be able to add and remove Dev UI without impacting your other production endpoints. * Remove `AddDevUI()` and do not map OpenAI endpoints from `MapDevUI()` * Fix comment wording * Revise documentation --------- Co-authored-by: Daniel Roth <daroth@microsoft.com> * Python: DevUI: Add OpenAI Responses API proxy support + HIL for Workflows (#1737) * DevUI: Add OpenAI Responses API proxy support with enhanced UI features This commit adds support for proxying requests to OpenAI's Responses API, allowing DevUI to route conversations to OpenAI models when configured to enable testing. Backend changes: - Add OpenAI proxy executor with conversation routing logic - Enhance event mapper to support OpenAI Responses API format - Extend server endpoints to handle OpenAI proxy mode - Update models with OpenAI-specific response types - Remove emojis from logging and CLI output for cleaner text Frontend changes: - Add settings modal with OpenAI proxy configuration UI - Enhance agent and workflow views with improved state management - Add new UI components (separator, switch) for settings - Update debug panel with better event filtering - Improve message renderers for OpenAI content types - Update types and API client for OpenAI integration * update ui, settings modal and workflow input form, add register cleanup hooks. * add workflow HIL support, user mode, other fixes * feat(devui): add human-in-the-loop (HIL) support with dynamic response schemas Implement HIL workflow support allowing workflows to pause for user input with dynamically generated JSON schemas based on response handler type hints. Key Features: - Automatic response schema extraction from @response_handler decorators - Dynamic form generation in UI based on Pydantic/dataclass response types - Checkpoint-based conversation storage for HIL requests/responses - Resume workflow execution after user provides HIL response Backend Changes: - Add extract_response_type_from_executor() to introspect response handlers - Enrich RequestInfoEvent with response_schema via _enrich_request_info_event_with_response_schema() - Map RequestInfoEvent to response.input.requested OpenAI event format - Store HIL responses in conversation history and restore checkpoints Frontend Changes: - Add HILInputModal component with SchemaFormRenderer for dynamic forms - Support Pydantic BaseModel and dataclass response types - Render enum fields as dropdowns, strings as text/textarea, numbers, booleans, arrays, objects - Display original request context alongside response form Testing: - Add tests for checkpoint storage (test_checkpoints.py) - Add schema generation tests for all input types (test_schema_generation.py) - Validate end-to-end HIL flow with spam workflow sample This enables workflows to seamlessly pause execution and request structured user input with type-safe, validated forms generated automatically from response type annotations. * improve HIL support, improve workflow execution view * ui updates * ui updates * improve HIL for workflows, add auth and view modes * update workflow * security improvements , ui fixes * fix mypy error * update loading spinner in ui --------- Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> * .NET: Remove launchSettings.json from .gitignore in dotnet/samples (#2006) * Remove launchSettings.json from .gitignore in dotnet/samples * Update dotnet/samples/GettingStarted/DevUI/DevUI_Step01_BasicUsage/Properties/launchSettings.json Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Update dotnet/samples/AGUIClientServer/AGUIServer/Properties/launchSettings.json Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * DevUI: Serialize workflow input as string to maintain conformance with OpenAI Responses format (#2021) Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> * Add Microsoft Agent Framework logo to assets (#2007) * Updated package versions (#2027) * DevUI: Prevent line breaks within words in the agent view (#2024) Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> * .NET [AG-UI]: Adds support for shared state. (#1996) * Product changes * Tests * Dojo project * Cleanups * Python: Fix underlying tool choice bug and all for return to previous Handoff subagent (#2037) * Fix tool_choice override bug and add enable_return_to_previous support * Add unit test for handoff checkpointing * Handle tools when we have them * added missing chatAgent params (#2044) * .NET: fix ChatCompletions Tools serialization (#2043) * fix serialization in chat completions on tools * nit * .NET: assign AgentCard's URL to mapped-endpoint if not defined explicitly (#2047) * fix serialization in chat completions on tools * nit * write e2e test for agent card resolve + adjust behavior * nit * Version 1.0.0-preview.251110.1 (#2048) * .NET: Remove moved OpenAPI sample and point to SK one. (#1997) * Remove moved OpenAPI sample and point to SK one. * Update dotnet/samples/GettingStarted/Agents/README.md Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Bump AWSSDK.Extensions.Bedrock.MEAI from 4.0.4.2 to 4.0.4.6 (#2031) --- updated-dependencies: - dependency-name: AWSSDK.Extensions.Bedrock.MEAI dependency-version: 4.0.4.6 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * .NET: Separate all memory and rag samples into their own folders (#2000) * Separate all memory and rag samples into their own folders * Fix broken link. * Python: .Net: Dotnet devui compatibility fixes (#2026) * DevUI: Add OpenAI Responses API proxy support with enhanced UI features This commit adds support for proxying requests to OpenAI's Responses API, allowing DevUI to route conversations to OpenAI models when configured to enable testing. Backend changes: - Add OpenAI proxy executor with conversation routing logic - Enhance event mapper to support OpenAI Responses API format - Extend server endpoints to handle OpenAI proxy mode - Update models with OpenAI-specific response types - Remove emojis from logging and CLI output for cleaner text Frontend changes: - Add settings modal with OpenAI proxy configuration UI - Enhance agent and workflow views with improved state management - Add new UI components (separator, switch) for settings - Update debug panel with better event filtering - Improve message renderers for OpenAI content types - Update types and API client for OpenAI integration * update ui, settings modal and workflow input form, add register cleanup hooks. * add workflow HIL support, user mode, other fixes * feat(devui): add human-in-the-loop (HIL) support with dynamic response schemas Implement HIL workflow support allowing workflows to pause for user input with dynamically generated JSON schemas based on response handler type hints. Key Features: - Automatic response schema extraction from @response_handler decorators - Dynamic form generation in UI based on Pydantic/dataclass response types - Checkpoint-based conversation storage for HIL requests/responses - Resume workflow execution after user provides HIL response Backend Changes: - Add extract_response_type_from_executor() to introspect response handlers - Enrich RequestInfoEvent with response_schema via _enrich_request_info_event_with_response_schema() - Map RequestInfoEvent to response.input.requested OpenAI event format - Store HIL responses in conversation history and restore checkpoints Frontend Changes: - Add HILInputModal component with SchemaFormRenderer for dynamic forms - Support Pydantic BaseModel and dataclass response types - Render enum fields as dropdowns, strings as text/textarea, numbers, booleans, arrays, objects - Display original request context alongside response form Testing: - Add tests for checkpoint storage (test_checkpoints.py) - Add schema generation tests for all input types (test_schema_generation.py) - Validate end-to-end HIL flow with spam workflow sample This enables workflows to seamlessly pause execution and request structured user input with type-safe, validated forms generated automatically from response type annotations. * improve HIL support, improve workflow execution view * ui updates * ui updates * improve HIL for workflows, add auth and view modes * update workflow * security improvements , ui fixes * fix mypy error * update loading spinner in ui * DevUI: Serialize workflow input as string to maintain conformance with OpenAI Responses format * Phase 1: Add /meta endpoint and fix workflow event naming for .NET DevUI compatibility * additional fixes for .NET DevUI workflow visualization item ID tracking **Problem:** .NET DevUI was generating different item IDs for ExecutorInvokedEvent and ExecutorCompletedEvent, causing only the first executor to highlight in the workflow graph. Long executor names and error messages also broke UI layout. **Changes:** - Add ExecutorActionItemResource to match Python DevUI implementation - Track item IDs per executor using dictionary in AgentRunResponseUpdateExtensions - Reuse same item ID across invoked/completed/failed events for proper pairing - Add truncateText() utility to workflow-utils.ts - Truncate executor names to 35 chars in execution timeline - Truncate error messages to 150 chars in workflow graph nodes ** Details:** - ExecutorActionItemResource registered with JSON source generation context - Dictionary cleaned up after executor completion/failure to prevent memory leaks - Frontend item tracking by unique item.id supports multiple executor runs - All changes follow existing codebase patterns and conventions Tested with review-workflow showing correct executor highlighting and state transitions for sequential and concurrent executors. * format fixes, remove cors tests * remove unecessary attributes --------- Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> Co-authored-by: Reuben Bond <reuben.bond@gmail.com> * DevUI: support having both an agent and a workflow with the same id in discovery (#2023) * Python: Fix Model ID attribute not showing up in `invoke_agent` span (#2061) * Best effort to surface the model id to invoke agent span * Fix tests * Fix tests * Version 1.0.0-preview.251107.2 (#2065) * Version 1.0.0-preview.251110.2 (#2067) * Update README.md to change Grafana links to Azure portal links for dashboard access (#1983) * .NET - Enable build & test on branch `feature-foundry-agents` (#2068) * Tests good, mkay * Update .github/workflows/dotnet-build-and-test.yml Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Enable feature build pipelines --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com> * Python: Add concrete AGUIChatClient (#2072) * Add concrete AGUIChatClient * Update logging docstrings and conventions * PR feedback * Updates to support client-side tool calls * .NET: Move catalog samples to the HostedAgents folder (#2090) * move catalog samples to the HostedAgents folder * move the catalog samples' projects to the HostedAgents folder * Bump OpenTelemetry.Instrumentation.Runtime from 1.12.0 to 1.13.0 (#1856) --- updated-dependencies: - dependency-name: OpenTelemetry.Instrumentation.Runtime dependency-version: 1.13.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * .NET: Bump Microsoft.SemanticKernel.Agents.Abstractions from 1.66.0 to 1.67.0 (#1962) * Bump Microsoft.SemanticKernel.Agents.Abstractions from 1.66.0 to 1.67.0 --- updated-dependencies: - dependency-name: Microsoft.SemanticKernel.Agents.Abstractions dependency-version: 1.67.0 dependency-type: direct:production update-type: version-update:semver-minor ... Signed-off-by: dependabot[bot] <support@github.com> * .NET: Bump all Microsoft.SemanticKernel packages from 1.66.* to 1.67.* (#1969) * Initial plan * Update all Microsoft.SemanticKernel packages to 1.67.* Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> * Remove unrelated changes to package-lock.json and yarn.lock Co-authored-by: markwallace-microsoft <127216156+markwallace-microsoft@users.noreply.github.com> --------- Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: markwallace-microsoft <127216156+markwallace-microsoft@users.noreply.github.com> --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: rogerbarreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: markwallace-microsoft <127216156+markwallace-microsoft@users.noreply.github.com> * .NET: fix: WorkflowAsAgent Sample (#1787) * fix: WorkflowAsAgent Sample * Also makes ChatForwardingExecutor public * feat: Expand ChatForwardingExecutor handled types Make ChatForwardingExecutor match the input types of ChatProtocolExecutor. * fix: Update for the new AgentRunResponseUpdate merge logic AIAgent always sends out List<ChatMessage> now. * Updated (#2076) * Bump vite in /python/samples/demos/chatkit-integration/frontend (#1918) Bumps [vite](https://github.com/vitejs/vite/tree/HEAD/packages/vite) from 7.1.9 to 7.1.12. - [Release notes](https://github.com/vitejs/vite/releases) - [Changelog](https://github.com/vitejs/vite/blob/v7.1.12/packages/vite/CHANGELOG.md) - [Commits](https://github.com/vitejs/vite/commits/v7.1.12/packages/vite) --- updated-dependencies: - dependency-name: vite dependency-version: 7.1.12 dependency-type: direct:development ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump Roslynator.Analyzers from 4.14.0 to 4.14.1 (#1857) --- updated-dependencies: - dependency-name: Roslynator.Analyzers dependency-version: 4.14.1 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> * Bump MishaKav/pytest-coverage-comment from 1.1.57 to 1.1.59 (#2034) Bumps [MishaKav/pytest-coverage-comment](https://github.com/mishakav/pytest-coverage-comment) from 1.1.57 to 1.1.59. - [Release notes](https://github.com/mishakav/pytest-coverage-comment/releases) - [Changelog](https://github.com/MishaKav/pytest-coverage-comment/blob/main/CHANGELOG.md) - [Commits](https://github.com/mishakav/pytest-coverage-comment/compare/v1.1.57...v1.1.59) --- updated-dependencies: - dependency-name: MishaKav/pytest-coverage-comment dependency-version: 1.1.59 dependency-type: direct:production update-type: version-update:semver-patch ... Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> * Python: Handle agent user input request in AgentExecutor (#2022) * Handle agent user input request in AgentExecutor * fix test * Address comments * Fix tests * Fix tests * Address comments * Address comments * Python: OpenAI Responses Image Generation Stream Support, Sample and Unit Tests (#1853) * support for image gen streaming * small fixes * fixes * added comment * Python: Fix MCP Tool Parameter Descriptions Not Propagated to LLMs (#1978) * mcp tool description fix * small fix * .NET: Allow extending agent run options via additional properties (#1872) * Allow extending agent run options via additional properties This mirrors the M.E.AI model in ChatOptions.AdditionalProperties which is very useful when building functionality pipelines. Fixes https://github.com/microsoft/agent-framework/issues/1815 * Expand XML documentation Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> * Add AdditionalProperties tests to AgentRunOptions Co-authored-by: kzu <169707+kzu@users.noreply.github.com> --------- Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com> Co-authored-by: kzu <169707+kzu@users.noreply.github.com> * Python: Use the last entry in the task history to avoid empty responses (#2101) * Use the last entry in the task history to avoid empty responses * History only contains Messages * Updated package versions (#2104) --------- Signed-off-by: dependabot[bot] <support@github.com> Co-authored-by: Reuben Bond <203839+ReubenBond@users.noreply.github.com> Co-authored-by: Peter Ibekwe <109177538+peibekwe@users.noreply.github.com> Co-authored-by: Jeff Handley <jeffhandley@users.noreply.github.com> Co-authored-by: Daniel Roth <daroth@microsoft.com> Co-authored-by: Victor Dibia <chuvidi2003@gmail.com> Co-authored-by: Mark Wallace <127216156+markwallace-microsoft@users.noreply.github.com> Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> Co-authored-by: Shawn Henry <sphenry@gmail.com> Co-authored-by: Javier Calvarro Nelson <jacalvar@microsoft.com> Co-authored-by: Evan Mattson <35585003+moonbox3@users.noreply.github.com> Co-authored-by: Eduard van Valkenburg <eavanvalkenburg@users.noreply.github.com> Co-authored-by: Korolev Dmitry <deagle.gross@gmail.com> Co-authored-by: westey <164392973+westey-m@users.noreply.github.com> Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com> Co-authored-by: Reuben Bond <reuben.bond@gmail.com> Co-authored-by: Tao Chen <taochen@microsoft.com> Co-authored-by: wuweng <wuweng@microsoft.com> Co-authored-by: Chris <66376200+crickman@users.noreply.github.com> Co-authored-by: Roger Barreto <19890735+rogerbarreto@users.noreply.github.com> Co-authored-by: SergeyMenshykh <68852919+SergeyMenshykh@users.noreply.github.com> Co-authored-by: Copilot <198982749+Copilot@users.noreply.github.com> Co-authored-by: Jacob Alber <jaalber@microsoft.com> Co-authored-by: Giles Odigwe <79032838+giles17@users.noreply.github.com> Co-authored-by: Daniel Cazzulino <daniel@cazzulino.com> Co-authored-by: kzu <169707+kzu@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
Unverified
parent
85fcd230bf
commit
361c47f30f
@@ -1282,6 +1282,312 @@ public sealed class AGUIAgentTests
|
||||
// AG-UI requirement: full history on every turn (which happens when ConversationId is null for FunctionInvokingChatClient)
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_ExtractsStateFromDataContent_AndRemovesStateMessageAsync()
|
||||
{
|
||||
// Arrange
|
||||
var stateData = new { counter = 42, status = "active" };
|
||||
string stateJson = JsonSerializer.Serialize(stateData);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
var dataContent = new DataContent(stateBytes, "application/json");
|
||||
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new TextMessageStartEvent { MessageId = "msg1", Role = AGUIRoles.Assistant },
|
||||
new TextMessageContentEvent { MessageId = "msg1", Delta = "Response" },
|
||||
new TextMessageEndEvent { MessageId = "msg1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages =
|
||||
[
|
||||
new ChatMessage(ChatRole.User, "Hello"),
|
||||
new ChatMessage(ChatRole.System, [dataContent])
|
||||
];
|
||||
|
||||
// Act
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
Assert.NotNull(captureHandler.CapturedState);
|
||||
Assert.Equal(42, captureHandler.CapturedState.Value.GetProperty("counter").GetInt32());
|
||||
Assert.Equal("active", captureHandler.CapturedState.Value.GetProperty("status").GetString());
|
||||
|
||||
// Verify state message was removed - only user message should be in the request
|
||||
Assert.Equal(1, captureHandler.CapturedMessageCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_WithNoStateDataContent_SendsEmptyStateAsync()
|
||||
{
|
||||
// Arrange
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new TextMessageStartEvent { MessageId = "msg1", Role = AGUIRoles.Assistant },
|
||||
new TextMessageContentEvent { MessageId = "msg1", Delta = "Response" },
|
||||
new TextMessageEndEvent { MessageId = "msg1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Hello")];
|
||||
|
||||
// Act
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
Assert.Null(captureHandler.CapturedState);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_WithMalformedStateJson_ThrowsInvalidOperationExceptionAsync()
|
||||
{
|
||||
// Arrange
|
||||
byte[] invalidJson = System.Text.Encoding.UTF8.GetBytes("{invalid json");
|
||||
var dataContent = new DataContent(invalidJson, "application/json");
|
||||
|
||||
using HttpClient httpClient = this.CreateMockHttpClient([]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages =
|
||||
[
|
||||
new ChatMessage(ChatRole.User, "Hello"),
|
||||
new ChatMessage(ChatRole.System, [dataContent])
|
||||
];
|
||||
|
||||
// Act & Assert
|
||||
InvalidOperationException ex = await Assert.ThrowsAsync<InvalidOperationException>(async () =>
|
||||
{
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
});
|
||||
|
||||
Assert.Contains("Failed to deserialize state JSON", ex.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_WithEmptyStateObject_SendsEmptyObjectAsync()
|
||||
{
|
||||
// Arrange
|
||||
var emptyState = new { };
|
||||
string stateJson = JsonSerializer.Serialize(emptyState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
var dataContent = new DataContent(stateBytes, "application/json");
|
||||
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages =
|
||||
[
|
||||
new ChatMessage(ChatRole.User, "Hello"),
|
||||
new ChatMessage(ChatRole.System, [dataContent])
|
||||
];
|
||||
|
||||
// Act
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
Assert.NotNull(captureHandler.CapturedState);
|
||||
Assert.Equal(JsonValueKind.Object, captureHandler.CapturedState.Value.ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_OnlyProcessesDataContentFromLastMessage_IgnoresEarlierOnesAsync()
|
||||
{
|
||||
// Arrange
|
||||
var oldState = new { counter = 10 };
|
||||
string oldStateJson = JsonSerializer.Serialize(oldState);
|
||||
byte[] oldStateBytes = System.Text.Encoding.UTF8.GetBytes(oldStateJson);
|
||||
var oldDataContent = new DataContent(oldStateBytes, "application/json");
|
||||
|
||||
var newState = new { counter = 20 };
|
||||
string newStateJson = JsonSerializer.Serialize(newState);
|
||||
byte[] newStateBytes = System.Text.Encoding.UTF8.GetBytes(newStateJson);
|
||||
var newDataContent = new DataContent(newStateBytes, "application/json");
|
||||
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages =
|
||||
[
|
||||
new ChatMessage(ChatRole.User, "First message"),
|
||||
new ChatMessage(ChatRole.System, [oldDataContent]),
|
||||
new ChatMessage(ChatRole.User, "Second message"),
|
||||
new ChatMessage(ChatRole.System, [newDataContent])
|
||||
];
|
||||
|
||||
// Act
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
Assert.NotNull(captureHandler.CapturedState);
|
||||
// Should use the new state from the last message
|
||||
Assert.Equal(20, captureHandler.CapturedState.Value.GetProperty("counter").GetInt32());
|
||||
|
||||
// Should have removed only the last state message
|
||||
Assert.Equal(3, captureHandler.CapturedMessageCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_WithNonJsonMediaType_IgnoresDataContentAsync()
|
||||
{
|
||||
// Arrange
|
||||
byte[] imageData = System.Text.Encoding.UTF8.GetBytes("fake image data");
|
||||
var dataContent = new DataContent(imageData, "image/png");
|
||||
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages =
|
||||
[
|
||||
new ChatMessage(ChatRole.User, [new TextContent("Hello"), dataContent])
|
||||
];
|
||||
|
||||
// Act
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.True(captureHandler.RequestWasMade);
|
||||
Assert.Null(captureHandler.CapturedState);
|
||||
// Message should not be removed since it's not state
|
||||
Assert.Equal(1, captureHandler.CapturedMessageCount);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_RoundTripState_PreservesJsonStructureAsync()
|
||||
{
|
||||
// Arrange - Server returns state snapshot
|
||||
var returnedState = new { counter = 100, nested = new { value = "test" } };
|
||||
JsonElement stateSnapshot = JsonSerializer.SerializeToElement(returnedState);
|
||||
|
||||
var captureHandler = new StateCapturingTestDelegatingHandler();
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateSnapshotEvent { Snapshot = stateSnapshot },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
captureHandler.AddResponse(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run2" },
|
||||
new TextMessageStartEvent { MessageId = "msg1", Role = AGUIRoles.Assistant },
|
||||
new TextMessageContentEvent { MessageId = "msg1", Delta = "Done" },
|
||||
new TextMessageEndEvent { MessageId = "msg1" },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run2" }
|
||||
]);
|
||||
using HttpClient httpClient = new(captureHandler);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Hello")];
|
||||
|
||||
// Act - First turn: receive state
|
||||
DataContent? receivedStateContent = null;
|
||||
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
if (update.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"))
|
||||
{
|
||||
receivedStateContent = (DataContent)update.Contents.First(c => c is DataContent);
|
||||
}
|
||||
}
|
||||
|
||||
// Second turn: send the received state back
|
||||
Assert.NotNull(receivedStateContent);
|
||||
messages.Add(new ChatMessage(ChatRole.System, [receivedStateContent]));
|
||||
await foreach (var _ in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
// Just consume the stream
|
||||
}
|
||||
|
||||
// Assert - Verify the round-tripped state
|
||||
Assert.NotNull(captureHandler.CapturedState);
|
||||
Assert.Equal(100, captureHandler.CapturedState.Value.GetProperty("counter").GetInt32());
|
||||
Assert.Equal("test", captureHandler.CapturedState.Value.GetProperty("nested").GetProperty("value").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task GetStreamingResponseAsync_ReceivesStateSnapshot_AsDataContentWithAdditionalPropertiesAsync()
|
||||
{
|
||||
// Arrange
|
||||
var state = new { sessionId = "abc123", step = 5 };
|
||||
JsonElement stateSnapshot = JsonSerializer.SerializeToElement(state);
|
||||
|
||||
using HttpClient httpClient = this.CreateMockHttpClient(
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateSnapshotEvent { Snapshot = stateSnapshot },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
]);
|
||||
|
||||
var chatClient = new AGUIChatClient(httpClient, "http://localhost/agent", null, AGUIJsonSerializerContext.Default.Options);
|
||||
List<ChatMessage> messages = [new ChatMessage(ChatRole.User, "Test")];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (var update in chatClient.GetStreamingResponseAsync(messages, null))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
ChatResponseUpdate stateUpdate = updates.First(u => u.Contents.Any(c => c is DataContent));
|
||||
Assert.NotNull(stateUpdate.AdditionalProperties);
|
||||
Assert.True((bool)stateUpdate.AdditionalProperties!["is_state_snapshot"]!);
|
||||
|
||||
DataContent dataContent = (DataContent)stateUpdate.Contents[0];
|
||||
Assert.Equal("application/json", dataContent.MediaType);
|
||||
|
||||
string jsonText = System.Text.Encoding.UTF8.GetString(dataContent.Data.ToArray());
|
||||
JsonElement deserializedState = JsonSerializer.Deserialize<JsonElement>(jsonText);
|
||||
Assert.Equal("abc123", deserializedState.GetProperty("sessionId").GetString());
|
||||
Assert.Equal(5, deserializedState.GetProperty("step").GetInt32());
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class TestDelegatingHandler : DelegatingHandler
|
||||
@@ -1376,3 +1682,58 @@ internal sealed class CapturingTestDelegatingHandler : DelegatingHandler
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
internal sealed class StateCapturingTestDelegatingHandler : DelegatingHandler
|
||||
{
|
||||
private readonly Queue<Func<HttpRequestMessage, Task<HttpResponseMessage>>> _responseFactories = new();
|
||||
|
||||
public bool RequestWasMade { get; private set; }
|
||||
public JsonElement? CapturedState { get; private set; }
|
||||
public int CapturedMessageCount { get; private set; }
|
||||
|
||||
public void AddResponse(BaseEvent[] events)
|
||||
{
|
||||
this._responseFactories.Enqueue(_ => Task.FromResult(CreateResponse(events)));
|
||||
}
|
||||
|
||||
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
|
||||
{
|
||||
this.RequestWasMade = true;
|
||||
|
||||
// Capture the state and message count from the request
|
||||
#if NET472 || NETSTANDARD2_0
|
||||
string requestBody = await request.Content!.ReadAsStringAsync().ConfigureAwait(false);
|
||||
#else
|
||||
string requestBody = await request.Content!.ReadAsStringAsync(cancellationToken).ConfigureAwait(false);
|
||||
#endif
|
||||
RunAgentInput? input = JsonSerializer.Deserialize(requestBody, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
if (input != null)
|
||||
{
|
||||
if (input.State.ValueKind != JsonValueKind.Undefined && input.State.ValueKind != JsonValueKind.Null)
|
||||
{
|
||||
this.CapturedState = input.State;
|
||||
}
|
||||
this.CapturedMessageCount = input.Messages.Count();
|
||||
}
|
||||
|
||||
if (this._responseFactories.Count == 0)
|
||||
{
|
||||
throw new InvalidOperationException("No more responses configured for StateCapturingTestDelegatingHandler.");
|
||||
}
|
||||
|
||||
var factory = this._responseFactories.Dequeue();
|
||||
return await factory(request);
|
||||
}
|
||||
|
||||
private static HttpResponseMessage CreateResponse(BaseEvent[] events)
|
||||
{
|
||||
string sseContent = string.Join("", events.Select(e =>
|
||||
$"data: {JsonSerializer.Serialize(e, AGUIJsonSerializerContext.Default.BaseEvent)}\n\n"));
|
||||
|
||||
return new HttpResponseMessage
|
||||
{
|
||||
StatusCode = HttpStatusCode.OK,
|
||||
Content = new StringContent(sseContent)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+408
@@ -369,4 +369,412 @@ public sealed class ChatResponseUpdateAGUIExtensionsTests
|
||||
Assert.Equal("call_2", functionCalls[1].CallId);
|
||||
Assert.Equal("Tool2", functionCalls[1].Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_ConvertsStateSnapshotEvent_ToDataContentWithJsonAsync()
|
||||
{
|
||||
// Arrange
|
||||
JsonElement stateSnapshot = JsonSerializer.SerializeToElement(new { counter = 42, status = "active" });
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateSnapshotEvent { Snapshot = stateSnapshot },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
ChatResponseUpdate stateUpdate = updates.First(u => u.Contents.Any(c => c is DataContent));
|
||||
Assert.Equal(ChatRole.Assistant, stateUpdate.Role);
|
||||
Assert.Equal("thread1", stateUpdate.ConversationId);
|
||||
Assert.Equal("run1", stateUpdate.ResponseId);
|
||||
|
||||
DataContent dataContent = Assert.IsType<DataContent>(stateUpdate.Contents[0]);
|
||||
Assert.Equal("application/json", dataContent.MediaType);
|
||||
|
||||
// Verify the JSON content
|
||||
string jsonText = System.Text.Encoding.UTF8.GetString(dataContent.Data.ToArray());
|
||||
JsonElement deserializedState = JsonSerializer.Deserialize<JsonElement>(jsonText);
|
||||
Assert.Equal(42, deserializedState.GetProperty("counter").GetInt32());
|
||||
Assert.Equal("active", deserializedState.GetProperty("status").GetString());
|
||||
|
||||
// Verify additional properties
|
||||
Assert.NotNull(stateUpdate.AdditionalProperties);
|
||||
Assert.True((bool)stateUpdate.AdditionalProperties["is_state_snapshot"]!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithNullStateSnapshot_DoesNotEmitUpdateAsync()
|
||||
{
|
||||
// Arrange
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateSnapshotEvent { Snapshot = null },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.DoesNotContain(updates, u => u.Contents.Any(c => c is DataContent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithEmptyObjectStateSnapshot_EmitsDataContentAsync()
|
||||
{
|
||||
// Arrange
|
||||
JsonElement emptyState = JsonSerializer.SerializeToElement(new { });
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateSnapshotEvent { Snapshot = emptyState },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
ChatResponseUpdate stateUpdate = updates.First(u => u.Contents.Any(c => c is DataContent));
|
||||
DataContent dataContent = Assert.IsType<DataContent>(stateUpdate.Contents[0]);
|
||||
string jsonText = System.Text.Encoding.UTF8.GetString(dataContent.Data.ToArray());
|
||||
Assert.Equal("{}", jsonText);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithComplexStateSnapshot_PreservesJsonStructureAsync()
|
||||
{
|
||||
// Arrange
|
||||
var complexState = new
|
||||
{
|
||||
user = new { name = "Alice", age = 30 },
|
||||
items = new[] { "item1", "item2", "item3" },
|
||||
metadata = new { timestamp = "2024-01-01T00:00:00Z", version = 2 }
|
||||
};
|
||||
JsonElement stateSnapshot = JsonSerializer.SerializeToElement(complexState);
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new StateSnapshotEvent { Snapshot = stateSnapshot }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
ChatResponseUpdate stateUpdate = updates.First();
|
||||
DataContent dataContent = Assert.IsType<DataContent>(stateUpdate.Contents[0]);
|
||||
string jsonText = System.Text.Encoding.UTF8.GetString(dataContent.Data.ToArray());
|
||||
JsonElement roundTrippedState = JsonSerializer.Deserialize<JsonElement>(jsonText);
|
||||
|
||||
Assert.Equal("Alice", roundTrippedState.GetProperty("user").GetProperty("name").GetString());
|
||||
Assert.Equal(30, roundTrippedState.GetProperty("user").GetProperty("age").GetInt32());
|
||||
Assert.Equal(3, roundTrippedState.GetProperty("items").GetArrayLength());
|
||||
Assert.Equal("item1", roundTrippedState.GetProperty("items")[0].GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithStateSnapshotAndTextMessages_EmitsBothAsync()
|
||||
{
|
||||
// Arrange
|
||||
JsonElement state = JsonSerializer.SerializeToElement(new { step = 1 });
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new TextMessageStartEvent { MessageId = "msg1", Role = AGUIRoles.Assistant },
|
||||
new TextMessageContentEvent { MessageId = "msg1", Delta = "Processing..." },
|
||||
new TextMessageEndEvent { MessageId = "msg1" },
|
||||
new StateSnapshotEvent { Snapshot = state },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.Contains(updates, u => u.Contents.Any(c => c is TextContent));
|
||||
Assert.Contains(updates, u => u.Contents.Any(c => c is DataContent));
|
||||
}
|
||||
|
||||
#region State Delta Tests
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_ConvertsStateDeltaEvent_ToDataContentWithJsonPatchAsync()
|
||||
{
|
||||
// Arrange - Create JSON Patch operations (RFC 6902)
|
||||
JsonElement stateDelta = JsonSerializer.SerializeToElement(new object[]
|
||||
{
|
||||
new { op = "replace", path = "/counter", value = 43 },
|
||||
new { op = "add", path = "/newField", value = "test" }
|
||||
});
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateDeltaEvent { Delta = stateDelta },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
ChatResponseUpdate deltaUpdate = updates.First(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json-patch+json"));
|
||||
Assert.Equal(ChatRole.Assistant, deltaUpdate.Role);
|
||||
Assert.Equal("thread1", deltaUpdate.ConversationId);
|
||||
Assert.Equal("run1", deltaUpdate.ResponseId);
|
||||
|
||||
DataContent dataContent = Assert.IsType<DataContent>(deltaUpdate.Contents[0]);
|
||||
Assert.Equal("application/json-patch+json", dataContent.MediaType);
|
||||
|
||||
// Verify the JSON Patch content
|
||||
string jsonText = System.Text.Encoding.UTF8.GetString(dataContent.Data.ToArray());
|
||||
JsonElement deserializedDelta = JsonSerializer.Deserialize<JsonElement>(jsonText);
|
||||
Assert.Equal(JsonValueKind.Array, deserializedDelta.ValueKind);
|
||||
Assert.Equal(2, deserializedDelta.GetArrayLength());
|
||||
|
||||
// Verify first operation
|
||||
JsonElement firstOp = deserializedDelta[0];
|
||||
Assert.Equal("replace", firstOp.GetProperty("op").GetString());
|
||||
Assert.Equal("/counter", firstOp.GetProperty("path").GetString());
|
||||
Assert.Equal(43, firstOp.GetProperty("value").GetInt32());
|
||||
|
||||
// Verify second operation
|
||||
JsonElement secondOp = deserializedDelta[1];
|
||||
Assert.Equal("add", secondOp.GetProperty("op").GetString());
|
||||
Assert.Equal("/newField", secondOp.GetProperty("path").GetString());
|
||||
Assert.Equal("test", secondOp.GetProperty("value").GetString());
|
||||
|
||||
// Verify additional properties
|
||||
Assert.NotNull(deltaUpdate.AdditionalProperties);
|
||||
Assert.True((bool)deltaUpdate.AdditionalProperties["is_state_delta"]!);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithNullStateDelta_DoesNotEmitUpdateAsync()
|
||||
{
|
||||
// Arrange
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateDeltaEvent { Delta = null },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert - Only run started and finished should be present
|
||||
Assert.Equal(2, updates.Count);
|
||||
Assert.IsType<ChatResponseUpdate>(updates[0]); // Run started
|
||||
Assert.IsType<ChatResponseUpdate>(updates[1]); // Run finished
|
||||
Assert.DoesNotContain(updates, u => u.Contents.Any(c => c is DataContent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithEmptyStateDelta_EmitsUpdateAsync()
|
||||
{
|
||||
// Arrange - Empty JSON Patch array is valid
|
||||
JsonElement emptyDelta = JsonSerializer.SerializeToElement(Array.Empty<object>());
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateDeltaEvent { Delta = emptyDelta },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.Contains(updates, u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json-patch+json"));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsChatResponseUpdatesAsync_WithMultipleStateDeltaEvents_ConvertsAllAsync()
|
||||
{
|
||||
// Arrange
|
||||
JsonElement delta1 = JsonSerializer.SerializeToElement(new[] { new { op = "replace", path = "/counter", value = 1 } });
|
||||
JsonElement delta2 = JsonSerializer.SerializeToElement(new[] { new { op = "replace", path = "/counter", value = 2 } });
|
||||
JsonElement delta3 = JsonSerializer.SerializeToElement(new[] { new { op = "replace", path = "/counter", value = 3 } });
|
||||
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateDeltaEvent { Delta = delta1 },
|
||||
new StateDeltaEvent { Delta = delta2 },
|
||||
new StateDeltaEvent { Delta = delta3 },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
var deltaUpdates = updates.Where(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json-patch+json")).ToList();
|
||||
Assert.Equal(3, deltaUpdates.Count);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsAGUIEventStreamAsync_ConvertsDataContentWithJsonPatch_ToStateDeltaEventAsync()
|
||||
{
|
||||
// Arrange - Create a ChatResponseUpdate with JSON Patch DataContent
|
||||
JsonElement patchOps = JsonSerializer.SerializeToElement(new object[]
|
||||
{
|
||||
new { op = "remove", path = "/oldField" },
|
||||
new { op = "add", path = "/newField", value = "newValue" }
|
||||
});
|
||||
byte[] jsonBytes = JsonSerializer.SerializeToUtf8Bytes(patchOps);
|
||||
DataContent dataContent = new(jsonBytes, "application/json-patch+json");
|
||||
|
||||
List<ChatResponseUpdate> updates =
|
||||
[
|
||||
new ChatResponseUpdate(ChatRole.Assistant, [dataContent])
|
||||
{
|
||||
MessageId = "msg1"
|
||||
}
|
||||
];
|
||||
|
||||
// Act
|
||||
List<BaseEvent> outputEvents = [];
|
||||
await foreach (BaseEvent evt in updates.ToAsyncEnumerableAsync().AsAGUIEventStreamAsync("thread1", "run1", AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
outputEvents.Add(evt);
|
||||
}
|
||||
|
||||
// Assert
|
||||
StateDeltaEvent? deltaEvent = outputEvents.OfType<StateDeltaEvent>().FirstOrDefault();
|
||||
Assert.NotNull(deltaEvent);
|
||||
Assert.NotNull(deltaEvent.Delta);
|
||||
Assert.Equal(JsonValueKind.Array, deltaEvent.Delta.Value.ValueKind);
|
||||
|
||||
// Verify patch operations
|
||||
JsonElement delta = deltaEvent.Delta.Value;
|
||||
Assert.Equal(2, delta.GetArrayLength());
|
||||
Assert.Equal("remove", delta[0].GetProperty("op").GetString());
|
||||
Assert.Equal("/oldField", delta[0].GetProperty("path").GetString());
|
||||
Assert.Equal("add", delta[1].GetProperty("op").GetString());
|
||||
Assert.Equal("/newField", delta[1].GetProperty("path").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task AsAGUIEventStreamAsync_WithBothSnapshotAndDelta_EmitsBothEventsAsync()
|
||||
{
|
||||
// Arrange
|
||||
JsonElement snapshot = JsonSerializer.SerializeToElement(new { counter = 0 });
|
||||
byte[] snapshotBytes = JsonSerializer.SerializeToUtf8Bytes(snapshot);
|
||||
DataContent snapshotContent = new(snapshotBytes, "application/json");
|
||||
|
||||
JsonElement delta = JsonSerializer.SerializeToElement(new[] { new { op = "replace", path = "/counter", value = 1 } });
|
||||
byte[] deltaBytes = JsonSerializer.SerializeToUtf8Bytes(delta);
|
||||
DataContent deltaContent = new(deltaBytes, "application/json-patch+json");
|
||||
|
||||
List<ChatResponseUpdate> updates =
|
||||
[
|
||||
new ChatResponseUpdate(ChatRole.Assistant, [snapshotContent]) { MessageId = "msg1" },
|
||||
new ChatResponseUpdate(ChatRole.Assistant, [deltaContent]) { MessageId = "msg2" }
|
||||
];
|
||||
|
||||
// Act
|
||||
List<BaseEvent> outputEvents = [];
|
||||
await foreach (BaseEvent evt in updates.ToAsyncEnumerableAsync().AsAGUIEventStreamAsync("thread1", "run1", AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
outputEvents.Add(evt);
|
||||
}
|
||||
|
||||
// Assert
|
||||
Assert.Contains(outputEvents, e => e is StateSnapshotEvent);
|
||||
Assert.Contains(outputEvents, e => e is StateDeltaEvent);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StateDeltaEvent_RoundTrip_PreservesJsonPatchOperationsAsync()
|
||||
{
|
||||
// Arrange - Create complex JSON Patch with various operations
|
||||
JsonElement originalDelta = JsonSerializer.SerializeToElement(new object[]
|
||||
{
|
||||
new { op = "add", path = "/user/email", value = "test@example.com" },
|
||||
new { op = "remove", path = "/user/tempData" },
|
||||
new { op = "replace", path = "/user/lastLogin", value = "2025-11-09T12:00:00Z" },
|
||||
new { op = "move", from = "/user/oldAddress", path = "/user/previousAddress" },
|
||||
new { op = "copy", from = "/user/name", path = "/user/displayName" },
|
||||
new { op = "test", path = "/user/version", value = 2 }
|
||||
});
|
||||
|
||||
List<BaseEvent> events =
|
||||
[
|
||||
new RunStartedEvent { ThreadId = "thread1", RunId = "run1" },
|
||||
new StateDeltaEvent { Delta = originalDelta },
|
||||
new RunFinishedEvent { ThreadId = "thread1", RunId = "run1" }
|
||||
];
|
||||
|
||||
// Act - Convert to ChatResponseUpdate and back to events
|
||||
List<ChatResponseUpdate> updates = [];
|
||||
await foreach (ChatResponseUpdate update in events.ToAsyncEnumerableAsync().AsChatResponseUpdatesAsync(AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
List<BaseEvent> roundTripEvents = [];
|
||||
await foreach (BaseEvent evt in updates.ToAsyncEnumerableAsync().AsAGUIEventStreamAsync("thread1", "run1", AGUIJsonSerializerContext.Default.Options))
|
||||
{
|
||||
roundTripEvents.Add(evt);
|
||||
}
|
||||
|
||||
// Assert
|
||||
StateDeltaEvent? roundTripDelta = roundTripEvents.OfType<StateDeltaEvent>().FirstOrDefault();
|
||||
Assert.NotNull(roundTripDelta);
|
||||
Assert.NotNull(roundTripDelta.Delta);
|
||||
|
||||
JsonElement delta = roundTripDelta.Delta.Value;
|
||||
Assert.Equal(6, delta.GetArrayLength());
|
||||
|
||||
// Verify each operation type
|
||||
Assert.Equal("add", delta[0].GetProperty("op").GetString());
|
||||
Assert.Equal("remove", delta[1].GetProperty("op").GetString());
|
||||
Assert.Equal("replace", delta[2].GetProperty("op").GetString());
|
||||
Assert.Equal("move", delta[3].GetProperty("op").GetString());
|
||||
Assert.Equal("copy", delta[4].GetProperty("op").GetString());
|
||||
Assert.Equal("test", delta[5].GetProperty("op").GetString());
|
||||
}
|
||||
|
||||
#endregion State Delta Tests
|
||||
}
|
||||
|
||||
@@ -18,7 +18,12 @@ public class AgentRunOptionsTests
|
||||
var options = new AgentRunOptions
|
||||
{
|
||||
ContinuationToken = new object(),
|
||||
AllowBackgroundResponses = true
|
||||
AllowBackgroundResponses = true,
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary
|
||||
{
|
||||
["key1"] = "value1",
|
||||
["key2"] = 42
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
@@ -28,6 +33,10 @@ public class AgentRunOptionsTests
|
||||
Assert.NotNull(clone);
|
||||
Assert.Same(options.ContinuationToken, clone.ContinuationToken);
|
||||
Assert.Equal(options.AllowBackgroundResponses, clone.AllowBackgroundResponses);
|
||||
Assert.NotNull(clone.AdditionalProperties);
|
||||
Assert.NotSame(options.AdditionalProperties, clone.AdditionalProperties);
|
||||
Assert.Equal("value1", clone.AdditionalProperties["key1"]);
|
||||
Assert.Equal(42, clone.AdditionalProperties["key2"]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
@@ -42,7 +51,12 @@ public class AgentRunOptionsTests
|
||||
var options = new AgentRunOptions
|
||||
{
|
||||
ContinuationToken = ResponseContinuationToken.FromBytes(new byte[] { 1, 2, 3 }),
|
||||
AllowBackgroundResponses = true
|
||||
AllowBackgroundResponses = true,
|
||||
AdditionalProperties = new AdditionalPropertiesDictionary
|
||||
{
|
||||
["key1"] = "value1",
|
||||
["key2"] = 42
|
||||
}
|
||||
};
|
||||
|
||||
// Act
|
||||
@@ -54,5 +68,13 @@ public class AgentRunOptionsTests
|
||||
Assert.NotNull(deserialized);
|
||||
Assert.Equivalent(ResponseContinuationToken.FromBytes(new byte[] { 1, 2, 3 }), deserialized!.ContinuationToken);
|
||||
Assert.Equal(options.AllowBackgroundResponses, deserialized.AllowBackgroundResponses);
|
||||
Assert.NotNull(deserialized.AdditionalProperties);
|
||||
Assert.Equal(2, deserialized.AdditionalProperties.Count);
|
||||
Assert.True(deserialized.AdditionalProperties.TryGetValue("key1", out object? value1));
|
||||
Assert.IsType<JsonElement>(value1);
|
||||
Assert.Equal("value1", ((JsonElement)value1!).GetString());
|
||||
Assert.True(deserialized.AdditionalProperties.TryGetValue("key2", out object? value2));
|
||||
Assert.IsType<JsonElement>(value2);
|
||||
Assert.Equal(42, ((JsonElement)value2!).GetInt32());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Text.Json;
|
||||
using System.Threading.Tasks;
|
||||
using A2A;
|
||||
using Microsoft.Agents.AI.Hosting.A2A.UnitTests.Internal;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Microsoft.Agents.AI.Hosting.A2A.UnitTests;
|
||||
|
||||
public sealed class A2AIntegrationTests
|
||||
{
|
||||
/// <summary>
|
||||
/// Verifies that calling the A2A card endpoint with MapA2A returns an agent card with a URL populated.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task MapA2A_WithAgentCard_CardEndpointReturnsCardWithUrlAsync()
|
||||
{
|
||||
// Arrange
|
||||
WebApplicationBuilder builder = WebApplication.CreateBuilder();
|
||||
builder.WebHost.UseTestServer();
|
||||
|
||||
IChatClient mockChatClient = new DummyChatClient();
|
||||
builder.Services.AddKeyedSingleton("chat-client", mockChatClient);
|
||||
IHostedAgentBuilder agentBuilder = builder.AddAIAgent("test-agent", "Test instructions", chatClientServiceKey: "chat-client");
|
||||
builder.Services.AddLogging();
|
||||
|
||||
using WebApplication app = builder.Build();
|
||||
|
||||
var agentCard = new AgentCard
|
||||
{
|
||||
Name = "Test Agent",
|
||||
Description = "A test agent for A2A communication",
|
||||
Version = "1.0"
|
||||
};
|
||||
|
||||
// Map A2A with the agent card
|
||||
app.MapA2A(agentBuilder, "/a2a/test-agent", agentCard);
|
||||
|
||||
await app.StartAsync();
|
||||
|
||||
try
|
||||
{
|
||||
// Get the test server client
|
||||
TestServer testServer = app.Services.GetRequiredService<IServer>() as TestServer
|
||||
?? throw new InvalidOperationException("TestServer not found");
|
||||
var httpClient = testServer.CreateClient();
|
||||
|
||||
// Act - Query the agent card endpoint
|
||||
var requestUri = new Uri("/a2a/test-agent/v1/card", UriKind.Relative);
|
||||
var response = await httpClient.GetAsync(requestUri);
|
||||
|
||||
// Assert
|
||||
Assert.True(response.IsSuccessStatusCode, $"Expected successful response but got {response.StatusCode}");
|
||||
|
||||
var content = await response.Content.ReadAsStringAsync();
|
||||
var jsonDoc = JsonDocument.Parse(content);
|
||||
var root = jsonDoc.RootElement;
|
||||
|
||||
// Verify the card has expected properties
|
||||
Assert.True(root.TryGetProperty("name", out var nameProperty));
|
||||
Assert.Equal("Test Agent", nameProperty.GetString());
|
||||
|
||||
Assert.True(root.TryGetProperty("description", out var descProperty));
|
||||
Assert.Equal("A test agent for A2A communication", descProperty.GetString());
|
||||
|
||||
// Verify the card has a URL property and it's not null/empty
|
||||
Assert.True(root.TryGetProperty("url", out var urlProperty));
|
||||
Assert.NotEqual(JsonValueKind.Null, urlProperty.ValueKind);
|
||||
|
||||
var url = urlProperty.GetString();
|
||||
Assert.NotNull(url);
|
||||
Assert.NotEmpty(url);
|
||||
Assert.StartsWith("http", url, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Equal($"{testServer.BaseAddress.ToString().TrimEnd('/')}/a2a/test-agent/v1/card", url);
|
||||
}
|
||||
finally
|
||||
{
|
||||
await app.StopAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-24
@@ -1,10 +1,8 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using A2A;
|
||||
using Microsoft.Agents.AI.Hosting.A2A.UnitTests.Internal;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
@@ -478,25 +476,4 @@ public sealed class EndpointRouteA2ABuilderExtensionsTests
|
||||
var result = app.MapA2A(agentBuilder, "/a2a", agentCard);
|
||||
Assert.NotNull(result);
|
||||
}
|
||||
|
||||
private sealed class DummyChatClient : IChatClient
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public object? GetService(Type serviceType, object? serviceKey = null) =>
|
||||
serviceType.IsInstanceOfType(this) ? this : null;
|
||||
|
||||
public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.AI;
|
||||
|
||||
namespace Microsoft.Agents.AI.Hosting.A2A.UnitTests.Internal;
|
||||
|
||||
internal sealed class DummyChatClient : IChatClient
|
||||
{
|
||||
public void Dispose()
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public Task<ChatResponse> GetResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public object? GetService(Type serviceType, object? serviceKey = null) =>
|
||||
serviceType.IsInstanceOfType(this) ? this : null;
|
||||
|
||||
public IAsyncEnumerable<ChatResponseUpdate> GetStreamingResponseAsync(IEnumerable<ChatMessage> messages, ChatOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
}
|
||||
+4
-1
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
|
||||
<PropertyGroup>
|
||||
<TargetFrameworks>$(ProjectsCoreTargetFrameworks)</TargetFrameworks>
|
||||
@@ -6,6 +6,9 @@
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Microsoft.AspNetCore.TestHost" VersionOverride="8.0.21" Condition="'$(TargetFramework)' == 'net8.0'" />
|
||||
<PackageReference Include="Microsoft.AspNetCore.TestHost" Condition="'$(TargetFramework)' != 'net8.0'" />
|
||||
|
||||
<PackageReference Include="System.Net.ServerSentEvents" VersionOverride="10.0.0-rc.2.25502.107" />
|
||||
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" VersionOverride="10.0.0-rc.2.25502.107" />
|
||||
</ItemGroup>
|
||||
|
||||
+441
@@ -0,0 +1,441 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Diagnostics.CodeAnalysis;
|
||||
using System.Linq;
|
||||
using System.Net.Http;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Text.Json;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using FluentAssertions;
|
||||
using Microsoft.Agents.AI.AGUI;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.AspNetCore.Hosting.Server;
|
||||
using Microsoft.AspNetCore.TestHost;
|
||||
using Microsoft.Extensions.AI;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
|
||||
namespace Microsoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests;
|
||||
|
||||
public sealed class SharedStateTests : IAsyncDisposable
|
||||
{
|
||||
private WebApplication? _app;
|
||||
private HttpClient? _client;
|
||||
|
||||
[Fact]
|
||||
public async Task StateSnapshot_IsReturnedAsDataContent_WithCorrectMediaTypeAsync()
|
||||
{
|
||||
// Arrange
|
||||
var initialState = new { counter = 42, status = "active" };
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "update state");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
|
||||
// Act
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
updates.Should().NotBeEmpty();
|
||||
|
||||
// Should receive state snapshot as DataContent with application/json media type
|
||||
AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
stateUpdate.Should().NotBeNull("should receive state snapshot update");
|
||||
|
||||
DataContent? dataContent = stateUpdate!.Contents.OfType<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
dataContent.Should().NotBeNull();
|
||||
|
||||
// Verify the state content
|
||||
string receivedJson = System.Text.Encoding.UTF8.GetString(dataContent!.Data.ToArray());
|
||||
JsonElement receivedState = JsonSerializer.Deserialize<JsonElement>(receivedJson);
|
||||
receivedState.GetProperty("counter").GetInt32().Should().Be(43, "state should be incremented");
|
||||
receivedState.GetProperty("status").GetString().Should().Be("active");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StateSnapshot_HasCorrectAdditionalPropertiesAsync()
|
||||
{
|
||||
// Arrange
|
||||
var initialState = new { step = 1 };
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "process");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
|
||||
// Act
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
stateUpdate.Should().NotBeNull();
|
||||
|
||||
ChatResponseUpdate chatUpdate = stateUpdate!.AsChatResponseUpdate();
|
||||
chatUpdate.AdditionalProperties.Should().NotBeNull();
|
||||
chatUpdate.AdditionalProperties.Should().ContainKey("is_state_snapshot");
|
||||
((bool)chatUpdate.AdditionalProperties!["is_state_snapshot"]!).Should().BeTrue();
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ComplexState_WithNestedObjectsAndArrays_RoundTripsCorrectlyAsync()
|
||||
{
|
||||
// Arrange
|
||||
var complexState = new
|
||||
{
|
||||
sessionId = "test-123",
|
||||
nested = new { value = "test", count = 10 },
|
||||
array = new[] { 1, 2, 3 },
|
||||
tags = new[] { "tag1", "tag2" }
|
||||
};
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(complexState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "process complex state");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
|
||||
// Act
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
AgentRunResponseUpdate? stateUpdate = updates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
stateUpdate.Should().NotBeNull();
|
||||
|
||||
DataContent? dataContent = stateUpdate!.Contents.OfType<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
string receivedJson = System.Text.Encoding.UTF8.GetString(dataContent!.Data.ToArray());
|
||||
JsonElement receivedState = JsonSerializer.Deserialize<JsonElement>(receivedJson);
|
||||
|
||||
receivedState.GetProperty("sessionId").GetString().Should().Be("test-123");
|
||||
receivedState.GetProperty("nested").GetProperty("count").GetInt32().Should().Be(10);
|
||||
receivedState.GetProperty("array").GetArrayLength().Should().Be(3);
|
||||
receivedState.GetProperty("tags").GetArrayLength().Should().Be(2);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task StateSnapshot_CanBeUsedInSubsequentRequest_ForStateRoundTripAsync()
|
||||
{
|
||||
// Arrange
|
||||
var initialState = new { counter = 1, sessionId = "round-trip-test" };
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "increment");
|
||||
|
||||
List<AgentRunResponseUpdate> firstRoundUpdates = [];
|
||||
|
||||
// Act - First round
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
firstRoundUpdates.Add(update);
|
||||
}
|
||||
|
||||
// Extract state snapshot from first round
|
||||
AgentRunResponseUpdate? firstStateUpdate = firstRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
firstStateUpdate.Should().NotBeNull();
|
||||
DataContent? firstStateContent = firstStateUpdate!.Contents.OfType<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
|
||||
// Second round - use returned state
|
||||
ChatMessage secondStateMessage = new(ChatRole.System, [firstStateContent!]);
|
||||
ChatMessage secondUserMessage = new(ChatRole.User, "increment again");
|
||||
|
||||
List<AgentRunResponseUpdate> secondRoundUpdates = [];
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([secondUserMessage, secondStateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
secondRoundUpdates.Add(update);
|
||||
}
|
||||
|
||||
// Assert - Second round should have incremented counter again
|
||||
AgentRunResponseUpdate? secondStateUpdate = secondRoundUpdates.FirstOrDefault(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
secondStateUpdate.Should().NotBeNull();
|
||||
|
||||
DataContent? secondStateContent = secondStateUpdate!.Contents.OfType<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
string secondStateJson = System.Text.Encoding.UTF8.GetString(secondStateContent!.Data.ToArray());
|
||||
JsonElement secondState = JsonSerializer.Deserialize<JsonElement>(secondStateJson);
|
||||
|
||||
secondState.GetProperty("counter").GetInt32().Should().Be(3, "counter should be incremented twice: 1 -> 2 -> 3");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task WithoutState_AgentBehavesNormally_NoStateSnapshotReturnedAsync()
|
||||
{
|
||||
// Arrange
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
ChatMessage userMessage = new(ChatRole.User, "hello");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
|
||||
// Act
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
updates.Should().NotBeEmpty();
|
||||
|
||||
// Should NOT have state snapshot when no state is sent
|
||||
bool hasStateSnapshot = updates.Any(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
hasStateSnapshot.Should().BeFalse("should not return state snapshot when no state is provided");
|
||||
|
||||
// Should have normal text response
|
||||
updates.Should().Contain(u => u.Contents.Any(c => c is TextContent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task EmptyState_DoesNotTriggerStateHandlingAsync()
|
||||
{
|
||||
// Arrange
|
||||
var emptyState = new { };
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(emptyState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "hello");
|
||||
|
||||
List<AgentRunResponseUpdate> updates = [];
|
||||
|
||||
// Act
|
||||
await foreach (AgentRunResponseUpdate update in agent.RunStreamingAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None))
|
||||
{
|
||||
updates.Add(update);
|
||||
}
|
||||
|
||||
// Assert
|
||||
updates.Should().NotBeEmpty();
|
||||
|
||||
// Empty state {} should not trigger state snapshot mechanism
|
||||
bool hasEmptyStateSnapshot = updates.Any(u => u.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
hasEmptyStateSnapshot.Should().BeFalse("empty state should be treated as no state");
|
||||
|
||||
// Should have normal response
|
||||
updates.Should().Contain(u => u.Contents.Any(c => c is TextContent));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task NonStreamingRunAsync_WithState_ReturnsStateInResponseAsync()
|
||||
{
|
||||
// Arrange
|
||||
var initialState = new { counter = 5 };
|
||||
var fakeAgent = new FakeStateAgent();
|
||||
|
||||
await this.SetupTestServerAsync(fakeAgent);
|
||||
var chatClient = new AGUIChatClient(this._client!, "", null);
|
||||
AIAgent agent = chatClient.CreateAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []);
|
||||
ChatClientAgentThread thread = (ChatClientAgentThread)agent.GetNewThread();
|
||||
|
||||
string stateJson = JsonSerializer.Serialize(initialState);
|
||||
byte[] stateBytes = System.Text.Encoding.UTF8.GetBytes(stateJson);
|
||||
DataContent stateContent = new(stateBytes, "application/json");
|
||||
ChatMessage stateMessage = new(ChatRole.System, [stateContent]);
|
||||
ChatMessage userMessage = new(ChatRole.User, "process");
|
||||
|
||||
// Act
|
||||
AgentRunResponse response = await agent.RunAsync([userMessage, stateMessage], thread, new AgentRunOptions(), CancellationToken.None);
|
||||
|
||||
// Assert
|
||||
response.Should().NotBeNull();
|
||||
response.Messages.Should().NotBeEmpty();
|
||||
|
||||
// Should have message with DataContent containing state
|
||||
bool hasStateMessage = response.Messages.Any(m => m.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
hasStateMessage.Should().BeTrue("response should contain state message");
|
||||
|
||||
ChatMessage? stateResponseMessage = response.Messages.FirstOrDefault(m => m.Contents.Any(c => c is DataContent dc && dc.MediaType == "application/json"));
|
||||
stateResponseMessage.Should().NotBeNull();
|
||||
|
||||
DataContent? dataContent = stateResponseMessage!.Contents.OfType<DataContent>().FirstOrDefault(dc => dc.MediaType == "application/json");
|
||||
string receivedJson = System.Text.Encoding.UTF8.GetString(dataContent!.Data.ToArray());
|
||||
JsonElement receivedState = JsonSerializer.Deserialize<JsonElement>(receivedJson);
|
||||
receivedState.GetProperty("counter").GetInt32().Should().Be(6);
|
||||
}
|
||||
|
||||
private async Task SetupTestServerAsync(FakeStateAgent fakeAgent)
|
||||
{
|
||||
WebApplicationBuilder builder = WebApplication.CreateBuilder();
|
||||
builder.Services.AddAGUI();
|
||||
builder.WebHost.UseTestServer();
|
||||
|
||||
this._app = builder.Build();
|
||||
|
||||
this._app.MapAGUI("/agent", fakeAgent);
|
||||
|
||||
await this._app.StartAsync();
|
||||
|
||||
TestServer testServer = this._app.Services.GetRequiredService<IServer>() as TestServer
|
||||
?? throw new InvalidOperationException("TestServer not found");
|
||||
|
||||
this._client = testServer.CreateClient();
|
||||
this._client.BaseAddress = new Uri("http://localhost/agent");
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
this._client?.Dispose();
|
||||
if (this._app != null)
|
||||
{
|
||||
await this._app.DisposeAsync();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
[SuppressMessage("Performance", "CA1812:Avoid uninstantiated internal classes", Justification = "Instantiated in tests")]
|
||||
internal sealed class FakeStateAgent : AIAgent
|
||||
{
|
||||
public override string? Description => "Agent for state testing";
|
||||
|
||||
public override Task<AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
return this.RunStreamingAsync(messages, thread, options, cancellationToken).ToAgentRunResponseAsync(cancellationToken);
|
||||
}
|
||||
|
||||
public override async IAsyncEnumerable<AgentRunResponseUpdate> RunStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
[EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
// Check for state in ChatOptions.AdditionalProperties (set by AG-UI hosting layer)
|
||||
if (options is ChatClientAgentRunOptions { ChatOptions.AdditionalProperties: { } properties } &&
|
||||
properties.TryGetValue("ag_ui_state", out object? stateObj) &&
|
||||
stateObj is JsonElement state &&
|
||||
state.ValueKind == JsonValueKind.Object)
|
||||
{
|
||||
// Check if state object has properties (not empty {})
|
||||
bool hasProperties = false;
|
||||
foreach (JsonProperty _ in state.EnumerateObject())
|
||||
{
|
||||
hasProperties = true;
|
||||
break;
|
||||
}
|
||||
|
||||
if (hasProperties)
|
||||
{
|
||||
// State is present and non-empty - modify it and return as DataContent
|
||||
Dictionary<string, object?> modifiedState = [];
|
||||
foreach (JsonProperty prop in state.EnumerateObject())
|
||||
{
|
||||
if (prop.Name == "counter" && prop.Value.ValueKind == JsonValueKind.Number)
|
||||
{
|
||||
modifiedState[prop.Name] = prop.Value.GetInt32() + 1;
|
||||
}
|
||||
else if (prop.Value.ValueKind == JsonValueKind.Number)
|
||||
{
|
||||
modifiedState[prop.Name] = prop.Value.GetInt32();
|
||||
}
|
||||
else if (prop.Value.ValueKind == JsonValueKind.String)
|
||||
{
|
||||
modifiedState[prop.Name] = prop.Value.GetString();
|
||||
}
|
||||
else if (prop.Value.ValueKind == JsonValueKind.Object || prop.Value.ValueKind == JsonValueKind.Array)
|
||||
{
|
||||
modifiedState[prop.Name] = prop.Value;
|
||||
}
|
||||
}
|
||||
|
||||
// Return modified state as DataContent
|
||||
string modifiedStateJson = JsonSerializer.Serialize(modifiedState);
|
||||
byte[] modifiedStateBytes = System.Text.Encoding.UTF8.GetBytes(modifiedStateJson);
|
||||
DataContent modifiedStateContent = new(modifiedStateBytes, "application/json");
|
||||
|
||||
yield return new AgentRunResponseUpdate
|
||||
{
|
||||
MessageId = Guid.NewGuid().ToString("N"),
|
||||
Role = ChatRole.Assistant,
|
||||
Contents = [modifiedStateContent]
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Always return a text response
|
||||
string messageId = Guid.NewGuid().ToString("N");
|
||||
yield return new AgentRunResponseUpdate
|
||||
{
|
||||
MessageId = messageId,
|
||||
Role = ChatRole.Assistant,
|
||||
Contents = [new TextContent("State processed")]
|
||||
};
|
||||
|
||||
await Task.CompletedTask;
|
||||
}
|
||||
|
||||
public override AgentThread GetNewThread() => new FakeInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
{
|
||||
return new FakeInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
}
|
||||
|
||||
private sealed class FakeInMemoryAgentThread : InMemoryAgentThread
|
||||
{
|
||||
public FakeInMemoryAgentThread()
|
||||
: base()
|
||||
{
|
||||
}
|
||||
|
||||
public FakeInMemoryAgentThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null)
|
||||
: base(serializedThread, jsonSerializerOptions)
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
public override object? GetService(Type serviceType, object? serviceKey = null) => null;
|
||||
}
|
||||
+258
@@ -190,6 +190,264 @@ public sealed class AGUIEndpointRouteBuilderExtensionsTests
|
||||
Assert.Equal("Second", capturedMessages[1].Text);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MapAGUIAgent_ProducesValidAGUIEventStream_WithRunStartAndFinishAsync()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = new();
|
||||
RunAgentInput input = new()
|
||||
{
|
||||
ThreadId = "thread1",
|
||||
RunId = "run1",
|
||||
Messages = [new AGUIUserMessage { Id = "m1", Content = "Test" }]
|
||||
};
|
||||
string json = JsonSerializer.Serialize(input, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
MemoryStream responseStream = new();
|
||||
httpContext.Response.Body = responseStream;
|
||||
|
||||
RequestDelegate handler = this.CreateRequestDelegate((messages, tools, context, props) => new TestAgent());
|
||||
|
||||
// Act
|
||||
await handler(httpContext);
|
||||
|
||||
// Assert
|
||||
responseStream.Position = 0;
|
||||
string responseContent = Encoding.UTF8.GetString(responseStream.ToArray());
|
||||
|
||||
List<JsonElement> events = ParseSseEvents(responseContent);
|
||||
|
||||
JsonElement runStarted = Assert.Single(events, static e => e.GetProperty("type").GetString() == AGUIEventTypes.RunStarted);
|
||||
JsonElement runFinished = Assert.Single(events, static e => e.GetProperty("type").GetString() == AGUIEventTypes.RunFinished);
|
||||
|
||||
Assert.Equal("thread1", runStarted.GetProperty("threadId").GetString());
|
||||
Assert.Equal("run1", runStarted.GetProperty("runId").GetString());
|
||||
Assert.Equal("thread1", runFinished.GetProperty("threadId").GetString());
|
||||
Assert.Equal("run1", runFinished.GetProperty("runId").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MapAGUIAgent_ProducesTextMessageEvents_InCorrectOrderAsync()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = new();
|
||||
RunAgentInput input = new()
|
||||
{
|
||||
ThreadId = "thread1",
|
||||
RunId = "run1",
|
||||
Messages = [new AGUIUserMessage { Id = "m1", Content = "Hello" }]
|
||||
};
|
||||
string json = JsonSerializer.Serialize(input, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
MemoryStream responseStream = new();
|
||||
httpContext.Response.Body = responseStream;
|
||||
|
||||
RequestDelegate handler = this.CreateRequestDelegate((messages, tools, context, props) => new TestAgent());
|
||||
|
||||
// Act
|
||||
await handler(httpContext);
|
||||
|
||||
// Assert
|
||||
responseStream.Position = 0;
|
||||
string responseContent = Encoding.UTF8.GetString(responseStream.ToArray());
|
||||
|
||||
List<JsonElement> events = ParseSseEvents(responseContent);
|
||||
List<string?> eventTypes = new(events.Count);
|
||||
foreach (JsonElement evt in events)
|
||||
{
|
||||
eventTypes.Add(evt.GetProperty("type").GetString());
|
||||
}
|
||||
|
||||
Assert.Contains(AGUIEventTypes.RunStarted, eventTypes);
|
||||
Assert.Contains(AGUIEventTypes.TextMessageContent, eventTypes);
|
||||
Assert.Contains(AGUIEventTypes.RunFinished, eventTypes);
|
||||
|
||||
int runStartIndex = eventTypes.IndexOf(AGUIEventTypes.RunStarted);
|
||||
int firstContentIndex = eventTypes.IndexOf(AGUIEventTypes.TextMessageContent);
|
||||
int runFinishIndex = eventTypes.LastIndexOf(AGUIEventTypes.RunFinished);
|
||||
|
||||
Assert.True(runStartIndex < firstContentIndex, "Run start should precede text content.");
|
||||
Assert.True(firstContentIndex < runFinishIndex, "Text content should precede run finish.");
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MapAGUIAgent_EmitsTextMessageContent_WithCorrectDeltaAsync()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = new();
|
||||
RunAgentInput input = new()
|
||||
{
|
||||
ThreadId = "thread1",
|
||||
RunId = "run1",
|
||||
Messages = [new AGUIUserMessage { Id = "m1", Content = "Test" }]
|
||||
};
|
||||
string json = JsonSerializer.Serialize(input, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
MemoryStream responseStream = new();
|
||||
httpContext.Response.Body = responseStream;
|
||||
|
||||
RequestDelegate handler = this.CreateRequestDelegate((messages, tools, context, props) => new TestAgent());
|
||||
|
||||
// Act
|
||||
await handler(httpContext);
|
||||
|
||||
// Assert
|
||||
responseStream.Position = 0;
|
||||
string responseContent = Encoding.UTF8.GetString(responseStream.ToArray());
|
||||
|
||||
List<JsonElement> events = ParseSseEvents(responseContent);
|
||||
JsonElement textContentEvent = Assert.Single(events, static e => e.GetProperty("type").GetString() == AGUIEventTypes.TextMessageContent);
|
||||
|
||||
Assert.Equal("Test response", textContentEvent.GetProperty("delta").GetString());
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MapAGUIAgent_WithCustomAgent_ProducesExpectedStreamStructureAsync()
|
||||
{
|
||||
// Arrange
|
||||
AIAgent customAgentFactory(IEnumerable<ChatMessage> messages, IEnumerable<AITool> tools, IEnumerable<KeyValuePair<string, string>> context, JsonElement props)
|
||||
{
|
||||
return new MultiResponseAgent();
|
||||
}
|
||||
|
||||
DefaultHttpContext httpContext = new();
|
||||
RunAgentInput input = new()
|
||||
{
|
||||
ThreadId = "custom_thread",
|
||||
RunId = "custom_run",
|
||||
Messages = [new AGUIUserMessage { Id = "m1", Content = "Multi" }]
|
||||
};
|
||||
string json = JsonSerializer.Serialize(input, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
MemoryStream responseStream = new();
|
||||
httpContext.Response.Body = responseStream;
|
||||
|
||||
RequestDelegate handler = this.CreateRequestDelegate(customAgentFactory);
|
||||
|
||||
// Act
|
||||
await handler(httpContext);
|
||||
|
||||
// Assert
|
||||
responseStream.Position = 0;
|
||||
string responseContent = Encoding.UTF8.GetString(responseStream.ToArray());
|
||||
|
||||
List<JsonElement> events = ParseSseEvents(responseContent);
|
||||
List<JsonElement> contentEvents = new();
|
||||
foreach (JsonElement evt in events)
|
||||
{
|
||||
if (evt.GetProperty("type").GetString() == AGUIEventTypes.TextMessageContent)
|
||||
{
|
||||
contentEvents.Add(evt);
|
||||
}
|
||||
}
|
||||
|
||||
Assert.True(contentEvents.Count >= 3, $"Expected at least 3 text_message.content events, got {contentEvents.Count}");
|
||||
|
||||
List<string?> deltas = new(contentEvents.Count);
|
||||
foreach (JsonElement contentEvent in contentEvents)
|
||||
{
|
||||
deltas.Add(contentEvent.GetProperty("delta").GetString());
|
||||
}
|
||||
|
||||
Assert.Contains("First", deltas);
|
||||
Assert.Contains(" part", deltas);
|
||||
Assert.Contains(" of response", deltas);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task MapAGUIAgent_ProducesCorrectThreadAndRunIds_InAllEventsAsync()
|
||||
{
|
||||
// Arrange
|
||||
DefaultHttpContext httpContext = new();
|
||||
RunAgentInput input = new()
|
||||
{
|
||||
ThreadId = "test_thread_123",
|
||||
RunId = "test_run_456",
|
||||
Messages = [new AGUIUserMessage { Id = "m1", Content = "Test" }]
|
||||
};
|
||||
string json = JsonSerializer.Serialize(input, AGUIJsonSerializerContext.Default.RunAgentInput);
|
||||
httpContext.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(json));
|
||||
MemoryStream responseStream = new();
|
||||
httpContext.Response.Body = responseStream;
|
||||
|
||||
RequestDelegate handler = this.CreateRequestDelegate((messages, tools, context, props) => new TestAgent());
|
||||
|
||||
// Act
|
||||
await handler(httpContext);
|
||||
|
||||
// Assert
|
||||
responseStream.Position = 0;
|
||||
string responseContent = Encoding.UTF8.GetString(responseStream.ToArray());
|
||||
|
||||
List<JsonElement> events = ParseSseEvents(responseContent);
|
||||
JsonElement runStarted = Assert.Single(events, static e => e.GetProperty("type").GetString() == AGUIEventTypes.RunStarted);
|
||||
|
||||
Assert.Equal("test_thread_123", runStarted.GetProperty("threadId").GetString());
|
||||
Assert.Equal("test_run_456", runStarted.GetProperty("runId").GetString());
|
||||
}
|
||||
|
||||
private static List<JsonElement> ParseSseEvents(string responseContent)
|
||||
{
|
||||
List<JsonElement> events = [];
|
||||
using StringReader reader = new(responseContent);
|
||||
StringBuilder dataBuilder = new();
|
||||
string? line;
|
||||
|
||||
while ((line = reader.ReadLine()) != null)
|
||||
{
|
||||
if (line.StartsWith("data:", StringComparison.Ordinal))
|
||||
{
|
||||
string payload = line.Length > 5 && line[5] == ' '
|
||||
? line.Substring(6)
|
||||
: line.Substring(5);
|
||||
dataBuilder.Append(payload);
|
||||
}
|
||||
else if (line.Length == 0 && dataBuilder.Length > 0)
|
||||
{
|
||||
using JsonDocument document = JsonDocument.Parse(dataBuilder.ToString());
|
||||
events.Add(document.RootElement.Clone());
|
||||
dataBuilder.Clear();
|
||||
}
|
||||
}
|
||||
|
||||
if (dataBuilder.Length > 0)
|
||||
{
|
||||
using JsonDocument document = JsonDocument.Parse(dataBuilder.ToString());
|
||||
events.Add(document.RootElement.Clone());
|
||||
}
|
||||
|
||||
return events;
|
||||
}
|
||||
|
||||
private sealed class MultiResponseAgent : AIAgent
|
||||
{
|
||||
public override string Id => "multi-response-agent";
|
||||
|
||||
public override string? Description => "Agent that produces multiple text chunks";
|
||||
|
||||
public override AgentThread GetNewThread() => new TestInMemoryAgentThread();
|
||||
|
||||
public override AgentThread DeserializeThread(JsonElement serializedThread, JsonSerializerOptions? jsonSerializerOptions = null) =>
|
||||
new TestInMemoryAgentThread(serializedThread, jsonSerializerOptions);
|
||||
|
||||
public override Task<AgentRunResponse> RunAsync(IEnumerable<ChatMessage> messages, AgentThread? thread = null, AgentRunOptions? options = null, CancellationToken cancellationToken = default)
|
||||
{
|
||||
throw new NotImplementedException();
|
||||
}
|
||||
|
||||
public override async IAsyncEnumerable<AgentRunResponseUpdate> RunStreamingAsync(
|
||||
IEnumerable<ChatMessage> messages,
|
||||
AgentThread? thread = null,
|
||||
AgentRunOptions? options = null,
|
||||
[System.Runtime.CompilerServices.EnumeratorCancellation] CancellationToken cancellationToken = default)
|
||||
{
|
||||
await Task.CompletedTask;
|
||||
yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, "First"));
|
||||
yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " part"));
|
||||
yield return new AgentRunResponseUpdate(new ChatResponseUpdate(ChatRole.Assistant, " of response"));
|
||||
}
|
||||
}
|
||||
|
||||
private RequestDelegate CreateRequestDelegate(
|
||||
Func<IEnumerable<ChatMessage>, IEnumerable<AITool>, IEnumerable<KeyValuePair<string, string>>, JsonElement, AIAgent> factory)
|
||||
{
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
{
|
||||
"model": "gpt-4o-mini",
|
||||
"messages": [
|
||||
{
|
||||
"role": "user",
|
||||
"content": "What's the weather like in San Francisco?"
|
||||
}
|
||||
],
|
||||
"max_completion_tokens": 256,
|
||||
"temperature": 0.7,
|
||||
"top_p": 1,
|
||||
"tools": [
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"description": "Get the current weather in a given location",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"location": {
|
||||
"type": "string",
|
||||
"description": "The city and state, e.g. San Francisco, CA"
|
||||
},
|
||||
"unit": {
|
||||
"type": "string",
|
||||
"enum": [ "celsius", "fahrenheit" ],
|
||||
"description": "Temperature unit"
|
||||
}
|
||||
},
|
||||
"required": [ "location" ]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_time",
|
||||
"description": "Get the current time in a given timezone",
|
||||
"parameters": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"timezone": {
|
||||
"type": "string",
|
||||
"description": "The IANA timezone, e.g. America/Los_Angeles"
|
||||
}
|
||||
},
|
||||
"required": [ "timezone" ]
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
{
|
||||
"id": "chatcmpl-tools-test-001",
|
||||
"object": "chat.completion",
|
||||
"created": 1234567890,
|
||||
"model": "gpt-4o-mini",
|
||||
"choices": [
|
||||
{
|
||||
"index": 0,
|
||||
"message": {
|
||||
"role": "assistant",
|
||||
"content": null,
|
||||
"tool_calls": [
|
||||
{
|
||||
"id": "call_abc123",
|
||||
"type": "function",
|
||||
"function": {
|
||||
"name": "get_weather",
|
||||
"arguments": "{\"location\": \"San Francisco, CA\", \"unit\": \"fahrenheit\"}"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"finish_reason": "tool_calls"
|
||||
}
|
||||
],
|
||||
"usage": {
|
||||
"prompt_tokens": 85,
|
||||
"completion_tokens": 32,
|
||||
"total_tokens": 117,
|
||||
"prompt_tokens_details": {
|
||||
"cached_tokens": 0,
|
||||
"audio_tokens": 0
|
||||
},
|
||||
"completion_tokens_details": {
|
||||
"reasoning_tokens": 0,
|
||||
"audio_tokens": 0,
|
||||
"accepted_prediction_tokens": 0,
|
||||
"rejected_prediction_tokens": 0
|
||||
}
|
||||
},
|
||||
"service_tier": "default"
|
||||
}
|
||||
-12
@@ -27,16 +27,4 @@
|
||||
</None>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\function_calling\request.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\function_calling\response.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\json_mode\request.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\json_mode\response.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\multi_turn\request.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\multi_turn\response.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\streaming\request.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\system_message\request.json" />
|
||||
<Content Remove="ConformanceTraces\ChatCompletions\system_message\response.json" />
|
||||
</ItemGroup>
|
||||
|
||||
</Project>
|
||||
|
||||
+130
@@ -456,6 +456,136 @@ public sealed class OpenAIChatCompletionsConformanceTests : ConformanceTestBase
|
||||
Assert.Equal(JsonValueKind.String, jsonRoot.GetProperty("occupation").ValueKind);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task ToolsSerializationDeserializationAsync()
|
||||
{
|
||||
// Arrange
|
||||
string requestJson = LoadChatCompletionsTraceFile("tools/request.json");
|
||||
using var expectedResponseDoc = LoadChatCompletionsTraceDocument("tools/response.json");
|
||||
|
||||
HttpClient client = await this.CreateTestServerAsync(
|
||||
"tools-agent",
|
||||
"You are a helpful assistant with access to weather and time tools.",
|
||||
"tool-call",
|
||||
(msg) => [new FunctionCallContent("call_abc123", "get_weather", new Dictionary<string, object?>() {
|
||||
{ "location", "San Francisco, CA" },
|
||||
{ "unit", "fahrenheit" }
|
||||
})]
|
||||
);
|
||||
|
||||
// Act
|
||||
HttpResponseMessage httpResponse = await this.SendChatCompletionRequestAsync(client, "tools-agent", requestJson);
|
||||
using var responseDoc = await ParseResponseAsync(httpResponse);
|
||||
var response = responseDoc.RootElement;
|
||||
|
||||
// Parse the request
|
||||
using var requestDoc = JsonDocument.Parse(requestJson);
|
||||
var request = requestDoc.RootElement;
|
||||
|
||||
// Assert - Request has tools array with proper structure
|
||||
AssertJsonPropertyExists(request, "tools");
|
||||
var tools = request.GetProperty("tools");
|
||||
Assert.Equal(JsonValueKind.Array, tools.ValueKind);
|
||||
Assert.Equal(2, tools.GetArrayLength());
|
||||
|
||||
// Assert - First tool (get_weather)
|
||||
var weatherTool = tools[0];
|
||||
AssertJsonPropertyEquals(weatherTool, "type", "function");
|
||||
AssertJsonPropertyExists(weatherTool, "function");
|
||||
|
||||
var weatherFunction = weatherTool.GetProperty("function");
|
||||
AssertJsonPropertyEquals(weatherFunction, "name", "get_weather");
|
||||
AssertJsonPropertyExists(weatherFunction, "description");
|
||||
AssertJsonPropertyExists(weatherFunction, "parameters");
|
||||
|
||||
var weatherParams = weatherFunction.GetProperty("parameters");
|
||||
AssertJsonPropertyEquals(weatherParams, "type", "object");
|
||||
AssertJsonPropertyExists(weatherParams, "properties");
|
||||
AssertJsonPropertyExists(weatherParams, "required");
|
||||
|
||||
// Verify location property exists
|
||||
var properties = weatherParams.GetProperty("properties");
|
||||
AssertJsonPropertyExists(properties, "location");
|
||||
AssertJsonPropertyExists(properties, "unit");
|
||||
|
||||
// Assert - Second tool (get_time)
|
||||
var timeTool = tools[1];
|
||||
AssertJsonPropertyEquals(timeTool, "type", "function");
|
||||
|
||||
var timeFunction = timeTool.GetProperty("function");
|
||||
AssertJsonPropertyEquals(timeFunction, "name", "get_time");
|
||||
AssertJsonPropertyExists(timeFunction, "description");
|
||||
AssertJsonPropertyExists(timeFunction, "parameters");
|
||||
|
||||
// Assert - Response structure
|
||||
AssertJsonPropertyExists(response, "id");
|
||||
AssertJsonPropertyEquals(response, "object", "chat.completion");
|
||||
AssertJsonPropertyExists(response, "created");
|
||||
AssertJsonPropertyExists(response, "model");
|
||||
|
||||
// Assert - Response has tool_calls in choices
|
||||
var choices = response.GetProperty("choices");
|
||||
Assert.Equal(JsonValueKind.Array, choices.ValueKind);
|
||||
Assert.True(choices.GetArrayLength() > 0);
|
||||
|
||||
var choice = choices[0];
|
||||
AssertJsonPropertyExists(choice, "finish_reason");
|
||||
AssertJsonPropertyEquals(choice, "finish_reason", anyOfValues: ["tool_calls", "stop"]);
|
||||
AssertJsonPropertyExists(choice, "message");
|
||||
|
||||
var message = choice.GetProperty("message");
|
||||
AssertJsonPropertyEquals(message, "role", "assistant");
|
||||
AssertJsonPropertyExists(message, "tool_calls");
|
||||
|
||||
// Assert - Tool calls array structure
|
||||
var toolCalls = message.GetProperty("tool_calls");
|
||||
Assert.Equal(JsonValueKind.Array, toolCalls.ValueKind);
|
||||
Assert.True(toolCalls.GetArrayLength() > 0);
|
||||
|
||||
var toolCall = toolCalls[0];
|
||||
AssertJsonPropertyExists(toolCall, "id");
|
||||
AssertJsonPropertyEquals(toolCall, "type", "function");
|
||||
AssertJsonPropertyExists(toolCall, "function");
|
||||
|
||||
var callFunction = toolCall.GetProperty("function");
|
||||
AssertJsonPropertyEquals(callFunction, "name", "get_weather");
|
||||
AssertJsonPropertyExists(callFunction, "arguments");
|
||||
|
||||
// Assert - Tool call arguments are valid JSON
|
||||
string arguments = callFunction.GetProperty("arguments").GetString()!;
|
||||
using var argsDoc = JsonDocument.Parse(arguments);
|
||||
var argsRoot = argsDoc.RootElement;
|
||||
AssertJsonPropertyExists(argsRoot, "location");
|
||||
AssertJsonPropertyEquals(argsRoot, "location", "San Francisco, CA");
|
||||
AssertJsonPropertyEquals(argsRoot, "unit", "fahrenheit");
|
||||
|
||||
// Assert - Message content is null when tool_calls present
|
||||
if (message.TryGetProperty("content", out var contentProp))
|
||||
{
|
||||
Assert.Equal(JsonValueKind.Null, contentProp.ValueKind);
|
||||
}
|
||||
|
||||
// Assert - Usage statistics
|
||||
AssertJsonPropertyExists(response, "usage");
|
||||
var usage = response.GetProperty("usage");
|
||||
AssertJsonPropertyExists(usage, "prompt_tokens");
|
||||
AssertJsonPropertyExists(usage, "completion_tokens");
|
||||
AssertJsonPropertyExists(usage, "total_tokens");
|
||||
|
||||
var promptTokens = usage.GetProperty("prompt_tokens").GetInt32();
|
||||
var completionTokens = usage.GetProperty("completion_tokens").GetInt32();
|
||||
var totalTokens = usage.GetProperty("total_tokens").GetInt32();
|
||||
|
||||
Assert.True(promptTokens > 0);
|
||||
Assert.True(completionTokens > 0);
|
||||
Assert.Equal(promptTokens + completionTokens, totalTokens);
|
||||
|
||||
// Assert - Service tier
|
||||
AssertJsonPropertyExists(response, "service_tier");
|
||||
var serviceTier = response.GetProperty("service_tier").GetString();
|
||||
Assert.NotNull(serviceTier);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Helper to parse chat completion chunks from SSE response.
|
||||
/// </summary>
|
||||
|
||||
+3
-3
@@ -45,7 +45,7 @@ public sealed class OpenAIHttpApiIntegrationTests : IAsyncDisposable
|
||||
// Act - Create response (non-streaming, non-background)
|
||||
var createResponseRequest = new
|
||||
{
|
||||
model = AgentName,
|
||||
metadata = new { entity_id = AgentName },
|
||||
conversation = conversationId,
|
||||
input = UserMessage,
|
||||
stream = false
|
||||
@@ -122,7 +122,7 @@ public sealed class OpenAIHttpApiIntegrationTests : IAsyncDisposable
|
||||
// Act - Create response (streaming, non-background)
|
||||
var createResponseRequest = new
|
||||
{
|
||||
model = AgentName,
|
||||
metadata = new { entity_id = AgentName },
|
||||
conversation = conversationId,
|
||||
input = UserMessage,
|
||||
stream = true
|
||||
@@ -196,7 +196,7 @@ public sealed class OpenAIHttpApiIntegrationTests : IAsyncDisposable
|
||||
// Act - Create response (non-streaming, background)
|
||||
var createResponseRequest = new
|
||||
{
|
||||
model = AgentName,
|
||||
metadata = new { entity_id = AgentName },
|
||||
conversation = conversationId,
|
||||
input = UserMessage,
|
||||
stream = false,
|
||||
|
||||
+7
-8
@@ -168,23 +168,23 @@ public sealed class OpenAIResponsesAgentResolutionIntegrationTests : IAsyncDispo
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Verifies that agent resolution using the model property works correctly.
|
||||
/// Verifies that agent resolution using the metadata.entity_id property works correctly.
|
||||
/// </summary>
|
||||
[Fact]
|
||||
public async Task CreateResponse_WithModelProperty_ResolvesCorrectAgentAsync()
|
||||
public async Task CreateResponse_WithMetadataEntityId_ResolvesCorrectAgentAsync()
|
||||
{
|
||||
// Arrange
|
||||
const string AgentName = "model-agent";
|
||||
const string AgentName = "metadata-agent";
|
||||
const string Instructions = "You are a helpful assistant.";
|
||||
const string ExpectedResponse = "Response via model property";
|
||||
const string ExpectedResponse = "Response via metadata.entity_id";
|
||||
|
||||
this._httpClient = await this.CreateTestServerWithAgentResolutionAsync(
|
||||
(AgentName, Instructions, ExpectedResponse));
|
||||
|
||||
// Act - Use raw HTTP request to control the model property
|
||||
// Act - Use raw HTTP request with metadata.entity_id
|
||||
using StringContent requestContent = new(JsonSerializer.Serialize(new
|
||||
{
|
||||
model = AgentName,
|
||||
metadata = new { entity_id = AgentName },
|
||||
input = new[]
|
||||
{
|
||||
new { type = "message", role = "user", content = "Test message" }
|
||||
@@ -235,7 +235,7 @@ public sealed class OpenAIResponsesAgentResolutionIntegrationTests : IAsyncDispo
|
||||
using HttpResponseMessage httpResponse = await this._httpClient!.PostAsync(new Uri("/v1/responses", UriKind.Relative), requestContent);
|
||||
|
||||
// Assert
|
||||
Assert.Equal(System.Net.HttpStatusCode.NotFound, httpResponse.StatusCode);
|
||||
Assert.Equal(System.Net.HttpStatusCode.BadRequest, httpResponse.StatusCode);
|
||||
|
||||
string responseJson = await httpResponse.Content.ReadAsStringAsync();
|
||||
Assert.Contains("non-existent-agent", responseJson);
|
||||
@@ -268,7 +268,6 @@ public sealed class OpenAIResponsesAgentResolutionIntegrationTests : IAsyncDispo
|
||||
|
||||
string responseJson = await httpResponse.Content.ReadAsStringAsync();
|
||||
Assert.Contains("agent.name", responseJson, StringComparison.OrdinalIgnoreCase);
|
||||
Assert.Contains("model", responseJson, StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
|
||||
+14
@@ -344,6 +344,20 @@ public sealed class OpenAIResponsesSerializationTests : ConformanceTestBase
|
||||
Assert.NotNull(request.Input);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_InvalidInputObject_ThrowsHelpfulException()
|
||||
{
|
||||
// Arrange
|
||||
const string Json = "{\"model\":\"gpt-4o-mini\",\"input\":{\"input\":\"testing!\"},\"stream\":true}";
|
||||
|
||||
// Act & Assert
|
||||
var exception = Assert.Throws<JsonException>(() =>
|
||||
JsonSerializer.Deserialize(Json, OpenAIHostingJsonContext.Default.CreateResponse));
|
||||
|
||||
Assert.Contains("ResponseInput must be either a string or an array of messages", exception.Message);
|
||||
Assert.Contains("Objects are not supported", exception.Message);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Deserialize_AllRequests_CanBeDeserialized()
|
||||
{
|
||||
|
||||
+154
@@ -0,0 +1,154 @@
|
||||
// Copyright (c) Microsoft. All rights reserved.
|
||||
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Agents.AI.Workflows.Declarative.ObjectModel;
|
||||
using Microsoft.Bot.ObjectModel;
|
||||
using Microsoft.PowerFx.Types;
|
||||
using Xunit.Abstractions;
|
||||
|
||||
namespace Microsoft.Agents.AI.Workflows.Declarative.UnitTests.ObjectModel;
|
||||
|
||||
/// <summary>
|
||||
/// Tests for <see cref="SetMultipleVariablesExecutor"/>.
|
||||
/// </summary>
|
||||
public sealed class SetMultipleVariablesExecutorTest(ITestOutputHelper output) : WorkflowActionExecutorTest(output)
|
||||
{
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesAsync()
|
||||
{
|
||||
// Arrange, Act, Assert
|
||||
await this.ExecuteTestAsync(
|
||||
displayName: nameof(SetMultipleVariablesAsync),
|
||||
assignments: [
|
||||
new AssignmentCase("Variable1", new NumberDataValue(42), FormulaValue.New(42)),
|
||||
new AssignmentCase("Variable2", new StringDataValue("Test"), FormulaValue.New("Test")),
|
||||
new AssignmentCase("Variable3", new BooleanDataValue(true), FormulaValue.New(true))
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesWithExpressionsAsync()
|
||||
{
|
||||
// Arrange
|
||||
this.State.Set("SourceNumber", FormulaValue.New(10));
|
||||
this.State.Set("SourceText", FormulaValue.New("Hello"));
|
||||
this.State.Bind();
|
||||
|
||||
// Act, Assert
|
||||
await this.ExecuteTestAsync(
|
||||
displayName: nameof(SetMultipleVariablesWithExpressionsAsync),
|
||||
assignments: [
|
||||
new AssignmentCase("CalcVariable", ValueExpression.Expression("Local.SourceNumber * 2"), FormulaValue.New(20)),
|
||||
new AssignmentCase("ConcatVariable", ValueExpression.Expression(@"Concatenate(Local.SourceText, "" World"")"), FormulaValue.New("Hello World")),
|
||||
new AssignmentCase("BoolVariable", ValueExpression.Expression("Local.SourceNumber > 5"), FormulaValue.New(true))
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesWithVariableReferencesAsync()
|
||||
{
|
||||
// Arrange
|
||||
this.State.Set("Source1", FormulaValue.New(123));
|
||||
this.State.Set("Source2", FormulaValue.New("Reference"));
|
||||
this.State.Bind();
|
||||
|
||||
// Act, Assert
|
||||
await this.ExecuteTestAsync(
|
||||
displayName: nameof(SetMultipleVariablesWithVariableReferencesAsync),
|
||||
assignments: [
|
||||
new AssignmentCase("Target1", ValueExpression.Variable(PropertyPath.TopicVariable("Source1")), FormulaValue.New(123)),
|
||||
new AssignmentCase("Target2", ValueExpression.Variable(PropertyPath.TopicVariable("Source2")), FormulaValue.New("Reference"))
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesWithNullValuesAsync()
|
||||
{
|
||||
// Arrange, Act, Assert
|
||||
await this.ExecuteTestAsync(
|
||||
displayName: nameof(SetMultipleVariablesWithNullValuesAsync),
|
||||
assignments: [
|
||||
new AssignmentCase("NullVar1", null, FormulaValue.NewBlank()),
|
||||
new AssignmentCase("NormalVar", new StringDataValue("NotNull"), FormulaValue.New("NotNull")),
|
||||
new AssignmentCase("NullVar2", null, FormulaValue.NewBlank())
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesUpdateExistingAsync()
|
||||
{
|
||||
// Arrange
|
||||
this.State.Set("ExistingVar1", FormulaValue.New(999));
|
||||
this.State.Set("ExistingVar2", FormulaValue.New("OldValue"));
|
||||
|
||||
// Act, Assert
|
||||
await this.ExecuteTestAsync(
|
||||
displayName: nameof(SetMultipleVariablesUpdateExistingAsync),
|
||||
assignments: [
|
||||
new AssignmentCase("ExistingVar1", new NumberDataValue(111), FormulaValue.New(111)),
|
||||
new AssignmentCase("ExistingVar2", new StringDataValue("NewValue"), FormulaValue.New("NewValue")),
|
||||
new AssignmentCase("NewVar", new BooleanDataValue(false), FormulaValue.New(false))
|
||||
]);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task SetMultipleVariablesEmptyAssignmentsAsync()
|
||||
{
|
||||
// Arrange
|
||||
SetMultipleVariables model = this.CreateModel(nameof(SetMultipleVariablesEmptyAssignmentsAsync), []);
|
||||
|
||||
// Arrange, Act, Assert
|
||||
Assert.Throws<DeclarativeModelException>(() =>
|
||||
{
|
||||
// Empty variables assignment should fail RequiredProperties validation.
|
||||
_ = new SetMultipleVariablesExecutor(model, this.State);
|
||||
});
|
||||
}
|
||||
|
||||
private async Task ExecuteTestAsync(string displayName, AssignmentCase[] assignments)
|
||||
{
|
||||
// Arrange
|
||||
SetMultipleVariables model = this.CreateModel(displayName, assignments);
|
||||
|
||||
// Act
|
||||
SetMultipleVariablesExecutor action = new(model, this.State);
|
||||
await this.ExecuteAsync(action);
|
||||
|
||||
// Assert
|
||||
VerifyModel(model, action);
|
||||
foreach (AssignmentCase assignment in assignments)
|
||||
{
|
||||
this.VerifyState(assignment.VariableName, assignment.ExpectedValue);
|
||||
}
|
||||
}
|
||||
|
||||
private SetMultipleVariables CreateModel(string displayName, AssignmentCase[] assignments)
|
||||
{
|
||||
SetMultipleVariables.Builder actionBuilder = new()
|
||||
{
|
||||
Id = this.CreateActionId(),
|
||||
DisplayName = this.FormatDisplayName(displayName),
|
||||
};
|
||||
|
||||
foreach (AssignmentCase assignment in assignments)
|
||||
{
|
||||
ValueExpression.Builder? valueExpressionBuilder = assignment.ValueExpression switch
|
||||
{
|
||||
null => null,
|
||||
DataValue dataValue => new ValueExpression.Builder(ValueExpression.Literal(dataValue)),
|
||||
ValueExpression valueExpression => new ValueExpression.Builder(valueExpression),
|
||||
_ => throw new System.ArgumentException($"Unsupported value type: {assignment.ValueExpression?.GetType().Name}")
|
||||
};
|
||||
|
||||
actionBuilder.Assignments.Add(new VariableAssignment.Builder()
|
||||
{
|
||||
Variable = PropertyPath.Create(FormatVariablePath(assignment.VariableName)),
|
||||
Value = valueExpressionBuilder,
|
||||
});
|
||||
}
|
||||
|
||||
return AssignParent<SetMultipleVariables>(actionBuilder);
|
||||
}
|
||||
|
||||
private sealed record AssignmentCase(string VariableName, object? ValueExpression, FormulaValue ExpectedValue);
|
||||
}
|
||||
Reference in New Issue
Block a user