crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Task ignores a passing guardrail's TaskOutput, model or dict result, losing output_pydantic / output_json

Open willnhansen opened this issue 2 weeks ago • 2 comments

Description

When a Task guardrail passes and returns anything other than a str, _invoke_guardrail_function (and the async _ainvoke_guardrail_function) doesn't apply the result to the structured output. The success branch only re-exports a str result. A TaskOutput is swapped in without export, and any other type is ignored. This causes two problems:

  1. A returned model or dict is discarded. With (True, Score(...)) or (True, {...}), raw, .pydantic and .json_dict keep the agent's original values, so the guardrail's transformation is lost.
  2. With an LLM that answers in text (no native structured output), structured output is lost entirely. While guardrails run, the first-attempt output is left unexported (pydantic=None, json_dict=None). So (True, output), the natural "looks fine" pass-through, and the two cases above all end with .pydantic / .json_dict = None. This reaches CrewOutput.pydantic too, when it's the last task.

Agent and LiteAgent guardrails already handle a BaseModel result (agent/core.py, lite_agent.py). The docs' "Handling Guardrail Results" example returns (True, data) with data a parsed dict.

Steps to Reproduce

  1. Create a Task with output_pydantic=Score and a guardrail that returns (True, output), (True, Score(...)) or (True, {...}).
  2. Run it with an agent whose answer is valid JSON for Score.
  3. Read result.pydantic.

Expected behavior

  • (True, output) gives the same .pydantic / .json_dict as no guardrail, or as (True, output.raw).
  • A returned model or dict becomes the output: raw is its JSON, and .pydantic / .json_dict are filled.

Screenshots/Code snippets

import json
from unittest.mock import Mock
from pydantic import BaseModel
from crewai import Task

class Score(BaseModel):
    name: str
    score: int

agent = Mock(role="r", crew=None, last_messages=[])
agent.execute_task.return_value = json.dumps({"name": "x", "score": 3})

for label, g in [
    ("(True, output.raw)", lambda o: (True, o.raw)),
    ("(True, output)", lambda o: (True, o)),
    ("(True, Score)", lambda o: (True, Score(name="y", score=9))),
    ("(True, dict)", lambda o: (True, {"name": "z", "score": 1})),
]:
    out = Task(description="d", expected_output="e", output_pydantic=Score, guardrail=g).execute_sync(agent=agent)
    print(label, out.pydantic)
(True, output.raw) name='x' score=3
(True, output) None
(True, Score) None
(True, dict) None

The mock agent above returns text. output_json and aexecute_sync behave the same way.

Operating System

Other (specify in additional context)

Python Version

3.12

crewAI Version

1.15.41 (main @ 2817a95)

crewAI Tools Version

not used

Virtual Environment

Venv

Evidence

The same check end to end, with a real Agent and Crew and a stub BaseLLM (no network), on main:

Guardrail returns Text-mode LLM: crew.pydantic Native structured output: crew.pydantic
no guardrail x/3 x/3
(True, output.raw) x/3 x/3
(True, output) None x/3
(True, Score(y, 9)) None x/3 (returned model ignored)
(True, {"name": "z", "score": 1}) None x/3 (returned dict ignored)

Possible Solution

Apply the passing result in one helper shared by the sync and async paths:

  • A TaskOutput with empty structured fields is exported from its raw.
  • A model or dict becomes the new raw and is exported.
  • str is unchanged.

Additional context

macOS 26.7, Python 3.13 (neither is in the dropdowns).

  • #4369 (closed as stale; PRs #4433, #4624 and #4650 were closed unmerged for inactivity) is the input side of the same skip: the guardrail receives output.pydantic = None on the first attempt. This issue is the output side: what happens to the guardrail's passing result. The two are complementary. Exporting before the guardrail, as those PRs did, would fix only the text-mode (True, output) case here, not a returned model or dict being ignored. Fixing this keeps the current design of exporting only after the guardrail passes, and doesn't change what the guardrail receives.
  • #8788 is the same idea for Agent.kickoff with response_format.

Prepared with Claude Code assistance and reviewed by the account owner. Please add the llm-generated label; the author cannot add it.

willnhansen avatar Nov 16 '26 07:11 willnhansen

Same bug bit me looking at guardrails — a passing guardrail returning a TaskOutput just gets dropped and the task falls back to the raw string. #9485 looks like it handles it. If it stalls I'd be glad to pick it up — I'd share one _apply_guardrail_result helper across the sync and async paths so both handle TaskOutput/model/dict the same way, with a test for a passing guardrail returning a TaskOutput.

PCTEJA avatar Nov 16 '26 12:11 PCTEJA

Verified by reading the code at main (lib/crewai/src/crewai/task.py, _invoke_guardrail_function :1425 and _ainvoke_guardrail_function :1545 — the two are line-for-line mirrors on the success branch).

The report is accurate: on guardrail_result.success, only two result types are handled — str (raw replaced + _export_output fills .pydantic / .json_dict) and TaskOutput (swapped in whole, with tool_failures merged, but without _export_output). Any other type — a BaseModel or a dict — hits neither branch and return task_output hands back the original output untouched, so the guardrail's transformation is silently discarded. That also explains the evidence table's asymmetry: with a text-mode LLM the first-attempt output is still unexported when the guardrail runs, so (True, output) leaves .pydantic = None, while with native structured output the fields were already filled before the guardrail, masking the bug.

Two notes for the fix:

  • The proposed shared helper should export in the TaskOutput branch too (a TaskOutput with empty structured fields needs _export_output(task_output.raw)), not only for model/dict results — otherwise (True, output) in text mode stays broken.
  • Agent/LiteAgent guardrails already accept a BaseModel result (as the report notes), so the Task path accepting model/dict would align the three call sites; worth checking whether their export helper can be reused instead of adding a third variant.

surlymochan avatar Nov 17 '26 05:11 surlymochan