{"record":{"id":"1f09697c517d1424","repo":"microsoft/autogen","slug":"the-team-is-already-running-it-cannot-run-again-u","errorCode":null,"errorMessage":"The team is already running, it cannot run again until it is stopped.","messagePattern":"The team is already running, it cannot run again until it is stopped\\.","errorType":"exception","errorClass":"ValueError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py","lineNumber":484,"sourceCode":"            messages = []\n            for msg in task:\n                if not isinstance(msg, BaseChatMessage):\n                    raise ValueError(\"All messages in task list must be valid BaseChatMessage types\")\n                messages.append(msg)\n        else:\n            raise ValueError(\"Task must be a string, a BaseChatMessage, or a list of BaseChatMessage.\")\n        # Check if the messages types are registered with the message factory.\n        if messages is not None:\n            for msg in messages:\n                if not self._message_factory.is_registered(msg.__class__):\n                    raise ValueError(\n                        f\"Message type {msg.__class__} is not registered with the message factory. \"\n                        \"Please register it with the message factory by adding it to the \"\n                        \"custom_message_types list when creating the team.\"\n                    )\n\n        if self._is_running:\n            raise ValueError(\"The team is already running, it cannot run again until it is stopped.\")\n        self._is_running = True\n\n        if self._embedded_runtime:\n            # Start the embedded runtime.\n            assert isinstance(self._runtime, SingleThreadedAgentRuntime)\n            self._runtime.start()\n\n        if not self._initialized:\n            await self._init(self._runtime)\n\n        shutdown_task: asyncio.Task[None] | None = None\n        if self._embedded_runtime:\n\n            async def stop_runtime() -> None:\n                assert isinstance(self._runtime, SingleThreadedAgentRuntime)\n                try:\n                    # This will propagate any exceptions raised.\n                    await self._runtime.stop_when_idle()","sourceCodeStart":466,"sourceCodeEnd":502,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py#L466-L502","documentation":"A team cannot have two concurrent runs: _is_running is set True when run_stream starts and cleared only when the stream finishes. A second run() / run_stream() call while the first is still streaming raises this immediately to prevent interleaved message queues and corrupted state.","triggerScenarios":"Awaiting team.run() twice concurrently (asyncio.gather(team.run(...), team.run(...))), or calling run() on a team whose earlier run_stream generator was started but never fully consumed/closed — an abandoned generator leaves _is_running True until GC finalizes the generator's finally block.","commonSituations":"Two coroutines sharing one team object; a FastAPI/queue handler that starts a new run before the previous response stream completed; abandoning a run_stream async generator early (breaking out of the async for loop without closing it).","solutions":["Ensure the previous run fully completes: iterate run_stream to exhaustion or await the run() coroutine before starting a new one.","When abandoning a stream early, explicitly close the generator: await stream.aclose().","Serialize access with an asyncio.Lock around team runs, or create a fresh team instance per concurrent request."],"exampleFix":"# before\nstream = team.run_stream(task=\"a\")\nasync for msg in stream: break  # abandoned -> _is_running stays True\nawait team.run(task=\"b\")  # ValueError\n\n# after\nstream = team.run_stream(task=\"a\")\nasync for msg in stream: break\nawait stream.aclose()  # releases _is_running\nawait team.run(task=\"b\")","handlingStrategy":"try-catch","validationCode":"team_lock = asyncio.Lock()  # serialize all runs per team\nasync with team_lock:\n    result = await team.run(task=\"hi\")","typeGuard":null,"tryCatchPattern":"try:\n    result = await team.run(task=task)\nexcept ValueError as e:\n    if \"already running\" in str(e):\n        # wait for current run, then retry once\n        await current_run_task\n        result = await team.run(task=task)\n    else:\n        raise","preventionTips":["One run at a time per team instance; use an asyncio.Lock to enforce it.","Always exhaust run_stream generators or await stream.aclose() when abandoning them early.","Create a fresh team per concurrent request instead of sharing one instance."],"tags":["python","autogen","asyncio","concurrency","lifecycle"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}