You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

HelloAgent.cs 1.9 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // HelloAgent.cs
  3. using Microsoft.AutoGen.Contracts;
  4. using Microsoft.AutoGen.Core;
  5. using Microsoft.Extensions.Hosting;
  6. using Microsoft.Extensions.Logging;
  7. namespace Samples;
  8. [TypeSubscription("HelloTopic")]
  9. public class HelloAgent(
  10. IHostApplicationLifetime hostApplicationLifetime,
  11. AgentId id,
  12. IAgentRuntime runtime,
  13. Logger<BaseAgent>? logger = null) : BaseAgent(id, runtime, "Hello Agent", logger),
  14. IHandle<NewMessageReceived>,
  15. IHandle<ConversationClosed>,
  16. IHandle<Shutdown>
  17. {
  18. // This will capture the message sent in Program.cs
  19. public async ValueTask HandleAsync(NewMessageReceived item, MessageContext messageContext)
  20. {
  21. Console.Out.WriteLine(item.Message); // Print message to console
  22. ConversationClosed goodbye = new ConversationClosed
  23. {
  24. UserId = this.Id.Type,
  25. UserMessage = "Goodbye"
  26. };
  27. // This will publish the new message type which will be handled by the ConversationClosed handler
  28. await this.PublishMessageAsync(goodbye, new TopicId("HelloTopic"));
  29. }
  30. public async ValueTask HandleAsync(ConversationClosed item, MessageContext messageContext)
  31. {
  32. var goodbye = $"{item.UserId} said {item.UserMessage}"; // Print goodbye message to console
  33. Console.Out.WriteLine(goodbye);
  34. if (Environment.GetEnvironmentVariable("STAY_ALIVE_ON_GOODBYE") != "true")
  35. {
  36. // Publish message that will be handled by shutdown handler
  37. await this.PublishMessageAsync(new Shutdown(), new TopicId("HelloTopic"));
  38. }
  39. }
  40. public async ValueTask HandleAsync(Shutdown item, MessageContext messageContext)
  41. {
  42. Console.WriteLine("Shutting down...");
  43. hostApplicationLifetime.StopApplication(); // Shuts down application
  44. }
  45. }