-
Notifications
You must be signed in to change notification settings - Fork 1.9k
.NET: Add MapAGUI overload that resolves the agent per request via a factory #6251
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
darthmolen
wants to merge
3
commits into
microsoft:main
Choose a base branch
from
darthmolen:feature/mapagui-factory-delegate
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+279
−46
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
3c9bb0a
Add MapAGUI overload that resolves the agent per request via a factory
stevenmolencsat e8844f6
Add integration tests for the per-request MapAGUI factory overload
stevenmolencsat 87d41db
Merge remote-tracking branch 'origin/main' into feature/mapagui-facto…
stevenmolencsat File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
115 changes: 115 additions & 0 deletions
115
...crosoft.Agents.AI.Hosting.AGUI.AspNetCore.IntegrationTests/MapAGUIFactoryDelegateTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,115 @@ | ||
| // Copyright (c) Microsoft. All rights reserved. | ||
|
|
||
| using System; | ||
| using System.Collections.Generic; | ||
| using System.Net.Http; | ||
| using System.Text; | ||
| 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; | ||
|
|
||
| /// <summary> | ||
| /// Integration tests for the per-request factory-delegate overload of | ||
| /// <c>MapAGUI(endpoints, agentName, pattern, Func<IServiceProvider, string, AIAgent>)</c>. | ||
| /// Unlike the startup-capture overloads, the factory is invoked once per request from the request's | ||
| /// <see cref="IServiceProvider"/>. | ||
| /// </summary> | ||
| public sealed class MapAGUIFactoryDelegateTests : IAsyncDisposable | ||
| { | ||
| private WebApplication? _app; | ||
| private HttpClient? _client; | ||
|
|
||
| [Fact] | ||
| public async Task MapAGUI_WithFactoryDelegate_InvokesFactoryPerRequest_AndStreamsAsync() | ||
| { | ||
| // Arrange - map the endpoint with a factory that records how many times it is invoked. | ||
| int factoryInvocations = 0; | ||
| await this.SetupTestServerWithFactoryAsync((_, name) => | ||
| { | ||
| Interlocked.Increment(ref factoryInvocations); | ||
| return new FakeSessionAgent(name); | ||
| }); | ||
|
|
||
| var chatClient = new AGUIChatClient(this._client!, "", null); | ||
| AIAgent agent = chatClient.AsAIAgent(instructions: null, name: "assistant", description: "Sample assistant", tools: []); | ||
| AgentSession session = await agent.CreateSessionAsync(); | ||
|
|
||
| // Act - two turns => two HTTP requests. | ||
| List<AgentResponseUpdate> firstTurn = []; | ||
| await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([new ChatMessage(ChatRole.User, "First")], session, new AgentRunOptions(), CancellationToken.None)) | ||
| { | ||
| firstTurn.Add(update); | ||
| } | ||
|
|
||
| List<AgentResponseUpdate> secondTurn = []; | ||
| await foreach (AgentResponseUpdate update in agent.RunStreamingAsync([new ChatMessage(ChatRole.User, "Second")], session, new AgentRunOptions(), CancellationToken.None)) | ||
| { | ||
| secondTurn.Add(update); | ||
| } | ||
|
|
||
| // Assert - the factory ran once per request (not captured once at startup), and the agent streamed. | ||
| factoryInvocations.Should().Be(2, "the factory delegate is invoked per request"); | ||
| firstTurn.Should().NotBeEmpty(); | ||
| firstTurn.ToAgentResponse().Messages[0].Text.Should().Contain("Hello from session agent"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task MapAGUI_WithFactoryDelegate_WhenFactoryReturnsNull_FailsTheRequestAsync() | ||
| { | ||
| // Arrange - a factory that returns null should surface a clear failure when a request arrives. | ||
| await this.SetupTestServerWithFactoryAsync((_, _) => null!); | ||
|
|
||
| const string Json = """ | ||
| {"threadId":"t1","runId":"r1","messages":[{"id":"m1","role":"user","content":"hi"}],"tools":[],"context":[],"state":{}} | ||
| """; | ||
| using StringContent content = new(Json, Encoding.UTF8, "application/json"); | ||
|
|
||
| // Act | ||
| Func<Task> act = async () => | ||
| { | ||
| using HttpResponseMessage response = await this._client!.PostAsync((Uri?)null, content); | ||
| response.EnsureSuccessStatusCode(); | ||
| }; | ||
|
|
||
| // Assert - the factory returning null surfaces a clear InvalidOperationException naming the agent. | ||
| (await act.Should().ThrowAsync<InvalidOperationException>()) | ||
| .WithMessage("*factory for 'factory-agent' returned null*"); | ||
| } | ||
|
|
||
| private async Task SetupTestServerWithFactoryAsync(Func<IServiceProvider, string, AIAgent> factory) | ||
| { | ||
| WebApplicationBuilder builder = WebApplication.CreateBuilder(); | ||
| builder.WebHost.UseTestServer(); | ||
| builder.Services.AddAGUI(); | ||
|
|
||
| this._app = builder.Build(); | ||
|
|
||
| // Per-request factory overload — no keyed AIAgent registration required. | ||
| this._app.MapAGUI("factory-agent", "/agent", factory); | ||
|
|
||
| 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(); | ||
| } | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.