CrewAI tasks accept a guardrail: a check on the task output that, when it fails, sends the reason back and retries the task. A guardrail can be a Python function returning whether the output passes, or a plain-language rule judged by the model’s own language model. Put the guardrail on the task, not on the agent: in a crew, an agent-level guardrail is not applied to crew tasks, so a check placed there silently never runs.
What you need
- A CrewAI crew with at least one task already running
- One rule the output must meet, for example every claim must carry a source
- Python with the crewai package installed
Step 1: Write the guardrail as a function or a rule
Write a small function that takes the task output and returns whether it passes and what is wrong, or write the rule in plain language for the model to judge. Keep the rule to one check, so a failure tells you exactly what to fix.
Step 2: Attach the guardrail to the task
Set the guardrail on the Task, not on the Agent, and set how many times a failed task should be retried. In a crew the task guardrail is the one that runs.
Step 3: Run the crew with a bad output on purpose
Give the crew an input likely to break the rule and confirm the guardrail catches it, the task retries, and the final output passes. If a bad output slips through, the guardrail is on the wrong object.
Worked example: synthetic source-check run
The table below is a synthetic example. It shows the expected result of the guardrail; no crew was run.
| Check | Expected | Result |
|---|---|---|
| First output missing sources | Caught | Pass |
| Task retried | Yes | Pass |
| Final output has sources | Yes | Pass |
| Bad output never delivered | 0 delivered | Pass |
Expected result (UNTESTED). the guardrail catches the missing sources, the task retries, and only the corrected output is delivered. This check was not run live; the table shows the expected result for the synthetic example.
Limits
- In a crew, put the check on the task: an agent-level guardrail is not applied to crew tasks.
- A guardrail that keeps failing is retried only a limited number of times, then the task returns its last output.
- A plain-language guardrail is judged by the model itself, so it can pass output a strict function would reject.
