fix: clear agent executor messages between tasks to prevent memory leak #4328
+2
−0
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Description: Currently, when an Agent is reused for multiple tasks within a Crew, the agent_executor.messages history is not cleared. This causes context leakage where instructions or data from Task 1 persist into Task 2, leading to potential hallucinations and unnecessary token usage.
Changes:
Modified src/crewai/agent/core.py in _update_executor_parameters to clear the agent_executor.messages list before a new task begins.
Testing:
Verified with a reproduction script that checks the length of agent_executor.messages after consecutive tasks.
Confirmed memory resets to 0 (or baseline) instead of accumulating.
Note
Low Risk
Low risk because it is a small, localized change that only clears per-executor message state between task runs; the main risk is unintentionally removing any desired cross-task conversational continuity.
Overview
Prevents cross-task context leakage when reusing an
Agentby clearingagent_executor.messagesat the start of_update_executor_parametersbefore updating task/tool/prompt settings.This keeps executor message history from accumulating across tasks, reducing unintended prompt carryover and excess token usage.
Written by Cursor Bugbot for commit 7ca68fa. This will update automatically on new commits. Configure here.