autogen/src/agnext/application_components/single_threaded_agent_runtime.py

99 lines
3.5 KiB
Python
Raw Normal View History

2024-05-15 12:31:13 -04:00
import asyncio
from asyncio import Future
from dataclasses import dataclass
from typing import Dict, Generic, List, Set, Type, TypeVar
2024-05-17 11:09:59 -04:00
from ..core.agent import Agent
from ..core.agent_runtime import AgentRuntime
from ..core.message import Message
2024-05-15 12:31:13 -04:00
T = TypeVar("T", bound=Message)
@dataclass
class BroadcastMessageEnvolope(Generic[T]):
"""A message envelope for broadcasting messages to all agents that can handle
the message of the type T."""
2024-05-15 12:31:13 -04:00
message: T
future: Future[List[T]]
@dataclass
class SendMessageEnvelope(Generic[T]):
"""A message envelope for sending a message to a specific agent that can handle
the message of the type T."""
2024-05-15 12:31:13 -04:00
message: T
destination: Agent[T]
future: Future[T]
@dataclass
class ResponseMessageEnvelope(Generic[T]):
"""A message envelope for sending a response to a message."""
...
2024-05-15 12:31:13 -04:00
class SingleThreadedAgentRuntime(AgentRuntime[T]):
2024-05-15 12:31:13 -04:00
def __init__(self) -> None:
self._message_queue: List[BroadcastMessageEnvolope[T] | SendMessageEnvelope[T]] = []
2024-05-15 12:31:13 -04:00
self._per_type_subscribers: Dict[Type[T], List[Agent[T]]] = {}
self._agents: Set[Agent[T]] = set()
def add_agent(self, agent: Agent[T]) -> None:
for message_type in agent.subscriptions:
if message_type not in self._per_type_subscribers:
self._per_type_subscribers[message_type] = []
self._per_type_subscribers[message_type].append(agent)
2024-05-15 12:31:13 -04:00
self._agents.add(agent)
# Returns the response of the message
def send_message(self, message: T, destination: Agent[T]) -> Future[T]:
loop = asyncio.get_event_loop()
future: Future[T] = loop.create_future()
self._message_queue.append(SendMessageEnvelope(message, destination, future))
2024-05-15 12:31:13 -04:00
return future
# Returns the response of all handling agents
def broadcast_message(self, message: T) -> Future[List[T]]:
future: Future[List[T]] = asyncio.get_event_loop().create_future()
self._message_queue.append(BroadcastMessageEnvolope(message, future))
2024-05-15 12:31:13 -04:00
return future
async def _process_send(self, message_envelope: SendMessageEnvelope[T]) -> None:
recipient = message_envelope.destination
2024-05-15 12:31:13 -04:00
if recipient not in self._agents:
message_envelope.future.set_exception(Exception("Recipient not found"))
2024-05-15 12:31:13 -04:00
return
response = await recipient.on_message(message_envelope.message)
message_envelope.future.set_result(response)
2024-05-15 12:31:13 -04:00
async def _process_broadcast(self, message_envelope: BroadcastMessageEnvolope[T]) -> None:
2024-05-15 12:31:13 -04:00
responses: List[T] = []
for agent in self._per_type_subscribers.get(type(message_envelope.message), []):
response = await agent.on_message(message_envelope.message)
2024-05-15 12:31:13 -04:00
responses.append(response)
message_envelope.future.set_result(responses)
2024-05-15 12:31:13 -04:00
async def process_next(self) -> None:
if len(self._message_queue) == 0:
2024-05-15 12:31:13 -04:00
# Yield control to the event loop to allow other tasks to run
await asyncio.sleep(0)
return
message_envelope = self._message_queue.pop(0)
2024-05-15 12:31:13 -04:00
match message_envelope:
case SendMessageEnvelope(message, destination, future):
asyncio.create_task(self._process_send(SendMessageEnvelope(message, destination, future)))
case BroadcastMessageEnvolope(message, future):
asyncio.create_task(self._process_broadcast(BroadcastMessageEnvolope(message, future)))
2024-05-15 12:31:13 -04:00
# Yield control to the message loop to allow other tasks to run
2024-05-15 12:31:13 -04:00
await asyncio.sleep(0)