crewai - ✅(Solved) Fix [BUG] TypeError: the JSON object must be str, bytes or bytearray, not <PydanticModel> when combining ConditionalTask + output_pydantic + guardrail + context [1 pull requests, 3 comments, 3 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
crewAIInc/crewAI#5458Fetched 2026-04-16 06:44:48
View on GitHub
Comments
3
Participants
3
Timeline
8
Reactions
0
Timeline (top)
commented ×3cross-referenced ×1labeled ×1mentioned ×1

When using a ConditionalTask with output_pydantic, a custom guardrail, and context from another task that also uses output_pydantic, CrewAI internally calls json.loads() on a Pydantic object instead of its serialized JSON string, causing a Type Error.

Error Unexpected error during model conversion: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput. Returning original result.

Crew Execution Failed

Error Message

When using a ConditionalTask with output_pydantic, a custom guardrail, and context from another task that also uses output_pydantic, CrewAI internally calls json.loads() on a Pydantic object instead of its serialized JSON string, causing a Type Error. Error Unexpected error during model conversion: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput. Returning original result. 5. Observe the TypeError: the JSON object must be str, bytes or bytearray, not pydantic error. except Exception as e: return (False, f"Validation error: {str(e)}")

Root Cause

When using a ConditionalTask with output_pydantic, a custom guardrail, and context from another task that also uses output_pydantic, CrewAI internally calls json.loads() on a Pydantic object instead of its serialized JSON string, causing a Type Error.

Error Unexpected error during model conversion: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput. Returning original result.

Crew Execution Failed

Fix Action

Fixed

PR fix notes

PR #5459: fix: handle BaseModel result in convert_to_model to prevent TypeError

Description (problem / solution / changelog)

Summary

Fixes #5458

When combining ConditionalTask + output_pydantic + guardrails + context, a guardrail retry can cause the agent to return a Pydantic BaseModel instance instead of a raw JSON string. This instance is then passed to convert_to_model(), which calls json.loads(result) on it — but json.loads expects str | bytes | bytearray, not a model object:

TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput

Root Cause

In lib/crewai/src/crewai/utilities/converter.py, convert_to_model() assumes result is always a string (line 188: json.loads(result, strict=False)). When _invoke_guardrail_function in task.py retries via agent.execute_task() and the agent returns structured output, result is a BaseModel instance.

Fix

Added an early check in convert_to_model(): if result is already a BaseModel, serialize it to JSON with model_dump_json() before proceeding. This ensures json.loads always receives a string, regardless of whether the result came from a first-pass or retry execution.

The fix is minimal (6 lines) and does not change any behavior for string results.

Made with Cursor

Changed files

  • lib/crewai/src/crewai/utilities/converter.py (modified, +6/-0)
RAW_BUFFERClick to expand / collapse

Description

When using a ConditionalTask with output_pydantic, a custom guardrail, and context from another task that also uses output_pydantic, CrewAI internally calls json.loads() on a Pydantic object instead of its serialized JSON string, causing a Type Error.

Error Unexpected error during model conversion: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput. Returning original result.

Crew Execution Failed

Steps to Reproduce

  1. Create a Task with output_pydantic set to a Pydantic model.
  2. Create a ConditionalTask that references the first task in context, and also has its own output_pydantic, a condition function, and a guardrail function.
  3. Add both tasks to a Crew with Process.sequential.
  4. Run crew.kickoff().
  5. Observe the TypeError: the JSON object must be str, bytes or bytearray, not pydantic error.

Expected behavior

Expected Behavior

The guardrail should receive result.pydantic as a proper Pydantic object and result.raw as a JSON string. The crew should complete successfully.

Actual Behavior

CrewAI internally attempts json.loads() on the DrugClassificationOutput Pydantic object (from the context task) instead of its serialized string, raising: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput

Screenshots/Code snippets

from typing import List, Tuple, Any, Optional from pydantic import BaseModel, Field from crewai import Agent, Task, Crew, Process from crewai.tasks.conditional_task import ConditionalTask from crewai.tasks.task_output import TaskOutput

Pydantic Models

class DrugClassificationOutput(BaseModel): company_drugs: List[str] = Field(default_factory=list) other_drugs: List[str] = Field(default_factory=list)

class ValidationOutput(BaseModel): original_classification: bool validated_classification: bool validation_reason: str elements_found: dict = Field(default_factory=dict)

Condition

def is_nr_classified(output) -> bool: return True

Guardrail

def validation_guardrail(result: TaskOutput) -> Tuple[bool, Any]: try: output = result.pydantic return (True, result.raw) except Exception as e: return (False, f"Validation error: {str(e)}")

Agents

classification_agent = Agent( role="Drug Classifier", goal="Classify drugs", backstory="Expert pharmacologist", )

validation_agent = Agent( role="Validator", goal="Validate classifications", backstory="Expert reviewer", )

Tasks

drug_classification_task = Task( description="Classify drugs in: {text}", expected_output="DrugClassificationOutput object", agent=classification_agent, output_pydantic=DrugClassificationOutput,
)

validation_task = ConditionalTask( description="Validate the classification for: {text}", expected_output="ValidationOutput object", condition=is_nr_classified, agent=validation_agent, context=[drug_classification_task],
guardrail=validation_guardrail,
output_pydantic=ValidationOutput,
)

Crew

crew = Crew( agents=[classification_agent, validation_agent], tasks=[drug_classification_task, validation_task], process=Process.sequential, verbose=True, )

result = crew.kickoff(inputs={"text": "Patient received Clindamycin and developed rash."})

Operating System

Windows 11

Python Version

3.12

crewAI Version

CrewAI Version: 1.14.0

crewAI Tools Version

Virtual Environment

Venv

Evidence

<img width="975" height="350" alt="Image" src="https://github.com/user-attachments/assets/0ed963b7-da3e-4c78-b84e-c1521f590a38" />

Possible Solution

None

Additional context

Analysis The issue appears to be in the internal serialization path when:

  1. A context task has output_pydantic set
  2. A ConditionalTask consumes that context
  3. The ConditionalTask also has a guardrail and its own output_pydantic The Pydantic object from the context task is passed directly to json.loads() without calling .model_dump_json() first.

extent analysis

TL;DR

The issue can be resolved by modifying the guardrail function to properly serialize the Pydantic object from the context task before passing it to json.loads().

Guidance

  • The error occurs because the Pydantic object is being passed directly to json.loads() without serialization. To fix this, modify the validation_guardrail function to serialize the result.pydantic object using its model_dump_json() method or the json.dumps() function.
  • Verify that the validation_guardrail function is receiving the expected TaskOutput object and that the result.pydantic attribute is a valid Pydantic object.
  • Check the crewai library documentation to see if there are any built-in methods for serializing Pydantic objects or handling this specific use case.
  • Consider adding error handling to the validation_guardrail function to catch and handle any exceptions that may occur during serialization or deserialization.

Example

def validation_guardrail(result: TaskOutput) -> Tuple[bool, Any]:
    try:
        output = result.pydantic
        serialized_output = output.model_dump_json()  # Serialize the Pydantic object
        return (True, serialized_output)
    except Exception as e:
        return (False, f"Validation error: {str(e)}")

Notes

The provided code snippet assumes that the model_dump_json() method is available on the Pydantic object. If this method is not available, you may need to use the json.dumps() function to serialize the object.

Recommendation

Apply the workaround by modifying the validation_guardrail function to properly serialize the Pydantic object. This should resolve the TypeError and allow the crew to complete successfully.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

Expected behavior

Expected Behavior

The guardrail should receive result.pydantic as a proper Pydantic object and result.raw as a JSON string. The crew should complete successfully.

Actual Behavior

CrewAI internally attempts json.loads() on the DrugClassificationOutput Pydantic object (from the context task) instead of its serialized string, raising: TypeError: the JSON object must be str, bytes or bytearray, not DrugClassificationOutput

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

crewai - ✅(Solved) Fix [BUG] TypeError: the JSON object must be str, bytes or bytearray, not <PydanticModel> when combining ConditionalTask + output_pydantic + guardrail + context [1 pull requests, 3 comments, 3 participants]