{"record":{"id":"37012b3200868b5e","repo":"microsoft/autogen","slug":"runtime-must-be-running-when-sending-message","errorCode":null,"errorMessage":"Runtime must be running when sending message.","messagePattern":"Runtime must be running when sending message\\.","errorType":"validation","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py","lineNumber":377,"sourceCode":"        telemetry_metadata: Mapping[str, str],\n    ) -> None:\n        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        with self._trace_helper.trace_block(send_type, recipient, parent=telemetry_metadata):\n            await self._host_connection.send(runtime_message)\n\n    async def send_message(\n        self,\n        message: Any,\n        recipient: AgentId,\n        *,\n        sender: AgentId | None = None,\n        cancellation_token: CancellationToken | None = None,\n        message_id: str | None = None,\n    ) -> Any:\n        # TODO: use message_id\n        if not self._running:\n            raise ValueError(\"Runtime must be running when sending message.\")\n        if self._host_connection is None:\n            raise RuntimeError(\"Host connection is not set.\")\n        data_type = self._serialization_registry.type_name(message)\n        with self._trace_helper.trace_block(\n            \"create\", recipient, parent=None, extraAttributes={\"message_type\": data_type}\n        ):\n            # create a new future for the result\n            future = asyncio.get_event_loop().create_future()\n            request_id = await self._get_new_request_id()\n            self._pending_requests[request_id] = future\n            serialized_message = self._serialization_registry.serialize(\n                message, type_name=data_type, data_content_type=JSON_DATA_CONTENT_TYPE\n            )\n            telemetry_metadata = get_telemetry_grpc_metadata()\n            runtime_message = agent_worker_pb2.Message(\n                request=agent_worker_pb2.RpcRequest(\n                    request_id=request_id,\n                    target=agent_worker_pb2.AgentId(type=recipient.type, key=recipient.key),","sourceCodeStart":359,"sourceCodeEnd":395,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-ext/src/autogen_ext/runtimes/grpc/_worker_runtime.py#L359-L395","documentation":"GrpcWorkerAgentRuntime.send_message (the AgentRuntime RPC entry point) verifies the runtime is running before accepting a directed message; if _running is False it raises ValueError('Runtime must be running when sending message.') because there is no host connection to carry the request.","triggerScenarios":"Calling `await runtime.send_message(msg, recipient)` (or an agent proxy's call) before `await runtime.start()` has completed, or after stop().","commonSituations":"Forgetting start() in scripts/notebooks; sending during shutdown; agents constructed before the runtime lifecycle begins that send eagerly on instantiation.","solutions":["Call and await `runtime.start()` before any send_message / agent call","Structure code with an async context manager (`async with runtime: ...`) so start/stop ordering is enforced","If a send races shutdown, catch the ValueError and retry once the runtime restarts or drop the message deliberately"],"exampleFix":"# before\nruntime = GrpcWorkerAgentRuntime(host_address)\nawait runtime.send_message(msg, agent_id)  # ValueError\n\n# after\nruntime = GrpcWorkerAgentRuntime(host_address)\nawait runtime.start()\nawait runtime.send_message(msg, agent_id)","handlingStrategy":"validation","validationCode":"started = False\nasync def ensure_running(runtime):\n    global started\n    if not started:\n        await runtime.start()\n        started = True\n\nawait ensure_running(runtime)\nawait runtime.send_message(msg, recipient)","typeGuard":null,"tryCatchPattern":"try:\n    await runtime.send_message(msg, recipient)\nexcept ValueError as e:\n    if \"must be running\" in str(e):\n        await runtime.start()\n        await runtime.send_message(msg, recipient)\n    else:\n        raise","preventionTips":["Always await start() before any send/publish","Use an async context manager for the runtime lifecycle","Lazy agents should send only from message handlers, not constructors"],"tags":["python","autogen","grpc","lifecycle","messaging"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T22:17:37.221Z"}