A programming framework for agentic AI
Migrate Python distributed runtime to use cloud events for event (#4407)
Jack Gerritsa4067f6c0af6
diff --git a/protos/agent_worker.proto b/protos/agent_worker.protoindex 61b00333c..4d346dfec 100644--- a/protos/agent_worker.proto+++ b/protos/agent_worker.proto@@ -117,12 +117,11 @@ message Message {oneof message {RpcRequest request = 1;RpcResponse response = 2;- Event event = 3;+ cloudevent.CloudEvent cloudEvent = 3;RegisterAgentTypeRequest registerAgentTypeRequest = 4;RegisterAgentTypeResponse registerAgentTypeResponse = 5;AddSubscriptionRequest addSubscriptionRequest = 6;AddSubscriptionResponse addSubscriptionResponse = 7;- cloudevent.CloudEvent cloudEvent = 8;}}diff --git a/python/packages/autogen-core/src/autogen_core/application/_constants.py b/python/packages/autogen-core/src/autogen_core/application/_constants.pynew file mode 100644index 000000000..6dab3fffd--- /dev/null+++ b/python/packages/autogen-core/src/autogen_core/application/_constants.py@@ -0,0 +1,13 @@+GRPC_IMPORT_ERROR_STR = (+ "Distributed runtime features require additional dependencies. Install them with: pip install autogen-core[grpc]"+)++DATA_CONTENT_TYPE_ATTR = "datacontenttype"+DATA_SCHEMA_ATTR = "dataschema"+AGENT_SENDER_TYPE_ATTR = "agagentsendertype"+AGENT_SENDER_KEY_ATTR = "agagentsenderkey"+MESSAGE_KIND_ATTR = "agmsgkind"+MESSAGE_KIND_VALUE_PUBLISH = "publish"+MESSAGE_KIND_VALUE_RPC_REQUEST = "rpc_request"+MESSAGE_KIND_VALUE_RPC_RESPONSE = "rpc_response"+MESSAGE_KIND_VALUE_RPC_ERROR = "error"diff --git a/python/packages/autogen-core/src/autogen_core/application/_utils.py b/python/packages/autogen-core/src/autogen_core/application/_utils.pydeleted file mode 100644index 10fbfd1b8..000000000--- a/python/packages/autogen-core/src/autogen_core/application/_utils.py+++ /dev/null@@ -1,3 +0,0 @@-GRPC_IMPORT_ERROR_STR = (- "Distributed runtime features require additional dependencies. Install them with: pip install autogen-core[grpc]"-)diff --git a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime.py b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime.pyindex 0e5fb933a..24007fadf 100644--- a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime.py+++ b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime.py@@ -28,11 +28,15 @@ from typing import (cast,)+from google.protobuf import any_pb2from opentelemetry.trace import TracerProviderfrom typing_extensions import Self, deprecated+from autogen_core.application.protos import cloudevent_pb2+from ..base import (JSON_DATA_CONTENT_TYPE,+ PROTOBUF_DATA_CONTENT_TYPE,Agent,AgentId,AgentInstantiationContext,@@ -49,8 +53,9 @@ from ..base import (from ..base._serialization import MessageSerializer, SerializationRegistryfrom ..base._type_helpers import ChannelArgumentTypefrom ..components import TypePrefixSubscription, TypeSubscription+from . import _constants+from ._constants import GRPC_IMPORT_ERROR_STRfrom ._helpers import SubscriptionManager, get_impl-from ._utils import GRPC_IMPORT_ERROR_STRfrom .protos import agent_worker_pb2, agent_worker_pb2_grpcfrom .telemetry import MessageRuntimeTracingConfig, TraceHelper, get_telemetry_grpc_metadata@@ -178,6 +183,7 @@ class WorkerAgentRuntime(AgentRuntime):host_address: str,tracer_provider: TracerProvider | None = None,extra_grpc_config: ChannelArgumentType | None = None,+ payload_serialization_format: str = JSON_DATA_CONTENT_TYPE,) -> None:self._host_address = host_addressself._trace_helper = TraceHelper(tracer_provider, MessageRuntimeTracingConfig("Worker Runtime"))@@ -198,6 +204,11 @@ class WorkerAgentRuntime(AgentRuntime):self._serialization_registry = SerializationRegistry()self._extra_grpc_config = extra_grpc_config or []+ if payload_serialization_format not in {JSON_DATA_CONTENT_TYPE, PROTOBUF_DATA_CONTENT_TYPE}:+ raise ValueError(f"Unsupported payload serialization format: {payload_serialization_format}")++ self._payload_serialization_format = payload_serialization_format+def start(self) -> None:"""Start the runtime in a background task."""if self._running:@@ -236,8 +247,10 @@ class WorkerAgentRuntime(AgentRuntime):self._background_tasks.add(task)task.add_done_callback(self._raise_on_exception)task.add_done_callback(self._background_tasks.discard)- case "event":- task = asyncio.create_task(self._process_event(message.event))+ case "cloudEvent":+ # The proto typing doesnt resolve this one+ cloud_event = cast(cloudevent_pb2.CloudEvent, message.cloudEvent) # type: ignore+ task = asyncio.create_task(self._process_event(cloud_event))self._background_tasks.add(task)task.add_done_callback(self._raise_on_exception)task.add_done_callback(self._background_tasks.discard)@@ -257,8 +270,6 @@ class WorkerAgentRuntime(AgentRuntime):task.add_done_callback(self._background_tasks.discard)case None:logger.warning("No message")- case other:- logger.error(f"Unknown message type: {other}")except Exception as e:logger.error("Error in read loop", exc_info=e)@@ -381,30 +392,64 @@ class WorkerAgentRuntime(AgentRuntime):if message_id is None:message_id = str(uuid.uuid4())- # TODO: consume message_id-message_type = self._serialization_registry.type_name(message)with self._trace_helper.trace_block("create", topic_id, parent=None, extraAttributes={"message_type": message_type}):serialized_message = self._serialization_registry.serialize(- message, type_name=message_type, data_content_type=JSON_DATA_CONTENT_TYPE+ message, type_name=message_type, data_content_type=self._payload_serialization_format)- telemetry_metadata = get_telemetry_grpc_metadata()- runtime_message = agent_worker_pb2.Message(- event=agent_worker_pb2.Event(- topic_type=topic_id.type,- topic_source=topic_id.source,- source=agent_worker_pb2.AgentId(type=sender.type, key=sender.key) if sender is not None else None,- metadata=telemetry_metadata,- payload=agent_worker_pb2.Payload(- data_type=message_type,- data=serialized_message,- data_content_type=JSON_DATA_CONTENT_TYPE,- ),++ sender_id = sender or AgentId("unknown", "unknown")+ attributes = {+ _constants.DATA_CONTENT_TYPE_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(+ ce_string=self._payload_serialization_format+ ),+ _constants.DATA_SCHEMA_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(ce_string=message_type),+ _constants.AGENT_SENDER_TYPE_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(+ ce_string=sender_id.type+ ),+ _constants.AGENT_SENDER_KEY_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(+ ce_string=sender_id.key+ ),+ _constants.MESSAGE_KIND_ATTR: cloudevent_pb2.CloudEvent.CloudEventAttributeValue(+ ce_string=_constants.MESSAGE_KIND_VALUE_PUBLISH+ ),+ }++ # If sending JSON we fill text_data with the serialized message+ # If sending Protobuf we fill proto_data with the serialized message+ # TODO: add an encoding field for serializer++ if self._payload_serialization_format == JSON_DATA_CONTENT_TYPE:+ runtime_message = agent_worker_pb2.Message(+ cloudEvent=cloudevent_pb2.CloudEvent(+ id=message_id,+ spec_version="1.0",+ type=topic_id.type,+ source=topic_id.source,+ attributes=attributes,+ # TODO: use text, or proto fields appropriately+ binary_data=serialized_message,+ )+ )+ else:+ # We need to unpack the serialized proto back into an Any+ # TODO: find a way to prevent the roundtrip serialization+ any_proto = any_pb2.Any()+ any_proto.ParseFromString(serialized_message)+ runtime_message = agent_worker_pb2.Message(+ cloudEvent=cloudevent_pb2.CloudEvent(+ id=message_id,+ spec_version="1.0",+ type=topic_id.type,+ source=topic_id.source,+ attributes=attributes,+ proto_data=any_proto,+ ))- )+ telemetry_metadata = get_telemetry_grpc_metadata()task = asyncio.create_task(self._send_message(runtime_message, "publish", topic_id, telemetry_metadata))self._background_tasks.add(task)task.add_done_callback(self._raise_on_exception)@@ -523,28 +568,58 @@ class WorkerAgentRuntime(AgentRuntime):else:future.set_result(result)- async def _process_event(self, event: agent_worker_pb2.Event) -> None:- message = self._serialization_registry.deserialize(- event.payload.data, type_name=event.payload.data_type, data_content_type=event.payload.data_content_type- )+ async def _process_event(self, event: cloudevent_pb2.CloudEvent) -> None:+ event_attributes = event.attributessender: AgentId | None = None- if event.HasField("source"):- sender = AgentId(event.source.type, event.source.key)- topic_id = TopicId(event.topic_type, event.topic_source)+ if (+ _constants.AGENT_SENDER_TYPE_ATTR in event_attributes+ and _constants.AGENT_SENDER_KEY_ATTR in event_attributes+ ):+ sender = AgentId(+ event_attributes[_constants.AGENT_SENDER_TYPE_ATTR].ce_string,+ event_attributes[_constants.AGENT_SENDER_KEY_ATTR].ce_string,+ )+ topic_id = TopicId(event.type, event.source)# Get the recipients for the topic.recipients = await self._subscription_manager.get_subscribed_recipients(topic_id)++ message_content_type = event_attributes[_constants.DATA_CONTENT_TYPE_ATTR].ce_string+ message_type = event_attributes[_constants.DATA_SCHEMA_ATTR].ce_string++ if message_content_type == JSON_DATA_CONTENT_TYPE:+ message = self._serialization_registry.deserialize(+ event.binary_data, type_name=message_type, data_content_type=message_content_type+ )+ elif message_content_type == PROTOBUF_DATA_CONTENT_TYPE:+ # TODO: find a way to prevent the roundtrip serialization+ proto_binary_data = event.proto_data.SerializeToString()+ message = self._serialization_registry.deserialize(+ proto_binary_data, type_name=message_type, data_content_type=message_content_type+ )+ else:+ raise ValueError(f"Unsupported message content type: {message_content_type}")++ # TODO: dont read these values in the runtime+ topic_type_suffix = topic_id.type.split(":", maxsplit=1)[1] if ":" in topic_id.type else ""+ is_rpc = topic_type_suffix == _constants.MESSAGE_KIND_VALUE_RPC_REQUEST+ is_marked_rpc_type = (+ _constants.MESSAGE_KIND_ATTR in event_attributes+ and event_attributes[_constants.MESSAGE_KIND_ATTR].ce_string == _constants.MESSAGE_KIND_VALUE_RPC_REQUEST+ )+ if is_rpc and not is_marked_rpc_type:+ warnings.warn("Received RPC request with topic type suffix but not marked as RPC request.", stacklevel=2)+# Send the message to each recipient.responses: List[Awaitable[Any]] = []for agent_id in recipients:if agent_id == sender:continue- # TODO: consume message_idmessage_context = MessageContext(sender=sender,topic_id=topic_id,- is_rpc=False,+ is_rpc=is_rpc,cancellation_token=CancellationToken(),- message_id="NOT_DEFINED_TODO_FIX",+ message_id=event.id,)agent = await self._get_agent(agent_id)with MessageHandlerContext.populate_context(agent.id):@@ -554,7 +629,7 @@ class WorkerAgentRuntime(AgentRuntime):"process",agent.id,parent=event.metadata,- extraAttributes={"message_type": event.payload.data_type},+ extraAttributes={"message_type": message_type},):await agent.on_message(message, ctx=message_context)diff --git a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host.py b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host.pyindex d7fee07ff..b9befce58 100644--- a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host.py+++ b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host.py@@ -4,7 +4,7 @@ import signalfrom typing import Optional, Sequencefrom ..base._type_helpers import ChannelArgumentType-from ._utils import GRPC_IMPORT_ERROR_STR+from ._constants import GRPC_IMPORT_ERROR_STRfrom ._worker_runtime_host_servicer import WorkerAgentRuntimeHostServicertry:diff --git a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host_servicer.py b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host_servicer.pyindex 7c597bd07..e24a7db3f 100644--- a/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host_servicer.py+++ b/python/packages/autogen-core/src/autogen_core/application/_worker_runtime_host_servicer.py@@ -2,21 +2,21 @@ import asyncioimport loggingfrom _collections_abc import AsyncIterator, Iteratorfrom asyncio import Future, Task-from typing import Any, Dict, Set+from typing import Any, Dict, Set, castfrom autogen_core.base._type_prefix_subscription import TypePrefixSubscriptionfrom ..base import Subscription, TopicIdfrom ..components import TypeSubscription+from ._constants import GRPC_IMPORT_ERROR_STRfrom ._helpers import SubscriptionManager-from ._utils import GRPC_IMPORT_ERROR_STRtry:import grpcexcept ImportError as e:raise ImportError(GRPC_IMPORT_ERROR_STR) from e-from .protos import agent_worker_pb2, agent_worker_pb2_grpc+from .protos import agent_worker_pb2, agent_worker_pb2_grpc, cloudevent_pb2logger = logging.getLogger("autogen_core")event_logger = logging.getLogger("autogen_core.events")@@ -84,7 +84,7 @@ class WorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):for agent_type in agent_types:logger.info(f"Removing agent type {agent_type} from agent type to client id mapping")del self._agent_type_to_client_id[agent_type]- for sub_id in self._client_id_to_subscription_id_mapping.get(client_id, []):+ for sub_id in self._client_id_to_subscription_id_mapping.get(client_id, set()):logger.info(f"Client id {client_id} disconnected. Removing corresponding subscription with id {id}")await self._subscription_manager.remove_subscription(sub_id)logger.info(f"Client {client_id} disconnected successfully")@@ -114,8 +114,9 @@ class WorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):self._background_tasks.add(task)task.add_done_callback(self._raise_on_exception)task.add_done_callback(self._background_tasks.discard)- case "event":- event: agent_worker_pb2.Event = message.event+ case "cloudEvent":+ # The proto typing doesnt resolve this one+ event = cast(cloudevent_pb2.CloudEvent, message.cloudEvent) # type: ignoretask = asyncio.create_task(self._process_event(event))self._background_tasks.add(task)task.add_done_callback(self._raise_on_exception)@@ -138,8 +139,6 @@ class WorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):logger.warning(f"Received unexpected message type: {oneofcase}")case None:logger.warning("Received empty message")- case other:- logger.error(f"Received unexpected message: {other}")async def _process_request(self, request: agent_worker_pb2.RpcRequest, client_id: int) -> None:# Deliver the message to a client given the target agent type.@@ -178,8 +177,8 @@ class WorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):future = self._pending_responses[client_id].pop(response.request_id)future.set_result(response)- async def _process_event(self, event: agent_worker_pb2.Event) -> None:- topic_id = TopicId(type=event.topic_type, source=event.topic_source)+ async def _process_event(self, event: cloudevent_pb2.CloudEvent) -> None:+ topic_id = TopicId(type=event.type, source=event.source)recipients = await self._subscription_manager.get_subscribed_recipients(topic_id)# Get the client ids of the recipients.async with self._agent_type_to_client_id_lock:@@ -192,7 +191,7 @@ class WorkerAgentRuntimeHostServicer(agent_worker_pb2_grpc.AgentRpcServicer):logger.error(f"Agent {recipient.type} and its client not found for topic {topic_id}.")# Deliver the event to clients.for client_id in client_ids:- await self._send_queues[client_id].put(agent_worker_pb2.Message(event=event))+ await self._send_queues[client_id].put(agent_worker_pb2.Message(cloudEvent=event))async def _process_register_agent_type_request(self, register_agent_type_req: agent_worker_pb2.RegisterAgentTypeRequest, client_id: intdiff --git a/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.py b/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.pyindex 8f143d770..319ee2c63 100644--- a/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.py+++ b/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.py@@ -16,7 +16,7 @@ import cloudevent_pb2 as cloudevent__pb2from google.protobuf import any_pb2 as google_dot_protobuf_dot_any__pb2-DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12\x61gent_worker.proto\x12\x06\x61gents\x1a\x10\x63loudevent.proto\x1a\x19google/protobuf/any.proto\"\'\n\x07TopicId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0e\n\x06source\x18\x02 \x01(\t\"$\n\x07\x41gentId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0b\n\x03key\x18\x02 \x01(\t\"E\n\x07Payload\x12\x11\n\tdata_type\x18\x01 \x01(\t\x12\x19\n\x11\x64\x61ta_content_type\x18\x02 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\x89\x02\n\nRpcRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12$\n\x06source\x18\x02 \x01(\x0b\x32\x0f.agents.AgentIdH\x00\x88\x01\x01\x12\x1f\n\x06target\x18\x03 \x01(\x0b\x32\x0f.agents.AgentId\x12\x0e\n\x06method\x18\x04 \x01(\t\x12 \n\x07payload\x18\x05 \x01(\x0b\x32\x0f.agents.Payload\x12\x32\n\x08metadata\x18\x06 \x03(\x0b\x32 .agents.RpcRequest.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\t\n\x07_source\"\xb8\x01\n\x0bRpcResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12 \n\x07payload\x18\x02 \x01(\x0b\x32\x0f.agents.Payload\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12\x33\n\x08metadata\x18\x04 \x03(\x0b\x32!.agents.RpcResponse.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe4\x01\n\x05\x45vent\x12\x12\n\ntopic_type\x18\x01 \x01(\t\x12\x14\n\x0ctopic_source\x18\x02 \x01(\t\x12$\n\x06source\x18\x03 \x01(\x0b\x32\x0f.agents.AgentIdH\x00\x88\x01\x01\x12 \n\x07payload\x18\x04 \x01(\x0b\x32\x0f.agents.Payload\x12-\n\x08metadata\x18\x05 \x03(\x0b\x32\x1b.agents.Event.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\t\n\x07_source\"<\n\x18RegisterAgentTypeRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\"^\n\x19RegisterAgentTypeResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\":\n\x10TypeSubscription\x12\x12\n\ntopic_type\x18\x01 \x01(\t\x12\x12\n\nagent_type\x18\x02 \x01(\t\"G\n\x16TypePrefixSubscription\x12\x19\n\x11topic_type_prefix\x18\x01 \x01(\t\x12\x12\n\nagent_type\x18\x02 \x01(\t\"\x96\x01\n\x0cSubscription\x12\x34\n\x10typeSubscription\x18\x01 \x01(\x0b\x32\x18.agents.TypeSubscriptionH\x00\x12@\n\x16typePrefixSubscription\x18\x02 \x01(\x0b\x32\x1e.agents.TypePrefixSubscriptionH\x00\x42\x0e\n\x0csubscription\"X\n\x16\x41\x64\x64SubscriptionRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12*\n\x0csubscription\x18\x02 \x01(\x0b\x32\x14.agents.Subscription\"\\\n\x17\x41\x64\x64SubscriptionResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"\x9d\x01\n\nAgentState\x12!\n\x08\x61gent_id\x18\x01 \x01(\x0b\x32\x0f.agents.AgentId\x12\x0c\n\x04\x65Tag\x18\x02 \x01(\t\x12\x15\n\x0b\x62inary_data\x18\x03 \x01(\x0cH\x00\x12\x13\n\ttext_data\x18\x04 \x01(\tH\x00\x12*\n\nproto_data\x18\x05 \x01(\x0b\x32\x14.google.protobuf.AnyH\x00\x42\x06\n\x04\x64\x61ta\"j\n\x10GetStateResponse\x12\'\n\x0b\x61gent_state\x18\x01 \x01(\x0b\x32\x12.agents.AgentState\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"B\n\x11SaveStateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\x05\x65rror\x18\x02 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"\xc6\x03\n\x07Message\x12%\n\x07request\x18\x01 \x01(\x0b\x32\x12.agents.RpcRequestH\x00\x12\'\n\x08response\x18\x02 \x01(\x0b\x32\x13.agents.RpcResponseH\x00\x12\x1e\n\x05\x65vent\x18\x03 \x01(\x0b\x32\r.agents.EventH\x00\x12\x44\n\x18registerAgentTypeRequest\x18\x04 \x01(\x0b\x32 .agents.RegisterAgentTypeRequestH\x00\x12\x46\n\x19registerAgentTypeResponse\x18\x05 \x01(\x0b\x32!.agents.RegisterAgentTypeResponseH\x00\x12@\n\x16\x61\x64\x64SubscriptionRequest\x18\x06 \x01(\x0b\x32\x1e.agents.AddSubscriptionRequestH\x00\x12\x42\n\x17\x61\x64\x64SubscriptionResponse\x18\x07 \x01(\x0b\x32\x1f.agents.AddSubscriptionResponseH\x00\x12,\n\ncloudEvent\x18\x08 \x01(\x0b\x32\x16.cloudevent.CloudEventH\x00\x42\t\n\x07message2\xb2\x01\n\x08\x41gentRpc\x12\x33\n\x0bOpenChannel\x12\x0f.agents.Message\x1a\x0f.agents.Message(\x01\x30\x01\x12\x35\n\x08GetState\x12\x0f.agents.AgentId\x1a\x18.agents.GetStateResponse\x12:\n\tSaveState\x12\x12.agents.AgentState\x1a\x19.agents.SaveStateResponseB!\xaa\x02\x1eMicrosoft.AutoGen.Abstractionsb\x06proto3')+DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x12\x61gent_worker.proto\x12\x06\x61gents\x1a\x10\x63loudevent.proto\x1a\x19google/protobuf/any.proto\"\'\n\x07TopicId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0e\n\x06source\x18\x02 \x01(\t\"$\n\x07\x41gentId\x12\x0c\n\x04type\x18\x01 \x01(\t\x12\x0b\n\x03key\x18\x02 \x01(\t\"E\n\x07Payload\x12\x11\n\tdata_type\x18\x01 \x01(\t\x12\x19\n\x11\x64\x61ta_content_type\x18\x02 \x01(\t\x12\x0c\n\x04\x64\x61ta\x18\x03 \x01(\x0c\"\x89\x02\n\nRpcRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12$\n\x06source\x18\x02 \x01(\x0b\x32\x0f.agents.AgentIdH\x00\x88\x01\x01\x12\x1f\n\x06target\x18\x03 \x01(\x0b\x32\x0f.agents.AgentId\x12\x0e\n\x06method\x18\x04 \x01(\t\x12 \n\x07payload\x18\x05 \x01(\x0b\x32\x0f.agents.Payload\x12\x32\n\x08metadata\x18\x06 \x03(\x0b\x32 .agents.RpcRequest.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\t\n\x07_source\"\xb8\x01\n\x0bRpcResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12 \n\x07payload\x18\x02 \x01(\x0b\x32\x0f.agents.Payload\x12\r\n\x05\x65rror\x18\x03 \x01(\t\x12\x33\n\x08metadata\x18\x04 \x03(\x0b\x32!.agents.RpcResponse.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\"\xe4\x01\n\x05\x45vent\x12\x12\n\ntopic_type\x18\x01 \x01(\t\x12\x14\n\x0ctopic_source\x18\x02 \x01(\t\x12$\n\x06source\x18\x03 \x01(\x0b\x32\x0f.agents.AgentIdH\x00\x88\x01\x01\x12 \n\x07payload\x18\x04 \x01(\x0b\x32\x0f.agents.Payload\x12-\n\x08metadata\x18\x05 \x03(\x0b\x32\x1b.agents.Event.MetadataEntry\x1a/\n\rMetadataEntry\x12\x0b\n\x03key\x18\x01 \x01(\t\x12\r\n\x05value\x18\x02 \x01(\t:\x02\x38\x01\x42\t\n\x07_source\"<\n\x18RegisterAgentTypeRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0c\n\x04type\x18\x02 \x01(\t\"^\n\x19RegisterAgentTypeResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\":\n\x10TypeSubscription\x12\x12\n\ntopic_type\x18\x01 \x01(\t\x12\x12\n\nagent_type\x18\x02 \x01(\t\"G\n\x16TypePrefixSubscription\x12\x19\n\x11topic_type_prefix\x18\x01 \x01(\t\x12\x12\n\nagent_type\x18\x02 \x01(\t\"\x96\x01\n\x0cSubscription\x12\x34\n\x10typeSubscription\x18\x01 \x01(\x0b\x32\x18.agents.TypeSubscriptionH\x00\x12@\n\x16typePrefixSubscription\x18\x02 \x01(\x0b\x32\x1e.agents.TypePrefixSubscriptionH\x00\x42\x0e\n\x0csubscription\"X\n\x16\x41\x64\x64SubscriptionRequest\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12*\n\x0csubscription\x18\x02 \x01(\x0b\x32\x14.agents.Subscription\"\\\n\x17\x41\x64\x64SubscriptionResponse\x12\x12\n\nrequest_id\x18\x01 \x01(\t\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"\x9d\x01\n\nAgentState\x12!\n\x08\x61gent_id\x18\x01 \x01(\x0b\x32\x0f.agents.AgentId\x12\x0c\n\x04\x65Tag\x18\x02 \x01(\t\x12\x15\n\x0b\x62inary_data\x18\x03 \x01(\x0cH\x00\x12\x13\n\ttext_data\x18\x04 \x01(\tH\x00\x12*\n\nproto_data\x18\x05 \x01(\x0b\x32\x14.google.protobuf.AnyH\x00\x42\x06\n\x04\x64\x61ta\"j\n\x10GetStateResponse\x12\'\n\x0b\x61gent_state\x18\x01 \x01(\x0b\x32\x12.agents.AgentState\x12\x0f\n\x07success\x18\x02 \x01(\x08\x12\x12\n\x05\x65rror\x18\x03 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"B\n\x11SaveStateResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\x05\x65rror\x18\x02 \x01(\tH\x00\x88\x01\x01\x42\x08\n\x06_error\"\xa6\x03\n\x07Message\x12%\n\x07request\x18\x01 \x01(\x0b\x32\x12.agents.RpcRequestH\x00\x12\'\n\x08response\x18\x02 \x01(\x0b\x32\x13.agents.RpcResponseH\x00\x12,\n\ncloudEvent\x18\x03 \x01(\x0b\x32\x16.cloudevent.CloudEventH\x00\x12\x44\n\x18registerAgentTypeRequest\x18\x04 \x01(\x0b\x32 .agents.RegisterAgentTypeRequestH\x00\x12\x46\n\x19registerAgentTypeResponse\x18\x05 \x01(\x0b\x32!.agents.RegisterAgentTypeResponseH\x00\x12@\n\x16\x61\x64\x64SubscriptionRequest\x18\x06 \x01(\x0b\x32\x1e.agents.AddSubscriptionRequestH\x00\x12\x42\n\x17\x61\x64\x64SubscriptionResponse\x18\x07 \x01(\x0b\x32\x1f.agents.AddSubscriptionResponseH\x00\x42\t\n\x07message2\xb2\x01\n\x08\x41gentRpc\x12\x33\n\x0bOpenChannel\x12\x0f.agents.Message\x1a\x0f.agents.Message(\x01\x30\x01\x12\x35\n\x08GetState\x12\x0f.agents.AgentId\x1a\x18.agents.GetStateResponse\x12:\n\tSaveState\x12\x12.agents.AgentState\x1a\x19.agents.SaveStateResponseB!\xaa\x02\x1eMicrosoft.AutoGen.Abstractionsb\x06proto3')_globals = globals()_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)@@ -69,7 +69,7 @@ if _descriptor._USE_C_DESCRIPTORS == False:_globals['_SAVESTATERESPONSE']._serialized_start=1807_globals['_SAVESTATERESPONSE']._serialized_end=1873_globals['_MESSAGE']._serialized_start=1876- _globals['_MESSAGE']._serialized_end=2330- _globals['_AGENTRPC']._serialized_start=2333- _globals['_AGENTRPC']._serialized_end=2511+ _globals['_MESSAGE']._serialized_end=2298+ _globals['_AGENTRPC']._serialized_start=2301+ _globals['_AGENTRPC']._serialized_end=2479# @@protoc_insertion_point(module_scope)diff --git a/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.pyi b/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.pyiindex 728bfafcc..79e384ab9 100644--- a/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.pyi+++ b/python/packages/autogen-core/src/autogen_core/application/protos/agent_worker_pb2.pyi@@ -437,18 +437,17 @@ class Message(google.protobuf.message.Message):REQUEST_FIELD_NUMBER: builtins.intRESPONSE_FIELD_NUMBER: builtins.int- EVENT_FIELD_NUMBER: builtins.int+ CLOUDEVENT_FIELD_NUMBER: builtins.intREGISTERAGENTTYPEREQUEST_FIELD_NUMBER: builtins.intREGISTERAGENTTYPERESPONSE_FIELD_NUMBER: builtins.intADDSUBSCRIPTIONREQUEST_FIELD_NUMBER: builtins.intADDSUBSCRIPTIONRESPONSE_FIELD_NUMBER: builtins.int- CLOUDEVENT_FIELD_NUMBER: builtins.int@propertydef request(self) -> global___RpcRequest: ...@propertydef response(self) -> global___RpcResponse: ...@property- def event(self) -> global___Event: ...+ def cloudEvent(self) -> cloudevent_pb2.CloudEvent: ...@propertydef registerAgentTypeRequest(self) -> global___RegisterAgentTypeRequest: ...@property@@ -457,22 +456,19 @@ class Message(google.protobuf.message.Message):def addSubscriptionRequest(self) -> global___AddSubscriptionRequest: ...@propertydef addSubscriptionResponse(self) -> global___AddSubscriptionResponse: ...- @property- def cloudEvent(self) -> cloudevent_pb2.CloudEvent: ...def __init__(self,*,request: global___RpcRequest | None = ...,response: global___RpcResponse | None = ...,- event: global___Event | None = ...,+ cloudEvent: cloudevent_pb2.CloudEvent | None = ...,registerAgentTypeRequest: global___RegisterAgentTypeRequest | None = ...,registerAgentTypeResponse: global___RegisterAgentTypeResponse | None = ...,addSubscriptionRequest: global___AddSubscriptionRequest | None = ...,addSubscriptionResponse: global___AddSubscriptionResponse | None = ...,- cloudEvent: cloudevent_pb2.CloudEvent | None = ...,) -> None: ...- def HasField(self, field_name: typing.Literal["addSubscriptionRequest", b"addSubscriptionRequest", "addSubscriptionResponse", b"addSubscriptionResponse", "cloudEvent", b"cloudEvent", "event", b"event", "message", b"message", "registerAgentTypeRequest", b"registerAgentTypeRequest", "registerAgentTypeResponse", b"registerAgentTypeResponse", "request", b"request", "response", b"response"]) -> builtins.bool: ...- def ClearField(self, field_name: typing.Literal["addSubscriptionRequest", b"addSubscriptionRequest", "addSubscriptionResponse", b"addSubscriptionResponse", "cloudEvent", b"cloudEvent", "event", b"event", "message", b"message", "registerAgentTypeRequest", b"registerAgentTypeRequest", "registerAgentTypeResponse", b"registerAgentTypeResponse", "request", b"request", "response", b"response"]) -> None: ...- def WhichOneof(self, oneof_group: typing.Literal["message", b"message"]) -> typing.Literal["request", "response", "event", "registerAgentTypeRequest", "registerAgentTypeResponse", "addSubscriptionRequest", "addSubscriptionResponse", "cloudEvent"] | None: ...+ def HasField(self, field_name: typing.Literal["addSubscriptionRequest", b"addSubscriptionRequest", "addSubscriptionResponse", b"addSubscriptionResponse", "cloudEvent", b"cloudEvent", "message", b"message", "registerAgentTypeRequest", b"registerAgentTypeRequest", "registerAgentTypeResponse", b"registerAgentTypeResponse", "request", b"request", "response", b"response"]) -> builtins.bool: ...+ def ClearField(self, field_name: typing.Literal["addSubscriptionRequest", b"addSubscriptionRequest", "addSubscriptionResponse", b"addSubscriptionResponse", "cloudEvent", b"cloudEvent", "message", b"message", "registerAgentTypeRequest", b"registerAgentTypeRequest", "registerAgentTypeResponse", b"registerAgentTypeResponse", "request", b"request", "response", b"response"]) -> None: ...+ def WhichOneof(self, oneof_group: typing.Literal["message", b"message"]) -> typing.Literal["request", "response", "cloudEvent", "registerAgentTypeRequest", "registerAgentTypeResponse", "addSubscriptionRequest", "addSubscriptionResponse"] | None: ...global___Message = Messagediff --git a/python/packages/autogen-core/src/autogen_core/base/__init__.py b/python/packages/autogen-core/src/autogen_core/base/__init__.pyindex e4463e7ee..8d95083ec 100644--- a/python/packages/autogen-core/src/autogen_core/base/__init__.py+++ b/python/packages/autogen-core/src/autogen_core/base/__init__.py@@ -16,6 +16,7 @@ from ._message_context import MessageContextfrom ._message_handler_context import MessageHandlerContextfrom ._serialization import (JSON_DATA_CONTENT_TYPE,+ PROTOBUF_DATA_CONTENT_TYPE,MessageSerializer,SerializationRegistry,UnknownPayload,@@ -43,6 +44,7 @@ __all__ = ["SubscriptionInstantiationContext","MessageHandlerContext","JSON_DATA_CONTENT_TYPE",+ "PROTOBUF_DATA_CONTENT_TYPE","MessageSerializer","try_get_known_serializers_for_type","UnknownPayload",diff --git a/python/packages/autogen-core/tests/test_utils/__init__.py b/python/packages/autogen-core/tests/test_utils/__init__.pyindex 92096550c..5de7519fc 100644--- a/python/packages/autogen-core/tests/test_utils/__init__.py+++ b/python/packages/autogen-core/tests/test_utils/__init__.py@@ -23,12 +23,14 @@ class LoopbackAgent(RoutedAgent):def __init__(self) -> None:super().__init__("A loop back agent.")self.num_calls = 0+ self.received_messages: list[Any] = []@message_handlerasync def on_new_message(self, message: MessageType | ContentMessage, ctx: MessageContext) -> MessageType | ContentMessage:self.num_calls += 1+ self.received_messages.append(message)return messagediff --git a/python/packages/autogen-core/tests/test_worker_runtime.py b/python/packages/autogen-core/tests/test_worker_runtime.pyindex 26c95dc01..2a7d3acdc 100644--- a/python/packages/autogen-core/tests/test_worker_runtime.py+++ b/python/packages/autogen-core/tests/test_worker_runtime.py@@ -1,22 +1,28 @@import asyncioimport loggingimport os-from typing import List+from typing import Any, Listimport pytestfrom autogen_core.application import WorkerAgentRuntime, WorkerAgentRuntimeHostfrom autogen_core.base import (+ PROTOBUF_DATA_CONTENT_TYPE,AgentId,AgentType,+ MessageContext,+ Subscription,TopicId,try_get_known_serializers_for_type,)-from autogen_core.base._subscription import Subscriptionfrom autogen_core.components import (DefaultTopicId,+ RoutedAgent,TypeSubscription,+ default_subscription,+ event,type_subscription,)+from protos.serialization_test_pb2 import ProtoMessagefrom test_utils import (CascadingAgent,CascadingMessageType,@@ -401,6 +407,62 @@ async def test_disconnected_agent() -> None:await worker1_2.stop()+@default_subscription+class ProtoReceivingAgent(RoutedAgent):+ def __init__(self) -> None:+ super().__init__("A loop back agent.")+ self.num_calls = 0+ self.received_messages: list[Any] = []++ @event+ async def on_new_message(self, message: ProtoMessage, ctx: MessageContext) -> None:+ self.num_calls += 1+ self.received_messages.append(message)+++async def test_proto_payloads() -> None:+ host_address = "localhost:50057"+ host = WorkerAgentRuntimeHost(address=host_address)+ host.start()+ receiver_runtime = WorkerAgentRuntime(+ host_address=host_address, payload_serialization_format=PROTOBUF_DATA_CONTENT_TYPE+ )+ receiver_runtime.start()+ publisher_runtime = WorkerAgentRuntime(+ host_address=host_address, payload_serialization_format=PROTOBUF_DATA_CONTENT_TYPE+ )+ publisher_runtime.add_message_serializer(try_get_known_serializers_for_type(ProtoMessage))+ publisher_runtime.start()++ await ProtoReceivingAgent.register(receiver_runtime, "name", ProtoReceivingAgent)++ await publisher_runtime.publish_message(ProtoMessage(message="Hello!"), topic_id=DefaultTopicId())++ await asyncio.sleep(2)++ # Agent in default namespace should have received the message+ long_running_agent = await receiver_runtime.try_get_underlying_agent_instance(+ AgentId("name", "default"), type=ProtoReceivingAgent+ )+ assert long_running_agent.num_calls == 1+ assert long_running_agent.received_messages[0].message == "Hello!"++ # Agent in other namespace should not have received the message+ other_long_running_agent = await receiver_runtime.try_get_underlying_agent_instance(+ AgentId("name", key="other"), type=ProtoReceivingAgent+ )+ assert other_long_running_agent.num_calls == 0+ assert len(other_long_running_agent.received_messages) == 0++ await receiver_runtime.stop()+ await publisher_runtime.stop()+ await host.stop()+++# TODO add tests for failure to deserialize++@pytest.mark.asyncioasync def test_grpc_max_message_size() -> None:default_max_size = 2**22