fix: process.py to use validate_and_repair_json from utils.py (#4576)

Refactor process.py to use validate_and_repair_json from utils.py for nested dict tweaks
This commit is contained in:
anovazzi1 2024-11-13 15:58:40 -03:00 • committed by GitHub
commit 34b107b98e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 30 additions and 1 deletions

View file

@ -6,6 +6,7 @@ from loguru import logger
from pydantic import BaseModel
from langflow.graph.vertex.base import Vertex
from langflow.processing.utils import validate_and_repair_json
from langflow.schema.graph import InputValue, Tweaks
from langflow.schema.schema import INPUT_FIELD_NAME
from langflow.services.deps import get_settings_service
@ -142,7 +143,10 @@ def apply_tweaks(node: dict[str, Any], node_tweaks: dict[str, Any]) -> None:
if tweak_name not in template_data:
continue
if tweak_name in template_data:
if isinstance(tweak_value, dict):
if template_data[tweak_name]["type"] == "NestedDict":
value = validate_and_repair_json(tweak_value)
template_data[tweak_name]["value"] = value
elif isinstance(tweak_value, dict):
for k, v in tweak_value.items():
_k = "file_path" if template_data[tweak_name]["type"] == "file" else k
template_data[tweak_name][_k] = v

View file

@ -0,0 +1,25 @@
import json
from typing import Any
from json_repair import repair_json
def validate_and_repair_json(json_str: str | dict) -> dict[str, Any] | str:
"""Validates a JSON string and attempts to repair it if invalid.
Args:
json_str (str): The JSON string to validate/repair
Returns:
Union[Dict[str, Any], str]: The parsed JSON dict if valid/repairable,
otherwise returns the original string
"""
if not isinstance(json_str, str):
return json_str
try:
# If invalid, attempt repair
repaired = repair_json(json_str)
return json.loads(repaired)
except (json.JSONDecodeError, ImportError):
# Return original if repair fails or module not found
return json_str