Skip to content

Commit e400567

Browse files
authored
Rysweet hello fix (#3683)
Fixing the HelloWorld sample and some refactoring of .NET code, adding App and Host classes in client and runtime.
1 parent 39aa073 commit e400567

File tree

17 files changed

+173
-67
lines changed

17 files changed

+173
-67
lines changed

dotnet/AutoGen.sln

+7-3
Original file line numberDiff line numberDiff line change
@@ -93,9 +93,6 @@ EndProject
9393
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "AgentChat", "AgentChat", "{C7A2D42D-9277-47AC-862B-D86DF9D6AD48}"
9494
EndProject
9595
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "dev-team", "dev-team", "{616F30DF-1F41-4047-BAA4-64BA03BF5AEA}"
96-
ProjectSection(SolutionItems) = preProject
97-
samples\dev-team\DevTeam.ServiceDefaults\DevTeam.ServiceDefaults.csproj = samples\dev-team\DevTeam.ServiceDefaults\DevTeam.ServiceDefaults.csproj
98-
EndProjectSection
9996
EndProject
10097
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DevTeam.AgentHost", "samples\dev-team\DevTeam.AgentHost\DevTeam.AgentHost.csproj", "{7228A701-C79D-4E15-BF45-48D11F721A84}"
10198
EndProject
@@ -127,6 +124,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "HelloAgents.Web", "samples\
127124
EndProject
128125
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Hello", "samples\Hello\Hello.csproj", "{6C9135E6-9D15-4D86-B3F4-9666DB87060A}"
129126
EndProject
127+
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Microsoft.AutoGen.ServiceDefaults", "src\Microsoft.AutoGen.ServiceDefaults\Microsoft.AutoGen.ServiceDefaults.csproj", "{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D}"
128+
EndProject
130129
Global
131130
GlobalSection(SolutionConfigurationPlatforms) = preSolution
132131
Debug|Any CPU = Debug|Any CPU
@@ -337,6 +336,10 @@ Global
337336
{6C9135E6-9D15-4D86-B3F4-9666DB87060A}.Debug|Any CPU.Build.0 = Debug|Any CPU
338337
{6C9135E6-9D15-4D86-B3F4-9666DB87060A}.Release|Any CPU.ActiveCfg = Release|Any CPU
339338
{6C9135E6-9D15-4D86-B3F4-9666DB87060A}.Release|Any CPU.Build.0 = Release|Any CPU
339+
{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
340+
{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D}.Debug|Any CPU.Build.0 = Debug|Any CPU
341+
{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D}.Release|Any CPU.ActiveCfg = Release|Any CPU
342+
{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D}.Release|Any CPU.Build.0 = Release|Any CPU
340343
EndGlobalSection
341344
GlobalSection(SolutionProperties) = preSolution
342345
HideSolutionNode = FALSE
@@ -397,6 +400,7 @@ Global
397400
{6B88F4B3-26AB-4034-B0AC-5BA6EEDEB8E5} = {F7AC0FF1-8500-49C6-8CB3-97C6D52C8BEF}
398401
{8B56BE22-5CF4-44BB-AFA5-732FEA2AFF0B} = {F7AC0FF1-8500-49C6-8CB3-97C6D52C8BEF}
399402
{6C9135E6-9D15-4D86-B3F4-9666DB87060A} = {FBFEAD1F-29EB-4D99-A672-0CD8473E10B9}
403+
{F70C6FD7-9615-4EDD-8D55-5460FCC5A46D} = {18BF8DD7-0585-48BF-8F97-AD333080CE06}
400404
EndGlobalSection
401405
GlobalSection(ExtensibilityGlobals) = postSolution
402406
SolutionGuid = {93384647-528D-46C8-922C-8DB36A382F0B}

dotnet/samples/Hello/Program.cs

+18-20
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,15 @@
11
using Microsoft.AutoGen.Agents.Abstractions;
22
using Microsoft.AutoGen.Agents.Client;
3-
using Microsoft.AutoGen.Agents.Runtime;
43
using Microsoft.Extensions.DependencyInjection;
54
using Microsoft.Extensions.Hosting;
65

7-
var builder = Host.CreateApplicationBuilder(args);
8-
builder.AddAgentService();
9-
builder.UseOrleans(siloBuilder =>
10-
{
11-
siloBuilder.UseLocalhostClustering(); ;
12-
});
13-
builder.AddAgentWorker("https://localhost:5000");
14-
var app = builder.Build();
15-
await app.StartAsync();
16-
app.Services.GetRequiredService<AgentWorkerRuntime>();
17-
var evt = new NewMessageReceived
6+
// send a message to the agent
7+
var app = await App.PublishMessageAsync("HelloAgents", new NewMessageReceived
188
{
199
Message = "World"
20-
}.ToCloudEvent("HelloAgents");
10+
}, local: true);
11+
12+
await App.RuntimeApp!.WaitForShutdownAsync();
2113
await app.WaitForShutdownAsync();
2214

2315
[TopicSubscription("HelloAgents")]
@@ -32,27 +24,33 @@ public class HelloAgent(
3224
{
3325
public async Task Handle(NewMessageReceived item)
3426
{
35-
var response = await SayHello(item.Message);
27+
var response = await SayHello(item.Message).ConfigureAwait(false);
3628
var evt = new Output
3729
{
3830
Message = response
3931
}.ToCloudEvent(this.AgentId.Key);
40-
await PublishEvent(evt);
32+
await PublishEvent(evt).ConfigureAwait(false);
33+
var goodbye = new ConversationClosed
34+
{
35+
UserId = this.AgentId.Key,
36+
UserMessage = "Goodbye"
37+
}.ToCloudEvent(this.AgentId.Key);
38+
await PublishEvent(goodbye).ConfigureAwait(false);
4139
}
42-
4340
public async Task Handle(ConversationClosed item)
4441
{
45-
var goodbye = "Goodbye!";
42+
var goodbye = $"********************* {item.UserId} said {item.UserMessage} ************************";
4643
var evt = new Output
4744
{
4845
Message = goodbye
4946
}.ToCloudEvent(this.AgentId.Key);
50-
await PublishEvent(evt);
47+
await PublishEvent(evt).ConfigureAwait(false);
48+
await Task.Delay(60000);
49+
await App.ShutdownAsync();
5150
}
52-
5351
public async Task<string> SayHello(string ask)
5452
{
55-
var response = $"Hello {ask}";
53+
var response = $"\n\n\n\n***************Hello {ask}**********************\n\n\n\n";
5654
return response;
5755
}
5856
}

dotnet/samples/dev-team/DevTeam.AgentHost/DevTeam.AgentHost.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
<ItemGroup>
1212
<ProjectReference Include="../../../src/Microsoft.AutoGen.Agents.Runtime/Microsoft.AutoGen.Agents.Runtime.csproj" />
13-
<ProjectReference Include="..\DevTeam.ServiceDefaults\DevTeam.ServiceDefaults.csproj" />
13+
<ProjectReference Include="../../../src/Microsoft.AutoGen.ServiceDefaults/Microsoft.AutoGen.ServiceDefaults.csproj" />
1414
</ItemGroup>
1515

1616
</Project>

dotnet/samples/dev-team/DevTeam.Agents/DevTeam.Agents.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
<ProjectReference Include="../../../src/Microsoft.AutoGen.Agents.Client/Microsoft.AutoGen.Agents.Client.csproj" />
1212

13-
<ProjectReference Include="..\DevTeam.ServiceDefaults\DevTeam.ServiceDefaults.csproj" />
13+
<ProjectReference Include="../../../src/Microsoft.AutoGen.ServiceDefaults/Microsoft.AutoGen.ServiceDefaults.csproj" />
1414
<ProjectReference Include="..\DevTeam.Shared\DevTeam.Shared.csproj" />
1515
<ProjectReference Include="..\..\..\src\Microsoft.AutoGen.Agents.Extensions\SemanticKernel\Microsoft.AutoGen.Agents.Extensions.SemanticKernel.csproj" />
1616
</ItemGroup>

dotnet/samples/dev-team/DevTeam.Backend/DevTeam.Backend.csproj

+1-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
</ItemGroup>
3030

3131
<ItemGroup>
32-
<ProjectReference Include="..\DevTeam.ServiceDefaults\DevTeam.ServiceDefaults.csproj" />
32+
<ProjectReference Include="../../../src/Microsoft.AutoGen.ServiceDefaults/Microsoft.AutoGen.ServiceDefaults.csproj" />
3333
<ProjectReference Include="..\DevTeam.Shared\DevTeam.Shared.csproj" />
3434
<ProjectReference Include="..\..\..\src\Microsoft.AutoGen.Agents.Extensions\SemanticKernel\Microsoft.AutoGen.Agents.Extensions.SemanticKernel.csproj" />
3535
</ItemGroup>

dotnet/src/Microsoft.AutoGen.Agents.Client/AgentClient.cs

+5-1
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,22 @@
11
using System.Diagnostics;
2+
using Google.Protobuf;
23
using Microsoft.AutoGen.Agents.Abstractions;
34
using Microsoft.Extensions.DependencyInjection;
45
using Microsoft.Extensions.Logging;
56

67
namespace Microsoft.AutoGen.Agents.Client;
78

8-
// TODO: Extract this to be part of the Client
99
public sealed class AgentClient(ILogger<AgentClient> logger, AgentWorkerRuntime runtime, DistributedContextPropagator distributedContextPropagator,
1010
[FromKeyedServices("EventTypes")] EventTypes eventTypes)
1111
: AgentBase(new ClientContext(logger, runtime, distributedContextPropagator), eventTypes)
1212
{
1313
public async ValueTask PublishEventAsync(CloudEvent evt) => await PublishEvent(evt);
1414
public async ValueTask<RpcResponse> SendRequestAsync(AgentId target, string method, Dictionary<string, string> parameters) => await RequestAsync(target, method, parameters);
1515

16+
public async ValueTask PublishEventAsync(string topic, IMessage evt)
17+
{
18+
await PublishEventAsync(evt.ToCloudEvent(topic)).ConfigureAwait(false);
19+
}
1620
private sealed class ClientContext(ILogger<AgentClient> logger, AgentWorkerRuntime runtime, DistributedContextPropagator distributedContextPropagator) : IAgentContext
1721
{
1822
public AgentId AgentId { get; } = new AgentId("client", Guid.NewGuid().ToString());

dotnet/src/Microsoft.AutoGen.Agents.Client/AgentWorkerRuntime.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -170,7 +170,7 @@ private async ValueTask RegisterAgentType(string type, Type agentType)
170170
var events = agentType.GetInterfaces()
171171
.Where(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IHandle<>))
172172
.Select(i => i.GetGenericArguments().First().Name);
173-
var state = agentType.BaseType?.GetGenericArguments().First();
173+
//var state = agentType.BaseType?.GetGenericArguments().First();
174174
var topicTypes = agentType.GetCustomAttributes<TopicSubscriptionAttribute>().Select(t => t.Topic);
175175

176176
await WriteChannelAsync(new Message

dotnet/src/Microsoft.AutoGen.Agents.Client/Agents/IOAgent/ConsoleAgent/ConsoleAgent.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33

44
namespace Microsoft.AutoGen.Agents.Client;
55

6-
public class ConsoleAgent : IOAgent<AgentState>,
6+
public abstract class ConsoleAgent : IOAgent<AgentState>,
77
IUseConsole,
88
IHandle<Input>,
99
IHandle<Output>
@@ -32,6 +32,7 @@ public override async Task Handle(Output item)
3232
{
3333
// Assuming item has a property `Content` that we want to write to the console
3434
Console.WriteLine(item.Message);
35+
await ProcessOutput(item.Message);
3536

3637
var evt = new OutputWritten
3738
{
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
using Microsoft.AutoGen.Agents.Abstractions;
2+
using Microsoft.Extensions.DependencyInjection;
23
using Microsoft.Extensions.Logging;
34

45
namespace Microsoft.AutoGen.Agents.Client;
56

67
[TopicSubscription("FileIO")]
7-
public class FileAgent : IOAgent<AgentState>,
8+
public abstract class FileAgent(
9+
IAgentContext context,
10+
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
11+
string inputPath = "input.txt",
12+
string outputPath = "output.txt"
13+
) : IOAgent<AgentState>(context, typeRegistry),
814
IUseFiles,
915
IHandle<Input>,
1016
IHandle<Output>
1117
{
12-
public FileAgent(IAgentContext context, EventTypes typeRegistry, string filePath) : base(context, typeRegistry)
13-
{
14-
_filePath = filePath;
15-
}
16-
private readonly string _filePath;
17-
1818
public override async Task Handle(Input item)
1919
{
20-
2120
// validate that the file exists
22-
if (!File.Exists(_filePath))
21+
if (!File.Exists(inputPath))
2322
{
24-
string errorMessage = $"File not found: {_filePath}";
23+
var errorMessage = $"File not found: {inputPath}";
2524
Logger.LogError(errorMessage);
2625
//publish IOError event
2726
var err = new IOError
@@ -31,36 +30,30 @@ public override async Task Handle(Input item)
3130
await PublishEvent(err);
3231
return;
3332
}
34-
3533
string content;
3634
using (var reader = new StreamReader(item.Message))
3735
{
3836
content = await reader.ReadToEndAsync();
3937
}
40-
4138
await ProcessInput(content);
42-
4339
var evt = new InputProcessed
4440
{
4541
Route = _route
4642
}.ToCloudEvent(this.AgentId.Key);
4743
await PublishEvent(evt);
4844
}
49-
5045
public override async Task Handle(Output item)
5146
{
52-
using (var writer = new StreamWriter(_filePath, append: true))
47+
using (var writer = new StreamWriter(outputPath, append: true))
5348
{
5449
await writer.WriteLineAsync(item.Message);
5550
}
56-
5751
var evt = new OutputWritten
5852
{
5953
Route = _route
6054
}.ToCloudEvent(this.AgentId.Key);
6155
await PublishEvent(evt);
6256
}
63-
6457
public override async Task<string> ProcessInput(string message)
6558
{
6659
var evt = new InputProcessed
@@ -70,14 +63,12 @@ public override async Task<string> ProcessInput(string message)
7063
await PublishEvent(evt);
7164
return message;
7265
}
73-
7466
public override Task ProcessOutput(string message)
7567
{
7668
// Implement your output processing logic here
7769
return Task.CompletedTask;
7870
}
7971
}
80-
8172
public interface IUseFiles
8273
{
8374
}

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
namespace Microsoft.AutoGen.Agents.Client;
88

9-
public class WebAPIAgent : IOAgent<AgentState>,
9+
public abstract class WebAPIAgent : IOAgent<AgentState>,
1010
IUseWebAPI,
1111
IHandle<Input>,
1212
IHandle<Output>
@@ -16,8 +16,8 @@ public class WebAPIAgent : IOAgent<AgentState>,
1616
public WebAPIAgent(
1717
IAgentContext context,
1818
[FromKeyedServices("EventTypes")] EventTypes typeRegistry,
19-
string url,
20-
ILogger<WebAPIAgent> logger) : base(
19+
ILogger<WebAPIAgent> logger,
20+
string url = "/agents/webio") : base(
2121
context,
2222
typeRegistry)
2323
{
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
using Google.Protobuf;
2+
using Microsoft.AspNetCore.Builder;
3+
using Microsoft.Extensions.DependencyInjection;
4+
5+
namespace Microsoft.AutoGen.Agents.Client;
6+
7+
public static class App
8+
{
9+
// need a variable to store the runtime instance
10+
public static WebApplication? RuntimeApp { get; set; }
11+
public static WebApplication? ClientApp { get; set; }
12+
public static async ValueTask<WebApplication> StartAsync(AgentTypes? agentTypes = null, bool local = false)
13+
{
14+
// start the server runtime
15+
RuntimeApp ??= await Runtime.Host.StartAsync(local);
16+
var clientBuilder = WebApplication.CreateBuilder();
17+
var appBuilder = clientBuilder.AddAgentWorker();
18+
agentTypes ??= AgentTypes.GetAgentTypesFromAssembly()
19+
?? throw new InvalidOperationException("No agent types found in the assembly");
20+
foreach (var type in agentTypes.Types)
21+
{
22+
appBuilder.AddAgent(type.Key, type.Value);
23+
}
24+
ClientApp = clientBuilder.Build();
25+
await ClientApp.StartAsync().ConfigureAwait(false);
26+
return ClientApp;
27+
}
28+
29+
public static async ValueTask<WebApplication> PublishMessageAsync(
30+
string topic,
31+
IMessage message,
32+
AgentTypes? agentTypes = null,
33+
bool local = false)
34+
{
35+
if (ClientApp == null)
36+
{
37+
ClientApp = await App.StartAsync(agentTypes, local);
38+
}
39+
var client = ClientApp.Services.GetRequiredService<AgentClient>() ?? throw new InvalidOperationException("Client not started");
40+
await client.PublishEventAsync(topic, message).ConfigureAwait(false);
41+
return ClientApp;
42+
}
43+
44+
public static async ValueTask ShutdownAsync()
45+
{
46+
if (ClientApp == null)
47+
{
48+
throw new InvalidOperationException("Client not started");
49+
}
50+
await RuntimeApp!.StopAsync();
51+
await ClientApp.StopAsync();
52+
}
53+
}

0 commit comments

Comments
 (0)