Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion lib/crewai/src/crewai/agents/agent_builder/base_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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:

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  • The copied _token_usage keeps the original's counts. Resetting it to zero in base_agent.py:739 would keep kickoff_for_each usage totals right when the source LLM was already used.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 33a489c. A copied agent's _token_usage is now a fresh zeroed dict, so kickoff_for_each no longer adds the source LLM's existing counts once per input. The test sets the original total to 10 and checks the copy starts at 0.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Re-pushed bda2b9e with no change to the fix. It only merges main so the pip-audit check is green.

# 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
Expand Down
24 changes: 24 additions & 0 deletions lib/crewai/tests/agents/test_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading