Skip to content

fix: strip markdown code fences from LLM responses before JSON parsing#4627

Open
Anandesh-Sharma wants to merge 1 commit intocrewAIInc:mainfrom
Anandesh-Sharma:fix/4509-converter-strip-code-fences
Open

fix: strip markdown code fences from LLM responses before JSON parsing#4627
Anandesh-Sharma wants to merge 1 commit intocrewAIInc:mainfrom
Anandesh-Sharma:fix/4509-converter-strip-code-fences

Conversation

@Anandesh-Sharma
Copy link

Summary

  • Fixes Pydantic ValidationError when LLM returns JSON wrapped in markdown code fences (e.g., ```json ... ```)
  • Adds _strip_code_fences() helper that extracts content from markdown code fence blocks before model_validate_json()
  • Applied to both function-calling and non-function-calling converter paths in Converter.to_pydantic()
  • This commonly occurs during memory saving when the LLM wraps TaskEvaluation JSON in code fences

Fixes #4509

Test plan

  • Verify JSON wrapped in ```json ... ``` is correctly parsed
  • Verify JSON wrapped in ``` ... ``` (no language tag) is correctly parsed
  • Verify plain JSON without fences still works correctly
  • Verify memory saving works when LLM returns code-fenced JSON

🤖 Generated with Claude Code

LLMs sometimes wrap JSON responses in markdown code fences like
\`\`\`json ... \`\`\`, even when instructed to return valid JSON. This
causes model_validate_json() to fail with a Pydantic ValidationError
(e.g., "Invalid JSON: expected value at line 1 column 1").

Add _strip_code_fences() helper that extracts content from markdown
code fence blocks before attempting JSON parsing, applied to both
function-calling and non-function-calling converter paths.

Fixes crewAIInc#4509

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BUG] Pydantic Validation error while saving in Memory

1 participant