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.

README.md 5.2 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  1. # AutoGen 0.4 .NET Hello World Sample
  2. This [sample](Program.cs) demonstrates how to create a simple .NET console application that listens for an event and then orchestrates a series of actions in response.
  3. ## Prerequisites
  4. To run this sample, you'll need: [.NET 8.0](https://dotnet.microsoft.com/en-us/) or later.
  5. Also recommended is the [GitHub CLI](https://cli.github.com/).
  6. ## Instructions to run the sample
  7. ```bash
  8. # Clone the repository
  9. gh repo clone microsoft/autogen
  10. cd dotnet/samples/Hello
  11. dotnet run
  12. ```
  13. ## Key Concepts
  14. This sample illustrates how to create your own agent that inherits from a base agent and listens for an event. It also shows how to use the SDK's App Runtime locally to start the agent and send messages.
  15. Flow Diagram:
  16. ```mermaid
  17. %%{init: {'theme':'forest'}}%%
  18. graph LR;
  19. A[Main] --> |"PublishEventAsync(NewMessage('World'))"| B{"Handle(NewMessageReceived item, CancellationToken cancellationToken = default)"}
  20. B --> |"PublishEventAsync(Output('***Hello, World***'))"| C[ConsoleAgent]
  21. C --> D{"WriteConsole()"}
  22. B --> |"PublishEventAsync(ConversationClosed('Goodbye'))"| E{"Handle(ConversationClosed item, CancellationToken cancellationToken = default)"}
  23. B --> |"PublishEventAsync(Output('***Goodbye***'))"| C
  24. E --> F{"Shutdown()"}
  25. ```
  26. ### Writing Event Handlers
  27. The heart of an autogen application are the event handlers. Agents select a ```TopicSubscription``` to listen for events on a specific topic. When an event is received, the agent's event handler is called with the event data.
  28. Within that event handler you may optionally *emit* new events, which are then sent to the event bus for other agents to process. The EventTypes are declared gRPC ProtoBuf messages that are used to define the schema of the event. The default protos are available via the ```Microsoft.AutoGen.Contracts;``` namespace and are defined in [autogen/protos](/autogen/protos). The EventTypes are registered in the agent's constructor using the ```IHandle``` interface.
  29. ```csharp
  30. TopicSubscription("HelloAgents")]
  31. public class HelloAgent(
  32. iAgentWorker worker,
  33. [FromKeyedServices("AgentsMetadata")] AgentsMetadata typeRegistry) : ConsoleAgent(
  34. worker,
  35. typeRegistry),
  36. ISayHello,
  37. IHandle<NewMessageReceived>,
  38. IHandle<ConversationClosed>
  39. {
  40. public async Task Handle(NewMessageReceived item, CancellationToken cancellationToken = default)
  41. {
  42. var response = await SayHello(item.Message).ConfigureAwait(false);
  43. var evt = new Output
  44. {
  45. Message = response
  46. }.ToCloudEvent(this.AgentId.Key);
  47. await PublishEventAsync(evt).ConfigureAwait(false);
  48. var goodbye = new ConversationClosed
  49. {
  50. UserId = this.AgentId.Key,
  51. UserMessage = "Goodbye"
  52. }.ToCloudEvent(this.AgentId.Key);
  53. await PublishEventAsync(goodbye).ConfigureAwait(false);
  54. }
  55. ```
  56. ### Inheritance and Composition
  57. This sample also illustrates inheritance in AutoGen. The `HelloAgent` class inherits from `ConsoleAgent`, which is a base class that provides a `WriteConsole` method.
  58. ### Starting the Application Runtime
  59. AuotoGen provides a flexible runtime ```Microsoft.AutoGen.Agents.App``` that can be started in a variety of ways. The `Program.cs` file demonstrates how to start the runtime locally and send a message to the agent all in one go using the ```App.PublishMessageAsync``` method.
  60. ```csharp
  61. // send a message to the agent
  62. var app = await App.PublishMessageAsync("HelloAgents", new NewMessageReceived
  63. {
  64. Message = "World"
  65. }, local: true);
  66. await App.RuntimeApp!.WaitForShutdownAsync();
  67. await app.WaitForShutdownAsync();
  68. ```
  69. ### Sending Messages
  70. The set of possible Messages is defined in gRPC ProtoBuf specs. These are then turned into C# classes by the gRPC tools. You can define your own Message types by creating a new .proto file in your project and including the gRPC tools in your ```.csproj``` file:
  71. ```proto
  72. syntax = "proto3";
  73. package devteam;
  74. option csharp_namespace = "DevTeam.Shared";
  75. message NewAsk {
  76. string org = 1;
  77. string repo = 2;
  78. string ask = 3;
  79. int64 issue_number = 4;
  80. }
  81. message ReadmeRequested {
  82. string org = 1;
  83. string repo = 2;
  84. int64 issue_number = 3;
  85. string ask = 4;
  86. }
  87. ```
  88. ```xml
  89. <ItemGroup>
  90. <PackageReference Include="Google.Protobuf" />
  91. <PackageReference Include="Grpc.Tools" PrivateAssets="All" />
  92. <Protobuf Include="..\Protos\messages.proto" Link="Protos\messages.proto" />
  93. </ItemGroup>
  94. ```
  95. You can send messages using the [```Microsoft.AutoGen.Agents.AgentWorker``` class](autogen/dotnet/src/Microsoft.AutoGen/Agents/AgentWorker.cs). Messages are wrapped in [the CloudEvents specification](https://cloudevents.io) and sent to the event bus.
  96. ### Managing State
  97. There is a simple API for persisting agent state.
  98. ```csharp
  99. await Store(new AgentState
  100. {
  101. AgentId = this.AgentId,
  102. TextData = entry
  103. }).ConfigureAwait(false);
  104. ```
  105. which can be read back using Read:
  106. ```csharp
  107. State = await Read<AgentState>(this.AgentId).ConfigureAwait(false);
  108. ```