[BUG] Agent.kickoff() guardrail retry discards the validation feedback
Description
Agent.kickoff() with a guardrail and guardrail_max_retries > 0 does not pass the guardrail failure back to the model on retry. _process_kickoff_guardrail() appends the error to executor.state.messages (lib/crewai/src/crewai/agent/core.py:2156 on main at af4efdc6), but _execute_and_build_output() then calls AgentExecutor.invoke(), which clears state.messages (lib/crewai/src/crewai/agents/agent_executor.py:3053) and rebuilds the prompt from the original inputs (:3077). The retry therefore sees exactly the same prompt as the first attempt.
Impact: with a deterministic model or a strict format guardrail, every retry reproduces the rejected answer, burns guardrail_max_retries LLM calls, and finally raises "guardrail failed validation" even though the model was never told why its answer failed.
This is distinct from #7252 (async retry crashes because executor.invoke() returns a coroutine) and #8219 (Task guardrail retries lose the upstream task's context). This report is about the synchronous Agent.kickoff() path and the missing validation feedback.
Steps to Reproduce
- Use
crewaimain ataf4efdc6(1.15.28) with Python 3.13. - Save the script below and run it. It uses a scripted
BaseLLM, so no API key or network access is required. - Compare the messages received by the two LLM calls.
from __future__ import annotations
from typing import Any
from crewai import Agent
from crewai.llms.base_llm import BaseLLM
class ScriptedLLM(BaseLLM):
def __init__(self) -> None:
super().__init__(model="scripted")
self.calls: list[list[dict[str, Any]]] = []
def supports_function_calling(self) -> bool:
return False
def call(self, messages: Any, **kwargs: Any) -> str:
self.calls.append([dict(m) for m in messages])
if len(self.calls) == 1:
return "Thought: I can answer directly.\nFinal Answer: wrong answer"
return "Thought: I can answer directly.\nFinal Answer: MAGIC"
def guardrail(output: Any) -> tuple[bool, Any]:
if "MAGIC" in output.raw:
return True, output
return False, "The answer must contain the word MAGIC."
llm = ScriptedLLM()
agent = Agent(
role="tester",
goal="answer",
backstory="test",
llm=llm,
guardrail=guardrail,
guardrail_max_retries=1,
verbose=False,
)
result = agent.kickoff("Answer the question.")
print("result:", result.raw)
for index, messages in enumerate(llm.calls, start=1):
text = "\n".join(str(message.get("content") or "") for message in messages)
print(f"call {index} sees feedback:", "must contain the word MAGIC" in text)
print(" roles:", [message.get("role") for message in messages])
Expected behavior
The second call should contain the guardrail error and the rejected answer, for example Previous attempt failed validation: The answer must contain the word MAGIC. and wrong answer, so the model can correct itself. Task guardrails already do this through I18N_DEFAULT.errors("validation_error"), and LiteAgent already course-corrects on validation errors (commit 7e6171d5).
Screenshots/Code snippets
The full reproducer is above. The relevant code path is:
lib/crewai/src/crewai/agent/core.py:2156—executor._append_message_to_state(...)lib/crewai/src/crewai/agents/agent_executor.py:3053—self.state.messages.clear()lib/crewai/src/crewai/agents/agent_executor.py:3077—self._setup_messages(inputs)
Operating System
Windows 11. The defect is in the Python data flow and is OS-independent.
Python Version
3.13 (tested on 3.13.12; the issue form only lists 3.10–3.12).
crewAI Version
1.15.28 (main at af4efdc6).
crewAI Tools Version
1.15.28.
Virtual Environment
Venv (uv).
Evidence
Output on main:
result: MAGIC
call 1 sees feedback: False
roles: ['system', 'user']
call 2 sees feedback: False
roles: ['system', 'user']
The second call's prompt is the original prompt only:
You are tester. test
Your personal goal is: answer
Current Task: Answer the question.
Provide your complete response:
A regression test asserting that the second call contains the feedback fails on main with:
assert "must contain MAGIC" in retry_text
E AssertionError: assert 'must contain MAGIC' in 'You are tester. test\nYour personal goal is: answer\n\nCurrent Task: Answer the question.\n\nProvide your complete response:'
Possible Solution
Carry the feedback through the retry input that invoke() rebuilds from. In _process_kickoff_guardrail(), format I18N_DEFAULT.errors("validation_error") with the guardrail error and output.raw, then append that text to inputs["input"] before calling _execute_and_build_output(). This reuses the template Task guardrails already use, keeps attached files on the original user turn, and needs no public API change.
A regression test can assert that the second LLM call contains both the error text and the previous rejected answer.
Additional context
Disclosure per CONTRIBUTING: this report and the linked fix were prepared with AI assistance. Please apply the bug and llm-generated labels.
Why this is not a duplicate:
- #7252 is the async path failing because
executor.invoke()returns a coroutine; this report is the sync path, where the retry runs but loses the feedback. - #8219 is about Task guardrail retries dropping the upstream task's context; this report is about
Agent.kickoff()guardrail feedback.
This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.
This issue was closed because it has been stalled for 5 days with no activity.