From 512928895b80ccd7b6bc4db244e93bc04fbb9847 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Fri, 13 Dec 2024 13:03:13 -0800 Subject: [PATCH 01/13] wip --- .../Hello/HelloAIAgents/HelloAIAgent.cs | 2 - dotnet/samples/Hello/HelloAIAgents/Program.cs | 2 - .../IOAgent/ConsoleAgent/ConsoleAgent.cs | 2 +- .../Agents/IOAgent/IOAgent.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 74 ++++++++++--------- .../Microsoft.AutoGen/Core/AgentExtensions.cs | 4 +- .../Core/IHandleExtensions.cs | 38 ++++++++++ 7 files changed, 82 insertions(+), 42 deletions(-) create mode 100644 dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs diff --git a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs index 7261ee45d6ef..4c1981c061ae 100644 --- a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs +++ b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs @@ -8,11 +8,9 @@ namespace Hello; [TopicSubscription("agents")] public class HelloAIAgent( - IAgentRuntime context, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IHostApplicationLifetime hostApplicationLifetime, IChatClient client) : HelloAgent( - context, typeRegistry, hostApplicationLifetime), IHandle diff --git a/dotnet/samples/Hello/HelloAIAgents/Program.cs b/dotnet/samples/Hello/HelloAIAgents/Program.cs index a15effa5aaf0..b5696307a408 100644 --- a/dotnet/samples/Hello/HelloAIAgents/Program.cs +++ b/dotnet/samples/Hello/HelloAIAgents/Program.cs @@ -33,10 +33,8 @@ namespace Hello { [TopicSubscription("agents")] public class HelloAgent( - IAgentRuntime context, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IHostApplicationLifetime hostApplicationLifetime) : ConsoleAgent( - context, typeRegistry), ISayHello, IHandle, diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs index 082d55e7fcdb..492538f4e62b 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([FromKeyedServices("EventTypes")] EventTypes typeRegistry) : base(typeRegistry) { _route = "console"; } diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs index 16dcd9598262..d44e29b775f3 100644 --- a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs +++ b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs @@ -8,7 +8,7 @@ namespace Microsoft.AutoGen.Agents; public abstract class IOAgent : Agent { public string _route = "base"; - protected IOAgent(IAgentRuntime context, EventTypes eventTypes) : base(context, eventTypes) + protected IOAgent(EventTypes eventTypes) : base(eventTypes) { } public virtual async Task Handle(Input item) diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index f7a2ac8f736c..9ad2b30a2d25 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -13,35 +13,41 @@ using Microsoft.Extensions.Logging; namespace Microsoft.AutoGen.Core; - -public abstract class Agent : IDisposable, IHandle +/// +/// Represents the base class for an agent in the AutoGen system. +/// +public abstract class Agent { - public static readonly ActivitySource s_source = new("AutoGen.Agent"); - public AgentId AgentId => _runtime.AgentId; private readonly object _lock = new(); private readonly ConcurrentDictionary> _pendingRequests = []; - private readonly Channel _mailbox = Channel.CreateUnbounded(); - private readonly IAgentRuntime _runtime; - public string Route { get; set; } = "base"; + /// + /// The activity source for tracing. + /// + public static readonly ActivitySource s_source = new("Microsoft.AutoGen.Core.Agent"); + /// + /// Gets the unique identifier of the agent. + /// + public AgentId AgentId => Runtime!.AgentId; + private readonly Channel _mailbox = Channel.CreateUnbounded(); protected internal ILogger _logger; - public IAgentRuntime Context => _runtime; + public IAgentRuntime? Runtime { get; private set; } + private readonly ConcurrentDictionary _handlersByMessageType; + internal Task Completion { get; private set; } + protected readonly EventTypes EventTypes; protected Agent( - IAgentRuntime runtime, EventTypes eventTypes, ILogger? logger = null) { - _runtime = runtime; - runtime.AgentInstance = this; - this.EventTypes = eventTypes; + EventTypes = eventTypes; _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger(); + _handlersByMessageType = new(GetType().GetHandlersLookupTable()); AddImplicitSubscriptionsAsync().AsTask().Wait(); Completion = Start(); } - internal Task Completion { get; } private async ValueTask AddImplicitSubscriptionsAsync() { @@ -66,7 +72,7 @@ private async ValueTask AddImplicitSubscriptionsAsync() } }; // explicitly wait for this to complete - await _runtime.SendMessageAsync(new Message { AddSubscriptionRequest = subscriptionRequest }).ConfigureAwait(true); + await Runtime.SendMessageAsync(new Message { AddSubscriptionRequest = subscriptionRequest }).ConfigureAwait(true); } // using reflection, find all methods that Handle and subscribe to the topic T @@ -82,13 +88,18 @@ private async ValueTask AddImplicitSubscriptionsAsync() } } + + /// + /// Starts the message pump for the agent. + /// + /// A task representing the asynchronous operation. internal Task Start() { var didSuppress = false; - if (!ExecutionContext.IsFlowSuppressed()) + if (!ExecutionRuntime.IsFlowSuppressed()) { didSuppress = true; - ExecutionContext.SuppressFlow(); + ExecutionRuntime.SuppressFlow(); } try @@ -99,7 +110,7 @@ internal Task Start() { if (didSuppress) { - ExecutionContext.RestoreFlow(); + ExecutionRuntime.RestoreFlow(); } } } @@ -173,18 +184,18 @@ public List Subscribe(string topic) } } }; - _runtime.SendMessageAsync(message).AsTask().Wait(); + Runtime.SendMessageAsync(message).AsTask().Wait(); return new List { topic }; } public async Task StoreAsync(AgentState state, CancellationToken cancellationToken = default) { - await _runtime.StoreAsync(state, cancellationToken).ConfigureAwait(false); + await Runtime.StoreAsync(state, cancellationToken).ConfigureAwait(false); return; } public async Task ReadAsync(AgentId agentId, CancellationToken cancellationToken = default) where T : IMessage, new() { - var agentstate = await _runtime.ReadAsync(agentId, cancellationToken).ConfigureAwait(false); + var agentstate = await Runtime.ReadAsync(agentId, cancellationToken).ConfigureAwait(false); return agentstate.FromAgentState(); } private void OnResponseCore(RpcResponse response) @@ -207,13 +218,13 @@ private async Task OnRequestCoreAsync(RpcRequest request, CancellationToken canc 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 Runtime.SendResponseAsync(request, response, cancellationToken).ConfigureAwait(false); } protected async Task RequestAsync(AgentId target, string method, Dictionary parameters) @@ -233,11 +244,11 @@ protected async Task RequestAsync(AgentId target, string method, Di } }; - var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Context ?? default); + var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Runtime ?? default); activity?.SetTag("peer.service", target.ToString()); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - Context!.Update(request, activity); + Runtime!.Update(request, activity); await this.InvokeWithActivityAsync( static async (state, ct) => { @@ -245,7 +256,7 @@ static async (state, ct) => self._pendingRequests.AddOrUpdate(request.RequestId, _ => completion, (_, __) => completion); - await state.Item1.Context!.SendRequestAsync(state.Item1, state.request, ct).ConfigureAwait(false); + await state.Item1.Runtime!.SendRequestAsync(state.Item1, state.request, ct).ConfigureAwait(false); await completion.Task.ConfigureAwait(false); }, @@ -266,15 +277,15 @@ public async ValueTask PublishMessageAsync(T message, string? source = null, public async ValueTask PublishEventAsync(CloudEvent item, CancellationToken cancellationToken = default) { - var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Context ?? default); + var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Runtime ?? default); activity?.SetTag("peer.service", $"{item.Type}/{item.Source}"); // TODO: fix activity - _runtime.Update(item, activity); + Runtime.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.Runtime.PublishEventAsync(state.Event).ConfigureAwait(false); }, (this, item), activity, @@ -320,7 +331,7 @@ public Task CallHandler(CloudEvent item) return Task.CompletedTask; } - public Task HandleRequest(RpcRequest request) => Task.FromResult(new RpcResponse { Error = "Not implemented" }); + public Task HandleRequestAsync(RpcRequest request) => Task.FromResult(new RpcResponse { Error = "Not implemented" }); //TODO: should this be async and cancellable? public virtual Task HandleObject(object item) @@ -344,9 +355,4 @@ public async ValueTask PublishEventAsync(string topic, IMessage evt, Cancellatio { await PublishEventAsync(evt.ToCloudEvent(topic), cancellationToken).ConfigureAwait(false); } - - public void Dispose() - { - throw new NotImplementedException(); - } } diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs index 49efcb50e962..c18713e84c43 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 metadata) { Activity? activity; - var (traceParent, traceState) = agent.Context.GetTraceIdAndState(metadata); + var (traceParent, traceState) = agent.Runtime.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.Runtime.ExtractMetadata(metadata); foreach (var baggageItem in baggage) { diff --git a/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/IHandleExtensions.cs new file mode 100644 index 000000000000..44014a4abcca --- /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; + +/// +/// Provides extension methods for types implementing the IHandle interface. +/// +public static class IHandleExtensions +{ + /// + /// Gets all the handler methods from the interfaces implemented by the specified type. + /// + /// The type to get the handler methods from. + /// An array of MethodInfo objects representing the handler methods. + 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(); + } + + /// + /// Gets a lookup table of handler methods from the interfaces implemented by the specified type. + /// + /// The type to get the handler methods from. + /// A dictionary where the key is the generic type and the value is the MethodInfo of the handler method. + public static Dictionary GetHandlersLookupTable(this Type type) + { + var handlers = type.GetHandlers(); + return handlers.ToDictionary(h => + { + var generic = h.DeclaringType!.GetGenericArguments(); + return generic[0]; + }); + } +} From 4433ca3d39087a4178c5f489ac3bacd13189e397 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Mon, 16 Dec 2024 11:30:35 -0800 Subject: [PATCH 02/13] wip --- .../Core.Grpc/GrpcAgentWorker.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 5 ++-- .../{AgentRuntime.cs => AgentMessenger.cs} | 4 ++-- .../Core/AgentMessengerFactory.cs | 15 ++++++++++++ .../src/Microsoft.AutoGen/Core/AgentWorker.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/Client.cs | 2 +- .../Microsoft.AutoGen/Core/IAgentRuntime.cs | 23 ------------------- 7 files changed, 23 insertions(+), 30 deletions(-) rename dotnet/src/Microsoft.AutoGen/Core/{AgentRuntime.cs => AgentMessenger.cs} (96%) create mode 100644 dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs delete mode 100644 dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs diff --git a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs index 2d86ebd301e2..38ce279dfeca 100644 --- a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs @@ -178,7 +178,7 @@ private Agent GetOrActivateAgent(AgentId agentId) { if (_agentTypes.TryGetValue(agentId.Type, out var agentType)) { - var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); + var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context); _agents.TryAdd((agentId.Type, agentId.Key), agent); } diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index 9ad2b30a2d25..6e6ae243bee5 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -29,10 +29,10 @@ public abstract class Agent /// /// Gets the unique identifier of the agent. /// - public AgentId AgentId => Runtime!.AgentId; + public AgentId AgentId => Messenger.AgentId; private readonly Channel _mailbox = Channel.CreateUnbounded(); protected internal ILogger _logger; - public IAgentRuntime? Runtime { get; private set; } + public AgentMessenger Messenger { get; private set; } private readonly ConcurrentDictionary _handlersByMessageType; internal Task Completion { get; private set; } @@ -45,6 +45,7 @@ protected Agent( EventTypes = eventTypes; _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger(); _handlersByMessageType = new(GetType().GetHandlersLookupTable()); + Messenger = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); AddImplicitSubscriptionsAsync().AsTask().Wait(); Completion = Start(); } diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs similarity index 96% rename from dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs rename to dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs index 63290927a74f..003ab293032e 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentRuntime.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs @@ -1,5 +1,5 @@ // Copyright (c) Microsoft Corporation. All rights reserved. -// AgentRuntime.cs +// AgentMessenger.cs using System.Diagnostics; using Google.Protobuf.Collections; @@ -9,7 +9,7 @@ namespace Microsoft.AutoGen.Core; -public sealed class AgentRuntime(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) : IAgentRuntime +public sealed class AgentMessenger(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) { private readonly IAgentWorker worker = worker; diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs new file mode 100644 index 000000000000..164c34b40a2a --- /dev/null +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// AgentMessengerFactory.cs + +using System.Diagnostics; +using Microsoft.AutoGen.Contracts; +using Microsoft.Extensions.Logging; + +namespace Microsoft.AutoGen.Core; +public static class AgentMessengerFactory +{ + public static AgentMessenger Create(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) + { + return new AgentMessenger(agentId, worker, logger, distributedContextPropagator); + } +} \ No newline at end of file diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs index d88b61e39e97..6de992ae16c6 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs @@ -196,7 +196,7 @@ private Agent GetOrActivateAgent(AgentId agentId) { if (_agentTypes.TryGetValue(agentId.Type, out var agentType)) { - var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); + var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context); _agents.TryAdd((agentId.Type, agentId.Key), agent); } diff --git a/dotnet/src/Microsoft.AutoGen/Core/Client.cs b/dotnet/src/Microsoft.AutoGen/Core/Client.cs index 274154afa740..7f9fae52f0f1 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Client.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Client.cs @@ -9,6 +9,6 @@ namespace Microsoft.AutoGen.Core; public sealed class Client(IAgentWorker runtime, DistributedContextPropagator distributedContextPropagator, [FromKeyedServices("EventTypes")] EventTypes eventTypes, ILogger logger) - : Agent(new AgentRuntime(new AgentId("client", Guid.NewGuid().ToString()), runtime, logger, distributedContextPropagator), eventTypes) + : Agent(new AgentMessenger(new AgentId("client", Guid.NewGuid().ToString()), runtime, logger, distributedContextPropagator), eventTypes) { } diff --git a/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Core/IAgentRuntime.cs deleted file mode 100644 index fd2b71d43b0d..000000000000 --- 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 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 metadata); - IDictionary ExtractMetadata(IDictionary metadata); -} From d6c11f0863edc69b23790e7262fa6375671dbe0b Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Mon, 16 Dec 2024 20:40:00 -0800 Subject: [PATCH 03/13] wip --- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 28 +++++++++---------- .../Core/AgentMessengerFactory.cs | 2 +- .../src/Microsoft.AutoGen/Core/AgentWorker.cs | 28 ++++++------------- 3 files changed, 24 insertions(+), 34 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index 6e6ae243bee5..d5d76c07d833 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -29,7 +29,7 @@ public abstract class Agent /// /// Gets the unique identifier of the agent. /// - public AgentId AgentId => Messenger.AgentId; + public AgentId AgentId => new AgentId(this.GetType().Name, new Guid().ToString()); private readonly Channel _mailbox = Channel.CreateUnbounded(); protected internal ILogger _logger; public AgentMessenger Messenger { get; private set; } @@ -38,14 +38,14 @@ public abstract class Agent protected readonly EventTypes EventTypes; - protected Agent( + protected Agent(IAgentWorker worker, EventTypes eventTypes, ILogger? logger = null) { EventTypes = eventTypes; _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger(); _handlersByMessageType = new(GetType().GetHandlersLookupTable()); - Messenger = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); + Messenger = AgentMessengerFactory.Create(AgentId, worker, _logger, DistributedContextPropagator.Current); AddImplicitSubscriptionsAsync().AsTask().Wait(); Completion = Start(); } @@ -73,7 +73,7 @@ private async ValueTask AddImplicitSubscriptionsAsync() } }; // 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 and subscribe to the topic T @@ -185,18 +185,18 @@ public List Subscribe(string topic) } } }; - Runtime.SendMessageAsync(message).AsTask().Wait(); + Messenger.SendMessageAsync(message).AsTask().Wait(); return new List { 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 ReadAsync(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(); } private void OnResponseCore(RpcResponse response) @@ -225,7 +225,7 @@ private async Task OnRequestCoreAsync(RpcRequest request, CancellationToken canc { 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 RequestAsync(AgentId target, string method, Dictionary parameters) @@ -245,11 +245,11 @@ protected async Task RequestAsync(AgentId target, string method, Di } }; - var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Runtime ?? default); + var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Messenger ?? default); activity?.SetTag("peer.service", target.ToString()); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); - Runtime!.Update(request, activity); + Messenger!.Update(request, activity); await this.InvokeWithActivityAsync( static async (state, ct) => { @@ -257,7 +257,7 @@ static async (state, ct) => self._pendingRequests.AddOrUpdate(request.RequestId, _ => completion, (_, __) => completion); - await state.Item1.Runtime!.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); }, @@ -278,15 +278,15 @@ public async ValueTask PublishMessageAsync(T message, string? source = null, public async ValueTask PublishEventAsync(CloudEvent item, CancellationToken cancellationToken = default) { - var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Runtime ?? default); + var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Messenger ?? default); 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, diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs index 164c34b40a2a..47b2e20d3601 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.Logging; namespace Microsoft.AutoGen.Core; -public static class AgentMessengerFactory +public class AgentMessengerFactory(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator, ILogger logger) { public static AgentMessenger Create(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) { diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs index 6de992ae16c6..0d84321bc983 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs @@ -11,39 +11,29 @@ namespace Microsoft.AutoGen.Core; -public class AgentWorker : +public class AgentWorker( +IHostApplicationLifetime hostApplicationLifetime, +IServiceProvider serviceProvider, +[FromKeyedServices("AgentTypes")] IEnumerable> configuredAgentTypes, +DistributedContextPropagator distributedContextPropagator) : IHostedService, IAgentWorker { private readonly ConcurrentDictionary _agentTypes = new(); private readonly ConcurrentDictionary<(string Type, string Key), Agent> _agents = new(); - private readonly ILogger _logger; private readonly Channel _mailbox = Channel.CreateUnbounded(); private readonly ConcurrentDictionary _agentStates = new(); private readonly ConcurrentDictionary _pendingClientRequests = new(); - private readonly CancellationTokenSource _shutdownCts; - private readonly IServiceProvider _serviceProvider; - private readonly IEnumerable> _configuredAgentTypes; + private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping); + private readonly IServiceProvider _serviceProvider = serviceProvider; + private readonly IEnumerable> _configuredAgentTypes = configuredAgentTypes; private readonly ConcurrentDictionary _subscriptionsByAgentType = new(); private readonly ConcurrentDictionary> _subscriptionsByTopic = new(); - private readonly DistributedContextPropagator _distributedContextPropagator; + private readonly DistributedContextPropagator _distributedContextPropagator = distributedContextPropagator; private readonly CancellationTokenSource _shutdownCancellationToken = new(); private Task? _mailboxTask; private readonly object _channelLock = new(); - public AgentWorker( - IHostApplicationLifetime hostApplicationLifetime, - IServiceProvider serviceProvider, - [FromKeyedServices("AgentTypes")] IEnumerable> configuredAgentTypes, - ILogger 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) { From 3fa3cdfacb567b1a38d4ed29cf2d5cf01abfd7f2 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Mon, 16 Dec 2024 20:42:26 -0800 Subject: [PATCH 04/13] wip --- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index d5d76c07d833..40cd133187cb 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -97,10 +97,10 @@ private async ValueTask AddImplicitSubscriptionsAsync() internal Task Start() { var didSuppress = false; - if (!ExecutionRuntime.IsFlowSuppressed()) + if (!ExecutionContext.IsFlowSuppressed()) { didSuppress = true; - ExecutionRuntime.SuppressFlow(); + ExecutionContext.SuppressFlow(); } try @@ -111,7 +111,7 @@ internal Task Start() { if (didSuppress) { - ExecutionRuntime.RestoreFlow(); + ExecutionContext.RestoreFlow(); } } } From cb5f59cec33bfa3c0e916604ab9f2fd4b957e6d7 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 07:32:43 -0800 Subject: [PATCH 05/13] getting rid of IAgentRuntime --- .../Agents/AIAgent/InferenceAgent.cs | 4 ++-- .../Agents/AIAgent/SKAiAgent.cs | 21 +++++++++---------- .../Agents/IOAgent/FileAgent/FileAgent.cs | 4 ++-- .../Agents/IOAgent/IOAgent.cs | 6 ++---- .../Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs | 4 ++-- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 7 ++++--- .../Microsoft.AutoGen/Core/AgentExtensions.cs | 4 ++-- .../Core/AgentMessengerFactory.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/Client.cs | 9 ++------ .../AgentTests.cs | 9 ++++---- 10 files changed, 32 insertions(+), 38 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/InferenceAgent.cs index f4f06db40eef..bfcd7c6cc179 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.Extensions.AI; namespace Microsoft.AutoGen.Agents; public abstract class InferenceAgent( - 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 0aec9a493807..eb1ed50286ab 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.Memory; namespace Microsoft.AutoGen.Agents; -public abstract class SKAiAgent : Agent where T : class, new() +public abstract class SKAiAgent( + IAgentWorker worker, + ISemanticTextMemory memory, + Kernel kernel, + EventTypes typeRegistry) : Agent( + worker, + typeRegistry) where T : class, new() { - protected AgentState _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 _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/FileAgent/FileAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/FileAgent/FileAgent.cs index 7e37a1f0cfc6..ddab8a61ed58 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, IHandle diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/IOAgent.cs index d44e29b775f3..e2b53d694885 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.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(EventTypes eventTypes) : base(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 fe79279ebe5d..3e43096bee29 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 logger, string url = "/agents/webio") : base( - context, + worker, typeRegistry) { _url = url; diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index 40cd133187cb..a1a76c737f97 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -29,7 +29,7 @@ public abstract class Agent /// /// Gets the unique identifier of the agent. /// - public AgentId AgentId => new AgentId(this.GetType().Name, new Guid().ToString()); + public AgentId AgentId { get; private set; } private readonly Channel _mailbox = Channel.CreateUnbounded(); protected internal ILogger _logger; public AgentMessenger Messenger { get; private set; } @@ -43,6 +43,7 @@ protected Agent(IAgentWorker worker, ILogger? logger = null) { EventTypes = eventTypes; + AgentId = new AgentId(this.GetType().Name, new Guid().ToString()); _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger(); _handlersByMessageType = new(GetType().GetHandlersLookupTable()); Messenger = AgentMessengerFactory.Create(AgentId, worker, _logger, DistributedContextPropagator.Current); @@ -245,7 +246,7 @@ protected async Task RequestAsync(AgentId target, string method, Di } }; - var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Messenger ?? default); + var activity = s_source.StartActivity($"Call '{method}'", ActivityKind.Client, Activity.Current?.Context ?? default); activity?.SetTag("peer.service", target.ToString()); var completion = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); @@ -278,7 +279,7 @@ public async ValueTask PublishMessageAsync(T message, string? source = null, public async ValueTask PublishEventAsync(CloudEvent item, CancellationToken cancellationToken = default) { - var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Messenger ?? default); + var activity = s_source.StartActivity($"PublishEventAsync '{item.Type}'", ActivityKind.Client, Activity.Current?.Context ?? default); activity?.SetTag("peer.service", $"{item.Type}/{item.Source}"); // TODO: fix activity diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentExtensions.cs index c18713e84c43..911107f784c5 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 metadata) { Activity? activity; - var (traceParent, traceState) = agent.Runtime.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.Runtime.ExtractMetadata(metadata); + var baggage = agent.Messenger.ExtractMetadata(metadata); foreach (var baggageItem in baggage) { diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs index 47b2e20d3601..ff588a12b78c 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs @@ -6,7 +6,7 @@ using Microsoft.Extensions.Logging; namespace Microsoft.AutoGen.Core; -public class AgentMessengerFactory(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator, ILogger logger) +public class AgentMessengerFactory() { public static AgentMessenger Create(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) { diff --git a/dotnet/src/Microsoft.AutoGen/Core/Client.cs b/dotnet/src/Microsoft.AutoGen/Core/Client.cs index 7f9fae52f0f1..1d523005fedf 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 logger) - : Agent(new AgentMessenger(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/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs index bd169d644b53..79944a6dfed4 100644 --- a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs +++ b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs @@ -23,12 +23,13 @@ public class AgentTests(InMemoryAgentRuntimeFixture fixture) [Fact] public async Task ItInvokeRightHandlerTestAsync() { - var mockContext = new Mock(); + var mockContext = new Mock(); + var mockWorker = new Mock(); mockContext.SetupGet(x => x.AgentId).Returns(new AgentId("test", "test")); // mock SendMessageAsync mockContext.Setup(x => x.SendMessageAsync(It.IsAny(), It.IsAny())) .Returns(new ValueTask()); - var agent = new TestAgent(mockContext.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger(new LoggerFactory())); + var agent = new TestAgent(mockWorker.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger(new LoggerFactory())); await agent.HandleObject("hello world"); await agent.HandleObject(42); @@ -65,9 +66,9 @@ await client.PublishMessageAsync(new TextMessage() public class TestAgent : Agent, IHandle, IHandle, IHandle { public TestAgent( - IAgentRuntime context, + IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes eventTypes, - Logger? logger = null) : base(context, eventTypes, logger) + Logger? logger = null) : base(worker, eventTypes, logger) { } From 71db586b37c4e4e81adda9f0fb11f9d106577ab3 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 07:46:28 -0800 Subject: [PATCH 06/13] build fixup --- README.md | 4 ++-- dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs | 2 ++ dotnet/samples/Hello/HelloAIAgents/Program.cs | 2 ++ dotnet/samples/Hello/HelloAgent/Program.cs | 4 ++-- dotnet/samples/Hello/HelloAgent/README.md | 4 ++-- dotnet/samples/Hello/HelloAgentState/Program.cs | 4 ++-- dotnet/samples/Hello/HelloAgentState/README.md | 4 ++-- dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs | 4 ++-- .../dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs | 4 ++-- .../dev-team/DevTeam.Agents/ProductManager/ProductManager.cs | 4 ++-- dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs | 4 ++-- dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs | 4 ++-- .../Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs | 2 +- 13 files changed, 25 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index caaf3052d6d7..684a587914cf 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, diff --git a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs index 4c1981c061ae..0e195ca5b1dd 100644 --- a/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs +++ b/dotnet/samples/Hello/HelloAIAgents/HelloAIAgent.cs @@ -8,9 +8,11 @@ namespace Hello; [TopicSubscription("agents")] public class HelloAIAgent( + IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IHostApplicationLifetime hostApplicationLifetime, IChatClient client) : HelloAgent( + worker, typeRegistry, hostApplicationLifetime), IHandle diff --git a/dotnet/samples/Hello/HelloAIAgents/Program.cs b/dotnet/samples/Hello/HelloAIAgents/Program.cs index b5696307a408..f9780d62af98 100644 --- a/dotnet/samples/Hello/HelloAIAgents/Program.cs +++ b/dotnet/samples/Hello/HelloAIAgents/Program.cs @@ -33,8 +33,10 @@ namespace Hello { [TopicSubscription("agents")] public class HelloAgent( + IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IHostApplicationLifetime hostApplicationLifetime) : ConsoleAgent( + worker, typeRegistry), ISayHello, IHandle, diff --git a/dotnet/samples/Hello/HelloAgent/Program.cs b/dotnet/samples/Hello/HelloAgent/Program.cs index 7da454774c4c..301d6b7d2b66 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, diff --git a/dotnet/samples/Hello/HelloAgent/README.md b/dotnet/samples/Hello/HelloAgent/README.md index 23051b45cac5..53e3d6a65eba 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, diff --git a/dotnet/samples/Hello/HelloAgentState/Program.cs b/dotnet/samples/Hello/HelloAgentState/Program.cs index f22ad8089983..dbb16c3bbb9b 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, diff --git a/dotnet/samples/Hello/HelloAgentState/README.md b/dotnet/samples/Hello/HelloAgentState/README.md index 2671d8e0de63..f46c66df1e1d 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, diff --git a/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs b/dotnet/samples/dev-team/DevTeam.Agents/Developer/Developer.cs index afddc34f0e63..ffc474a93124 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 @@ namespace DevTeam.Agents; [TopicSubscription("devteam")] -public class Dev(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) - : SKAiAgent(context, memory, kernel, typeRegistry), IDevelopApps, +public class Dev(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) + : SKAiAgent(worker, memory, kernel, typeRegistry), IDevelopApps, IHandle, IHandle { diff --git a/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs b/dotnet/samples/dev-team/DevTeam.Agents/DeveloperLead/DeveloperLead.cs index bda70ebe8773..ffeefe7d430f 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 @@ namespace DevTeam.Agents; [TopicSubscription("devteam")] -public class DeveloperLead(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) - : SKAiAgent(context, memory, kernel, typeRegistry), ILeadDevelopers, +public class DeveloperLead(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) + : SKAiAgent(worker, memory, kernel, typeRegistry), ILeadDevelopers, IHandle, IHandle { diff --git a/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs b/dotnet/samples/dev-team/DevTeam.Agents/ProductManager/ProductManager.cs index 5a89536d0ed4..5306a91838e3 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 @@ namespace DevTeam.Agents; [TopicSubscription("devteam")] -public class ProductManager(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) - : SKAiAgent(context, memory, kernel, typeRegistry), IManageProducts, +public class ProductManager(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, ILogger logger) + : SKAiAgent(worker, memory, kernel, typeRegistry), IManageProducts, IHandle, IHandle { diff --git a/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs b/dotnet/samples/dev-team/DevTeam.Backend/Agents/AzureGenie.cs index c23a62377e9e..85d498bcc5aa 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.Memory; namespace Microsoft.AI.DevTeam; -public class AzureGenie(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageAzure azureService) - : SKAiAgent(context, memory, kernel, typeRegistry), +public class AzureGenie(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageAzure azureService) + : SKAiAgent(worker, memory, kernel, typeRegistry), IHandle, IHandle diff --git a/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs b/dotnet/samples/dev-team/DevTeam.Backend/Agents/Hubber.cs index 3dc9b2a1a87c..3ba0eeb69b25 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 @@ namespace Microsoft.AI.DevTeam; -public class Hubber(IAgentRuntime context, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageGithub ghService) - : SKAiAgent(context, memory, kernel, typeRegistry), +public class Hubber(IAgentWorker worker, Kernel kernel, ISemanticTextMemory memory, [FromKeyedServices("EventTypes")] EventTypes typeRegistry, IManageGithub ghService) + : SKAiAgent(worker, memory, kernel, typeRegistry), IHandle, IHandle, IHandle, diff --git a/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs index 492538f4e62b..7bfe5ab8d786 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([FromKeyedServices("EventTypes")] EventTypes typeRegistry) : base(typeRegistry) + public ConsoleAgent(IAgentWorker worker, [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : base(worker, typeRegistry) { _route = "console"; } From 90afb26a65cb686b3484731cefa08ed217aa07ff Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 08:11:32 -0800 Subject: [PATCH 07/13] format --- dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs index eb1ed50286ab..1d0c57068e13 100644 --- a/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs +++ b/dotnet/src/Microsoft.AutoGen/Agents/AIAgent/SKAiAgent.cs @@ -13,7 +13,7 @@ public abstract class SKAiAgent( ISemanticTextMemory memory, Kernel kernel, EventTypes typeRegistry) : Agent( - worker, + worker, typeRegistry) where T : class, new() { protected AgentState _state = new(); diff --git a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs index a1a76c737f97..84fb80397378 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -90,7 +90,7 @@ private async ValueTask AddImplicitSubscriptionsAsync() } } - + /// /// Starts the message pump for the agent. /// diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs index ff588a12b78c..1f2e7380cc45 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs @@ -12,4 +12,4 @@ public static AgentMessenger Create(AgentId agentId, IAgentWorker worker, ILogge { return new AgentMessenger(agentId, worker, logger, distributedContextPropagator); } -} \ No newline at end of file +} From 26633a6adae6207e9b6edfaf848aa5c2580a0282 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 08:26:02 -0800 Subject: [PATCH 08/13] fix tests --- dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs | 10 +++------- .../test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs | 8 ++++---- 2 files changed, 7 insertions(+), 11 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs index 0d84321bc983..274b10dade78 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs @@ -2,20 +2,17 @@ // 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( IHostApplicationLifetime hostApplicationLifetime, IServiceProvider serviceProvider, -[FromKeyedServices("AgentTypes")] IEnumerable> configuredAgentTypes, -DistributedContextPropagator distributedContextPropagator) : +[FromKeyedServices("AgentTypes")] IEnumerable> configuredAgentTypes) : IHostedService, IAgentWorker { @@ -29,7 +26,6 @@ public class AgentWorker( private readonly IEnumerable> _configuredAgentTypes = configuredAgentTypes; private readonly ConcurrentDictionary _subscriptionsByAgentType = new(); private readonly ConcurrentDictionary> _subscriptionsByTopic = new(); - private readonly DistributedContextPropagator _distributedContextPropagator = distributedContextPropagator; private readonly CancellationTokenSource _shutdownCancellationToken = new(); private Task? _mailboxTask; private readonly object _channelLock = new(); @@ -186,8 +182,8 @@ private Agent GetOrActivateAgent(AgentId agentId) { if (_agentTypes.TryGetValue(agentId.Type, out var agentType)) { - var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); - agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context); + //var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); + agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, this); _agents.TryAdd((agentId.Type, agentId.Key), agent); } else diff --git a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs index 79944a6dfed4..753ec619fbef 100644 --- a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs +++ b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs @@ -23,12 +23,12 @@ public class AgentTests(InMemoryAgentRuntimeFixture fixture) [Fact] public async Task ItInvokeRightHandlerTestAsync() { - var mockContext = new Mock(); + //var mockContext = new Mock(); var mockWorker = new Mock(); - mockContext.SetupGet(x => x.AgentId).Returns(new AgentId("test", "test")); + //mockContext.SetupGet(x => x.AgentId).Returns(new AgentId("test", "test")); // mock SendMessageAsync - mockContext.Setup(x => x.SendMessageAsync(It.IsAny(), It.IsAny())) - .Returns(new ValueTask()); + //mockContext.Setup(x => x.SendMessageAsync(It.IsAny(), It.IsAny())) + // .Returns(new ValueTask()); var agent = new TestAgent(mockWorker.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger(new LoggerFactory())); await agent.HandleObject("hello world"); From 7267e1ff268dee906be8ec460ac5ee62f93a6430 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 09:10:40 -0800 Subject: [PATCH 09/13] fix tests --- dotnet/samples/Hello/HelloAgent/Program.cs | 2 +- .../HelloAppHostIntegrationTests.cs | 2 +- .../InMemoryRuntimeIntegrationTests.cs | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/dotnet/samples/Hello/HelloAgent/Program.cs b/dotnet/samples/Hello/HelloAgent/Program.cs index 301d6b7d2b66..dee73b1a47d3 100644 --- a/dotnet/samples/Hello/HelloAgent/Program.cs +++ b/dotnet/samples/Hello/HelloAgent/Program.cs @@ -35,7 +35,7 @@ public async Task Handle(NewMessageReceived item) 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/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs b/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs index 18b35bd7039c..ba83b07f72df 100644 --- a/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs +++ b/dotnet/test/Microsoft.AutoGen.Integration.Tests/HelloAppHostIntegrationTests.cs @@ -45,7 +45,7 @@ public async Task AppHostLogsHelloAgentE2E(TestEndpoints testEndpoints) //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 0795cf8be61d..b6bdd9eb72d9 100644 --- a/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs +++ b/dotnet/test/Microsoft.AutoGen.Integration.Tests/InMemoryRuntimeIntegrationTests.cs @@ -24,7 +24,7 @@ public async Task HelloAgentsE2EInMemory(string appHostAssemblyPath) 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)); } From 24481c11d3b5d1e0e7adfc29e4786274ceb755c5 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 09:18:36 -0800 Subject: [PATCH 10/13] tests fixup --- .../xlang/hello_python_agent/hello_python_agent.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 c50aacedd5b9..178b91de8826 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!") From 4ab164b86a4795ac06bb1996c916925fd6f3b8af Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 09:30:52 -0800 Subject: [PATCH 11/13] more cleanup --- dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs | 3 +-- dotnet/src/Microsoft.AutoGen/Core/Agent.cs | 2 +- dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs | 6 +----- dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs | 7 ++----- dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs | 1 - dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs | 5 ----- 6 files changed, 5 insertions(+), 19 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs index 38ce279dfeca..ae2b03cddce6 100644 --- a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs @@ -178,8 +178,7 @@ private Agent GetOrActivateAgent(AgentId agentId) { if (_agentTypes.TryGetValue(agentId.Type, out var agentType)) { - var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _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 84fb80397378..48ebc14eb986 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/Agent.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/Agent.cs @@ -46,7 +46,7 @@ protected Agent(IAgentWorker worker, AgentId = new AgentId(this.GetType().Name, new Guid().ToString()); _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger(); _handlersByMessageType = new(GetType().GetHandlersLookupTable()); - Messenger = AgentMessengerFactory.Create(AgentId, worker, _logger, DistributedContextPropagator.Current); + Messenger = AgentMessengerFactory.Create(worker, DistributedContextPropagator.Current); AddImplicitSubscriptionsAsync().AsTask().Wait(); Completion = Start(); } diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs index 003ab293032e..66b1c0c65da9 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessenger.cs @@ -4,18 +4,14 @@ 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 AgentMessenger(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) +public sealed class AgentMessenger(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator) { private readonly IAgentWorker worker = worker; - public AgentId AgentId { get; } = agentId; - private ILogger Logger { get; } = logger; - public Agent? AgentInstance { get; set; } private DistributedContextPropagator DistributedContextPropagator { get; } = distributedContextPropagator; public (string?, string?) GetTraceIdAndState(IDictionary metadata) { diff --git a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs index 1f2e7380cc45..c008f9f2d5aa 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentMessengerFactory.cs @@ -2,14 +2,11 @@ // AgentMessengerFactory.cs using System.Diagnostics; -using Microsoft.AutoGen.Contracts; -using Microsoft.Extensions.Logging; - namespace Microsoft.AutoGen.Core; public class AgentMessengerFactory() { - public static AgentMessenger Create(AgentId agentId, IAgentWorker worker, ILogger logger, DistributedContextPropagator distributedContextPropagator) + public static AgentMessenger Create(IAgentWorker worker, DistributedContextPropagator distributedContextPropagator) { - return new AgentMessenger(agentId, worker, logger, 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 274b10dade78..3b70461a39fd 100644 --- a/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core/AgentWorker.cs @@ -182,7 +182,6 @@ private Agent GetOrActivateAgent(AgentId agentId) { if (_agentTypes.TryGetValue(agentId.Type, out var agentType)) { - //var context = new AgentMessenger(agentId, this, _serviceProvider.GetRequiredService>(), _distributedContextPropagator); agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, this); _agents.TryAdd((agentId.Type, agentId.Key), agent); } diff --git a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs index 753ec619fbef..08a88da048de 100644 --- a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs +++ b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs @@ -23,12 +23,7 @@ public class AgentTests(InMemoryAgentRuntimeFixture fixture) [Fact] public async Task ItInvokeRightHandlerTestAsync() { - //var mockContext = new Mock(); var mockWorker = new Mock(); - //mockContext.SetupGet(x => x.AgentId).Returns(new AgentId("test", "test")); - // mock SendMessageAsync - //mockContext.Setup(x => x.SendMessageAsync(It.IsAny(), It.IsAny())) - // .Returns(new ValueTask()); var agent = new TestAgent(mockWorker.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger(new LoggerFactory())); await agent.HandleObject("hello world"); From d537185a3c32d91dbf95f8bee89bc0ae4c992590 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 09:40:45 -0800 Subject: [PATCH 12/13] format --- dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs | 1 - 1 file changed, 1 deletion(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs index ae2b03cddce6..dbb60e96b322 100644 --- a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs +++ b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs @@ -37,7 +37,6 @@ public sealed class GrpcAgentWorker( private readonly IServiceProvider _serviceProvider = serviceProvider; private readonly IEnumerable> _configuredAgentTypes = configuredAgentTypes; private readonly ILogger _logger = logger; - private readonly DistributedContextPropagator _distributedContextPropagator = distributedContextPropagator; private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping); private AsyncDuplexStreamingCall? _channel; private Task? _readTask; From e32941885428aac4dab7273887165f427625dc40 Mon Sep 17 00:00:00 2001 From: Ryan Sweet Date: Tue, 17 Dec 2024 10:02:29 -0800 Subject: [PATCH 13/13] UNUSED --- dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs index dbb60e96b322..f96f42a2c11b 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> configuredAgentTypes, - ILogger logger, - DistributedContextPropagator distributedContextPropagator) : + ILogger logger) : IHostedService, IDisposable, IAgentWorker { private readonly object _channelLock = new();