fix: make JSON serialization work with Callable objects (#4302)

Enhance JSON serialization with custom encoder for Callable objects
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-10-28 17:45:29 -03:00 committed by GitHub
commit 882f20d64f
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 12 additions and 4 deletions

View file

@ -8,6 +8,7 @@ from functools import partial
from fastapi.encoders import jsonable_encoder
from typing_extensions import Protocol
from langflow.schema.artifact import CUSTOM_ENCODERS
from langflow.schema.log import LoggableType
@ -53,7 +54,7 @@ class EventManager:
self.events[name] = _callback
def send_event(self, *, event_type: str, data: LoggableType) -> None:
jsonable_data = jsonable_encoder(data)
jsonable_data = jsonable_encoder(data, custom_encoder=CUSTOM_ENCODERS)
json_data = {"event": event_type, "data": jsonable_data}
event_id = uuid.uuid4()
str_data = json.dumps(json_data) + "\n\n"

View file

@ -1,4 +1,4 @@
from collections.abc import Generator
from collections.abc import Callable, Generator
from enum import Enum
from fastapi.encoders import jsonable_encoder
@ -51,6 +51,13 @@ def get_artifact_type(value, build_result=None) -> str:
return result.value
def encode_callable(obj: Callable):
return obj.__name__ if hasattr(obj, "__name__") else str(obj)
CUSTOM_ENCODERS = {Callable: encode_callable}
def post_process_raw(raw, artifact_type: str):
if artifact_type == ArtifactType.STREAM.value:
raw = ""
@ -65,10 +72,10 @@ def post_process_raw(raw, artifact_type: str):
elif artifact_type == ArtifactType.UNKNOWN.value and raw is not None:
if isinstance(raw, BaseModel | dict):
try:
raw = jsonable_encoder(raw)
raw = jsonable_encoder(raw, custom_encoder=CUSTOM_ENCODERS)
artifact_type = ArtifactType.OBJECT.value
except Exception: # noqa: BLE001
logger.opt(exception=True).debug("Error converting to json")
logger.opt(exception=True).debug(f"Error converting to json: {raw} ({type(raw)})")
raw = "Built Successfully ✨"
else:
raw = "Built Successfully ✨"