fix: handle BaseModel result in convert_to_model to prevent TypeError#5459
Open
aayushbaluni wants to merge 1 commit intocrewAIInc:mainfrom
Open
fix: handle BaseModel result in convert_to_model to prevent TypeError#5459aayushbaluni wants to merge 1 commit intocrewAIInc:mainfrom
aayushbaluni wants to merge 1 commit intocrewAIInc:mainfrom
Conversation
When a guardrail retry causes the agent to return a Pydantic BaseModel instance instead of a JSON string, json.loads() raises TypeError because it expects str/bytes, not a model object. Serialize the model to JSON before proceeding with validation. Fixes crewAIInc#5458 Made-with: Cursor
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.
Summary
Fixes #5458
When combining
ConditionalTask+output_pydantic+ guardrails + context, a guardrail retry can cause the agent to return a PydanticBaseModelinstance instead of a raw JSON string. This instance is then passed toconvert_to_model(), which callsjson.loads(result)on it — butjson.loadsexpectsstr | bytes | bytearray, not a model object:Root Cause
In
lib/crewai/src/crewai/utilities/converter.py,convert_to_model()assumesresultis always a string (line 188:json.loads(result, strict=False)). When_invoke_guardrail_functionintask.pyretries viaagent.execute_task()and the agent returns structured output,resultis aBaseModelinstance.Fix
Added an early check in
convert_to_model(): ifresultis already aBaseModel, serialize it to JSON withmodel_dump_json()before proceeding. This ensuresjson.loadsalways 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