Skip to content

Commit 10e40b5

Browse files
authored
Rysweet 5201 refactor runtime interface (#5204)
Changes to align the .NET code more with the python codebase. * rename *Worker to *Runtime * refactor shared runtime elements to AgentRuntimeBase * align runtime interface with python ## Why are these changes needed? Aligning the .NET with the python code and then we can evolve together from there. ## Related issue number Closes #5201
1 parent 42dc80c commit 10e40b5

18 files changed

Lines changed: 499 additions & 438 deletions

File tree

dotnet/samples/dev-team/DevTeam.Backend/Program.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
.AddAgent<ProductManager>(nameof(ProductManager))
3333
.AddAgent<DeveloperLead>(nameof(DeveloperLead));
3434

35-
builder.Services.AddSingleton<AgentWorker>();
35+
builder.Services.AddSingleton<AgentRuntime>();
3636
builder.Services.AddSingleton<WebhookEventProcessor, GithubWebHookProcessor>();
3737
builder.Services.AddSingleton<GithubAuthService>();
3838
builder.Services.AddSingleton<IManageAzure, AzureService>();

dotnet/src/Microsoft.AutoGen/Agents/IOAgent/WebAPIAgent/WebAPIAgent.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ public abstract class WebAPIAgent : IOAgent,
1717
private readonly string _url = "/agents/webio";
1818

1919
public WebAPIAgent(
20-
IAgentWorker worker,
20+
IAgentRuntime worker,
2121
[FromKeyedServices("AgentsMetadata")] AgentsMetadata typeRegistry,
2222
ILogger<WebAPIAgent> logger,
2323
string url = "/agents/webio") : base(

dotnet/src/Microsoft.AutoGen/Core.Grpc/App.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ public static async ValueTask<IHost> PublishMessageAsync(
4646
await StartAsync(builder, agents, local);
4747
}
4848
var client = Host.Services.GetRequiredService<Client>() ?? throw new InvalidOperationException("Host not started");
49-
await client.PublishEventAsync(topic, message, new CancellationToken()).ConfigureAwait(true);
49+
await client.PublishMessageAsync(message, topic, token: new CancellationToken()).ConfigureAwait(true);
5050
return Host;
5151
}
5252
public static async ValueTask ShutdownAsync()

dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorker.cs renamed to dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentRuntime.cs

Lines changed: 23 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Copyright (c) Microsoft Corporation. All rights reserved.
2-
// GrpcAgentWorker.cs
2+
// GrpcAgentRuntime.cs
33

44
using System.Collections.Concurrent;
55
using System.Reflection;
@@ -12,13 +12,17 @@
1212

1313
namespace Microsoft.AutoGen.Core.Grpc;
1414

15-
public sealed class GrpcAgentWorker(
15+
public sealed class GrpcAgentRuntime(
1616
AgentRpc.AgentRpcClient client,
1717
IHostApplicationLifetime hostApplicationLifetime,
1818
IServiceProvider serviceProvider,
1919
[FromKeyedServices("AgentTypes")] IEnumerable<Tuple<string, Type>> configuredAgentTypes,
20-
ILogger<GrpcAgentWorker> logger) :
21-
IHostedService, IDisposable, IAgentWorker
20+
ILogger<GrpcAgentRuntime> logger
21+
) : AgentRuntime(
22+
hostApplicationLifetime,
23+
serviceProvider,
24+
configuredAgentTypes
25+
), IDisposable
2226
{
2327
private readonly object _channelLock = new();
2428
private readonly ConcurrentDictionary<string, Type> _agentTypes = new();
@@ -35,13 +39,11 @@ public sealed class GrpcAgentWorker(
3539
private readonly AgentRpc.AgentRpcClient _client = client;
3640
public readonly IServiceProvider ServiceProvider = serviceProvider;
3741
private readonly IEnumerable<Tuple<string, Type>> _configuredAgentTypes = configuredAgentTypes;
38-
private readonly ILogger<GrpcAgentWorker> _logger = logger;
42+
private readonly ILogger<GrpcAgentRuntime> _logger = logger;
3943
private readonly CancellationTokenSource _shutdownCts = CancellationTokenSource.CreateLinkedTokenSource(hostApplicationLifetime.ApplicationStopping);
4044
private AsyncDuplexStreamingCall<Message, Message>? _channel;
4145
private Task? _readTask;
4246
private Task? _writeTask;
43-
44-
IServiceProvider IAgentWorker.ServiceProvider => ServiceProvider;
4547
public void Dispose()
4648
{
4749
_outboundMessagesChannel.Writer.TryComplete();
@@ -289,25 +291,24 @@ await WriteChannelAsync(new Message
289291
}
290292
}
291293
// new is intentional
292-
public async ValueTask SendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default)
294+
public new async ValueTask RuntimeSendResponseAsync(RpcResponse response, CancellationToken cancellationToken = default)
293295
{
294296
await WriteChannelAsync(new Message { Response = response }, cancellationToken).ConfigureAwait(false);
295297
}
296298

297-
public async ValueTask SendRequestAsync(Agent agent, RpcRequest request, CancellationToken cancellationToken = default)
299+
public new async ValueTask RuntimeSendRequestAsync(Agent agent, RpcRequest request, CancellationToken cancellationToken = default)
298300
{
299301
var requestId = Guid.NewGuid().ToString();
300302
_pendingRequests[requestId] = (agent, request.RequestId);
301303
request.RequestId = requestId;
302304
await WriteChannelAsync(new Message { Request = request }, cancellationToken).ConfigureAwait(false);
303305
}
304-
305-
public async ValueTask SendMessageAsync(Message message, CancellationToken cancellationToken = default)
306+
public new async ValueTask RuntimeWriteMessage(Message message, CancellationToken cancellationToken = default)
306307
{
307308
await WriteChannelAsync(message, cancellationToken).ConfigureAwait(false);
308309
}
309310

310-
public async ValueTask PublishEventAsync(CloudEvent @event, CancellationToken cancellationToken = default)
311+
public async ValueTask RuntimePublishEventAsync(CloudEvent @event, CancellationToken cancellationToken = default)
311312
{
312313
await WriteChannelAsync(new Message { CloudEvent = @event }, cancellationToken).ConfigureAwait(false);
313314
}
@@ -350,11 +351,10 @@ private AsyncDuplexStreamingCall<Message, Message> RecreateChannel(AsyncDuplexSt
350351

351352
return _channel;
352353
}
353-
354-
public async Task StartAsync(CancellationToken cancellationToken)
354+
public new async Task StartAsync(CancellationToken cancellationToken)
355355
{
356356
_channel = GetChannel();
357-
_logger.LogInformation("Starting GrpcAgentWorker, connecting to gRPC endpoint " + Environment.GetEnvironmentVariable("AGENT_HOST"));
357+
_logger.LogInformation("Starting " + GetType().Name + ",connecting to gRPC endpoint " + Environment.GetEnvironmentVariable("AGENT_HOST"));
358358

359359
StartCore();
360360

@@ -389,8 +389,7 @@ void StartCore()
389389
}
390390
}
391391
}
392-
393-
public async Task StopAsync(CancellationToken cancellationToken)
392+
public new async Task StopAsync(CancellationToken cancellationToken)
394393
{
395394
_shutdownCts.Cancel();
396395

@@ -410,8 +409,7 @@ public async Task StopAsync(CancellationToken cancellationToken)
410409
_channel?.Dispose();
411410
}
412411
}
413-
414-
public async ValueTask StoreAsync(AgentState value, CancellationToken cancellationToken = default)
412+
public new async ValueTask SaveStateAsync(AgentState value, CancellationToken cancellationToken = default)
415413
{
416414
var agentId = value.AgentId ?? throw new InvalidOperationException("AgentId is required when saving AgentState.");
417415
var response = _client.SaveState(value, null, null, cancellationToken);
@@ -421,7 +419,7 @@ public async ValueTask StoreAsync(AgentState value, CancellationToken cancellati
421419
}
422420
}
423421

424-
public async ValueTask<AgentState> ReadAsync(AgentId agentId, CancellationToken cancellationToken = default)
422+
public new async ValueTask<AgentState> LoadStateAsync(AgentId agentId, CancellationToken cancellationToken = default)
425423
{
426424
var response = await _client.GetStateAsync(agentId).ConfigureAwait(true);
427425
// if (response.Success && response.AgentState.AgentId is not null) - why is success always false?
@@ -434,20 +432,20 @@ public async ValueTask<AgentState> ReadAsync(AgentId agentId, CancellationToken
434432
throw new KeyNotFoundException($"Failed to read AgentState for {agentId}.");
435433
}
436434
}
437-
public async ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default)
435+
public new async ValueTask<List<Subscription>> GetSubscriptionsAsync(GetSubscriptionsRequest request, CancellationToken cancellationToken = default)
438436
{
439437
var response = await _client.GetSubscriptionsAsync(request, null, null, cancellationToken);
440438
return response.Subscriptions.ToList();
441439
}
442-
public ValueTask<AddSubscriptionResponse> SubscribeAsync(AddSubscriptionRequest request, CancellationToken cancellationToken = default)
440+
public new async Task<AddSubscriptionResponse> AddSubscriptionAsync(AddSubscriptionRequest request, CancellationToken cancellationToken = default)
443441
{
444442
var response = _client.AddSubscription(request, null, null, cancellationToken);
445-
return new ValueTask<AddSubscriptionResponse>(response);
443+
return response;
446444
}
447-
public ValueTask<RemoveSubscriptionResponse> UnsubscribeAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default)
445+
public new async ValueTask<RemoveSubscriptionResponse> RemoveSubscriptionAsync(RemoveSubscriptionRequest request, CancellationToken cancellationToken = default)
448446
{
449447
var response = _client.RemoveSubscription(request, null, null, cancellationToken);
450-
return new ValueTask<RemoveSubscriptionResponse>(response);
448+
return response;
451449
}
452450
}
453451

dotnet/src/Microsoft.AutoGen/Core.Grpc/GrpcAgentWorkerHostBuilderExtension.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -63,15 +63,15 @@ public static IHostApplicationBuilder AddGrpcAgentWorker(this IHostApplicationBu
6363
});
6464
var assemblies = AppDomain.CurrentDomain.GetAssemblies();
6565
builder.Services.TryAddSingleton(DistributedContextPropagator.Current);
66-
builder.Services.AddSingleton<IAgentWorker, GrpcAgentWorker>();
67-
builder.Services.AddSingleton<IHostedService>(sp => (IHostedService)sp.GetRequiredService<IAgentWorker>());
66+
builder.Services.AddSingleton<IAgentRuntime, GrpcAgentRuntime>();
67+
builder.Services.AddSingleton<IHostedService>(sp => (IHostedService)sp.GetRequiredService<IAgentRuntime>());
6868
builder.Services.AddKeyedSingleton("AgentsMetadata", (sp, key) =>
6969
{
7070
return ReflectionHelper.GetAgentsMetadata(assemblies);
7171
});
7272
builder.Services.AddSingleton((s) =>
7373
{
74-
var worker = s.GetRequiredService<IAgentWorker>();
74+
var worker = s.GetRequiredService<IAgentRuntime>();
7575
var client = ActivatorUtilities.CreateInstance<Client>(s);
7676
Agent.Initialize(worker, client);
7777
return client;

0 commit comments

Comments
 (0)