Skip to content

fix: handle control characters in LLM JSON responses#4420

Merged
kartik-mem0 merged 1 commit intomainfrom
fix/json-loads-strict-false
Mar 19, 2026
Merged

fix: handle control characters in LLM JSON responses#4420
kartik-mem0 merged 1 commit intomainfrom
fix/json-loads-strict-false

Conversation

@utkarsh240799
Copy link
Copy Markdown
Contributor

Description

  • Uses strict=False in all json.loads() calls that parse LLM responses in mem0/memory/main.py.
  • This allows control characters (newlines, tabs, etc.) inside JSON string values, which LLMs occasionally produce.
  • Applied to both sync (Memory) and async (AsyncMemory) code paths, covering new_memories_with_actions and new_retrieved_facts parsing.

Fixes #2194

Type of change

  • Bug fix (non-breaking change which fixes an issue)

Testing

Verified the fix handles the exact scenario from the issue:

import json

# Reproduces issue #2194 - literal newline in JSON string value
bad_json = '{"memory": [{"id": "0", "text": "app\n                         store", "event": "NONE"}]}'

# Before fix: raises JSONDecodeError: Invalid control character
json.loads(bad_json)  # FAILS

# After fix: parses successfully
json.loads(bad_json, strict=False)  # SUCCESS: {'memory': [{'id': '0', 'text': 'app\n                         store', 'event': 'NONE'}]}
  • strict=False only relaxes control character handling — all other JSON validation remains unchanged.
  • No behavior change for valid JSON responses (which is the common case).
  • Fallback extract_json() paths also updated to ensure consistent handling.

Checklist

  • My code follows the style guidelines of this project
  • I have performed a self-review of my own code
  • My changes generate no new warnings
  • New and existing unit tests pass locally with my changes

Maintainer Checklist

…ol characters (#2194)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@kartik-mem0 kartik-mem0 merged commit 410b79c into main Mar 19, 2026
8 checks passed
@kartik-mem0 kartik-mem0 deleted the fix/json-loads-strict-false branch March 19, 2026 12:01
jamebobob pushed a commit to jamebobob/mem0-vigil-recall that referenced this pull request Mar 29, 2026
Co-authored-by: utkarsh240799 <utkarsh240799@users.noreply.github.com>
Co-authored-by: Claude Opus 4.6 (1M context) <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.

When special characters such as line breaks exist in "new_memories_with_actions", json conversion fails

2 participants