Skip to content

A programming framework for agentic AI

Rysweet 4676 remove iagentruntime - collapse into iagentworker (#4740)

Ryan Sweetc1646f21c062
diff --git a/README.md b/README.md
index 1c34dc292..96362f2af 100644
--- a/README.md
+++ b/README.md
@@ -186,9 +186,9 @@ await app.WaitForShutdownAsync();
[TopicSubscription("agents")]
public class HelloAgent(
- IAgentContext context,
+ IAgentContext worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry) : ConsoleAgent(
- context,
+ worker,
typeRegistry),
ISayHello,
IHandle<NewMessageReceived>,
diff --git a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs
index 7261ee45d..0e195ca5b 100644
--- a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs
+++ b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs
@@ -8,11 +8,11 @@ using Microsoft.Extensions.AI;
namespace Hello;
[TopicSubscription("agents")]
public class HelloAIAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
IHostApplicationLifetime hostApplicationLifetime,
IChatClient client) : HelloAgent(
- context,
+ worker,
typeRegistry,
hostApplicationLifetime),
IHandle<NewMessageReceived>
diff --git a/dotnet/samples/Hello/HelloAIAgents/Program.cs b/dotnet/samples/Hello/HelloAIAgents/Program.cs
index a15effa5a..f9780d62a 100644
--- a/dotnet/samples/Hello/HelloAIAgents/Program.cs
+++ b/dotnet/samples/Hello/HelloAIAgents/Program.cs
@@ -33,10 +33,10 @@ namespace Hello
{
[TopicSubscription("agents")]
public class HelloAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
IHostApplicationLifetime hostApplicationLifetime) : ConsoleAgent(
- context,
+ worker,
typeRegistry),
ISayHello,
IHandle<NewMessageReceived>,
diff --git a/dotnet/samples/Hello/HelloAgent/Program.cs b/dotnet/samples/Hello/HelloAgent/Program.cs
index 7da454774..dee73b1a4 100644
--- a/dotnet/samples/Hello/HelloAgent/Program.cs
+++ b/dotnet/samples/Hello/HelloAgent/Program.cs
@@ -18,9 +18,9 @@ namespace Hello
{
[TopicSubscription("agents")]
public class HelloAgent(
- IAgentRuntime context, IHostApplicationLifetime hostApplicationLifetime,
+ IAgentWorker worker, IHostApplicationLifetime hostApplicationLifetime,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry) : Agent(
- context,
+ worker,
typeRegistry),
ISayHello,
IHandleConsole,
@@ -35,7 +35,7 @@ namespace Hello
await PublishMessageAsync(evt).ConfigureAwait(false);
var goodbye = new ConversationClosed
{
- UserId = this.AgentId.Key,
+ UserId = this.AgentId.Type,
UserMessage = "Goodbye"
};
await PublishMessageAsync(goodbye).ConfigureAwait(false);
diff --git a/dotnet/samples/Hello/HelloAgent/README.md b/dotnet/samples/Hello/HelloAgent/README.md
index 23051b45c..53e3d6a65 100644
--- a/dotnet/samples/Hello/HelloAgent/README.md
+++ b/dotnet/samples/Hello/HelloAgent/README.md
@@ -43,9 +43,9 @@ Within that event handler you may optionally *emit* new events, which are then s
```csharp
TopicSubscription("HelloAgents")]
public class HelloAgent(
- IAgentContext context,
+ iAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry) : ConsoleAgent(
- context,
+ worker,
typeRegistry),
ISayHello,
IHandle<NewMessageReceived>,
diff --git a/dotnet/samples/Hello/HelloAgentState/Program.cs b/dotnet/samples/Hello/HelloAgentState/Program.cs
index f22ad8089..dbb16c3bb 100644
--- a/dotnet/samples/Hello/HelloAgentState/Program.cs
+++ b/dotnet/samples/Hello/HelloAgentState/Program.cs
@@ -18,10 +18,10 @@ namespace Hello
{
[TopicSubscription("agents")]
public class HelloAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
IHostApplicationLifetime hostApplicationLifetime,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry) : Agent(
- context,
+ worker,
typeRegistry),
IHandleConsole,
IHandle<NewMessageReceived>,
diff --git a/dotnet/samples/Hello/HelloAgentState/README.md b/dotnet/samples/Hello/HelloAgentState/README.md
index 2671d8e0d..f46c66df1 100644
--- a/dotnet/samples/Hello/HelloAgentState/README.md
+++ b/dotnet/samples/Hello/HelloAgentState/README.md
@@ -43,9 +43,9 @@ Within that event handler you may optionally *emit* new events, which are then s
```csharp
TopicSubscription("HelloAgents")]
public class HelloAgent(
- IAgentContext context,
+ iAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry) : ConsoleAgent(
- context,
+ worker,
typeRegistry),
ISayHello,
IHandle<NewMessageReceived>,
diff --git a/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs b/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs
index afddc34f0..ffc474a93 100644
--- a/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs
+++ b/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs
@@ -11,8 +11,8 @@ using Microsoft.SemanticKernel.Memory;
namespace DevTeam.Agents;
[TopicSubscription("devteam")]
-public class Dev(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<Dev> logger)
- : SKAiAgent<DeveloperState>(context, memory, kernel, typeRegistry), IDevelopApps,
+public class Dev(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<Dev> logger)
+ : SKAiAgent<DeveloperState>(worker, memory, kernel, typeRegistry), IDevelopApps,
IHandle<CodeGenerationRequested>,
IHandle<CodeChainClosed>
{
diff --git a/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs b/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs
index bda70ebe8..ffeefe7d4 100644
--- a/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs
+++ b/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs
@@ -12,8 +12,8 @@ using Microsoft.SemanticKernel.Memory;
namespace DevTeam.Agents;
[TopicSubscription("devteam")]
-public class DeveloperLead(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<DeveloperLead> logger)
- : SKAiAgent<DeveloperLeadState>(context, memory, kernel, typeRegistry), ILeadDevelopers,
+public class DeveloperLead(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<DeveloperLead> logger)
+ : SKAiAgent<DeveloperLeadState>(worker, memory, kernel, typeRegistry), ILeadDevelopers,
IHandle<DevPlanRequested>,
IHandle<DevPlanChainClosed>
{
diff --git a/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs b/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs
index 5a89536d0..5306a9183 100644
--- a/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs
+++ b/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs
@@ -11,8 +11,8 @@ using Microsoft.SemanticKernel.Memory;
namespace DevTeam.Agents;
[TopicSubscription("devteam")]
-public class ProductManager(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<ProductManager> logger)
- : SKAiAgent<ProductManagerState>(context, memory, kernel, typeRegistry), IManageProducts,
+public class ProductManager(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger<ProductManager> logger)
+ : SKAiAgent<ProductManagerState>(worker, memory, kernel, typeRegistry), IManageProducts,
IHandle<ReadmeChainClosed>,
IHandle<ReadmeRequested>
{
diff --git a/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs b/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs
index c23a62377..85d498bcc 100644
--- a/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs
+++ b/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs
@@ -9,8 +9,8 @@ using Microsoft.SemanticKernel;
using Microsoft.SemanticKernel.Memory;
namespace Microsoft.AI.DevTeam;
-public class AzureGenie(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageAzure azureService)
- : SKAiAgent<object>(context, memory, kernel, typeRegistry),
+public class AzureGenie(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageAzure azureService)
+ : SKAiAgent<object>(worker, memory, kernel, typeRegistry),
IHandle<ReadmeCreated>,
IHandle<CodeCreated>
diff --git a/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs b/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs
index 3dc9b2a1a..3ba0eeb69 100644
--- a/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs
+++ b/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs
@@ -12,8 +12,8 @@ using Microsoft.SemanticKernel.Memory;
namespace Microsoft.AI.DevTeam;
-public class Hubber(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageGithub ghService)
- : SKAiAgent<object>(context, memory, kernel, typeRegistry),
+public class Hubber(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageGithub ghService)
+ : SKAiAgent<object>(worker, memory, kernel, typeRegistry),
IHandle<NewAsk>,
IHandle<ReadmeGenerated>,
IHandle<DevPlanGenerated>,
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs
index f4f06db40..bfcd7c6cc 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs
@@ -5,10 +5,10 @@ using Microsoft.AutoGen.Core;
using Microsoft.Extensions.AI;
namespace Microsoft.AutoGen.Agents;
public abstract class InferenceAgent<T>(
- IAgentRuntime context,
+ IAgentWorker worker,
EventTypes typeRegistry,
IChatClient client)
- : Agent(context, typeRegistry)
+ : Agent(worker, typeRegistry)
where T : IMessage, new()
{
protected IChatClient ChatClient { get; } = client;
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs
index 0aec9a493..1d0c57068 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs
@@ -8,18 +8,17 @@ using Microsoft.SemanticKernel.Connectors.OpenAI;
using Microsoft.SemanticKernel.Memory;
namespace Microsoft.AutoGen.Agents;
-public abstract class SKAiAgent<T> : Agent where T : class, new()
+public abstract class SKAiAgent<T>(
+ IAgentWorker worker,
+ ISemanticTextMemory memory,
+ Kernel kernel,
+ EventTypes typeRegistry) : Agent(
+ worker,
+ typeRegistry) where T : class, new()
{
- protected AgentState<T> _state;
- protected Kernel _kernel;
- private readonly ISemanticTextMemory _memory;
-
- public SKAiAgent(IAgentRuntime context, ISemanticTextMemory memory, Kernel kernel, EventTypes typeRegistry) : base(context, typeRegistry)
- {
- _state = new();
- _memory = memory;
- _kernel = kernel;
- }
+ protected AgentState<T> _state = new();
+ protected Kernel _kernel = kernel;
+ private readonly ISemanticTextMemory _memory = memory;
public void AddToHistory(string message, ChatUserType userType) => _state.History.Add(new ChatHistoryItem
{
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs
index 082d55e7f..7bfe5ab8d 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs
@@ -13,7 +13,7 @@ public abstract class ConsoleAgent : IOAgent,
{
// instead of the primary constructor above, make a constructr here that still calls the base constructor
- public ConsoleAgent(IAgentRuntime context, [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : base(context, typeRegistry)
+ public ConsoleAgent(IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : base(worker, typeRegistry)
{
_route = "console";
}
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/FileAgent/FileAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/FileAgent/FileAgent.cs
index 7e37a1f0c..ddab8a61e 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/FileAgent/FileAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/FileAgent/FileAgent.cs
@@ -9,11 +9,11 @@ namespace Microsoft.AutoGen.Agents;
[TopicSubscription("FileIO")]
public abstract class FileAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
string inputPath = "input.txt",
string outputPath = "output.txt"
- ) : IOAgent(context, typeRegistry),
+ ) : IOAgent(worker, typeRegistry),
IUseFiles,
IHandle<Input>,
IHandle<Output>
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs
index 16dcd9598..e2b53d694 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs
@@ -5,12 +5,10 @@ using Microsoft.AutoGen.Contracts;
using Microsoft.AutoGen.Core;
namespace Microsoft.AutoGen.Agents;
-public abstract class IOAgent : Agent
+public abstract class IOAgent(IAgentWorker worker, EventTypes eventTypes) : Agent(worker, eventTypes)
{
public string _route = "base";
- protected IOAgent(IAgentRuntime context, EventTypes eventTypes) : base(context, eventTypes)
- {
- }
+
public virtual async Task Handle(Input item)
{
diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs
index fe79279eb..3e43096be 100644
--- a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs
@@ -17,11 +17,11 @@ public abstract class WebAPIAgent : IOAgent,
private readonly string _url = "/agents/webio";
public WebAPIAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
ILogger<WebAPIAgent> logger,
string url = "/agents/webio") : base(
- context,
+ worker,
typeRegistry)
{
_url = url;
diff --git a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs
index 2d86ebd30..f96f42a2c 100644
--- a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs
@@ -2,7 +2,6 @@
// GrpcAgentWorker.cs
using System.Collections.Concurrent;
-using System.Diagnostics;
using System.Reflection;
using System.Threading.Channels;
using Grpc.Core;
@@ -18,8 +17,7 @@ public sealed class GrpcAgentWorker(
IHostApplicationLifetime hostApplicationLifetime,
IServiceProvider serviceProvider,
[FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, Type>> configuredAgentTypes,
- ILogger<GrpcAgentWorker> logger,
- DistributedContextPropagator distributedContextPropagator) :
+ ILogger<GrpcAgentWorker> logger) :
IHostedService, IDisposable, IAgentWorker
{
private readonly object _channelLock = new();
@@ -37,7 +35,6 @@ public sealed class GrpcAgentWorker(
private readonly IServiceProvider _serviceProvider = serviceProvider;
private readonly IEnumerable<Tuple<string, Type>> _configuredAgentTypes = configuredAgentTypes;
private readonly ILogger<GrpcAgentWorker> _logger = logger;
- private readonly DistributedContextPropagator _distributedContextPropagator = distributedContextPropagator;
private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping);
private AsyncDuplexStreamingCall<Message, Message>? _channel;
private Task? _readTask;
@@ -178,8 +175,7 @@ public sealed class GrpcAgentWorker(
{
if (_agentTypes.TryGetValue(agentId.Type, out var agentType))
{
- var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<Agent>>(), _distributedContextPropagator);
- agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);
+ agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, this);
_agents.TryAdd((agentId.Type, agentId.Key), agent);
}
else
diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs
index f2cb91fed..67905ecb0 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs
@@ -13,35 +13,43 @@ using Microsoft.AutoGen.Contracts;
using Microsoft.Extensions.Logging;
namespace Microsoft.AutoGen.Core;
-
+/// <summary>
+/// Represents the base class for an agent in the AutoGen system.
+/// </summary>
public abstract class Agent : IHandle
{
- public static readonly ActivitySource s_source = new("AutoGen.Agent");
- public AgentId AgentId => _runtime.AgentId;
private readonly object _lock = new();
private readonly ConcurrentDictionary<string, TaskCompletionSource<RpcResponse>> _pendingRequests = [];
- private readonly Channel<object> _mailbox = Channel.CreateUnbounded<object>();
- private readonly IAgentRuntime _runtime;
- public string Route { get; set; } = "base";
+ /// <summary>
+ /// The activity source for tracing.
+ /// </summary>
+ public static readonly ActivitySource s_source = new("Microsoft.AutoGen.Core.Agent");
+ /// <summary>
+ /// Gets the unique identifier of the agent.
+ /// </summary>
+ public AgentId AgentId { get; private set; }
+ private readonly Channel<object> _mailbox = Channel.CreateUnbounded<object>();
protected internal ILogger<Agent> _logger;
- public IAgentRuntime Context => _runtime;
+ public AgentMessenger Messenger { get; private set; }
+ private readonly ConcurrentDictionary<Type, MethodInfo> _handlersByMessageType;
+ internal Task Completion { get; private set; }
+
protected readonly EventTypes EventTypes;
- protected Agent(
- IAgentRuntime runtime,
+ protected Agent(IAgentWorker worker,
EventTypes eventTypes,
ILogger<Agent>? logger = null)
{
- _runtime = runtime;
- runtime.AgentInstance = this;
- this.EventTypes = eventTypes;
+ EventTypes = eventTypes;
+ AgentId = new AgentId(this.GetType().Name, new Guid().ToString());
_logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger<Agent>();
+ _handlersByMessageType = new(GetType().GetHandlersLookupTable());
+ Messenger = AgentMessengerFactory.Create(worker, DistributedContextPropagator.Current);
AddImplicitSubscriptionsAsync().AsTask().Wait();
Completion = Start();
}
- internal Task Completion { get; }
private async ValueTask AddImplicitSubscriptionsAsync()
{
@@ -66,7 +74,7 @@ public abstract class Agent : IHandle
}
};
// explicitly wait for this to complete
- await _runtime.SendMessageAsync(new Message { AddSubscriptionRequest = subscriptionRequest }).ConfigureAwait(true);
+ await Messenger.SendMessageAsync(new Message { AddSubscriptionRequest = subscriptionRequest }).ConfigureAwait(true);
}
// using reflection, find all methods that Handle<T> and subscribe to the topic T
@@ -82,6 +90,11 @@ public abstract class Agent : IHandle
}
}
+
+ /// <summary>
+ /// Starts the message pump for the agent.
+ /// </summary>
+ /// <returns>A task representing the asynchronous operation.</returns>
internal Task Start()
{
var didSuppress = false;
@@ -173,18 +186,18 @@ public abstract class Agent : IHandle
}
}
};
- _runtime.SendMessageAsync(message).AsTask().Wait();
+ Messenger.SendMessageAsync(message).AsTask().Wait();
return new List<string> { topic };
}
public async Task StoreAsync(AgentState state, CancellationToken cancellationToken = default)
{
- await _runtime.StoreAsync(state, cancellationToken).ConfigureAwait(false);
+ await Messenger.StoreAsync(state, cancellationToken).ConfigureAwait(false);
return;
}
public async Task<T> ReadAsync<T>(AgentId agentId, CancellationToken cancellationToken = default) where T : IMessage, new()
{
- var agentstate = await _runtime.ReadAsync(agentId, cancellationToken).ConfigureAwait(false);
+ var agentstate = await Messenger.ReadAsync(agentId, cancellationToken).ConfigureAwait(false);
return agentstate.FromAgentState<T>();
}
private void OnResponseCore(RpcResponse response)
@@ -207,13 +220,13 @@ public abstract class Agent : IHandle
try
{
- response = await HandleRequest(request).ConfigureAwait(false);
+ response = await HandleRequestAsync(request).ConfigureAwait(false);
}
catch (Exception ex)
{
response = new RpcResponse { Error = ex.Message };
}
- await _runtime.SendResponseAsync(request, response, cancellationToken).ConfigureAwait(false);
+ await Messenger.SendResponseAsync(request, response, cancellationToken).ConfigureAwait(false);
}
protected async Task<RpcResponse> RequestAsync(AgentId target, string method, Dictionary<string, string> parameters)
@@ -237,7 +250,7 @@ public abstract class Agent : IHandle
activity?.SetTag("peer.service", target.ToString());
var completion = new TaskCompletionSource<RpcResponse>(TaskCreationOptions.RunContinuationsAsynchronously);
- Context!.Update(request, activity);
+ Messenger!.Update(request, activity);
await this.InvokeWithActivityAsync(
static async (state, ct) =>
{
@@ -245,7 +258,7 @@ public abstract class Agent : IHandle
self._pendingRequests.AddOrUpdate(request.RequestId, _ => completion, (_, __) => completion);
- await state.Item1.Context!.SendRequestAsync(state.Item1, state.request, ct).ConfigureAwait(false);
+ await state.Item1.Messenger!.SendRequestAsync(state.Item1, state.request, ct).ConfigureAwait(false);
await completion.Task.ConfigureAwait(false);
},
@@ -270,11 +283,11 @@ public abstract class Agent : IHandle
activity?.SetTag("peer.service", $"{item.Type}/{item.Source}");
// TODO: fix activity
- _runtime.Update(item, activity);
+ Messenger.Update(item, activity);
await this.InvokeWithActivityAsync(
static async ((Agent Agent, CloudEvent Event) state, CancellationToken ct) =>
{
- await state.Agent._runtime.PublishEventAsync(state.Event).ConfigureAwait(false);
+ await state.Agent.Messenger.PublishEventAsync(state.Event).ConfigureAwait(false);
},
(this, item),
activity,
@@ -320,7 +333,7 @@ public abstract class Agent : IHandle
return Task.CompletedTask;
}
- public Task<RpcResponse> HandleRequest(RpcRequest request) => Task.FromResult(new RpcResponse { Error = "Not implemented" });
+ public Task<RpcResponse> HandleRequestAsync(RpcRequest request) => Task.FromResult(new RpcResponse { Error = "Not implemented" });
//TODO: should this be async and cancellable?
public virtual Task HandleObject(object item)
diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs
index 49efcb50e..911107f78 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs
@@ -22,7 +22,7 @@ public static class AgentExtensions
public static Activity? ExtractActivity(this Agent agent, string activityName, IDictionary<string, string> metadata)
{
Activity? activity;
- var (traceParent, traceState) = agent.Context.GetTraceIdAndState(metadata);
+ var (traceParent, traceState) = agent.Messenger.GetTraceIdAndState(metadata);
if (!string.IsNullOrEmpty(traceParent))
{
if (ActivityContext.TryParse(traceParent, traceState, isRemote: true, out var parentContext))
@@ -43,7 +43,7 @@ public static class AgentExtensions
activity.TraceStateString = traceState;
}
- var baggage = agent.Context.ExtractMetadata(metadata);
+ var baggage = agent.Messenger.ExtractMetadata(metadata);
foreach (var baggageItem in baggage)
{
diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs
similarity index 93%
rename from dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs
rename to dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs
index 63290927a..66b1c0c65 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs
@@ -1,21 +1,17 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
-// AgentRuntime.cs
+// AgentMessenger.cs
using System.Diagnostics;
using Google.Protobuf.Collections;
using Microsoft.AutoGen.Contracts;
-using Microsoft.Extensions.Logging;
using static Microsoft.AutoGen.Contracts.CloudEvent.Types;
namespace Microsoft.AutoGen.Core;
-public sealed class AgentRuntime(AgentId agentId, IAgentWorker worker, ILogger<Agent> logger, DistributedContextPropagator distributedContextPropagator) : IAgentRuntime
+public sealed class AgentMessenger(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator)
{
private readonly IAgentWorker worker = worker;
- public AgentId AgentId { get; } = agentId;
- private ILogger<Agent> Logger { get; } = logger;
- public Agent? AgentInstance { get; set; }
private DistributedContextPropagator DistributedContextPropagator { get; } = distributedContextPropagator;
public (string?, string?) GetTraceIdAndState(IDictionary<string, string> metadata)
{
diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs
new file mode 100644
index 000000000..c008f9f2d
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs
@@ -0,0 +1,12 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// AgentMessengerFactory.cs
+
+using System.Diagnostics;
+namespace Microsoft.AutoGen.Core;
+public class AgentMessengerFactory()
+{
+ public static AgentMessenger Create(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator)
+ {
+ return new AgentMessenger(worker, distributedContextPropagator);
+ }
+}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs
index d88b61e39..3b70461a3 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs
@@ -2,48 +2,34 @@
// AgentWorker.cs
using System.Collections.Concurrent;
-using System.Diagnostics;
using System.Threading.Channels;
using Microsoft.AutoGen.Contracts;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
-using Microsoft.Extensions.Logging;
namespace Microsoft.AutoGen.Core;
-public class AgentWorker :
+public class AgentWorker(
+IHostApplicationLifetime hostApplicationLifetime,
+IServiceProvider serviceProvider,
+[FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, Type>> configuredAgentTypes) :
IHostedService,
IAgentWorker
{
private readonly ConcurrentDictionary<string, Type> _agentTypes = new();
private readonly ConcurrentDictionary<(string Type, string Key), Agent> _agents = new();
- private readonly ILogger<AgentWorker> _logger;
private readonly Channel<object> _mailbox = Channel.CreateUnbounded<object>();
private readonly ConcurrentDictionary<string, AgentState> _agentStates = new();
private readonly ConcurrentDictionary<string, (Agent Agent, string OriginalRequestId)> _pendingClientRequests = new();
- private readonly CancellationTokenSource _shutdownCts;
- private readonly IServiceProvider _serviceProvider;
- private readonly IEnumerable<Tuple<string, Type>> _configuredAgentTypes;
+ private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping);
+ private readonly IServiceProvider _serviceProvider = serviceProvider;
+ private readonly IEnumerable<Tuple<string, Type>> _configuredAgentTypes = configuredAgentTypes;
private readonly ConcurrentDictionary<string, Subscription> _subscriptionsByAgentType = new();
private readonly ConcurrentDictionary<string, List<string>> _subscriptionsByTopic = new();
- private readonly DistributedContextPropagator _distributedContextPropagator;
private readonly CancellationTokenSource _shutdownCancellationToken = new();
private Task? _mailboxTask;
private readonly object _channelLock = new();
- public AgentWorker(
- IHostApplicationLifetime hostApplicationLifetime,
- IServiceProvider serviceProvider,
- [FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, Type>> configuredAgentTypes,
- ILogger<AgentWorker> logger,
- DistributedContextPropagator distributedContextPropagator)
- {
- _logger = logger;
- _serviceProvider = serviceProvider;
- _configuredAgentTypes = configuredAgentTypes;
- _distributedContextPropagator = distributedContextPropagator;
- _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping);
- }
// this is the in-memory version - we just pass the message directly to the agent(s) that handle this type of event
public async ValueTask PublishEventAsync(CloudEvent cloudEvent, CancellationToken cancellationToken = default)
{
@@ -196,8 +182,7 @@ public class AgentWorker :
{
if (_agentTypes.TryGetValue(agentId.Type, out var agentType))
{
- var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<Agent>>(), _distributedContextPropagator);
- agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);
+ agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, this);
_agents.TryAdd((agentId.Type, agentId.Key), agent);
}
else
diff --git a/dotnet/src/Microsoft.AutoGen/Core/Client.cs b/dotnet/src/Microsoft.AutoGen/Core/Client.cs
index 274154afa..1d523005f 100644
--- a/dotnet/src/Microsoft.AutoGen/Core/Client.cs
+++ b/dotnet/src/Microsoft.AutoGen/Core/Client.cs
@@ -1,14 +1,9 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Client.cs
-
-using System.Diagnostics;
-using Microsoft.AutoGen.Contracts;
using Microsoft.Extensions.DependencyInjection;
-using Microsoft.Extensions.Logging;
namespace Microsoft.AutoGen.Core;
-public sealed class Client(IAgentWorker runtime, DistributedContextPropagator distributedContextPropagator,
- [FromKeyedServices("EventTypes")] EventTypes eventTypes, ILogger<Client> logger)
- : Agent(new AgentRuntime(new AgentId("client", Guid.NewGuid().ToString()), runtime, logger, distributedContextPropagator), eventTypes)
+public sealed class Client(IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes eventTypes)
+ : Agent(worker, eventTypes)
{
}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs
deleted file mode 100644
index fd2b71d43..000000000
--- a/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs
+++ /dev/null
@@ -1,23 +0,0 @@
-// Copyright (c) Microsoft Corporation. All rights reserved.
-// IAgentRuntime.cs
-
-using System.Diagnostics;
-using Microsoft.AutoGen.Contracts;
-
-namespace Microsoft.AutoGen.Core;
-
-public interface IAgentRuntime
-{
- AgentId AgentId { get; }
- Agent? AgentInstance { get; set; }
- ValueTask StoreAsync(AgentState value, CancellationToken cancellationToken = default);
- ValueTask<AgentState> ReadAsync(AgentId agentId, CancellationToken cancellationToken = default);
- ValueTask SendResponseAsync(RpcRequest request, RpcResponse response, CancellationToken cancellationToken = default);
- ValueTask SendRequestAsync(Agent agent, RpcRequest request, CancellationToken cancellationToken = default);
- ValueTask SendMessageAsync(Message message, CancellationToken cancellationToken = default);
- ValueTask PublishEventAsync(CloudEvent @event, CancellationToken cancellationToken = default);
- void Update(RpcRequest request, Activity? activity);
- void Update(CloudEvent cloudEvent, Activity? activity);
- (string?, string?) GetTraceIdAndState(IDictionary<string, string> metadata);
- IDictionary<string, string> ExtractMetadata(IDictionary<string, string> metadata);
-}
diff --git a/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs
new file mode 100644
index 000000000..44014a4ab
--- /dev/null
+++ b/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs
@@ -0,0 +1,38 @@
+// Copyright (c) Microsoft Corporation. All rights reserved.
+// IHandleExtensions.cs
+
+using System.Reflection;
+
+namespace Microsoft.AutoGen.Core;
+
+/// <summary>
+/// Provides extension methods for types implementing the IHandle interface.
+/// </summary>
+public static class IHandleExtensions
+{
+ /// <summary>
+ /// Gets all the handler methods from the interfaces implemented by the specified type.
+ /// </summary>
+ /// <param name="type">The type to get the handler methods from.</param>
+ /// <returns>An array of MethodInfo objects representing the handler methods.</returns>
+ public static MethodInfo[] GetHandlers(this Type type)
+ {
+ var handlers = type.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandle<>));
+ return handlers.SelectMany(h => h.GetMethods().Where(m => m.Name == "Handle")).ToArray();
+ }
+
+ /// <summary>
+ /// Gets a lookup table of handler methods from the interfaces implemented by the specified type.
+ /// </summary>
+ /// <param name="type">The type to get the handler methods from.</param>
+ /// <returns>A dictionary where the key is the generic type and the value is the MethodInfo of the handler method.</returns>
+ public static Dictionary<Type, MethodInfo> GetHandlersLookupTable(this Type type)
+ {
+ var handlers = type.GetHandlers();
+ return handlers.ToDictionary(h =>
+ {
+ var generic = h.DeclaringType!.GetGenericArguments();
+ return generic[0];
+ });
+ }
+}
diff --git a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs
index bd169d644..08a88da04 100644
--- a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs
@@ -23,12 +23,8 @@ public class AgentTests(InMemoryAgentRuntimeFixture fixture)
[Fact]
public async Task ItInvokeRightHandlerTestAsync()
{
- var mockContext = new Mock<IAgentRuntime>();
- mockContext.SetupGet(x => x.AgentId).Returns(new AgentId("test", "test"));
- // mock SendMessageAsync
- mockContext.Setup(x => x.SendMessageAsync(It.IsAny<Message>(), It.IsAny<CancellationToken>()))
- .Returns(new ValueTask());
- var agent = new TestAgent(mockContext.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger<Agent>(new LoggerFactory()));
+ var mockWorker = new Mock<IAgentWorker>();
+ var agent = new TestAgent(mockWorker.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger<Agent>(new LoggerFactory()));
await agent.HandleObject("hello world");
await agent.HandleObject(42);
@@ -65,9 +61,9 @@ public class AgentTests(InMemoryAgentRuntimeFixture fixture)
public class TestAgent : Agent, IHandle<string>, IHandle<int>, IHandle<TextMessage>
{
public TestAgent(
- IAgentRuntime context,
+ IAgentWorker worker,
[FromKeyedServices("EventTypes")] EventTypes eventTypes,
- Logger<Agent>? logger = null) : base(context, eventTypes, logger)
+ Logger<Agent>? logger = null) : base(worker, eventTypes, logger)
{
}
diff --git a/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs b/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs
index 18b35bd70..ba83b07f7 100644
--- a/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs
@@ -45,7 +45,7 @@ public class HelloAppHostIntegrationTests(ITestOutputHelper testOutput)
//sleep to make sure the app is running
await Task.Delay(20000);
app.EnsureNoErrorsLogged();
- app.EnsureLogContains("HelloAgents said Goodbye");
+ app.EnsureLogContains("HelloAgent said Goodbye");
app.EnsureLogContains("Wild Hello from Python!");
await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(15));
diff --git a/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs b/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs
index 0795cf8be..b6bdd9eb7 100644
--- a/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs
+++ b/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs
@@ -24,7 +24,7 @@ public class InMemoryRuntimeIntegrationTests(ITestOutputHelper testOutput)
await Task.Delay(15000);
app.EnsureNoErrorsLogged();
app.EnsureLogContains("Hello World");
- app.EnsureLogContains("HelloAgents said Goodbye");
+ app.EnsureLogContains("HelloAgent said Goodbye");
await app.StopAsync().WaitAsync(TimeSpan.FromSeconds(15));
}
diff --git a/python/packages/autogen-core/samples/xlang/hello_python_agent/hello_python_agent.py b/python/packages/autogen-core/samples/xlang/hello_python_agent/hello_python_agent.py
index c50aacedd..178b91de8 100644
--- a/python/packages/autogen-core/samples/xlang/hello_python_agent/hello_python_agent.py
+++ b/python/packages/autogen-core/samples/xlang/hello_python_agent/hello_python_agent.py
@@ -42,11 +42,11 @@ async def main() -> None:
agnext_logger.info("2")
- await UserProxy.register(runtime, "HelloAgents", lambda: UserProxy())
- await runtime.add_subscription(DefaultSubscription(agent_type="HelloAgents"))
- await runtime.add_subscription(TypeSubscription(topic_type="agents.NewMessageReceived", agent_type="HelloAgents"))
- await runtime.add_subscription(TypeSubscription(topic_type="agents.ConversationClosed", agent_type="HelloAgents"))
- await runtime.add_subscription(TypeSubscription(topic_type="agents.Output", agent_type="HelloAgents"))
+ await UserProxy.register(runtime, "HelloAgent", lambda: UserProxy())
+ await runtime.add_subscription(DefaultSubscription(agent_type="HelloAgent"))
+ await runtime.add_subscription(TypeSubscription(topic_type="agents.NewMessageReceived", agent_type="HelloAgent"))
+ await runtime.add_subscription(TypeSubscription(topic_type="agents.ConversationClosed", agent_type="HelloAgent"))
+ await runtime.add_subscription(TypeSubscription(topic_type="agents.Output", agent_type="HelloAgent"))
agnext_logger.info("3")
new_message = NewMessageReceived(message="from Python!")