autogen/python/examples/core/inner_outer_direct.py

64 lines
2.1 KiB
Python
Raw Normal View History

"""
This example shows how to use direct messaging to implement
a simple interaction between an inner and an outer agent.
1. The outer agent receives a message, sends a message to the inner agent.
2. The inner agent receives the message, processes it, and sends a response to the outer agent.
3. The outer agent receives the response and processes it, and returns the final response.
"""
2024-05-15 12:31:13 -04:00
import asyncio
import logging
2024-05-15 12:31:13 -04:00
from dataclasses import dataclass
2024-06-04 10:00:05 -04:00
from agnext.application import SingleThreadedAgentRuntime
from agnext.components import TypeRoutedAgent, message_handler
from agnext.core import AgentId, CancellationToken
2024-05-15 12:31:13 -04:00
@dataclass
class MessageType:
body: str
2024-05-15 12:31:13 -04:00
sender: str
class Inner(TypeRoutedAgent):
def __init__(self) -> None:
super().__init__("The inner agent")
2024-05-15 12:31:13 -04:00
@message_handler()
async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:
return MessageType(body=f"Inner: {message.body}", sender=self.metadata["name"])
2024-05-15 12:31:13 -04:00
class Outer(TypeRoutedAgent):
def __init__(self, inner: AgentId) -> None:
super().__init__("The outer agent")
2024-05-15 12:31:13 -04:00
self._inner = inner
@message_handler()
async def on_new_message(self, message: MessageType, cancellation_token: CancellationToken) -> MessageType:
inner_response = self.send_message(message, self._inner)
2024-05-15 12:31:13 -04:00
inner_message = await inner_response
assert isinstance(inner_message, MessageType)
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-06-17 15:37:46 -04:00
runtime = SingleThreadedAgentRuntime()
inner = runtime.register_and_get("inner", Inner)
outer = runtime.register_and_get("outer", lambda: Outer(inner))
2024-05-15 12:31:13 -04:00
run_context = runtime.start()
2024-05-15 12:31:13 -04:00
response = await runtime.send_message(MessageType(body="Hello", sender="external"), outer)
print(response)
await run_context.stop()
2024-05-15 12:31:13 -04:00
if __name__ == "__main__":
import logging
logging.basicConfig(level=logging.WARNING)
logging.getLogger("agnext").setLevel(logging.DEBUG)
2024-05-15 12:31:13 -04:00
asyncio.run(main())