diff --git a/lib/crewai/src/crewai/agents/agent_builder/base_agent.py b/lib/crewai/src/crewai/agents/agent_builder/base_agent.py index d6f48ca2777..66121cfe288 100644 --- a/lib/crewai/src/crewai/agents/agent_builder/base_agent.py +++ b/lib/crewai/src/crewai/agents/agent_builder/base_agent.py @@ -2,7 +2,7 @@ from abc import ABC, abstractmethod from collections.abc import Sequence -from copy import copy as shallow_copy +from copy import copy as shallow_copy, deepcopy from hashlib import md5 from pathlib import Path import re @@ -731,6 +731,14 @@ def copy(self) -> Self: # type: ignore # Signature of "copy" incompatible with } existing_llm = shallow_copy(self._llm_for_copy()) + # copy.copy shares the LLM's mutable fields. Isolate the dicts a + # copied agent actually mutates: provider params and token totals. + if getattr(existing_llm, "additional_params", None) is not None: + existing_llm.additional_params = deepcopy(existing_llm.additional_params) + if getattr(existing_llm, "_token_usage", None) is not None: + # A copy starts a new run. kickoff_for_each sums each copy's + # lifetime totals, so carried-over counts would be added once per input. + existing_llm._token_usage = dict.fromkeys(existing_llm._token_usage, 0) copied_knowledge = shallow_copy(self.knowledge) copied_knowledge_storage = shallow_copy(self.knowledge_storage) existing_knowledge_sources = None diff --git a/lib/crewai/tests/agents/test_agent.py b/lib/crewai/tests/agents/test_agent.py index a080eefb608..14fe3fb710d 100644 --- a/lib/crewai/tests/agents/test_agent.py +++ b/lib/crewai/tests/agents/test_agent.py @@ -137,6 +137,30 @@ def test_agent_copy_does_not_emit_i18n_deprecation_warning(): ) +def test_agent_copy_isolates_llm_mutable_state(): + """A copied agent must not share the LLM's params or token totals.""" + llm = LLM(model="gpt-4o-mini") + llm.additional_params["bucket"] = [] + llm._token_usage["total_tokens"] = 10 + agent = Agent( + role="test role", + goal="test goal", + backstory="test backstory", + llm=llm, + ) + + copied = agent.copy() + copied.llm.additional_params["bucket"].append(1) + copied.llm._token_usage["total_tokens"] += 5 + + assert copied.llm is not agent.llm + assert copied.llm.additional_params is not agent.llm.additional_params + assert copied.llm._token_usage is not agent.llm._token_usage + assert agent.llm.additional_params["bucket"] == [] + assert agent.llm._token_usage["total_tokens"] == 10 + assert copied.llm._token_usage["total_tokens"] == 5 + + def test_agent_with_only_system_template(): """Test that an agent with only system_template works without errors.""" agent = Agent(