A programming framework for agentic AI
add a way to provide extra grpc options (#3667)
Mohammad Mazraeh29c23d53afc6
diff --git a/python/packages/autogen-core/docs/src/core-user-guide/core-concepts/faqs.md b/python/packages/autogen-core/docs/src/core-user-guide/core-concepts/faqs.mdindex 1ecc14ffb..5e12f8603 100644--- a/python/packages/autogen-core/docs/src/core-user-guide/core-concepts/faqs.md+++ b/python/packages/autogen-core/docs/src/core-user-guide/core-concepts/faqs.md@@ -15,3 +15,22 @@ This allows your agent to work in a distributed environment a well as a local onAn {py:class}`autogen_core.base.AgentId` is composed of a `type` and a `key`. The type corresponds to the factory that created the agent, and the key is a runtime, data dependent key for this instance.The key can correspond to a user id, a session id, or could just be "default" if you don't need to differentiate between instances. Each unique key will create a new instance of the agent, based on the factory provided. This allows the system to automatically scale to different instances of the same agent, and to manage the lifecycle of each instance independently based on how you choose to handle keys in your application.++## How do I increase the GRPC message size?++If you need to provide custom gRPC options, such as overriding the `max_send_message_length` and `max_receive_message_length`, you can define an `extra_grpc_config` variable and pass it to both the `WorkerAgentRuntimeHost` and `WorkerAgentRuntime` instances.++```python+# Define custom gRPC options+extra_grpc_config = [+ ("grpc.max_send_message_length", new_max_size),+ ("grpc.max_receive_message_length", new_max_size),+]++# Create instances of WorkerAgentRuntimeHost and WorkerAgentRuntime with the custom gRPC options++host = WorkerAgentRuntimeHost(address=host_address, extra_grpc_config=extra_grpc_config)+worker1 = WorkerAgentRuntime(host_address=host_address, extra_grpc_config=extra_grpc_config)+```++**Note**: When `WorkerAgentRuntime` creates a host connection for the clients, it uses `DEFAULT_GRPC_CONFIG` from `HostConnection` class as default set of values which will can be overriden if you pass parameters with the same name using `extra_grpc_config`.diff --git a/python/packages/autogen-core/src/autogen_core/application/__init__.py b/python/packages/autogen-core/src/autogen_core/application/__init__.pyindex 60bf1bb94..0caa89c6d 100644--- a/python/packages/autogen-core/src/autogen_core/application/__init__.py+++ b/python/packages/autogen-core/src/autogen_core/application/__init__.py@@ -6,8 +6,4 @@ from ._single_threaded_agent_runtime import SingleThreadedAgentRuntimefrom ._worker_runtime import WorkerAgentRuntimefrom ._worker_runtime_host import WorkerAgentRuntimeHost-__all__ = [- "SingleThreadedAgentRuntime",- "WorkerAgentRuntime",- "WorkerAgentRuntimeHost",-]+__all__ = ["SingleThreadedAgentRuntime", "WorkerAgentRuntime", "WorkerAgentRuntimeHost"]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 ab38cdfbf..ac3e00e4a 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@@ -34,6 +34,7 @@ from typing_extensions import Self, deprecatedfrom autogen_core.base import JSON_DATA_CONTENT_TYPEfrom autogen_core.base._serialization import MessageSerializer, SerializationRegistry+from autogen_core.base._type_helpers import ChannelArgumentTypefrom ..base import (Agent,@@ -63,6 +64,7 @@ event_logger = logging.getLogger("autogen_core.events")P = ParamSpec("P")T = TypeVar("T", bound=Agent)+type_func_alias = type@@ -78,20 +80,27 @@ class QueueAsyncIterable(AsyncIterator[Any], AsyncIterable[Any]):class HostConnection:- DEFAULT_GRPC_CONFIG: ClassVar[Mapping[str, Any]] = {- "methodConfig": [- {- "name": [{}],- "retryPolicy": {- "maxAttempts": 3,- "initialBackoff": "0.01s",- "maxBackoff": "5s",- "backoffMultiplier": 2,- "retryableStatusCodes": ["UNAVAILABLE"],- },- }- ],- }+ DEFAULT_GRPC_CONFIG: ClassVar[ChannelArgumentType] = [+ (+ "grpc.service_config",+ json.dumps(+ {+ "methodConfig": [+ {+ "name": [{}],+ "retryPolicy": {+ "maxAttempts": 3,+ "initialBackoff": "0.01s",+ "maxBackoff": "5s",+ "backoffMultiplier": 2,+ "retryableStatusCodes": ["UNAVAILABLE"],+ },+ }+ ],+ }+ ),+ )+ ]def __init__(self, channel: grpc.aio.Channel) -> None: # type: ignoreself._channel = channel@@ -100,9 +109,17 @@ class HostConnection:self._connection_task: Task[None] | None = None@classmethod- def from_host_address(cls, host_address: str, grpc_config: Mapping[str, Any] = DEFAULT_GRPC_CONFIG) -> Self:+ def from_host_address(cls, host_address: str, extra_grpc_config: ChannelArgumentType = DEFAULT_GRPC_CONFIG) -> Self:logger.info("Connecting to %s", host_address)- channel = grpc.aio.insecure_channel(host_address, options=[("grpc.service_config", json.dumps(grpc_config))])+ # Always use DEFAULT_GRPC_CONFIG and override it with provided grpc_config+ merged_options = [+ (k, v) for k, v in {**dict(HostConnection.DEFAULT_GRPC_CONFIG), **dict(extra_grpc_config)}.items()+ ]++ channel = grpc.aio.insecure_channel(+ host_address,+ options=merged_options,+ )instance = cls(channel)instance._connection_task = asyncio.create_task(instance._connect(channel, instance._send_queue, instance._recv_queue)@@ -150,7 +167,12 @@ class HostConnection:class WorkerAgentRuntime(AgentRuntime):- def __init__(self, host_address: str, tracer_provider: TracerProvider | None = None) -> None:+ def __init__(+ self,+ host_address: str,+ tracer_provider: TracerProvider | None = None,+ extra_grpc_config: ChannelArgumentType | None = None,+ ) -> None:self._host_address = host_addressself._trace_helper = TraceHelper(tracer_provider, MessageRuntimeTracingConfig("Worker Runtime"))self._per_type_subscribers: DefaultDict[tuple[str, str], Set[AgentId]] = defaultdict(set)@@ -168,13 +190,16 @@ class WorkerAgentRuntime(AgentRuntime):self._background_tasks: Set[Task[Any]] = set()self._subscription_manager = SubscriptionManager()self._serialization_registry = SerializationRegistry()+ self._extra_grpc_config = extra_grpc_config or []def start(self) -> None:"""Start the runtime in a background task."""if self._running:raise ValueError("Runtime is already running.")logger.info(f"Connecting to host: {self._host_address}")- self._host_connection = HostConnection.from_host_address(self._host_address)+ self._host_connection = HostConnection.from_host_address(+ self._host_address, extra_grpc_config=self._extra_grpc_config+ )logger.info("Connection established")if self._read_task is None:self._read_task = asyncio.create_task(self._run_read_loop())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 7a5590b21..e6585098b 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@@ -1,10 +1,12 @@import asyncioimport loggingimport signal-from typing import Sequence+from typing import Optional, Sequenceimport grpc+from autogen_core.base._type_helpers import ChannelArgumentType+from ._worker_runtime_host_servicer import WorkerAgentRuntimeHostServicerfrom .protos import agent_worker_pb2_grpc@@ -12,8 +14,8 @@ logger = logging.getLogger("autogen_core")class WorkerAgentRuntimeHost:- def __init__(self, address: str) -> None:- self._server = grpc.aio.server()+ def __init__(self, address: str, extra_grpc_config: Optional[ChannelArgumentType] = None) -> None:+ self._server = grpc.aio.server(options=extra_grpc_config)self._servicer = WorkerAgentRuntimeHostServicer()agent_worker_pb2_grpc.add_AgentRpcServicer_to_server(self._servicer, self._server)self._server.add_insecure_port(address)diff --git a/python/packages/autogen-core/src/autogen_core/base/_type_helpers.py b/python/packages/autogen-core/src/autogen_core/base/_type_helpers.pyindex 66e52e4b6..3dab707fe 100644--- a/python/packages/autogen-core/src/autogen_core/base/_type_helpers.py+++ b/python/packages/autogen-core/src/autogen_core/base/_type_helpers.py@@ -1,6 +1,9 @@from collections.abc import Sequencefrom types import NoneType, UnionType-from typing import Any, Optional, Type, Union, get_args, get_origin+from typing import Any, Optional, Tuple, Type, Union, get_args, get_origin++# Had to redefine this from grpc.aio._typing as using that one was causing mypy errors+ChannelArgumentType = Sequence[Tuple[str, Any]]def is_union(t: object) -> bool:diff --git a/python/packages/autogen-core/tests/test_runtime.py b/python/packages/autogen-core/tests/test_runtime.pyindex 762a05a4e..d1a1a3299 100644--- a/python/packages/autogen-core/tests/test_runtime.py+++ b/python/packages/autogen-core/tests/test_runtime.py@@ -14,11 +14,17 @@ from autogen_core.base import (from autogen_core.components import (DefaultTopicId,TypeSubscription,- default_subscription,type_subscription,)from opentelemetry.sdk.trace import TracerProvider-from test_utils import CascadingAgent, CascadingMessageType, LoopbackAgent, MessageType, NoopAgent+from test_utils import (+ CascadingAgent,+ CascadingMessageType,+ LoopbackAgent,+ LoopbackAgentWithDefaultSubscription,+ MessageType,+ NoopAgent,+)from test_utils.telemetry_test_utils import TestExporter, get_test_tracer_providertest_exporter = TestExporter()@@ -218,9 +224,6 @@ async def test_default_subscription() -> None:runtime = SingleThreadedAgentRuntime()runtime.start()- @default_subscription- class LoopbackAgentWithDefaultSubscription(LoopbackAgent): ...-await LoopbackAgentWithDefaultSubscription.register(runtime, "name", LoopbackAgentWithDefaultSubscription)agent_id = AgentId("name", key="default")@@ -267,9 +270,6 @@ async def test_default_subscription_publish_to_other_source() -> None:runtime = SingleThreadedAgentRuntime()runtime.start()- @default_subscription- class LoopbackAgentWithDefaultSubscription(LoopbackAgent): ...-await LoopbackAgentWithDefaultSubscription.register(runtime, "name", LoopbackAgentWithDefaultSubscription)agent_id = AgentId("name", key="default")diff --git a/python/packages/autogen-core/tests/test_utils/__init__.py b/python/packages/autogen-core/tests/test_utils/__init__.pyindex eb64be1d8..92096550c 100644--- a/python/packages/autogen-core/tests/test_utils/__init__.py+++ b/python/packages/autogen-core/tests/test_utils/__init__.py@@ -14,17 +14,28 @@ class CascadingMessageType:round: int+@dataclass+class ContentMessage:+ content: str++class LoopbackAgent(RoutedAgent):def __init__(self) -> None:super().__init__("A loop back agent.")self.num_calls = 0@message_handler- async def on_new_message(self, message: MessageType, ctx: MessageContext) -> MessageType:+ async def on_new_message(+ self, message: MessageType | ContentMessage, ctx: MessageContext+ ) -> MessageType | ContentMessage:self.num_calls += 1return message+@default_subscription+class LoopbackAgentWithDefaultSubscription(LoopbackAgent): ...++@default_subscriptionclass CascadingAgent(RoutedAgent):def __init__(self, max_rounds: int) -> None:@@ -46,24 +57,3 @@ class NoopAgent(BaseAgent):async def on_message(self, message: Any, ctx: MessageContext) -> Any:raise NotImplementedError---@dataclass-class MyMessage:- content: str---@default_subscription-class MyAgent(RoutedAgent):- def __init__(self, name: str) -> None:- super().__init__("My agent")- self._name = name- self._counter = 0-- @message_handler- async def my_message_handler(self, message: MyMessage, ctx: MessageContext) -> None:- self._counter += 1- if self._counter > 5:- return- content = f"{self._name}: Hello x {self._counter}"- await self.publish_message(MyMessage(content=content), DefaultTopicId())diff --git a/python/packages/autogen-core/tests/test_worker_runtime.py b/python/packages/autogen-core/tests/test_worker_runtime.pyindex 1f9698c04..0e232243d 100644--- a/python/packages/autogen-core/tests/test_worker_runtime.py+++ b/python/packages/autogen-core/tests/test_worker_runtime.py@@ -15,10 +15,17 @@ from autogen_core.base._subscription import Subscriptionfrom autogen_core.components import (DefaultTopicId,TypeSubscription,- default_subscription,type_subscription,)-from test_utils import CascadingAgent, CascadingMessageType, LoopbackAgent, MessageType, MyAgent, MyMessage, NoopAgent+from test_utils import (+ CascadingAgent,+ CascadingMessageType,+ ContentMessage,+ LoopbackAgent,+ LoopbackAgentWithDefaultSubscription,+ MessageType,+ NoopAgent,+)@pytest.mark.asyncio@@ -204,9 +211,6 @@ async def test_default_subscription() -> None:publisher.add_message_serializer(try_get_known_serializers_for_type(MessageType))publisher.start()- @default_subscription- class LoopbackAgentWithDefaultSubscription(LoopbackAgent): ...-await LoopbackAgentWithDefaultSubscription.register(worker, "name", lambda: LoopbackAgentWithDefaultSubscription())await publisher.publish_message(MessageType(), topic_id=DefaultTopicId())@@ -241,9 +245,6 @@ async def test_default_subscription_other_source() -> None:publisher.add_message_serializer(try_get_known_serializers_for_type(MessageType))publisher.start()- @default_subscription- class LoopbackAgentWithDefaultSubscription(LoopbackAgent): ...-await LoopbackAgentWithDefaultSubscription.register(runtime, "name", lambda: LoopbackAgentWithDefaultSubscription())await publisher.publish_message(MessageType(), topic_id=DefaultTopicId(source="other"))@@ -313,20 +314,20 @@ async def test_duplicate_subscription() -> None:host.start()try:worker1.start()- await MyAgent.register(worker1, "worker1", lambda: MyAgent("worker1"))+ await NoopAgent.register(worker1, "worker1", lambda: NoopAgent())worker1_2.start()# Note: This passes because worker1 is still runningwith pytest.raises(RuntimeError, match="Agent type worker1 already registered"):- await MyAgent.register(worker1_2, "worker1", lambda: MyAgent("worker1_2"))+ await NoopAgent.register(worker1_2, "worker1", lambda: NoopAgent())# This is somehow covered in test_disconnected_agent as well as a stop will also disconnect the agent.# Will keep them both for now as we might replace the way we simulate a disconnectawait worker1.stop()with pytest.raises(ValueError):- await MyAgent.register(worker1_2, "worker1", lambda: MyAgent("worker1_2"))+ await NoopAgent.register(worker1_2, "worker1", lambda: NoopAgent())except Exception as ex:raise ex@@ -354,7 +355,9 @@ async def test_disconnected_agent() -> None:try:worker1.start()- await MyAgent.register(worker1, "worker1", lambda: MyAgent("worker1"))+ await LoopbackAgentWithDefaultSubscription.register(+ worker1, "worker1", lambda: LoopbackAgentWithDefaultSubscription()+ )subscriptions1 = get_current_subscriptions()assert len(subscriptions1) == 1@@ -363,7 +366,7 @@ async def test_disconnected_agent() -> None:first_subscription_id = subscriptions1[0].id- await worker1.publish_message(MyMessage(content="Hello!"), DefaultTopicId())+ await worker1.publish_message(ContentMessage(content="Hello!"), DefaultTopicId())# This is a simple simulation of worker disconnctif worker1._host_connection is not None: # type: ignore[reportPrivateUsage]try:@@ -380,7 +383,9 @@ async def test_disconnected_agent() -> None:await asyncio.sleep(1)worker1_2.start()- await MyAgent.register(worker1_2, "worker1", lambda: MyAgent("worker1"))+ await LoopbackAgentWithDefaultSubscription.register(+ worker1_2, "worker1", lambda: LoopbackAgentWithDefaultSubscription()+ )subscriptions3 = get_current_subscriptions()assert len(subscriptions3) == 1@@ -394,10 +399,70 @@ async def test_disconnected_agent() -> None:finally:await worker1.stop()await worker1_2.stop()+++async def test_grpc_max_message_size() -> None:+ default_max_size = 2**22+ new_max_size = default_max_size * 2+ small_message = ContentMessage(content="small message")+ big_message = ContentMessage(content="." * (default_max_size + 1))++ extra_grpc_config = [+ ("grpc.max_send_message_length", new_max_size),+ ("grpc.max_receive_message_length", new_max_size),+ ]+ host_address = "localhost:50059"+ host = WorkerAgentRuntimeHost(address=host_address, extra_grpc_config=extra_grpc_config)+ worker1 = WorkerAgentRuntime(host_address=host_address, extra_grpc_config=extra_grpc_config)+ worker2 = WorkerAgentRuntime(host_address=host_address)+ worker3 = WorkerAgentRuntime(host_address=host_address, extra_grpc_config=extra_grpc_config)++ try:+ host.start()+ worker1.start()+ worker2.start()+ worker3.start()+ await LoopbackAgentWithDefaultSubscription.register(+ worker1, "worker1", lambda: LoopbackAgentWithDefaultSubscription()+ )+ await LoopbackAgentWithDefaultSubscription.register(+ worker2, "worker2", lambda: LoopbackAgentWithDefaultSubscription()+ )+ await LoopbackAgentWithDefaultSubscription.register(+ worker3, "worker3", lambda: LoopbackAgentWithDefaultSubscription()+ )++ # with pytest.raises(Exception):+ await worker1.publish_message(small_message, DefaultTopicId())+ # This is a simple simulation of worker disconnct+ await asyncio.sleep(1)+ agent_instance_2 = await worker2.try_get_underlying_agent_instance(+ AgentId("worker2", key="default"), type=LoopbackAgent+ )+ agent_instance_3 = await worker3.try_get_underlying_agent_instance(+ AgentId("worker3", key="default"), type=LoopbackAgent+ )+ assert agent_instance_2.num_calls == 1+ assert agent_instance_3.num_calls == 1++ await worker1.publish_message(big_message, DefaultTopicId())+ await asyncio.sleep(2)+ assert agent_instance_2.num_calls == 1 # Worker 2 won't receive the big message+ assert agent_instance_3.num_calls == 2 # Worker 3 will receive the big message as has increased message length+ except Exception as e:+ raise e+ finally:+ await worker1.stop()+ # await worker2.stop() # Worker 2 somehow breaks can can not be stopped.+ await worker3.stop()+await host.stop()if __name__ == "__main__":os.environ["GRPC_VERBOSITY"] = "DEBUG"os.environ["GRPC_TRACE"] = "all"+asyncio.run(test_disconnected_agent())+ asyncio.run(test_grpc_max_message_size())