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

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