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.

tutorial.md 6.7 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165
  1. # Tutorial
  2. > [!TIP]
  3. > If you'd prefer to just see the code the entire sample is available as a [project here](https://github.com/microsoft/autogen/tree/main/dotnet/samples/GettingStarted).
  4. In this tutorial we are going to define two agents, `Modifier` and `Checker`, that will count down from 10 to 1. The `Modifier` agent will modify the count and the `Checker` agent will check the count and stop the application when the count reaches 1.
  5. ## Defining the message types
  6. The first thing we need to do is to define the messages that will be passed between the agents, we're simply going to define them as classes.
  7. We're going to use `CountMessage` to pass the current count and `CountUpdate` to pass the updated count.
  8. [!code-csharp[](../../../dotnet/samples/GettingStarted/CountMessage.cs#snippet_CountMessage)]
  9. [!code-csharp[](../../../dotnet/samples/GettingStarted/CountUpdate.cs#snippet_CountUpdate)]
  10. By separating out the message types into strongly typed classes, we can build a workflow where agents react to certain types and produce certain types.
  11. ## Creating the agents
  12. ### Inherit from `BaseAgent`
  13. In AutoGen an agent is a class that can receive and send messages. The agent defines its own logic of what to do with the messages it receives. To define an agent, create a class that inherits from @Microsoft.AutoGen.Core.BaseAgent, like so:
  14. ```csharp
  15. using Microsoft.AutoGen.Contracts;
  16. using Microsoft.AutoGen.Core;
  17. public class Modifier(
  18. AgentId id,
  19. IAgentRuntime runtime,
  20. ) :
  21. BaseAgent(id, runtime, "MyAgent", null),
  22. {
  23. }
  24. ```
  25. We will see how to pass arguments to an agent when it is constructed, but for now you just need to know that @Microsoft.AutoGen.Contracts.AgentId and @Microsoft.AutoGen.Core.IAgentRuntime will always be passed to the constructor, and those should be forwarded to the base class constructor. The other two arguments are a description of the agent and an optional logger.
  26. Learn more about what an Agent ID is [here](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/core-concepts/agent-identity-and-lifecycle.html#agent-id).
  27. ### Create a handler
  28. Now, we want `Modifier` to receive `CountMessage` and produce `CountUpdate` after it modifies the count. To do this, we need to implement the `IHandle<CountMessage>` interface:
  29. ```csharp
  30. public class Modifier(
  31. // ...
  32. ) :
  33. BaseAgent(...),
  34. IHandle<CountMessage>
  35. {
  36. public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext)
  37. {
  38. // ...
  39. }
  40. }
  41. ```
  42. ### Add a subscription
  43. We've defined a function that will be called when a `CountMessage` is delivered to this agent, but there is still one step before the message will actually be delivered to the agent. The agent must subscribe to the topic to the message is published to. We can do this by adding the `TypeSubscription` attribute to the class:
  44. ```csharp
  45. [TypeSubscription("default")]
  46. public class Modifier(
  47. // ...
  48. ```
  49. Learn more about topics and subscriptions [here](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/core-concepts/topic-and-subscription.html).
  50. ### Publish a message
  51. Now that we have a handler for `CountMessage`, and we have the subscription in place we can publish a result out of the handler.
  52. ```csharp
  53. public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext)
  54. {
  55. int newValue = item.Content - 1;
  56. Console.WriteLine($"\nModifier:\nModified {item.Content} to {newValue}");
  57. CountUpdate updateMessage = new CountUpdate { NewCount = newValue };
  58. await this.PublishMessageAsync(updateMessage, topic: new TopicId("default"));
  59. }
  60. ```
  61. You'll notice that when we publish the message, we specify the topic to publish to. We're using a topic called `default` in this case, which is the same topic which we subscribed to. We could have used a different topic, but in this case we're keeping it simple.
  62. ### Passing arguments to the agent
  63. Let's extend our agent to make what we do to the count configurable. We'll do this by passing a function to the agent that will be used to modify the count.
  64. ```csharp
  65. using ModifyF = System.Func<int, int>;
  66. // ...
  67. [TypeSubscription("default")]
  68. public class Modifier(
  69. AgentId id,
  70. IAgentRuntime runtime,
  71. ModifyF modifyFunc // <-- Add this
  72. ) :
  73. BaseAgent(...),
  74. IHandle<CountMessage>
  75. {
  76. public async ValueTask HandleAsync(CountMessage item, MessageContext messageContext)
  77. {
  78. int newValue = modifyFunc(item.Content); // <-- use it here
  79. // ...
  80. }
  81. }
  82. ```
  83. ### Final Modifier implementation
  84. Here is the final implementation of the Modifier agent:
  85. [!code-csharp[](../../../dotnet/samples/GettingStarted/Modifier.cs#snippet_Modifier)]
  86. ### Checker
  87. We'll also define a Checker agent that will check the count and stop the application when the count reaches 1. Additionally, we'll use dependency injection to get a reference to the `IHostApplicationLifetime` service, which we can use to stop the application.
  88. [!code-csharp[](../../../dotnet/samples/GettingStarted/Checker.cs#snippet_Checker)]
  89. ## Putting it all together
  90. Now that we have our agents defined, we can put them together in a simple application that will count down from 10 to 1.
  91. After includes, the first thing to do is to define the two functions for modifying and checking for completion.
  92. [!code-csharp[](../../../dotnet/samples/GettingStarted/Program.cs#snippet_Program_funcs)]
  93. Then, we create a builder and do the following things:
  94. - Specify that we are using the in process runtime
  95. - Register our functions as services
  96. - Register the agent classes we defined earlier
  97. - Finally, build and start our app
  98. [!code-csharp[](../../../dotnet/samples/GettingStarted/Program.cs#snippet_Program_builder)]
  99. The app is now running, but we need to kick off the process with a message. We do this by publishing a `CountMessage` with an initial value of 10.
  100. Importantly we publish this to the "default" topic which is what our agents are subscribed to. Finally, we wait for the application to stop.
  101. [!code-csharp[](../../../dotnet/samples/GettingStarted/Program.cs#snippet_Program_publish)]
  102. That's it! You should see the count down from 10 to 1 in the console.
  103. Here's the full code for the `Program` class:
  104. [!code-csharp[](../../../dotnet/samples/GettingStarted/Program.cs#snippet_Program)]
  105. ## Things to try
  106. Here are some ideas to try with this sample:
  107. - Change the initial count
  108. - Create a new modifier function that counts up instead. (Don't forget to change the checker too!)
  109. - Create an agent that outputs to the console instead of the modifier or checker agent doing it themselves (hint: use a new message type)