-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathtest_routed_agent.py
213 lines (168 loc) · 7.95 KB
/
test_routed_agent.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import logging
from dataclasses import dataclass
from typing import Callable, cast
import pytest
from autogen_core.application import SingleThreadedAgentRuntime
from autogen_core.base import AgentId, MessageContext, TopicId
from autogen_core.components import RoutedAgent, TypeSubscription, event, message_handler, rpc
from test_utils import LoopbackAgent
@dataclass
class UnhandledMessageType: ...
@dataclass
class MessageType: ...
class CounterAgent(RoutedAgent):
def __init__(self) -> None:
super().__init__("A loop back agent.")
self.num_calls_rpc = 0
self.num_calls_broadcast = 0
@message_handler(match=lambda _, ctx: ctx.is_rpc)
async def on_rpc_message(self, message: MessageType, ctx: MessageContext) -> MessageType:
self.num_calls_rpc += 1
return message
@message_handler(match=lambda _, ctx: not ctx.is_rpc)
async def on_broadcast_message(self, message: MessageType, ctx: MessageContext) -> None:
self.num_calls_broadcast += 1
@pytest.mark.asyncio
async def test_routed_agent(caplog: pytest.LogCaptureFixture) -> None:
runtime = SingleThreadedAgentRuntime()
with caplog.at_level(logging.INFO):
await LoopbackAgent.register(runtime, "loopback", LoopbackAgent)
await runtime.add_subscription(TypeSubscription("default", "loopback"))
runtime.start()
await runtime.publish_message(UnhandledMessageType(), topic_id=TopicId("default", "default"))
await runtime.stop_when_idle()
assert any("Unhandled message: " in e.message for e in caplog.records)
@pytest.mark.asyncio
async def test_message_handler_router() -> None:
runtime = SingleThreadedAgentRuntime()
await CounterAgent.register(runtime, "counter", CounterAgent)
await runtime.add_subscription(TypeSubscription("default", "counter"))
agent_id = AgentId(type="counter", key="default")
# Send a broadcast message.
runtime.start()
await runtime.publish_message(MessageType(), topic_id=TopicId("default", "default"))
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=CounterAgent)
assert agent.num_calls_broadcast == 1
assert agent.num_calls_rpc == 0
# Send an RPC message.
runtime.start()
await runtime.send_message(MessageType(), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=CounterAgent)
assert agent.num_calls_broadcast == 1
assert agent.num_calls_rpc == 1
@dataclass
class TestMessage:
value: str
class RoutedAgentMessageCustomMatch(RoutedAgent):
def __init__(self) -> None:
super().__init__("")
self.handler_one_called = False
self.handler_two_called = False
@staticmethod
def match_one(message: TestMessage, ctx: MessageContext) -> bool:
return message.value == "one"
@message_handler(match=match_one)
async def handler_one(self, message: TestMessage, ctx: MessageContext) -> None:
self.handler_one_called = True
@message_handler(match=cast(Callable[[TestMessage, MessageContext], bool], lambda msg, ctx: msg.value == "two")) # type: ignore
async def handler_two(self, message: TestMessage, ctx: MessageContext) -> None:
self.handler_two_called = True
@pytest.mark.asyncio
async def test_routed_agent_message_matching() -> None:
runtime = SingleThreadedAgentRuntime()
await RoutedAgentMessageCustomMatch.register(runtime, "message_match", RoutedAgentMessageCustomMatch)
agent_id = AgentId(type="message_match", key="default")
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RoutedAgentMessageCustomMatch)
assert agent is not None
assert agent.handler_one_called is False
assert agent.handler_two_called is False
runtime.start()
await runtime.send_message(TestMessage("one"), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RoutedAgentMessageCustomMatch)
assert agent.handler_one_called is True
assert agent.handler_two_called is False
runtime.start()
await runtime.send_message(TestMessage("two"), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RoutedAgentMessageCustomMatch)
assert agent.handler_one_called is True
assert agent.handler_two_called is True
class EventAgent(RoutedAgent):
def __init__(self) -> None:
super().__init__("An event agent.")
self.num_calls = [0, 0]
@event(match=lambda msg, ctx: msg.value == "one") # type: ignore
async def on_event_one(self, message: TestMessage, ctx: MessageContext) -> None:
self.num_calls[0] += 1
@event(match=lambda msg, ctx: msg.value == "two") # type: ignore
async def on_event_two(self, message: TestMessage, ctx: MessageContext) -> None:
self.num_calls[1] += 1
@pytest.mark.asyncio
async def test_event() -> None:
runtime = SingleThreadedAgentRuntime()
await EventAgent.register(runtime, "counter", EventAgent)
await runtime.add_subscription(TypeSubscription("default", "counter"))
agent_id = AgentId(type="counter", key="default")
# Send a broadcast message.
runtime.start()
await runtime.publish_message(TestMessage("one"), topic_id=TopicId("default", "default"))
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=EventAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 0
# Send another broadcast message.
runtime.start()
await runtime.publish_message(TestMessage("two"), topic_id=TopicId("default", "default"))
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=EventAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 1
# Send an RPC message, expect no change.
runtime.start()
await runtime.send_message(TestMessage("one"), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=EventAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 1
class RPCAgent(RoutedAgent):
def __init__(self) -> None:
super().__init__("An RPC agent.")
self.num_calls = [0, 0]
@rpc(match=lambda msg, ctx: msg.value == "one") # type: ignore
async def on_rpc_one(self, message: TestMessage, ctx: MessageContext) -> TestMessage:
self.num_calls[0] += 1
return message
@rpc(match=lambda msg, ctx: msg.value == "two") # type: ignore
async def on_rpc_two(self, message: TestMessage, ctx: MessageContext) -> TestMessage:
self.num_calls[1] += 1
return message
@pytest.mark.asyncio
async def test_rpc() -> None:
runtime = SingleThreadedAgentRuntime()
await RPCAgent.register(runtime, "counter", RPCAgent)
await runtime.add_subscription(TypeSubscription("default", "counter"))
agent_id = AgentId(type="counter", key="default")
# Send an RPC message.
runtime.start()
await runtime.send_message(TestMessage("one"), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RPCAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 0
# Send another RPC message.
runtime.start()
await runtime.send_message(TestMessage("two"), recipient=agent_id)
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RPCAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 1
# Send a broadcast message, expect no change.
runtime.start()
await runtime.publish_message(TestMessage("one"), topic_id=TopicId("default", "default"))
await runtime.stop_when_idle()
agent = await runtime.try_get_underlying_agent_instance(agent_id, type=RPCAgent)
assert agent.num_calls[0] == 1
assert agent.num_calls[1] == 1