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.

inner_outer_direct.py 2.2 kB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. """
  2. This example shows how to use direct messaging to implement
  3. a simple interaction between an inner and an outer agent.
  4. 1. The outer agent receives a message, sends a message to the inner agent.
  5. 2. The inner agent receives the message, processes it, and sends a response to the outer agent.
  6. 3. The outer agent receives the response and processes it, and returns the final response.
  7. """
  8. import asyncio
  9. import logging
  10. from dataclasses import dataclass
  11. from agnext.application import SingleThreadedAgentRuntime
  12. from agnext.components import RoutedAgent, message_handler
  13. from agnext.core import AgentId, AgentInstantiationContext, MessageContext
  14. @dataclass
  15. class MessageType:
  16. body: str
  17. sender: str
  18. class Inner(RoutedAgent):
  19. def __init__(self) -> None:
  20. super().__init__("The inner agent")
  21. @message_handler()
  22. async def on_new_message(self, message: MessageType, ctx: MessageContext) -> MessageType:
  23. return MessageType(body=f"Inner: {message.body}", sender=self.metadata["type"])
  24. class Outer(RoutedAgent):
  25. def __init__(self, inner: AgentId) -> None:
  26. super().__init__("The outer agent")
  27. self._inner = inner
  28. @message_handler()
  29. async def on_new_message(self, message: MessageType, ctx: MessageContext) -> MessageType:
  30. inner_response = self.send_message(message, self._inner)
  31. inner_message = await inner_response
  32. assert isinstance(inner_message, MessageType)
  33. return MessageType(body=f"Outer: {inner_message.body}", sender=self.metadata["type"])
  34. async def main() -> None:
  35. runtime = SingleThreadedAgentRuntime()
  36. await runtime.register("inner", Inner)
  37. await runtime.register("outer", lambda: Outer(AgentId("outer", AgentInstantiationContext.current_agent_id().key)))
  38. outer = AgentId("outer", "default")
  39. runtime.start()
  40. response = await runtime.send_message(MessageType(body="Hello", sender="external"), outer)
  41. print(response)
  42. await runtime.stop()
  43. if __name__ == "__main__":
  44. import logging
  45. logging.basicConfig(level=logging.WARNING)
  46. logging.getLogger("agnext").setLevel(logging.DEBUG)
  47. asyncio.run(main())