A programming framework for agentic AI
refactor renaming agent base - 4667 (#4669)
Ryan Sweetc9ebe32bd787
diff --git a/dotnet/samples/Hello/HelloAgent/Program.cs b/dotnet/samples/Hello/HelloAgent/Program.csindex ce3fed2f6..66c020258 100644--- a/dotnet/samples/Hello/HelloAgent/Program.cs+++ b/dotnet/samples/Hello/HelloAgent/Program.cs@@ -19,7 +19,7 @@ namespace Hello[TopicSubscription("agents")]public class HelloAgent(IAgentRuntime context, IHostApplicationLifetime hostApplicationLifetime,- [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : AgentBase(+ [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : Agent(context,typeRegistry),ISayHello,diff --git a/dotnet/samples/Hello/HelloAgentState/Program.cs b/dotnet/samples/Hello/HelloAgentState/Program.csindex e3c9dd212..e260c9e11 100644--- a/dotnet/samples/Hello/HelloAgentState/Program.cs+++ b/dotnet/samples/Hello/HelloAgentState/Program.cs@@ -19,7 +19,7 @@ namespace Hellopublic class HelloAgent(IAgentRuntime context,IHostApplicationLifetime hostApplicationLifetime,- [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : AgentBase(+ [FromKeyedServices("EventTypes")] EventTypes typeRegistry) : Agent(context,typeRegistry),IHandleConsole,diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AgentBase.cs b/dotnet/src/Microsoft.AutoGen/Agents/Agent.cssimilarity index 94%rename from dotnet/src/Microsoft.AutoGen/Agents/AgentBase.csrename to dotnet/src/Microsoft.AutoGen/Agents/Agent.csindex da3337ab0..39ba48733 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/AgentBase.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Agent.cs@@ -1,5 +1,5 @@// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentBase.cs+// Agent.csusing System.Diagnostics;using System.Reflection;@@ -12,7 +12,7 @@ using Microsoft.Extensions.Logging;namespace Microsoft.AutoGen.Agents;-public abstract class AgentBase : IAgentBase, IHandle+public abstract class Agent : IAgentBase, IHandle{public static readonly ActivitySource s_source = new("AutoGen.Agent");public AgentId AgentId => _runtime.AgentId;@@ -23,19 +23,19 @@ public abstract class AgentBase : IAgentBase, IHandleprivate readonly IAgentRuntime _runtime;public string Route { get; set; } = "base";- protected internal ILogger<AgentBase> _logger;+ protected internal ILogger<Agent> _logger;public IAgentRuntime Context => _runtime;protected readonly EventTypes EventTypes;- protected AgentBase(+ protected Agent(IAgentRuntime runtime,EventTypes eventTypes,- ILogger<AgentBase>? logger = null)+ ILogger<Agent>? logger = null){_runtime = runtime;runtime.AgentInstance = this;this.EventTypes = eventTypes;- _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger<AgentBase>();+ _logger = logger ?? LoggerFactory.Create(builder => { }).CreateLogger<Agent>();AddImplicitSubscriptionsAsync().AsTask().Wait();Completion = Start();}@@ -133,7 +133,7 @@ public abstract class AgentBase : IAgentBase, IHandle{var activity = this.ExtractActivity(msg.CloudEvent.Type, msg.CloudEvent.Attributes);await this.InvokeWithActivityAsync(- static ((AgentBase Agent, CloudEvent Item) state, CancellationToken _) => state.Agent.CallHandler(state.Item),+ static ((Agent Agent, CloudEvent Item) state, CancellationToken _) => state.Agent.CallHandler(state.Item),(this, msg.CloudEvent),activity,msg.CloudEvent.Type, cancellationToken).ConfigureAwait(false);@@ -143,7 +143,7 @@ public abstract class AgentBase : IAgentBase, IHandle{var activity = this.ExtractActivity(msg.Request.Method, msg.Request.Metadata);await this.InvokeWithActivityAsync(- static ((AgentBase Agent, RpcRequest Request) state, CancellationToken ct) => state.Agent.OnRequestCoreAsync(state.Request, ct),+ static ((Agent Agent, RpcRequest Request) state, CancellationToken ct) => state.Agent.OnRequestCoreAsync(state.Request, ct),(this, msg.Request),activity,msg.Request.Method, cancellationToken).ConfigureAwait(false);@@ -237,7 +237,7 @@ public abstract class AgentBase : IAgentBase, IHandlevar completion = new TaskCompletionSource<RpcResponse>(TaskCreationOptions.RunContinuationsAsynchronously);_runtime.Update(request, activity);await this.InvokeWithActivityAsync(- static async ((AgentBase Agent, RpcRequest Request, TaskCompletionSource<RpcResponse>) state, CancellationToken ct) =>+ static async ((Agent Agent, RpcRequest Request, TaskCompletionSource<RpcResponse>) state, CancellationToken ct) =>{var (self, request, completion) = state;@@ -273,7 +273,7 @@ public abstract class AgentBase : IAgentBase, IHandle// TODO: fix activity_runtime.Update(item, activity);await this.InvokeWithActivityAsync(- static async ((AgentBase Agent, CloudEvent Event) state, CancellationToken ct) =>+ static async ((Agent Agent, CloudEvent Event) state, CancellationToken ct) =>{await state.Agent._runtime.PublishEventAsync(state.Event).ConfigureAwait(false);},diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AgentBaseExtensions.cs b/dotnet/src/Microsoft.AutoGen/Agents/AgentExtensions.cssimilarity index 83%rename from dotnet/src/Microsoft.AutoGen/Agents/AgentBaseExtensions.csrename to dotnet/src/Microsoft.AutoGen/Agents/AgentExtensions.csindex 38098e5dd..c92b2b6ff 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/AgentBaseExtensions.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/AgentExtensions.cs@@ -1,5 +1,5 @@// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentBaseExtensions.cs+// AgentExtensions.csusing System.Diagnostics;using Google.Protobuf.Collections;@@ -8,9 +8,9 @@ using static Microsoft.AutoGen.Abstractions.CloudEvent.Types;namespace Microsoft.AutoGen.Agents;/// <summary>-/// Provides extension methods for the <see cref="AgentBase"/> class.+/// Provides extension methods for the <see cref="Agent"/> class./// </summary>-public static class AgentBaseExtensions+public static class AgentExtensions{/// <summary>/// Extracts an <see cref="Activity"/> from the given agent and metadata.@@ -19,7 +19,7 @@ public static class AgentBaseExtensions/// <param name="activityName">The name of the activity.</param>/// <param name="metadata">The metadata containing trace information.</param>/// <returns>The extracted <see cref="Activity"/> or null if extraction fails.</returns>- public static Activity? ExtractActivity(this AgentBase agent, string activityName, IDictionary<string, string> metadata)+ public static Activity? ExtractActivity(this Agent agent, string activityName, IDictionary<string, string> metadata){Activity? activity;var (traceParent, traceState) = agent.Context.GetTraceIdAndState(metadata);@@ -28,12 +28,12 @@ public static class AgentBaseExtensionsif (ActivityContext.TryParse(traceParent, traceState, isRemote: true, out var parentContext)){// traceParent is a W3CId- activity = AgentBase.s_source.CreateActivity(activityName, ActivityKind.Server, parentContext);+ activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server, parentContext);}else{// Most likely, traceParent uses ActivityIdFormat.Hierarchical- activity = AgentBase.s_source.CreateActivity(activityName, ActivityKind.Server, traceParent);+ activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server, traceParent);}if (activity is not null)@@ -53,13 +53,13 @@ public static class AgentBaseExtensions}else{- activity = AgentBase.s_source.CreateActivity(activityName, ActivityKind.Server);+ activity = Agent.s_source.CreateActivity(activityName, ActivityKind.Server);}return activity;}- public static Activity? ExtractActivity(this AgentBase agent, string activityName, MapField<string, CloudEventAttributeValue> metadata)+ public static Activity? ExtractActivity(this Agent agent, string activityName, MapField<string, CloudEventAttributeValue> metadata){return ExtractActivity(agent, activityName, metadata.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.CeString));}@@ -75,7 +75,7 @@ public static class AgentBaseExtensions/// <param name="methodName">The name of the method being invoked.</param>/// <param name="cancellationToken">A token to monitor for cancellation requests.</param>/// <returns>A task representing the asynchronous operation.</returns>- public static async Task InvokeWithActivityAsync<TState>(this AgentBase agent, Func<TState, CancellationToken, Task> func, TState state, Activity? activity, string methodName, CancellationToken cancellationToken = default)+ public static async Task InvokeWithActivityAsync<TState>(this Agent agent, Func<TState, CancellationToken, Task> func, TState state, Activity? activity, string methodName, CancellationToken cancellationToken = default){if (activity is not null && activity.StartTimeUtc == default){diff --git a/dotnet/src/Microsoft.AutoGen/Agents/AgentRuntime.cs b/dotnet/src/Microsoft.AutoGen/Agents/AgentRuntime.csindex efa5fe1b6..8dbaf73cb 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/AgentRuntime.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/AgentRuntime.cs@@ -9,12 +9,12 @@ using static Microsoft.AutoGen.Abstractions.CloudEvent.Types;namespace Microsoft.AutoGen.Agents;-internal sealed class AgentRuntime(AgentId agentId, IAgentWorker worker, ILogger<AgentBase> logger, DistributedContextPropagator distributedContextPropagator) : IAgentRuntime+internal sealed class AgentRuntime(AgentId agentId, IAgentWorker worker, ILogger<Agent> logger, DistributedContextPropagator distributedContextPropagator) : IAgentRuntime{private readonly IAgentWorker worker = worker;public AgentId AgentId { get; } = agentId;- public ILogger<AgentBase> Logger { get; } = logger;+ public ILogger<Agent> Logger { get; } = logger;public IAgentBase? AgentInstance { get; set; }private DistributedContextPropagator DistributedContextPropagator { get; } = distributedContextPropagator;public (string?, string?) GetTraceIdAndState(IDictionary<string, string> metadata)diff --git a/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/InferenceAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/InferenceAgent.csindex bf68467e3..c4c2163a0 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/InferenceAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/InferenceAgent.cs@@ -9,7 +9,7 @@ public abstract class InferenceAgent<T>(IAgentRuntime context,EventTypes typeRegistry,IChatClient client)- : AgentBase(context, typeRegistry)+ : Agent(context, typeRegistry)where T : IMessage, new(){protected IChatClient ChatClient { get; } = client;diff --git a/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/SKAiAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/SKAiAgent.csindex db0d8241f..80dfa49f0 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/SKAiAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Agents/AIAgent/SKAiAgent.cs@@ -9,7 +9,7 @@ using Microsoft.SemanticKernel.Connectors.OpenAI;using Microsoft.SemanticKernel.Memory;namespace Microsoft.AutoGen.Agents;-public abstract class SKAiAgent<T> : AgentBase where T : class, new()+public abstract class SKAiAgent<T> : Agent where T : class, new(){protected AgentState<T> _state;protected Kernel _kernel;diff --git a/dotnet/src/Microsoft.AutoGen/Agents/Agents/IOAgent/IOAgent.cs b/dotnet/src/Microsoft.AutoGen/Agents/Agents/IOAgent/IOAgent.csindex fdd685240..dd86e6edd 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Agents/IOAgent/IOAgent.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Agents/IOAgent/IOAgent.cs@@ -5,7 +5,7 @@ using Microsoft.AutoGen.Abstractions;namespace Microsoft.AutoGen.Agents;-public abstract class IOAgent : AgentBase+public abstract class IOAgent : Agent{public string _route = "base";protected IOAgent(IAgentRuntime context, EventTypes eventTypes) : base(context, eventTypes)diff --git a/dotnet/src/Microsoft.AutoGen/Agents/Client.cs b/dotnet/src/Microsoft.AutoGen/Agents/Client.csindex 313685d79..05f988e1d 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Client.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Client.cs@@ -9,6 +9,6 @@ using Microsoft.Extensions.Logging;namespace Microsoft.AutoGen.Agents;public sealed class Client(IAgentWorker runtime, DistributedContextPropagator distributedContextPropagator,[FromKeyedServices("EventTypes")] EventTypes eventTypes, ILogger<Client> logger)- : AgentBase(new AgentRuntime(new AgentId("client", Guid.NewGuid().ToString()), runtime, logger, distributedContextPropagator), eventTypes)+ : Agent(new AgentRuntime(new AgentId("client", Guid.NewGuid().ToString()), runtime, logger, distributedContextPropagator), eventTypes){}diff --git a/dotnet/src/Microsoft.AutoGen/Agents/Services/AgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Agents/Services/AgentWorker.csindex f9a505053..ffa1aea1f 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Services/AgentWorker.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Services/AgentWorker.cs@@ -196,8 +196,8 @@ public class AgentWorker :{if (_agentTypes.TryGetValue(agentId.Type, out var agentType)){- var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<AgentBase>>(), _distributedContextPropagator);- agent = (AgentBase)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);+ var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<Agent>>(), _distributedContextPropagator);+ agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);_agents.TryAdd((agentId.Type, agentId.Key), agent);}elsediff --git a/dotnet/src/Microsoft.AutoGen/Agents/Services/Grpc/GrpcAgentWorker.cs b/dotnet/src/Microsoft.AutoGen/Agents/Services/Grpc/GrpcAgentWorker.csindex 636bca487..34ef328dd 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Services/Grpc/GrpcAgentWorker.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Services/Grpc/GrpcAgentWorker.cs@@ -193,8 +193,8 @@ public sealed class GrpcAgentWorker({if (_agentTypes.TryGetValue(agentId.Type, out var agentType)){- var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<AgentBase>>(), _distributedContextPropagator);- agent = (AgentBase)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);+ var context = new AgentRuntime(agentId, this, _serviceProvider.GetRequiredService<ILogger<Agent>>(), _distributedContextPropagator);+ agent = (Agent)ActivatorUtilities.CreateInstance(_serviceProvider, agentType, context);_agents.TryAdd((agentId.Type, agentId.Key), agent);}elsediff --git a/dotnet/src/Microsoft.AutoGen/Agents/Services/HostBuilderExtensions.cs b/dotnet/src/Microsoft.AutoGen/Agents/Services/HostBuilderExtensions.csindex f21096ccf..533349125 100644--- a/dotnet/src/Microsoft.AutoGen/Agents/Services/HostBuilderExtensions.cs+++ b/dotnet/src/Microsoft.AutoGen/Agents/Services/HostBuilderExtensions.cs@@ -18,7 +18,7 @@ public static class HostBuilderExtensionsprivate const string _defaultAgentServiceAddress = "https://localhost:53071";public static IHostApplicationBuilder AddAgent<- [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(this IHostApplicationBuilder builder, string typeName) where TAgent : AgentBase+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(this IHostApplicationBuilder builder, string typeName) where TAgent : Agent{builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, typeof(TAgent)));@@ -60,7 +60,7 @@ public static class HostBuilderExtensionsvar eventsMap = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes())- .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(AgentBase)) && !type.IsAbstract)+ .Where(type => type != null && ReflectionHelper.IsSubclassOfGeneric(type, typeof(Agent)) && !type.IsAbstract).Select(t => (t, t.GetInterfaces().Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandle<>)).Select(i => (GetMessageDescriptor(i.GetGenericArguments().First())?.FullName ?? "")).ToHashSet()))@@ -68,7 +68,7 @@ public static class HostBuilderExtensions// if the assembly contains any interfaces of type IHandler, then add all the methods of the interface to the eventsMapvar handlersMap = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes())- .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(AgentBase)) && !type.IsAbstract)+ .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(Agent)) && !type.IsAbstract).Select(t => (t, t.GetMethods().Where(m => m.Name == "Handle").Select(m => (GetMessageDescriptor(m.GetParameters().First().ParameterType)?.FullName ?? "")).ToHashSet()))@@ -76,7 +76,7 @@ public static class HostBuilderExtensions// get interfaces implemented by the agent and get the methods of the interface if they are named Handlevar ifaceHandlersMap = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes())- .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(AgentBase)) && !type.IsAbstract)+ .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(Agent)) && !type.IsAbstract).Select(t => t.GetInterfaces().Select(i => (t, i, i.GetMethods().Where(m => m.Name == "Handle")@@ -151,7 +151,7 @@ public sealed class AgentTypes(Dictionary<string, Type> types){var agents = AppDomain.CurrentDomain.GetAssemblies().SelectMany(assembly => assembly.GetTypes())- .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(AgentBase))+ .Where(type => ReflectionHelper.IsSubclassOfGeneric(type, typeof(Agent))&& !type.IsAbstract&& !type.Name.Equals(nameof(Client))).ToDictionary(type => type.Name, type => type);@@ -169,7 +169,7 @@ public sealed class EventTypes(TypeRegistry typeRegistry, Dictionary<string, Typpublic sealed class AgentApplicationBuilder(IHostApplicationBuilder builder){public AgentApplicationBuilder AddAgent<- [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(string typeName) where TAgent : AgentBase+ [DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicConstructors)] TAgent>(string typeName) where TAgent : Agent{builder.Services.AddKeyedSingleton("AgentTypes", (sp, key) => Tuple.Create(typeName, typeof(TAgent)));return this;diff --git a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentBaseTests.cs b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cssimilarity index 90%rename from dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentBaseTests.csrename to dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.csindex 7e272ce6b..35a7cb4c2 100644--- a/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentBaseTests.cs+++ b/dotnet/test/Microsoft.AutoGen.Agents.Tests/AgentTests.cs@@ -1,5 +1,5 @@// Copyright (c) Microsoft Corporation. All rights reserved.-// AgentBaseTests.cs+// AgentTests.csusing System.Collections.Concurrent;using FluentAssertions;@@ -10,12 +10,12 @@ using Microsoft.Extensions.Hosting;using Microsoft.Extensions.Logging;using Moq;using Xunit;-using static Microsoft.AutoGen.Agents.Tests.AgentBaseTests;+using static Microsoft.AutoGen.Agents.Tests.AgentTests;namespace Microsoft.AutoGen.Agents.Tests;[Collection(ClusterFixtureCollection.Name)]-public class AgentBaseTests(InMemoryAgentRuntimeFixture fixture)+public class AgentTests(InMemoryAgentRuntimeFixture fixture){private readonly InMemoryAgentRuntimeFixture _fixture = fixture;@@ -27,7 +27,7 @@ public class AgentBaseTests(InMemoryAgentRuntimeFixture fixture)// mock SendMessageAsyncmockContext.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<AgentBase>(new LoggerFactory()));+ var agent = new TestAgent(mockContext.Object, new EventTypes(TypeRegistry.Empty, [], []), new Logger<Agent>(new LoggerFactory()));await agent.HandleObject("hello world");await agent.HandleObject(42);@@ -61,12 +61,12 @@ public class AgentBaseTests(InMemoryAgentRuntimeFixture fixture)/// <summary>/// The test agent is a simple agent that is used for testing purposes./// </summary>- public class TestAgent : AgentBase, IHandle<string>, IHandle<int>, IHandle<TextMessage>+ public class TestAgent : Agent, IHandle<string>, IHandle<int>, IHandle<TextMessage>{public TestAgent(IAgentRuntime context,[FromKeyedServices("EventTypes")] EventTypes eventTypes,- Logger<AgentBase>? logger = null) : base(context, eventTypes, logger)+ Logger<Agent>? logger = null) : base(context, eventTypes, logger){}