Skip to content
Closed
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
9 changes: 7 additions & 2 deletions src/memos/mem_os/utils/format_utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import math
import random
import re

from typing import Any

Expand Down Expand Up @@ -533,7 +534,7 @@ def convert_graph_to_tree_forworkmem(
node_name = extract_node_name(memory)
memory_key = node.get("metadata", {}).get("key", node_name)
usage = node.get("metadata", {}).get("usage", [])
frequency = len(usage) if len(usage) < 100 else 100
frequency = min(100, len(usage))
node_map[node["id"]] = {
"id": node["id"],
"value": memory,
Expand Down Expand Up @@ -1413,4 +1414,8 @@ def clean_json_response(response: str) -> str:
"failed silently (check timed_with_status / generate() error "
"handling)."
)
return response.replace("```json", "").replace("```", "").strip()
# Only an opening fence (with its optional info string) at the very
# start and a closing fence at the very end are markdown markup. A
# global replace used to corrupt JSON string values that themselves
# contain fenced code, e.g. {"text": "```py\ncode```"}.
return re.sub(r"^```[^\n]*\n?|\n?```\s*$", "", response.strip()).strip()
20 changes: 20 additions & 0 deletions tests/mem_os/test_format_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,3 +73,23 @@ def test_clean_json_response_preserves_internal_backticks(self):
result = clean_json_response(input_str)
assert "`example`" in result
assert result.count("`") == 2 # Only internal backticks remain


def test_interior_code_fences_preserved():
"""The old global replace("```", "") corrupted JSON string values that
contain markdown code fences themselves."""
src = '```json\n{"text": "```py\\ncode```"}\n```'
assert clean_json_response(src) == '{"text": "```py\\ncode```"}'


def test_plain_fence_stripped():
assert clean_json_response('```json\n{"a": 1}\n```') == '{"a": 1}'
assert clean_json_response('```\n{"a": 1}\n```') == '{"a": 1}'


def test_no_fence_unchanged():
assert clean_json_response('{"a": 1}') == '{"a": 1}'


def test_opening_fence_only():
assert clean_json_response('```json\n{"a": 1}') == '{"a": 1}'
Loading