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.

AgentTests.cs 7.1 kB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // AgentTests.cs
  3. using System.Text.Json;
  4. using FluentAssertions;
  5. using Microsoft.AutoGen.Contracts;
  6. using Microsoft.Extensions.Logging;
  7. using Xunit;
  8. namespace Microsoft.AutoGen.Core.Tests;
  9. [Trait("Category", "UnitV2")]
  10. public class AgentTests()
  11. {
  12. [Fact]
  13. public async Task AgentShouldNotReceiveMessagesWhenNotSubscribedTest()
  14. {
  15. var runtime = new InProcessRuntime();
  16. await runtime.StartAsync();
  17. Logger<BaseAgent> logger = new(new LoggerFactory());
  18. TestAgent agent = null!;
  19. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  20. {
  21. agent = new TestAgent(id, runtime, logger);
  22. return ValueTask.FromResult(agent);
  23. });
  24. // Ensure the agent is actually created
  25. AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);
  26. // Validate agent ID
  27. agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");
  28. var topicType = "TestTopic";
  29. await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId(topicType)).ConfigureAwait(true);
  30. await runtime.RunUntilIdleAsync();
  31. agent.ReceivedMessages.Any().Should().BeFalse("Agent should not receive messages when not subscribed.");
  32. }
  33. [Fact]
  34. public async Task AgentShouldReceiveMessagesWhenSubscribedTest()
  35. {
  36. var runtime = new InProcessRuntime();
  37. await runtime.StartAsync();
  38. Logger<BaseAgent> logger = new(new LoggerFactory());
  39. SubscribedAgent agent = null!;
  40. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  41. {
  42. agent = new SubscribedAgent(id, runtime, logger);
  43. return ValueTask.FromResult(agent);
  44. });
  45. // Ensure the agent id is registered
  46. AgentId agentId = await runtime.GetAgentAsync("MyAgent", lazy: false);
  47. // Validate agent ID
  48. agentId.Should().Be(agent.Id, "Agent ID should match the registered agent");
  49. await runtime.RegisterImplicitAgentSubscriptionsAsync<SubscribedAgent>("MyAgent");
  50. var topicType = "TestTopic";
  51. await runtime.PublishMessageAsync(new TextMessage { Source = topicType, Content = "test" }, new TopicId(topicType)).ConfigureAwait(true);
  52. await runtime.RunUntilIdleAsync();
  53. agent.ReceivedMessages.Any().Should().BeTrue("Agent should receive messages when subscribed.");
  54. }
  55. [Fact]
  56. public async Task SendMessageAsyncShouldReturnResponseTest()
  57. {
  58. // Arrange
  59. var runtime = new InProcessRuntime();
  60. await runtime.StartAsync();
  61. Logger<BaseAgent> logger = new(new LoggerFactory());
  62. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) => ValueTask.FromResult(new TestAgent(id, runtime, logger)));
  63. await runtime.RegisterImplicitAgentSubscriptionsAsync<TestAgent>("MyAgent");
  64. var agentId = new AgentId("MyAgent", "TestAgent");
  65. var response = await runtime.SendMessageAsync(new RpcTextMessage { Source = "TestTopic", Content = "Request" }, agentId);
  66. // Assert
  67. Assert.NotNull(response);
  68. Assert.IsType<string>(response);
  69. if (response is string responseString)
  70. {
  71. Assert.Equal("Request", responseString);
  72. }
  73. }
  74. public class ReceiverAgent(AgentId id,
  75. IAgentRuntime runtime) : BaseAgent(id, runtime, "Receiver Agent", null),
  76. IHandle<string>
  77. {
  78. public ValueTask HandleAsync(string item, MessageContext messageContext)
  79. {
  80. ReceivedItems.Add(item);
  81. return ValueTask.CompletedTask;
  82. }
  83. public List<string> ReceivedItems { get; private set; } = [];
  84. }
  85. [Fact]
  86. public async Task SubscribeAsyncRemoveSubscriptionAsyncTest()
  87. {
  88. var runtime = new InProcessRuntime();
  89. await runtime.StartAsync();
  90. ReceiverAgent? agent = null;
  91. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  92. {
  93. agent = new ReceiverAgent(id, runtime);
  94. return ValueTask.FromResult(agent);
  95. });
  96. Assert.Null(agent);
  97. await runtime.GetAgentAsync("MyAgent", lazy: false);
  98. Assert.NotNull(agent);
  99. Assert.True(agent.ReceivedItems.Count == 0);
  100. var topicTypeName = "TestTopic";
  101. await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
  102. await Task.Delay(100);
  103. Assert.True(agent.ReceivedItems.Count == 0);
  104. var subscription = new TypeSubscription(topicTypeName, "MyAgent");
  105. await runtime.AddSubscriptionAsync(subscription);
  106. await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
  107. await Task.Delay(100);
  108. Assert.True(agent.ReceivedItems.Count == 1);
  109. Assert.Equal("info", agent.ReceivedItems[0]);
  110. await runtime.RemoveSubscriptionAsync(subscription.Id);
  111. await runtime.PublishMessageAsync("info", new TopicId(topicTypeName));
  112. await Task.Delay(100);
  113. Assert.True(agent.ReceivedItems.Count == 1);
  114. }
  115. public class AgentState
  116. {
  117. public required string Name { get; set; }
  118. public required int Value { get; set; }
  119. }
  120. public class StateAgent(AgentId id,
  121. IAgentRuntime runtime,
  122. AgentState state,
  123. Logger<BaseAgent>? logger = null) : BaseAgent(id, runtime, "Test Agent", logger),
  124. ISaveStateMixin<AgentState>
  125. {
  126. ValueTask<AgentState> ISaveStateMixin<AgentState>.SaveStateImpl()
  127. {
  128. return ValueTask.FromResult(_state);
  129. }
  130. ValueTask ISaveStateMixin<AgentState>.LoadStateImpl(AgentState state)
  131. {
  132. _state = state;
  133. return ValueTask.CompletedTask;
  134. }
  135. private AgentState _state = state;
  136. }
  137. [Fact]
  138. public async Task StateMixinTest()
  139. {
  140. var runtime = new InProcessRuntime();
  141. await runtime.StartAsync();
  142. await runtime.RegisterAgentFactoryAsync("MyAgent", (id, runtime) =>
  143. {
  144. return ValueTask.FromResult(new StateAgent(id, runtime, new AgentState { Name = "TestAgent", Value = 5 }));
  145. });
  146. var agentId = new AgentId("MyAgent", "default");
  147. // Get the state
  148. var state1 = await runtime.SaveAgentStateAsync(agentId);
  149. Assert.Equal("TestAgent", state1.GetProperty("Name").GetString());
  150. Assert.Equal(5, state1.GetProperty("Value").GetInt32());
  151. // Change the state
  152. var newState = new AgentState { Name = "TestAgent", Value = 100 };
  153. var jsonState = JsonSerializer.SerializeToElement(newState);
  154. await runtime.LoadAgentStateAsync(agentId, jsonState);
  155. // Get the state
  156. var state2 = await runtime.SaveAgentStateAsync(agentId);
  157. Assert.Equal("TestAgent", state2.GetProperty("Name").GetString());
  158. Assert.Equal(100, state2.GetProperty("Value").GetInt32());
  159. }
  160. }