{"record":{"id":"4c777ff182efc525","repo":"microsoft/autogen","slug":"the-team-cannot-be-loaded-while-it-is-running","errorCode":null,"errorMessage":"The team cannot be loaded while it is running.","messagePattern":"The team cannot be loaded while it is running\\.","errorType":"exception","errorClass":"RuntimeError","httpStatus":null,"severity":"error","filePath":"python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py","lineNumber":809,"sourceCode":"            # save_state method because we want to support saving state of remote agents.\n            agent_states[name] = await self._runtime.agent_save_state(agent_id)\n        # Save the state of the group chat manager.\n        agent_id = AgentId(type=self._group_chat_manager_topic_type, key=self._team_id)\n        agent_states[self._group_chat_manager_name] = await self._runtime.agent_save_state(agent_id)\n        return TeamState(agent_states=agent_states).model_dump()\n\n    async def load_state(self, state: Mapping[str, Any]) -> None:\n        \"\"\"Load an external state and overwrite the current state of the group chat team.\n\n        The state is loaded by calling the :meth:`~autogen_core.AgentRuntime.agent_load_state` method\n        on each participant and the group chat manager with their internal agent ID.\n        See :meth:`~autogen_agentchat.teams.BaseGroupChat.save_state` for the expected format of the state.\n        \"\"\"\n        if not self._initialized:\n            await self._init(self._runtime)\n\n        if self._is_running:\n            raise RuntimeError(\"The team cannot be loaded while it is running.\")\n        self._is_running = True\n\n        try:\n            team_state = TeamState.model_validate(state)\n            # Load the state of all participants.\n            for name, agent_type in zip(self._participant_names, self._participant_topic_types, strict=True):\n                agent_id = AgentId(type=agent_type, key=self._team_id)\n                if name not in team_state.agent_states:\n                    raise ValueError(f\"Agent state for {name} not found in the saved state.\")\n                await self._runtime.agent_load_state(agent_id, team_state.agent_states[name])\n            # Load the state of the group chat manager.\n            agent_id = AgentId(type=self._group_chat_manager_topic_type, key=self._team_id)\n            if self._group_chat_manager_name not in team_state.agent_states:\n                raise ValueError(f\"Agent state for {self._group_chat_manager_name} not found in the saved state.\")\n            await self._runtime.agent_load_state(agent_id, team_state.agent_states[self._group_chat_manager_name])\n\n        except ValidationError as e:\n            raise ValueError(","sourceCodeStart":791,"sourceCodeEnd":827,"githubUrl":"https://github.com/microsoft/autogen/blob/027ecf0a379bcc1d09956d46d12d44a3ad9cee14/python/packages/autogen-agentchat/src/autogen_agentchat/teams/_group_chat/_base_group_chat.py#L791-L827","documentation":"load_state() overwrites every participant's state, which is unsafe while messages are flowing: it initializes if needed, then refuses with RuntimeError if _is_running is True. The flag is set for the whole duration of the load itself and cleared in a finally block.","triggerScenarios":"Calling await team.load_state(state) while a run_stream generator is active (started but not exhausted/closed), or from a concurrent coroutine during await team.run().","commonSituations":"Hot-swapping conversation state from a UI 'switch session' action while a run is streaming; concurrent tasks sharing one team instance for run and checkpoint restore.","solutions":["Complete or stop the active run first (exhaust the stream or await stream.aclose()).","Use one asyncio.Lock to make run/load_state/reset mutually exclusive per team.","For per-request workloads, instantiate a fresh team and load state into it instead of mutating a running one."],"exampleFix":"# before\nasyncio.gather(team.run(task=\"a\"), team.load_state(saved))  # one of them raises\n\n# after\nlock = asyncio.Lock()\nasync with lock:\n    await team.run(task=\"a\")\nasync with lock:\n    await team.load_state(saved)","handlingStrategy":"validation","validationCode":"async with team_lock:\n    await team.load_state(state)  # same lock used for run/reset","typeGuard":null,"tryCatchPattern":"try:\n    await team.load_state(state)\nexcept RuntimeError as e:\n    if \"cannot be loaded while it is running\" in str(e):\n        await active_stream.aclose()\n        await team.load_state(state)\n    else:\n        raise","preventionTips":["Serialize run, reset, load_state, and save_state behind one asyncio.Lock per team.","For multi-session apps, build a fresh team per session and load state into it.","Never fire load_state from a callback that can race an active stream."],"tags":["python","autogen","state","lifecycle","asyncio"],"backgroundTag":null,"analyzedSha":"027ecf0a379bcc1d09956d46d12d44a3ad9cee14","analyzedAt":"2026-08-15T03:38:00.719Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}