2024-05-15 12:31:13 -04:00
|
|
|
import asyncio
|
|
|
|
from dataclasses import dataclass
|
|
|
|
|
2024-06-04 10:00:05 -04:00
|
|
|
from agnext.application import SingleThreadedAgentRuntime
|
2024-06-05 15:48:14 -04:00
|
|
|
from agnext.components import TypeRoutedAgent, message_handler
|
2024-05-27 17:10:56 -04:00
|
|
|
from agnext.core import Agent, AgentRuntime, CancellationToken
|
2024-05-15 12:31:13 -04:00
|
|
|
|
|
|
|
|
|
|
|
@dataclass
|
2024-05-20 13:32:08 -06:00
|
|
|
class MessageType:
|
2024-05-17 14:59:00 -07:00
|
|
|
body: str
|
2024-05-15 12:31:13 -04:00
|
|
|
sender: str
|
|
|
|
|
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
class Inner(TypeRoutedAgent): # type: ignore
|
|
|
|
def __init__(self, name: str, router: AgentRuntime) -> None: # type: ignore
|
|
|
|
super().__init__(name, "The inner agent", router)
|
2024-05-15 12:31:13 -04:00
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
@message_handler() # type: ignore
|
|
|
|
async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignore
|
2024-06-17 10:44:46 -04:00
|
|
|
return MessageType(body=f"Inner: {message.body}", sender=self.metadata["name"])
|
2024-05-15 12:31:13 -04:00
|
|
|
|
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
class Outer(TypeRoutedAgent): # type: ignore
|
|
|
|
def __init__(self, name: str, router: AgentRuntime, inner: Agent) -> None: # type: ignore
|
|
|
|
super().__init__(name, "The outter agent", router)
|
2024-05-15 12:31:13 -04:00
|
|
|
self._inner = inner
|
|
|
|
|
2024-06-09 12:11:36 -07:00
|
|
|
@message_handler() # type: ignore
|
|
|
|
async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType: # type: ignore
|
2024-05-26 08:45:02 -04:00
|
|
|
inner_response = self._send_message(message, self._inner)
|
2024-05-15 12:31:13 -04:00
|
|
|
inner_message = await inner_response
|
2024-05-23 16:00:05 -04:00
|
|
|
assert isinstance(inner_message, MessageType)
|
2024-06-17 10:44:46 -04:00
|
|
|
return MessageType(body=f"Outer: {inner_message.body}", sender=self.metadata["name"])
|
2024-05-15 12:31:13 -04:00
|
|
|
|
|
|
|
|
|
|
|
async def main() -> None:
|
2024-05-23 16:00:05 -04:00
|
|
|
router = SingleThreadedAgentRuntime()
|
2024-05-15 12:31:13 -04:00
|
|
|
inner = Inner("inner", router)
|
|
|
|
outer = Outer("outer", router, inner)
|
2024-05-17 14:59:00 -07:00
|
|
|
response = router.send_message(MessageType(body="Hello", sender="external"), outer)
|
2024-05-15 12:31:13 -04:00
|
|
|
|
|
|
|
while not response.done():
|
|
|
|
await router.process_next()
|
|
|
|
|
|
|
|
print(await response)
|
|
|
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
|
asyncio.run(main())
|