Skip to content
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
7 changes: 6 additions & 1 deletion langfuse/_utils/serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ def _default_inner(self, obj: Any) -> Any:
if isinstance(obj, (str, float, type(None))):
return obj

# Class objects (e.g. a pydantic model passed as a schema) would
# otherwise match the instance branches below and dump their namespace
if isinstance(obj, type):
return f"<class '{obj.__module__}.{obj.__qualname__}'>"

if self._depth >= self._MAX_DEPTH:
return f"<{type(obj).__name__}>"

Expand Down Expand Up @@ -214,7 +219,7 @@ def _default_inner(self, obj: Any) -> Any:
type(obj).__name__,
exc_info=e,
)
return f'"<not serializable object of type: {type(obj).__name__}>"'
return f"<not serializable object of type: {type(obj).__name__}>"

def encode(self, obj: Any) -> str:
self.seen.clear() # Clear seen objects before each encode call
Expand Down
23 changes: 23 additions & 0 deletions tests/unit/test_observe.py
Original file line number Diff line number Diff line change
Expand Up @@ -523,3 +523,26 @@ def marked() -> Any:

span = _finished_spans_by_name(memory_exporter, "marked")[0]
assert span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_OUTPUT] == "done"


def test_observe_records_class_argument_as_class_reference(
langfuse_memory_client: Any, memory_exporter: Any
) -> None:
class Invoice:
total: float = 0.0

@observe(name="extract")
def extract(text: str, schema: type) -> str:
return text

assert extract("hi", schema=Invoice) == "hi"

langfuse_memory_client.flush()

span = _finished_spans_by_name(memory_exporter, "extract")[0]
observed_input = json.loads(
span.attributes[LangfuseOtelSpanAttributes.OBSERVATION_INPUT]
)
assert observed_input["kwargs"]["schema"] == (
f"<class '{__name__}.{Invoice.__qualname__}'>"
)
32 changes: 32 additions & 0 deletions tests/unit/test_serializer.py
Original file line number Diff line number Diff line change
Expand Up @@ -570,3 +570,35 @@ def test_dict_with_non_string_keys_is_serialized(input_obj, expected):
result = json.loads(EventSerializer().encode(input_obj))

assert result == expected


class _PlainClass:
x = 1


@pytest.mark.parametrize(
"input_obj, expected",
[
(TestBaseModel, f"<class '{__name__}.TestBaseModel'>"),
(TestDataclass, f"<class '{__name__}.TestDataclass'>"),
(_PlainClass, f"<class '{__name__}._PlainClass'>"),
(TestEnum, f"<class '{__name__}.TestEnum'>"),
(int, "<class 'builtins.int'>"),
],
ids=["pydantic_model", "dataclass", "plain", "enum", "builtin"],
)
def test_class_objects_serialize_as_class_reference(input_obj, expected):
serializer = EventSerializer()

assert json.loads(serializer.encode(input_obj)) == expected
assert json.loads(serializer.encode({"schema": input_obj})) == {"schema": expected}


def test_failed_serialization_falls_back_to_plain_string():
class BrokenModel(BaseModel):
def model_dump(self, *args, **kwargs):
raise RuntimeError("boom")

result = json.loads(EventSerializer().encode({"value": BrokenModel()}))

assert result == {"value": "<not serializable object of type: BrokenModel>"}
Loading