Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Issue #1885: Extract JSON from Code Blocks and Handle Malformed JSON with json_repair #1978

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 19 additions & 2 deletions mem0/memory/main.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import re
import json_repair
import concurrent
import hashlib
import json
Expand Down Expand Up @@ -152,8 +154,14 @@ def _add_to_vector_store(self, messages, metadata, filters):
response_format={"type": "json_object"},
)

# Extract JSON content from code blocks in the response using a regular expression
search_result = re.search("(```json)((.*\n)+)(```)", response)
if search_result:
response = search_result.group(2).strip()

try:
new_retrieved_facts = json.loads(response)["facts"]
# Attempt to load the JSON response using json_repair to fix any invalid JSON syntax
new_retrieved_facts = json_repair.loads(response)["facts"]
except Exception as e:
logging.error(f"Error in new_retrieved_facts: {e}")
new_retrieved_facts = []
Expand All @@ -178,8 +186,17 @@ def _add_to_vector_store(self, messages, metadata, filters):
messages=[{"role": "user", "content": function_calling_prompt}],
response_format={"type": "json_object"},
)
new_memories_with_actions = json.loads(new_memories_with_actions)
# Extract JSON content from possible code blocks in response using re
search_result = re.search("(```json)((.*\n)+)(```)", new_memories_with_actions)
if search_result:
new_memories_with_actions = search_result.group(2).strip()

try:
# Attempt to load the JSON response using json_repair to fix any invalid JSON syntax
new_memories_with_actions = json_repair.loads(new_memories_with_actions)
except Exception as e:
logging.error(f"Could not load JSON from new_memories_with_actions: {e}")
new_memories_with_actions = []
returned_memories = []
try:
for resp in new_memories_with_actions["memory"]:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ openai = "^1.33.0"
posthog = "^3.5.0"
pytz = "^2024.1"
sqlalchemy = "^2.0.31"
json-repair = "^0.30.0"

[tool.poetry.group.graph.dependencies]
langchain-community = "^0.3.1"
Expand Down