Skip to content

A programming framework for agentic AI

feat: Enable queueing and step mode in InProcessRuntime (#5239)

Jacob Alber43e9c266c123
diff --git a/dotnet/samples/getting-started/Program.cs b/dotnet/samples/getting-started/Program.cs
index 1cff3c1ca..e5410d417 100644
--- a/dotnet/samples/getting-started/Program.cs
+++ b/dotnet/samples/getting-started/Program.cs
@@ -21,6 +21,7 @@ appBuilder.Services.TryAddSingleton(runUntilFunc);
appBuilder.AddAgent<Checker>("Checker");
appBuilder.AddAgent<Modifier>("Modifier");
var app = await appBuilder.BuildAsync();
+await app.StartAsync();
// Send the initial count to the agents app, running on the `local` runtime, and pass through the registered services via the application `builder`
await app.PublishMessageAsync(new CountMessage
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cs b/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cs
index 7efff53f6..44ad9b0e1 100644
--- a/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cs
+++ b/dotnet/src/Microsoft.AutoGen/Contracts/AgentProxy.cs
@@ -45,7 +45,7 @@ public class AgentProxy(AgentId agentId, IAgentRuntime runtime)
/// A token used to cancel an in-progress operation. Defaults to <c>null</c>.
/// </param>
/// <returns>A task representing the asynchronous operation, returning the response from the agent.</returns>
- public ValueTask<object?> SendMessageAsync(object message, AgentId sender, string? messageId = null, CancellationToken? cancellationToken = default)
+ public ValueTask<object?> SendMessageAsync(object message, AgentId sender, string? messageId = null, CancellationToken cancellationToken = default)
{
return this.runtime.SendMessageAsync(message, this.Id, sender, messageId, cancellationToken);
}
diff --git a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs
index a344f90ef..0d84fbe72 100644
--- a/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Contracts/IAgentRuntime.cs
@@ -22,7 +22,7 @@ public interface IAgentRuntime : ISaveState<IAgentRuntime>
/// <returns>A task representing the asynchronous operation, returning the response from the agent.</returns>
/// <exception cref="CantHandleException">Thrown if the recipient cannot handle the message.</exception>
/// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>
- public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);
+ public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken cancellationToken = default);
/// <summary>
/// Publishes a message to all agents subscribed to the given topic.
@@ -35,7 +35,7 @@ public interface IAgentRuntime : ISaveState<IAgentRuntime>
/// <param name="cancellationToken">A token to cancel the operation if needed.</param>
/// <returns>A task representing the asynchronous operation.</returns>
/// <exception cref="UndeliverableException">Thrown if the message cannot be delivered.</exception>
- public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = default);
+ public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken cancellationToken = default);
// TODO: Can we call this Resolve?
/// <summary>
diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cs
index 536cfeaaa..985294105 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentsApp.cs
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// AgentsApp.cs
+using System.Diagnostics;
using System.Reflection;
using Microsoft.AutoGen.Contracts;
using Microsoft.Extensions.DependencyInjection;
@@ -18,7 +19,7 @@ public class AgentsAppBuilder
{
this.builder = baseBuilder ?? new HostApplicationBuilder();
- this.builder.Services.AddSingleton<IAgentRuntime, InProcessRuntime>();
+ this.AddInProcessRuntime();
}
public IServiceCollection Services => this.builder.Services;
@@ -28,7 +29,18 @@ public class AgentsAppBuilder
this.AddAgentsFromAssemblies(AppDomain.CurrentDomain.GetAssemblies());
}
- public void AddAgentsFromAssemblies(params Assembly[] assemblies)
+ public AgentsAppBuilder AddInProcessRuntime()
+ {
+ this.Services.AddSingleton<IAgentRuntime, InProcessRuntime>();
+ this.Services.AddHostedService<InProcessRuntime>(services =>
+ {
+ return (services.GetRequiredService<IAgentRuntime>() as InProcessRuntime)!;
+ });
+
+ return this;
+ }
+
+ public AgentsAppBuilder AddAgentsFromAssemblies(params Assembly[] assemblies)
{
IEnumerable<Type> agentTypes = assemblies.SelectMany(assembly => assembly.GetTypes())
.Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(BaseAgent))
@@ -41,9 +53,11 @@ public class AgentsAppBuilder
// TODO: Expose skipClassSubscriptions and skipDirectMessageSubscription as parameters?
this.AddAgent(agentType.Name, agentType);
}
+
+ return this;
}
- private void AddAgent(AgentType agentType, Type runtimeType, bool skipClassSubscriptions = false, bool skipDirectMessageSubscription = false)
+ private AgentsAppBuilder AddAgent(AgentType agentType, Type runtimeType, bool skipClassSubscriptions = false, bool skipDirectMessageSubscription = false)
{
this.AgentTypeRegistrations.Add(async app =>
{
@@ -51,9 +65,11 @@ public class AgentsAppBuilder
await app.AgentRuntime.RegisterImplicitAgentSubscriptionsAsync(agentType, runtimeType, skipClassSubscriptions, skipDirectMessageSubscription);
return agentType;
});
+
+ return this;
}
- public void AddAgent<TAgent>(AgentType agentType, bool skipClassSubscriptions = false, bool skipDirectMessageSubscription = false) where TAgent : IHostableAgent
+ public AgentsAppBuilder AddAgent<TAgent>(AgentType agentType, bool skipClassSubscriptions = false, bool skipDirectMessageSubscription = false) where TAgent : IHostableAgent
=> this.AddAgent(agentType, typeof(TAgent), skipClassSubscriptions, skipDirectMessageSubscription);
public async ValueTask<AgentsApp> BuildAsync()
@@ -81,16 +97,42 @@ public class AgentsApp
public IServiceProvider Services => this.Host.Services;
+ public IHostApplicationLifetime ApplicationLifetime => this.Services.GetRequiredService<IHostApplicationLifetime>();
+
public IAgentRuntime AgentRuntime => this.Services.GetRequiredService<IAgentRuntime>();
- public async ValueTask StartAsync() => await this.Host.StartAsync();
+ private int runningCount;
+ public async ValueTask StartAsync()
+ {
+ if (Interlocked.Exchange(ref this.runningCount, 1) != 0)
+ {
+ throw new InvalidOperationException("Application is already running.");
+ }
- public async ValueTask ShutdownAsync() => await this.Host.StopAsync();
+ Debug.Assert(this.AgentRuntime != null);
- public ValueTask PublishMessageAsync<TMessage>(TMessage message, TopicId topic, string? messageId = null, CancellationToken? cancellationToken = default)
+ await this.Host.StartAsync();
+ }
+
+ public async ValueTask ShutdownAsync()
+ {
+ if (Interlocked.Exchange(ref this.runningCount, 0) != 1)
+ {
+ throw new InvalidOperationException("Application is already stopped.");
+ }
+
+ await this.Host.StopAsync();
+ }
+
+ public async ValueTask PublishMessageAsync<TMessage>(TMessage message, TopicId topic, string? messageId = null, CancellationToken cancellationToken = default)
where TMessage : notnull
{
- return this.AgentRuntime.PublishMessageAsync(message, topic, messageId: messageId, cancellationToken: cancellationToken);
+ if (Volatile.Read(ref this.runningCount) == 0)
+ {
+ await this.StartAsync();
+ }
+
+ await this.AgentRuntime.PublishMessageAsync(message, topic, messageId: messageId, cancellationToken: cancellationToken);
}
public Task WaitForShutdownAsync()
diff --git a/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
index 201738c16..f63199cd8 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/BaseAgent.cs
@@ -100,13 +100,13 @@ public abstract class BaseAgent : IAgent, IHostableAgent
return ValueTask.CompletedTask;
}
- public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, string? messageId = null, CancellationToken? cancellationToken = default)
+ public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, string? messageId = null, CancellationToken cancellationToken = default)
{
return this.Runtime.SendMessageAsync(message, recepient, sender: this.Id, messageId: messageId, cancellationToken: cancellationToken);
}
- public ValueTask PublishMessageAsync(object message, TopicId topic, string? messageId = null, CancellationToken? cancellationToken = default)
+ public ValueTask PublishMessageAsync(object message, TopicId topic, string? messageId = null, CancellationToken cancellationToken = default)
{
return this.Runtime.PublishMessageAsync(message, topic, sender: this.Id, messageId: messageId, cancellationToken: cancellationToken);
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
index 4cce4d47f..a259478fd 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/InProcessRuntime.cs
@@ -1,12 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// InProcessRuntime.cs
+using System.Collections.Concurrent;
+using System.Diagnostics;
using Microsoft.AutoGen.Contracts;
+using Microsoft.Extensions.Hosting;
namespace Microsoft.AutoGen.Core;
-public sealed class InProcessRuntime : IAgentRuntime
+public sealed class InProcessRuntime : IAgentRuntime, IHostedService
{
+ public bool DeliverToSelf { get; set; } //= false;
+
Dictionary<AgentId, IHostableAgent> agentInstances = new();
Dictionary<string, ISubscriptionDefinition> subscriptions = new();
Dictionary<AgentType, Func<AgentId, IAgentRuntime, ValueTask<IHostableAgent>>> agentFactories = new();
@@ -27,49 +32,85 @@ public sealed class InProcessRuntime : IAgentRuntime
{
}
- public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = null)
+ private ConcurrentQueue<MessageDelivery> messageDeliveryQueue = new();
+
+ private async ValueTask PublishMessageServicer(MessageEnvelope envelope, CancellationToken deliveryToken)
{
- return this.ExecuteTracedAsync(async () =>
+ if (!envelope.Topic.HasValue)
+ {
+ throw new InvalidOperationException("Message must have a topic to be published.");
+ }
+
+ TopicId topic = envelope.Topic.Value;
+ foreach (var subscription in this.subscriptions.Values.Where(subscription => subscription.Matches(topic)))
{
- messageId ??= Guid.NewGuid().ToString();
+ AgentId? sender = envelope.Sender;
- foreach (var subscription in this.subscriptions.Values.Where(subscription => subscription.Matches(topic)))
+ CancellationTokenSource combinedSource = CancellationTokenSource.CreateLinkedTokenSource(envelope.Cancellation, deliveryToken);
+ MessageContext messageContext = new(envelope.MessageId, combinedSource.Token)
{
- AgentId agentId = subscription.MapToAgent(topic);
- if (sender.HasValue && sender == agentId)
- {
- // TODO: enable re-entrant mode
- continue;
- }
-
- MessageContext messageContext = new(messageId ?? Guid.NewGuid().ToString(), cancellationToken ?? CancellationToken.None)
- {
- Sender = sender,
- Topic = topic,
- IsRpc = false
- };
+ Sender = sender,
+ Topic = topic,
+ IsRpc = false
+ };
- IHostableAgent agent = await this.EnsureAgentAsync(agentId);
- await agent.OnMessageAsync(message, messageContext);
+ AgentId agentId = subscription.MapToAgent(topic);
+ if (this.DeliverToSelf || sender.HasValue && sender == agentId)
+ {
+ continue;
}
+
+ IHostableAgent agent = await this.EnsureAgentAsync(agentId);
+
+ // TODO: Cancellation propagation!
+ await agent.OnMessageAsync(envelope.Message, messageContext);
+ }
+ }
+
+ public ValueTask PublishMessageAsync(object message, TopicId topic, AgentId? sender = null, string? messageId = null, CancellationToken cancellation = default)
+ {
+ return this.ExecuteTracedAsync(() =>
+ {
+ MessageDelivery delivery = new MessageEnvelope(message, messageId, cancellation)
+ .WithSender(sender)
+ .ForPublish(topic, this.PublishMessageServicer);
+
+ this.messageDeliveryQueue.Enqueue(delivery);
+
+ return ValueTask.CompletedTask;
});
}
- public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken? cancellationToken = null)
+ private async ValueTask<object?> SendMessageServicer(MessageEnvelope envelope, CancellationToken deliveryToken)
{
- return this.ExecuteTracedAsync(async () =>
+ if (!envelope.Receiver.HasValue)
{
- cancellationToken ??= CancellationToken.None;
- messageId ??= Guid.NewGuid().ToString();
+ throw new InvalidOperationException("Message must have a receiver to be sent.");
+ }
- MessageContext messageContext = new(messageId ?? Guid.NewGuid().ToString(), cancellationToken ?? CancellationToken.None)
- {
- Sender = sender,
- IsRpc = false
- };
+ CancellationTokenSource combinedSource = CancellationTokenSource.CreateLinkedTokenSource(envelope.Cancellation, deliveryToken);
+ MessageContext messageContext = new(envelope.MessageId, combinedSource.Token)
+ {
+ Sender = envelope.Sender,
+ IsRpc = false
+ };
- IHostableAgent agent = await this.EnsureAgentAsync(recepient);
- return await agent.OnMessageAsync(message, messageContext);
+ AgentId receiver = envelope.Receiver.Value;
+ IHostableAgent agent = await this.EnsureAgentAsync(receiver);
+
+ return await agent.OnMessageAsync(envelope.Message, messageContext);
+ }
+
+ public ValueTask<object?> SendMessageAsync(object message, AgentId recepient, AgentId? sender = null, string? messageId = null, CancellationToken cancellationToken = default)
+ {
+ return this.ExecuteTracedAsync(() =>
+ {
+ MessageDelivery delivery = new MessageEnvelope(message, messageId, cancellationToken)
+ .WithSender(sender)
+ .ForSend(recepient, this.SendMessageServicer);
+
+ this.messageDeliveryQueue.Enqueue(delivery);
+ return delivery.Future;
});
}
@@ -176,6 +217,8 @@ public sealed class InProcessRuntime : IAgentRuntime
}
public ValueTask<AgentType> RegisterAgentFactoryAsync<TAgent>(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<TAgent>> factoryFunc) where TAgent : IHostableAgent
+ // Declare the lambda return type explicitly, as otherwise the compiler will infer 'ValueTask<TAgent>'
+ // and recurse into the same call, causing a stack overflow.
=> this.RegisterAgentFactoryAsync(type, async ValueTask<IHostableAgent> (agentId, runtime) => await factoryFunc(agentId, runtime));
public ValueTask<AgentType> RegisterAgentFactoryAsync(AgentType type, Func<AgentId, IAgentRuntime, ValueTask<IHostableAgent>> factoryFunc)
@@ -194,4 +237,87 @@ public sealed class InProcessRuntime : IAgentRuntime
{
return ValueTask.FromResult(new AgentProxy(agentId, this));
}
+
+ public ValueTask ProcessNextMessage(CancellationToken cancellation = default)
+ {
+ Debug.WriteLine("Processing next message...");
+ if (this.messageDeliveryQueue.TryDequeue(out MessageDelivery? delivery))
+ {
+ Debug.WriteLine($"Processing message {delivery.Message.MessageId}...");
+ return delivery.InvokeAsync(cancellation);
+ }
+
+ return ValueTask.CompletedTask;
+ }
+
+ private Func<bool> shouldContinue = () => true;
+ private CancellationTokenSource? finishSource;
+ private async Task RunAsync(CancellationToken cancellation)
+ {
+ while (!cancellation.IsCancellationRequested && shouldContinue())
+ {
+ await this.ProcessNextMessage(cancellation);
+ }
+
+ await this.FinishAsync(this.finishSource?.Token ?? CancellationToken.None);
+ }
+
+ private CancellationTokenSource? shutdownSource;
+ private Task messageDeliveryTask = Task.CompletedTask;
+ public ValueTask StartAsync(CancellationToken token = default)
+ {
+ if (this.shutdownSource != null)
+ {
+ throw new InvalidOperationException("Runtime is already running.");
+ }
+
+ this.shutdownSource = new CancellationTokenSource();
+ this.messageDeliveryTask = Task.Run(() => this.RunAsync(this.shutdownSource.Token));
+
+ return ValueTask.CompletedTask;
+ }
+
+ public ValueTask StopAsync(CancellationToken token = default)
+ {
+ if (this.shutdownSource == null)
+ {
+ throw new InvalidOperationException("Runtime is not running.");
+ }
+
+ if (this.finishSource != null)
+ {
+ // TODO: Log as warning instead?
+ throw new InvalidOperationException("Runtime is already stopping.");
+ }
+
+ this.finishSource = CancellationTokenSource.CreateLinkedTokenSource(token);
+
+ this.shutdownSource.Cancel();
+ this.shutdownSource = null;
+
+ return ValueTask.CompletedTask;
+ }
+
+ public Task RunUntilIdleAsync()
+ {
+ this.shouldContinue = () => !this.messageDeliveryQueue.IsEmpty;
+
+ // TODO: Do we want detach semantics?
+ return this.messageDeliveryTask;
+ }
+
+ private async Task FinishAsync(CancellationToken token)
+ {
+ foreach (IHostableAgent agent in this.agentInstances.Values)
+ {
+ if (!token.IsCancellationRequested)
+ {
+ await agent.CloseAsync();
+ }
+ }
+ }
+
+ Task IHostedService.StartAsync(CancellationToken cancellationToken) => this.StartAsync(cancellationToken).AsTask();
+
+ Task IHostedService.StopAsync(CancellationToken cancellationToken) => this.StopAsync(cancellationToken).AsTask();
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
new file mode 100644
index 000000000..ab97dac84
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/Core/MessageDelivery.cs
@@ -0,0 +1,64 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// MessageDelivery.cs
+
+using Microsoft.AutoGen.Contracts;
+
+namespace Microsoft.AutoGen.Core;
+
+internal sealed class MessageDelivery(MessageEnvelope message, Func<MessageEnvelope, CancellationToken, ValueTask> servicer, IResultSink<object?>? resultSink = null)
+{
+ public MessageEnvelope Message { get; } = message;
+ public Func<MessageEnvelope, CancellationToken, ValueTask> Servicer { get; } = servicer;
+ public IResultSink<object?>? ResultSink { get; } = resultSink;
+
+ public ValueTask<object?> Future => this.ResultSink != null ? this.ResultSink.Future : ValueTask.FromResult((object?)null);
+
+ public ValueTask InvokeAsync(CancellationToken cancellation)
+ {
+ return this.Servicer(this.Message, cancellation);
+ }
+}
+
+internal sealed class MessageEnvelope
+{
+ public object Message { get; }
+ public string MessageId { get; }
+ public TopicId? Topic { get; private set; }
+ public AgentId? Sender { get; private set; }
+ public AgentId? Receiver { get; private set; }
+ public CancellationToken Cancellation { get; }
+
+ public MessageEnvelope(object message, string? messageId = null, CancellationToken cancellation = default)
+ {
+ this.Message = message;
+ this.MessageId = messageId ?? Guid.NewGuid().ToString();
+ this.Cancellation = cancellation;
+ }
+
+ public MessageEnvelope WithSender(AgentId? sender)
+ {
+ this.Sender = sender;
+ return this;
+ }
+
+ public MessageDelivery ForSend(AgentId receiver, Func<MessageEnvelope, CancellationToken, ValueTask<object?>> servicer)
+ {
+ this.Receiver = receiver;
+
+ ResultSink<object?> resultSink = new ResultSink<object?>();
+ Func<MessageEnvelope, CancellationToken, ValueTask> boundServicer = async (envelope, cancellation) =>
+ {
+ object? result = await servicer(envelope, cancellation);
+ resultSink.SetResult(result);
+ };
+
+ return new MessageDelivery(this, boundServicer, resultSink);
+ }
+
+ public MessageDelivery ForPublish(TopicId topic, Func<MessageEnvelope, CancellationToken, ValueTask> servicer)
+ {
+ this.Topic = topic;
+
+ return new MessageDelivery(this, servicer);
+ }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
new file mode 100644
index 000000000..512a81b1f
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/Core/ResultSink.cs
@@ -0,0 +1,54 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// ResultSink.cs
+
+using System.Threading.Tasks.Sources;
+
+namespace Microsoft.AutoGen.Core;
+
+internal interface IResultSink<TResult> : IValueTaskSource<TResult>
+{
+ void SetResult(TResult result);
+ void SetException(Exception exception);
+ void SetCancelled();
+
+ ValueTask<TResult> Future { get; }
+}
+
+internal sealed class ResultSink<TResult> : IResultSink<TResult>
+{
+ private ManualResetValueTaskSourceCore<TResult> core;
+
+ public TResult GetResult(short token)
+ {
+ return this.core.GetResult(token);
+ }
+
+ public ValueTaskSourceStatus GetStatus(short token)
+ {
+ return this.core.GetStatus(token);
+ }
+
+ public void OnCompleted(Action<object?> continuation, object? state, short token, ValueTaskSourceOnCompletedFlags flags)
+ {
+ this.core.OnCompleted(continuation, state, token, flags);
+ }
+
+ public bool IsCancelled { get; private set; }
+ public void SetCancelled()
+ {
+ this.IsCancelled = true;
+ this.core.SetException(new OperationCanceledException());
+ }
+
+ public void SetException(Exception exception)
+ {
+ this.core.SetException(exception);
+ }
+
+ public void SetResult(TResult result)
+ {
+ this.core.SetResult(result);
+ }
+
+ public ValueTask<TResult> Future => new(this, this.core.Version);
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
index 110fe4c84..d60d69ee7 100644
--- a/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Core.Tests/AgentTests.cs
@@ -14,6 +14,7 @@ public class AgentTests()
public async Task Agent_ShouldNotReceiveMessages_WhenNotSubscribed()
{
var runtime = new InProcessRuntime();
+ await runtime.StartAsync();
Logger<BaseAgent> logger = new(new LoggerFactory());
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));
@@ -23,8 +24,7 @@ public class AgentTests()
await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);
- //await Task.Yield();
- await Task.Delay(100);
+ await runtime.RunUntilIdleAsync();
TestAgent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");
}
@@ -33,6 +33,7 @@ public class AgentTests()
public async Task Agent_ShoulReceiveMessages_WhenSubscribed()
{
var runtime = new InProcessRuntime();
+ await runtime.StartAsync();
Logger<BaseAgent> logger = new(new LoggerFactory());
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new SubscribedAgent(id, runtime, logger)));
@@ -42,8 +43,7 @@ public class AgentTests()
await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId("TestTopic")).ConfigureAwait(true);
- //await Task.Yield();
- await Task.Delay(100);
+ await runtime.RunUntilIdleAsync();
TestAgent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");
}
@@ -53,11 +53,14 @@ public class AgentTests()
{
// Arrange
var runtime = new InProcessRuntime();
+ await runtime.StartAsync();
+
Logger<BaseAgent> logger = new(new LoggerFactory());
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));
await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");
var agentId = new AgentId("MyAgent", "TestAgent");
+
var response = await runtime.SendMessageAsync(new RpcTextMessage { Source = "TestTopic", Content = "Request" }, agentId);
// Assert
@@ -123,6 +126,7 @@ public class AgentTests()
public async Task SubscribeAsync_UnsubscribeAsync_and_GetSubscriptionsTest()
{
var runtime = new InProcessRuntime();
+ await runtime.StartAsync();
ReceiverAgent? agent = null;
await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
{
@@ -146,12 +150,14 @@ public class AgentTests()
await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
await Task.Delay(100);
+
Assert.True(agent.ReceivedItems.Count == 1);
Assert.Equal("info", agent.ReceivedItems[0]);
await runtime.RemoveSubscriptionAsync(subscription.Id);
await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
await Task.Delay(100);
+
Assert.True(agent.ReceivedItems.Count == 1);
}