Skip to content

A programming framework for agentic AI

fix: Improve PublishMessageAsync resilience (#5923)

Jacob Alber41e7e85c409d
diff --git a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs
index 845bdce74..1e6accc3f 100644
--- a/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/AgentChat/GroupChat/OutputCollectorAgent.cs
@@ -26,7 +26,7 @@ internal sealed class OutputSink : IOutputCollectionSink
}
private readonly object sync = new();
- private SemaphoreSlim semapohre = new SemaphoreSlim(1, 1);
+ private SemaphoreSlim semapohre = new SemaphoreSlim(0, 1);
private SinkFrame? receivingSinkFrame;
@@ -43,7 +43,12 @@ internal sealed class OutputSink : IOutputCollectionSink
frameAction(this.receivingSinkFrame);
}
- semapohre.Release();
+ // TODO: Replace the Semaphore with a TaskSource approach
+ try
+ {
+ semapohre.Release();
+ }
+ catch (SemaphoreFullException) { }
}
public void CollectMessage(AgentMessage message)
diff --git a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
index dddee1845..fc790e9f8 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
@@ -43,28 +43,45 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
}
TopicId topic = envelope.Topic.Value;
+ List<Exception> exceptions = new();
+
foreach (var subscription in this.subscriptions.Values.Where(subscription => subscription.Matches(topic)))
{
- AgentId? sender = envelope.Sender;
-
- CancellationTokenSource combinedSource = CancellationTokenSource.CreateLinkedTokenSource(envelope.Cancellation, deliveryToken);
- MessageContext messageContext = new(envelope.MessageId, combinedSource.Token)
+ try
{
- Sender = sender,
- Topic = topic,
- IsRpc = false
- };
+ deliveryToken.ThrowIfCancellationRequested();
+
+ AgentId? sender = envelope.Sender;
+
+ CancellationTokenSource combinedSource = CancellationTokenSource.CreateLinkedTokenSource(envelope.Cancellation, deliveryToken);
+ MessageContext messageContext = new(envelope.MessageId, combinedSource.Token)
+ {
+ Sender = sender,
+ Topic = topic,
+ IsRpc = false
+ };
+
+ AgentId agentId = subscription.MapToAgent(topic);
+ if (!this.DeliverToSelf && sender.HasValue && sender == agentId)
+ {
+ continue;
+ }
+
+ IHostableAgent agent = await this.EnsureAgentAsync(agentId);
- AgentId agentId = subscription.MapToAgent(topic);
- if (!this.DeliverToSelf && sender.HasValue && sender == agentId)
+ // TODO: Cancellation propagation!
+ await agent.OnMessageAsync(envelope.Message, messageContext);
+ }
+ catch (Exception ex)
{
- continue;
+ exceptions.Add(ex);
}
+ }
- IHostableAgent agent = await this.EnsureAgentAsync(agentId);
-
- // TODO: Cancellation propagation!
- await agent.OnMessageAsync(envelope.Message, messageContext);
+ if (exceptions.Count > 0)
+ {
+ // TODO: Unwrap TargetInvocationException?
+ throw new AggregateException("One or more exceptions occurred while processing the message.", exceptions);
}
}
@@ -78,7 +95,7 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
this.messageDeliveryQueue.Enqueue(delivery);
- return ValueTask.CompletedTask;
+ return delivery.FutureNoResult;
});
}
@@ -286,7 +303,7 @@ public sealed class InProcessRuntime : IAgentRuntime, IHostedService
}
}
- await Task.WhenAll(pendingTasks.Values.ToArray());
+ await Task.WhenAll(pendingTasks.Values.Where(t => t is not null).ToArray());
await this.FinishAsync(this.finishSource?.Token ?? CancellationToken.None);
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
index a0e76d9c6..0a086f5fa 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
@@ -13,6 +13,7 @@ internal sealed class MessageDelivery(MessageEnvelope message, Func<MessageEnvel
public IResultSink<object?> ResultSink { get; } = resultSink;
public ValueTask<object?> Future => this.ResultSink.Future;
+ public ValueTask FutureNoResult => this.ResultSink.FutureNoResult;
public ValueTask InvokeAsync(CancellationToken cancellation)
{
@@ -79,12 +80,12 @@ internal sealed class MessageEnvelope
await servicer(envelope, cancellation);
waitForPublish.SetResult(null);
}
- catch (Exception ex)
+ catch (Exception ex) // Do we want to special-case cancellation, and hoist the exception type like above?
{
waitForPublish.SetException(ex);
}
};
- return new MessageDelivery(this, servicer, waitForPublish);
+ return new MessageDelivery(this, boundServicer, waitForPublish);
}
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
index f5dbaf97d..1cad76f6d 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
@@ -5,13 +5,14 @@ using System.Threading.Tasks.Sources;
namespace Microsoft.AutoGen.Core;
-internal interface IResultSink<TResult> : IValueTaskSource<TResult>
+internal interface IResultSink<TResult> : IValueTaskSource<TResult>, IValueTaskSource
{
public void SetResult(TResult result);
public void SetException(Exception exception);
public void SetCancelled(OperationCanceledException? ocEx = null);
public ValueTask<TResult> Future { get; }
+ public ValueTask FutureNoResult { get; }
}
public sealed class ResultSink<TResult> : IResultSink<TResult>
@@ -50,5 +51,9 @@ public sealed class ResultSink<TResult> : IResultSink<TResult>
this.core.SetResult(result);
}
+ void IValueTaskSource.GetResult(short token) => _ = this.GetResult(token);
+
public ValueTask<TResult> Future => new(this, this.core.Version);
+ public ValueTask FutureNoResult => new(this, this.core.Version);
}
+
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/MessagingTestFixture.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/MessagingTestFixture.cs
new file mode 100644
index 000000000..cea551e41
--- /dev/null
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/MessagingTestFixture.cs
@@ -0,0 +1,63 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// MessagingTestFixture.cs
+
+using Microsoft.AutoGen.Contracts;
+
+namespace Microsoft.AutoGen.Core.Tests;
+
+public sealed class MessagingTestFixture
+{
+ private Dictionary<Type, object> AgentsTypeMap { get; } = new();
+ public InProcessRuntime Runtime { get; private set; } = new();
+
+ public ValueTask<AgentType> RegisterFactoryMapInstances<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factory)
+ where TAgent : IHostableAgent
+ {
+ Func<AgentId, IAgentRuntime, ValueTask<TAgent>> wrappedFactory = async (id, runtime) =>
+ {
+ TAgent agent = await factory(id, runtime);
+ this.GetAgentInstances<TAgent>()[id] = agent;
+ return agent;
+ };
+
+ return this.Runtime.RegisterAgentFactoryAsync(type, wrappedFactory);
+ }
+
+ public ValueTask RegisterDefaultSubscriptions<TAgentType>(AgentType type) where TAgentType : IHostableAgent
+ {
+ return this.Runtime.RegisterImplicitAgentSubscriptionsAsync<TAgentType>(type);
+ }
+
+ public Dictionary<AgentId, TAgent> GetAgentInstances<TAgent>() where TAgent : IHostableAgent
+ {
+ if (!AgentsTypeMap.TryGetValue(typeof(TAgent), out object? maybeAgentMap) ||
+ maybeAgentMap is not Dictionary<AgentId, TAgent> result)
+ {
+ this.AgentsTypeMap[typeof(TAgent)] = result = new Dictionary<AgentId, TAgent>();
+ }
+
+ return result;
+ }
+
+ public async ValueTask<object?> RunSendTestAsync(AgentId sendTarget, object message, string? messageId = null)
+ {
+ messageId ??= Guid.NewGuid().ToString();
+
+ await this.Runtime.StartAsync();
+
+ object? result = await this.Runtime.SendMessageAsync(message, sendTarget, messageId: messageId);
+
+ await this.Runtime.RunUntilIdleAsync();
+
+ return result;
+ }
+
+ public async ValueTask RunPublishTestAsync(TopicId sendTarget, object message, string? messageId = null)
+ {
+ messageId ??= Guid.NewGuid().ToString();
+
+ await this.Runtime.StartAsync();
+ await this.Runtime.PublishMessageAsync(message, sendTarget, messageId: messageId);
+ await this.Runtime.RunUntilIdleAsync();
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/PublishMessageTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/PublishMessageTests.cs
new file mode 100644
index 000000000..0240aa638
--- /dev/null
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/PublishMessageTests.cs
@@ -0,0 +1,184 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// PublishMessageTests.cs
+
+using System.Reflection;
+using FluentAssertions;
+using Microsoft.AutoGen.Contracts;
+using Microsoft.Extensions.Logging;
+using Xunit;
+
+namespace Microsoft.AutoGen.Core.Tests;
+
+public static class PublishTestsExtensions
+{
+ public static async ValueTask RegisterReceiverAgent(this MessagingTestFixture fixture,
+ string? agentNameSuffix = null,
+ params string[] topicTypes)
+ {
+ await fixture.RegisterFactoryMapInstances($"{nameof(ReceiverAgent)}{agentNameSuffix ?? string.Empty}",
+ (id, runtime) => ValueTask.FromResult(new ReceiverAgent(id, runtime, string.Empty)));
+
+ foreach (string topicType in topicTypes)
+ {
+ await fixture.Runtime.AddSubscriptionAsync(new TypeSubscription(topicType, $"{nameof(ReceiverAgent)}{agentNameSuffix ?? string.Empty}"));
+ }
+ }
+
+ public static async ValueTask RegisterErrorAgent(this MessagingTestFixture fixture,
+ string? agentNameSuffix = null,
+ params string[] topicTypes)
+ {
+ await fixture.RegisterFactoryMapInstances($"{nameof(ErrorAgent)}{agentNameSuffix ?? string.Empty}",
+ (id, runtime) => ValueTask.FromResult(new ErrorAgent(id, runtime, string.Empty)));
+
+ foreach (string topicType in topicTypes)
+ {
+ await fixture.Runtime.AddSubscriptionAsync(new TypeSubscription(topicType, $"{nameof(ErrorAgent)}{agentNameSuffix ?? string.Empty}"));
+ }
+ }
+}
+
+[Trait("Category", "UnitV2")]
+public class PublishMessageTests
+{
+ private sealed class PublisherAgent : BaseAgent, IHandle<BasicMessage>
+ {
+ private IList<TopicId> targetTopics;
+
+ public PublisherAgent(AgentId id, IAgentRuntime runtime, string description, IList<TopicId> targetTopics, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ this.targetTopics = targetTopics;
+ }
+
+ public async ValueTask HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ foreach (TopicId targetTopic in targetTopics)
+ {
+ BasicMessage message = new BasicMessage { Content = $"@{targetTopic}: {item.Content}" };
+ await this.Runtime.PublishMessageAsync(message, targetTopic);
+ }
+ }
+ }
+
+ [Fact]
+ public async Task Test_PublishMessage_Success()
+ {
+ MessagingTestFixture fixture = new MessagingTestFixture();
+
+ await fixture.RegisterReceiverAgent(topicTypes: "TestTopic");
+ await fixture.RegisterReceiverAgent("2", topicTypes: "TestTopic");
+
+ await fixture.RunPublishTestAsync(new TopicId("TestTopic"), new BasicMessage { Content = "1" });
+
+ fixture.GetAgentInstances<ReceiverAgent>().Values
+ .Should().HaveCount(2, "Two agents should have been created")
+ .And.AllSatisfy(receiverAgent => receiverAgent.Messages
+ .Should().NotBeNull()
+ .And.HaveCount(1)
+ .And.ContainSingle(m => m.Content == "1"));
+ }
+
+ [Fact]
+ public async Task Test_PublishMessage_SingleFailure()
+ {
+ MessagingTestFixture fixture = new MessagingTestFixture();
+
+ await fixture.RegisterErrorAgent(topicTypes: "TestTopic");
+
+ Func<Task> publishTask = async () => await fixture.RunPublishTestAsync(new TopicId("TestTopic"), new BasicMessage { Content = "1" });
+
+ // Test that we wrap single errors appropriately
+ (await publishTask.Should().ThrowAsync<AggregateException>())
+ .Which.Should().Match<AggregateException>(
+ ex => ex.InnerExceptions.Count == 1 &&
+ ex.InnerExceptions.All(
+ inEx => inEx is TargetInvocationException &&
+ ((TargetInvocationException)inEx).InnerException is TestException));
+
+ fixture.GetAgentInstances<ErrorAgent>().Values.Should().ContainSingle()
+ .Which.DidThrow.Should().BeTrue("Agent should have thrown an exception");
+ }
+
+ [Fact]
+ public async Task Test_PublishMessage_MultipleFailures()
+ {
+ MessagingTestFixture fixture = new MessagingTestFixture();
+
+ await fixture.RegisterErrorAgent(topicTypes: "TestTopic");
+ await fixture.RegisterErrorAgent("2", topicTypes: "TestTopic");
+
+ Func<Task> publishTask = async () => await fixture.RunPublishTestAsync(new TopicId("TestTopic"), new BasicMessage { Content = "1" });
+
+ // What we are really testing here is that a single exception does not prevent sending to the remaining agents
+ (await publishTask.Should().ThrowAsync<AggregateException>())
+ .Which.Should().Match<AggregateException>(
+ ex => ex.InnerExceptions.Count == 2 &&
+ ex.InnerExceptions.All(
+ inEx => inEx is TargetInvocationException &&
+ ((TargetInvocationException)inEx).InnerException is TestException));
+
+ fixture.GetAgentInstances<ErrorAgent>().Values
+ .Should().HaveCount(2)
+ .And.AllSatisfy(
+ agent => agent.DidThrow.Should().BeTrue("Agent should have thrown an exception"));
+ }
+
+ [Fact]
+ public async Task Test_PublishMessage_MixedSuccessFailure()
+ {
+ MessagingTestFixture fixture = new MessagingTestFixture();
+
+ await fixture.RegisterReceiverAgent(topicTypes: "TestTopic");
+ await fixture.RegisterReceiverAgent("2", topicTypes: "TestTopic");
+
+ await fixture.RegisterErrorAgent(topicTypes: "TestTopic");
+ await fixture.RegisterErrorAgent("2", topicTypes: "TestTopic");
+
+ Func<Task> publicTask = async () => await fixture.RunPublishTestAsync(new TopicId("TestTopic"), new BasicMessage { Content = "1" });
+
+ // What we are really testing here is that raising exceptions does not prevent sending to the remaining agents
+ (await publicTask.Should().ThrowAsync<AggregateException>())
+ .Which.Should().Match<AggregateException>(
+ ex => ex.InnerExceptions.Count == 2 &&
+ ex.InnerExceptions.All(
+ inEx => inEx is TargetInvocationException &&
+ ((TargetInvocationException)inEx).InnerException is TestException));
+
+ fixture.GetAgentInstances<ReceiverAgent>().Values
+ .Should().HaveCount(2, "Two ReceiverAgents should have been created")
+ .And.AllSatisfy(receiverAgent => receiverAgent.Messages
+ .Should().NotBeNull()
+ .And.HaveCount(1)
+ .And.ContainSingle(m => m.Content == "1"),
+ "ReceiverAgents should get published message regardless of ErrorAgents throwing exception.");
+
+ fixture.GetAgentInstances<ErrorAgent>().Values
+ .Should().HaveCount(2, "Two ErrorAgents should have been created")
+ .And.AllSatisfy(agent => agent.DidThrow.Should().BeTrue("ErrorAgent should have thrown an exception"));
+ }
+
+ [Fact]
+ public async Task Test_PublishMessage_RecurrentPublishSucceeds()
+ {
+ MessagingTestFixture fixture = new MessagingTestFixture();
+
+ await fixture.RegisterFactoryMapInstances(nameof(PublisherAgent),
+ (id, runtime) => ValueTask.FromResult(new PublisherAgent(id, runtime, string.Empty, new List<TopicId> { new TopicId("TestTopic") })));
+
+ await fixture.Runtime.AddSubscriptionAsync(new TypeSubscription("RunTest", nameof(PublisherAgent)));
+
+ await fixture.RegisterReceiverAgent(topicTypes: "TestTopic");
+ await fixture.RegisterReceiverAgent("2", topicTypes: "TestTopic");
+
+ await fixture.RunPublishTestAsync(new TopicId("RunTest"), new BasicMessage { Content = "1" });
+
+ TopicId testTopicId = new TopicId("TestTopic");
+ fixture.GetAgentInstances<ReceiverAgent>().Values
+ .Should().HaveCount(2, "Two ReceiverAgents should have been created")
+ .And.AllSatisfy(receiverAgent => receiverAgent.Messages
+ .Should().NotBeNull()
+ .And.HaveCount(1)
+ .And.ContainSingle(m => m.Content == $"@{testTopicId}: 1"));
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs
index cd048e680..d99ea423d 100644
--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/SendMessageTests.cs
@@ -11,13 +11,8 @@ using Xunit;
namespace Microsoft.AutoGen.Core.Tests;
[Trait("Category", "UnitV2")]
-public class SendMessageTests
+public partial class SendMessageTests
{
- private sealed class BasicMessage
- {
- public string Content { get; set; } = string.Empty;
- }
-
private sealed class SendOnAgent : BaseAgent, IHandle<BasicMessage>
{
private IList<Guid> targetKeys;
@@ -33,134 +28,24 @@ public class SendMessageTests
foreach (Guid targetKey in targetKeys)
{
AgentId targetId = new(nameof(ReceiverAgent), targetKey.ToString());
- BasicMessage message = new BasicMessage { Content = $"@{targetKey}: item.Content" };
+ BasicMessage message = new BasicMessage { Content = $"@{targetKey}: {item.Content}" };
await this.Runtime.SendMessageAsync(message, targetId);
}
}
}
- private sealed class ReceiverAgent : BaseAgent, IHandle<BasicMessage>
- {
- public List<BasicMessage> Messages { get; } = new();
-
- public ReceiverAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
- : base(id, runtime, description, logger)
- {
- }
-
- public ValueTask HandleAsync(BasicMessage item, MessageContext messageContext)
- {
- this.Messages.Add(item);
-
- return ValueTask.CompletedTask;
- }
- }
-
- private sealed class ProcessorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
- {
- private Func<string, string> ProcessFunc { get; }
-
- public ProcessorAgent(AgentId id, IAgentRuntime runtime, Func<string, string> processFunc, string description, ILogger<BaseAgent>? logger = null)
- : base(id, runtime, description, logger)
- {
- this.ProcessFunc = processFunc;
- }
-
- public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
- {
- BasicMessage result = new() { Content = this.ProcessFunc(item.Content) };
-
- return ValueTask.FromResult(result);
- }
- }
-
- private sealed class TestException : Exception
- { }
-
- private sealed class CancelAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
- {
- public CancelAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
- : base(id, runtime, description, logger)
- {
- }
-
- public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
- {
- CancellationToken cancelledToken = new CancellationToken(canceled: true);
- cancelledToken.ThrowIfCancellationRequested();
-
- return ValueTask.FromResult(item);
- }
- }
-
- private sealed class ErrorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
- {
- public ErrorAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
- : base(id, runtime, description, logger)
- {
- }
-
- public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
- {
- throw new TestException();
- }
- }
-
- private sealed class SendTestFixture
- {
- private Dictionary<Type, object> AgentsTypeMap { get; } = new();
- public InProcessRuntime Runtime { get; private set; } = new();
-
- public ValueTask<AgentType> RegisterFactoryMapInstances<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factory)
- where TAgent : IHostableAgent
- {
- Func<AgentId, IAgentRuntime, ValueTask<TAgent>> wrappedFactory = async (id, runtime) =>
- {
- TAgent agent = await factory(id, runtime);
- this.GetAgentInstances<TAgent>()[id] = agent;
- return agent;
- };
-
- return this.Runtime.RegisterAgentFactoryAsync(type, wrappedFactory);
- }
-
- public Dictionary<AgentId, TAgent> GetAgentInstances<TAgent>() where TAgent : IHostableAgent
- {
- if (!AgentsTypeMap.TryGetValue(typeof(TAgent), out object? maybeAgentMap) ||
- maybeAgentMap is not Dictionary<AgentId, TAgent> result)
- {
- this.AgentsTypeMap[typeof(TAgent)] = result = new Dictionary<AgentId, TAgent>();
- }
-
- return result;
- }
-
- public async ValueTask<object?> RunTestAsync(AgentId sendTarget, object message, string? messageId = null)
- {
- messageId ??= Guid.NewGuid().ToString();
-
- await this.Runtime.StartAsync();
-
- object? result = await this.Runtime.SendMessageAsync(message, sendTarget, messageId: messageId);
-
- await this.Runtime.RunUntilIdleAsync();
-
- return result;
- }
- }
-
[Fact]
public async Task Test_SendMessage_ReturnsValue()
{
Func<string, string> ProcessFunc = (s) => $"Processed({s})";
- SendTestFixture fixture = new SendTestFixture();
+ MessagingTestFixture fixture = new MessagingTestFixture();
await fixture.RegisterFactoryMapInstances(nameof(ProcessorAgent),
(id, runtime) => ValueTask.FromResult(new ProcessorAgent(id, runtime, ProcessFunc, string.Empty)));
AgentId targetAgent = new AgentId(nameof(ProcessorAgent), Guid.NewGuid().ToString());
- object? maybeResult = await fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" });
+ object? maybeResult = await fixture.RunSendTestAsync(targetAgent, new BasicMessage { Content = "1" });
maybeResult.Should().NotBeNull()
.And.BeOfType<BasicMessage>()
@@ -170,13 +55,13 @@ public class SendMessageTests
[Fact]
public async Task Test_SendMessage_Cancellation()
{
- SendTestFixture fixture = new SendTestFixture();
+ MessagingTestFixture fixture = new MessagingTestFixture();
await fixture.RegisterFactoryMapInstances(nameof(CancelAgent),
(id, runtime) => ValueTask.FromResult(new CancelAgent(id, runtime, string.Empty)));
AgentId targetAgent = new AgentId(nameof(CancelAgent), Guid.NewGuid().ToString());
- Func<Task> testAction = () => fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
+ Func<Task> testAction = () => fixture.RunSendTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
// TODO: Do we want to do the unwrap in this case?
await testAction.Should().ThrowAsync<OperationCanceledException>();
@@ -185,13 +70,13 @@ public class SendMessageTests
[Fact]
public async Task Test_SendMessage_Error()
{
- SendTestFixture fixture = new SendTestFixture();
+ MessagingTestFixture fixture = new MessagingTestFixture();
await fixture.RegisterFactoryMapInstances(nameof(ErrorAgent),
(id, runtime) => ValueTask.FromResult(new ErrorAgent(id, runtime, string.Empty)));
AgentId targetAgent = new AgentId(nameof(ErrorAgent), Guid.NewGuid().ToString());
- Func<Task> testAction = () => fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
+ Func<Task> testAction = () => fixture.RunSendTestAsync(targetAgent, new BasicMessage { Content = "1" }).AsTask();
(await testAction.Should().ThrowAsync<TargetInvocationException>())
.WithInnerException<TestException>();
@@ -202,7 +87,7 @@ public class SendMessageTests
{
Guid[] targetGuids = [Guid.NewGuid(), Guid.NewGuid()];
- SendTestFixture fixture = new SendTestFixture();
+ MessagingTestFixture fixture = new MessagingTestFixture();
Dictionary<AgentId, SendOnAgent> sendAgents = fixture.GetAgentInstances<SendOnAgent>();
Dictionary<AgentId, ReceiverAgent> receiverAgents = fixture.GetAgentInstances<ReceiverAgent>();
@@ -213,8 +98,9 @@ public class SendMessageTests
await fixture.RegisterFactoryMapInstances(nameof(ReceiverAgent),
(id, runtime) => ValueTask.FromResult(new ReceiverAgent(id, runtime, string.Empty)));
+ const string HelloContent = "Hello";
AgentId targetAgent = new AgentId(nameof(SendOnAgent), Guid.NewGuid().ToString());
- Task testTask = fixture.RunTestAsync(targetAgent, new BasicMessage { Content = "Hello" }).AsTask();
+ Task testTask = fixture.RunSendTestAsync(targetAgent, new BasicMessage { Content = HelloContent }).AsTask();
// We do not actually expect to wait the timeout here, but it is still better than waiting the 10 min
// timeout that the tests default to. A failure will fail regardless of what timeout value we set.
@@ -228,7 +114,7 @@ public class SendMessageTests
foreach (var targetKey in targetGuids)
{
var targetId = new AgentId(nameof(ReceiverAgent), targetKey.ToString());
- receiverAgents[targetId].Messages.Should().ContainSingle(m => m.Content == $"@{targetKey}: item.Content");
+ receiverAgents[targetId].Messages.Should().ContainSingle(m => m.Content == $"@{targetKey}: {HelloContent}");
}
}
}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgents.cs
similarity index 58%
rename from dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
rename to dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgents.cs
index fff15e312..ecbed4ac6 100644
--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgent.cs
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestAgents.cs
@@ -1,5 +1,5 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
-// TestAgent.cs
+// TestAgents.cs
using System.Text.Json;
using Microsoft.AutoGen.Contracts;
@@ -7,18 +7,6 @@ using Microsoft.Extensions.Logging;
namespace Microsoft.AutoGen.Core.Tests;
-public class TextMessage
-{
- public string Source { get; set; } = "";
- public string Content { get; set; } = "";
-}
-
-public class RpcTextMessage
-{
- public string Source { get; set; } = "";
- public string Content { get; set; } = "";
-}
-
/// <summary>
/// The test agent is a simple agent that is used for testing purposes.
/// </summary>
@@ -127,3 +115,84 @@ public class SubscribedSelfPublishAgent(AgentId id,
private TextMessage _text = new TextMessage { Source = "DefaultTopic", Content = "DefaultContent" };
public TextMessage Text => _text;
}
+
+public sealed class ReceiverAgent : BaseAgent, IHandle<BasicMessage>
+{
+ public List<BasicMessage> Messages { get; } = new();
+
+ public ReceiverAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public bool DidReceive => this.Messages.Count > 0;
+
+ public ValueTask HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ this.Messages.Add(item);
+
+ return ValueTask.CompletedTask;
+ }
+}
+
+public sealed class ProcessorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+{
+ private Func<string, string> ProcessFunc { get; }
+
+ public ProcessorAgent(AgentId id, IAgentRuntime runtime, Func<string, string> processFunc, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ this.ProcessFunc = processFunc;
+ }
+
+ public bool DidProcess => this.ProcessedMessage != null;
+ public BasicMessage? ProcessedMessage { get; private set; }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ this.ProcessedMessage = item;
+ BasicMessage result = new() { Content = this.ProcessFunc(item.Content) };
+
+ return ValueTask.FromResult(result);
+ }
+}
+
+public sealed class CancelAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+{
+ public CancelAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public bool DidCancel { get; private set; }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ this.DidCancel = true;
+
+ CancellationToken cancelledToken = new CancellationToken(canceled: true);
+ cancelledToken.ThrowIfCancellationRequested();
+
+ return ValueTask.FromResult(item);
+ }
+}
+
+public sealed class TestException : Exception
+{ }
+
+public sealed class ErrorAgent : BaseAgent, IHandle<BasicMessage, BasicMessage>
+{
+ public ErrorAgent(AgentId id, IAgentRuntime runtime, string description, ILogger<BaseAgent>? logger = null)
+ : base(id, runtime, description, logger)
+ {
+ }
+
+ public bool DidThrow { get; private set; }
+
+ public ValueTask<BasicMessage> HandleAsync(BasicMessage item, MessageContext messageContext)
+ {
+ this.DidThrow = true;
+
+ throw new TestException();
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/TestMessages.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestMessages.cs
new file mode 100644
index 000000000..da76e50f6
--- /dev/null
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/TestMessages.cs
@@ -0,0 +1,22 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// TestMessages.cs
+
+namespace Microsoft.AutoGen.Core.Tests;
+
+public class TextMessage
+{
+ public string Source { get; set; } = "";
+ public string Content { get; set; } = "";
+}
+
+public class RpcTextMessage
+{
+ public string Source { get; set; } = "";
+ public string Content { get; set; } = "";
+}
+
+public sealed class BasicMessage
+{
+ public string Content { get; set; } = string.Empty;
+}
+