Skip to content

Framework for orchestrating role-playing, autonomous AI agents. By fostering collaborative intelligence, CrewAI empowers agents to work together seamlessly, tackling complex tasks.

Serialize concrete Pydantic subclasses (#6187)

Vinicius Brasil9d44d0a5e5b2
diff --git a/lib/crewai/src/crewai/utilities/serialization.py b/lib/crewai/src/crewai/utilities/serialization.py
index 1b9e76588..8bc38b6f8 100644
--- a/lib/crewai/src/crewai/utilities/serialization.py
+++ b/lib/crewai/src/crewai/utilities/serialization.py
@@ -99,7 +99,7 @@ def to_serializable(
if isinstance(obj, BaseModel):
try:
return to_serializable(
- obj=obj.model_dump(mode="json", exclude=exclude),
+ obj=obj.model_dump(mode="json", exclude=exclude, serialize_as_any=True),
max_depth=max_depth,
_current_depth=_current_depth + 1,
_ancestors=new_ancestors,
diff --git a/lib/crewai/tests/utilities/test_serialization.py b/lib/crewai/tests/utilities/test_serialization.py
index 8ec68ead8..93817f285 100644
--- a/lib/crewai/tests/utilities/test_serialization.py
+++ b/lib/crewai/tests/utilities/test_serialization.py
@@ -21,6 +21,10 @@ class Person(BaseModel):
skills: List[str]
+class Container(BaseModel):
+ payload: BaseModel | None = None
+
+
@dataclass
class DataclassPerson:
name: str
@@ -114,6 +118,16 @@ def test_pydantic_model_serialization():
)
+def test_polymorphic_field_serializes_concrete_subclass():
+ container = Container(
+ payload=Address(street="1 Main", city="Tech City", country="Pythonia")
+ )
+
+ assert to_serializable(container) == {
+ "payload": {"street": "1 Main", "city": "Tech City", "country": "Pythonia"}
+ }
+
+
def test_dataclass_serialization_recurses_into_nested_values():
person = DataclassPerson(
name="Ada",