Skip to content

fix: strip markdown code fences from AI response before JSON parsing#4693

Open
geoClink wants to merge 1 commit into
TandoorRecipes:developfrom
geoClink:fix/strip-json-fence-ai-response
Open

fix: strip markdown code fences from AI response before JSON parsing#4693
geoClink wants to merge 1 commit into
TandoorRecipes:developfrom
geoClink:fix/strip-json-fence-ai-response

Conversation

@geoClink

@geoClink geoClink commented Jun 6, 2026

Copy link
Copy Markdown

Bug

When using Anthropic Claude as an AI provider, the aiproperties endpoint crashes with JSONDecodeError: Expecting value: line 1 column 1 (char 0). Claude wraps its JSON response in a markdown code fence (json ... ) which causes json.loads() to fail since the
first character is a backtick, not {.

Root Cause

response_format={"type": "json_object"} is passed to LiteLLM but the Anthropic backend does not enforce JSON-only responses the way
OpenAI does — Claude is free to return JSON wrapped in a markdown code fence.

Fix

Strip markdown code fences from the AI response before calling json.loads() using re.sub. If no code fence is present (e.g. OpenAI,
Gemini) the string passes through unchanged.

The fix is applied in two places:

  • AI property generation endpoint (aiproperties)
  • AI recipe import endpoint

Unable to test locally without an Anthropic API key, but the fix follows the exact pattern suggested in the issue report.

- Added regex substitution to extract JSON content from response text in `RecipeViewSet` and `AiImportView`
@geoClink

geoClink commented Jun 6, 2026

Copy link
Copy Markdown
Author

This is ready for review. The fix strips markdown code fences from the AI response before JSON parsing in both the aiproperties and AI import endpoints. If no code fence is present the string passes through unchanged, so existing OpenAI/Gemini providers are unaffected.

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.

1 participant