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.

fix(flow): support non-primitive types in SQLiteFlowPersistence (#7358) (#7376)

Rohit Kanithi9473098af5ef
diff --git a/lib/crewai/src/crewai/flow/persistence/sqlite.py b/lib/crewai/src/crewai/flow/persistence/sqlite.py
index 7724832e8..e0c7994fd 100644
--- a/lib/crewai/src/crewai/flow/persistence/sqlite.py
+++ b/lib/crewai/src/crewai/flow/persistence/sqlite.py
@@ -2,7 +2,7 @@
from __future__ import annotations
-from datetime import datetime, timezone
+from datetime import date, datetime, timezone
import json
import os
from pathlib import Path
@@ -21,6 +21,20 @@ if TYPE_CHECKING:
from crewai.flow.async_feedback.types import PendingFeedbackContext
+def _json_default(obj: Any) -> Any:
+ """Fallback serializer for non-primitive types in JSON dumps."""
+ if isinstance(obj, BaseModel):
+ try:
+ return obj.model_dump(mode="json")
+ except Exception:
+ return obj.model_dump(mode="python")
+ if isinstance(obj, (set, tuple)):
+ return list(obj)
+ if isinstance(obj, (date, datetime)):
+ return obj.isoformat()
+ return str(obj)
+
+
class SQLiteFlowPersistence(FlowPersistence):
"""SQLite-based implementation of flow state persistence.
@@ -139,7 +153,7 @@ class SQLiteFlowPersistence(FlowPersistence):
flow_uuid,
method_name,
datetime.now(timezone.utc).isoformat(),
- json.dumps(state_dict),
+ json.dumps(state_dict, default=_json_default),
),
)
@@ -147,7 +161,10 @@ class SQLiteFlowPersistence(FlowPersistence):
def _to_state_dict(state_data: dict[str, Any] | BaseModel) -> dict[str, Any]:
"""Convert state_data to a plain dict."""
if isinstance(state_data, BaseModel):
- return state_data.model_dump()
+ try:
+ return state_data.model_dump(mode="json")
+ except Exception:
+ return state_data.model_dump(mode="python")
if isinstance(state_data, dict):
return state_data
raise ValueError(
@@ -237,8 +254,8 @@ class SQLiteFlowPersistence(FlowPersistence):
""",
(
flow_uuid,
- json.dumps(context.to_dict()),
- json.dumps(state_dict),
+ json.dumps(context.to_dict(), default=_json_default),
+ json.dumps(state_dict, default=_json_default),
datetime.now(timezone.utc).isoformat(),
),
)
diff --git a/lib/crewai/tests/test_flow_persistence.py b/lib/crewai/tests/test_flow_persistence.py
index b405cc64d..ef5cb3f6f 100644
--- a/lib/crewai/tests/test_flow_persistence.py
+++ b/lib/crewai/tests/test_flow_persistence.py
@@ -472,3 +472,150 @@ async def test_akickoff_fork_conflict_with_from_checkpoint_raises():
msg = str(excinfo.value)
assert "from_checkpoint" in msg
assert "restore_from_state_id" in msg
+
+
+def test_persist_complex_types_structured_state(tmp_path):
+ """Test persisting state with datetime, UUID, and set fields."""
+ from datetime import datetime, timezone
+ import uuid
+ from typing import Any
+ from pydantic import Field
+
+ class CustomPayload:
+ """Custom un-serializable class for testing."""
+
+ def __str__(self) -> str:
+ return "custom_payload_str"
+
+ class ComplexState(FlowState):
+ """Structured state with non-primitive types for testing."""
+
+ created_at: datetime = Field(
+ default_factory=lambda: datetime.now(timezone.utc)
+ )
+ user_id: uuid.UUID = Field(default_factory=uuid.uuid4)
+ tags: set[str] = Field(default_factory=lambda: {"alpha", "beta"})
+ payload: Any = Field(default_factory=CustomPayload)
+ counter: int = 0
+
+ db_path = os.path.join(tmp_path, "test_complex_flows.db")
+ persistence = SQLiteFlowPersistence(db_path)
+
+ class ComplexFlow(Flow[ComplexState]):
+ """Flow with structured complex state."""
+
+ initial_state = ComplexState
+
+ @start()
+ @persist(persistence)
+ def step(self):
+ """Step that increments counter."""
+ self.state.counter += 1
+ return "done"
+
+ flow1 = ComplexFlow(persistence=persistence)
+ flow1.kickoff()
+ flow1_id = flow1.state.id
+ flow1_created_at = flow1.state.created_at
+ flow1_user_id = flow1.state.user_id
+
+ saved = persistence.load_state(flow1_id)
+ assert saved is not None
+ assert saved["counter"] == 1
+ assert isinstance(saved["created_at"], str)
+ assert isinstance(saved["user_id"], str)
+ assert set(saved["tags"]) == {"alpha", "beta"}
+ assert saved["payload"] == "custom_payload_str"
+
+ flow2 = ComplexFlow(persistence=persistence)
+ flow2.kickoff(inputs={"id": flow1_id})
+ assert flow2.state.id == flow1_id
+ assert flow2.state.counter == 2
+ assert isinstance(flow2.state.created_at, datetime)
+ assert flow2.state.created_at == flow1_created_at
+ assert isinstance(flow2.state.user_id, uuid.UUID)
+ assert flow2.state.user_id == flow1_user_id
+ assert isinstance(flow2.state.tags, set)
+ assert flow2.state.tags == {"alpha", "beta"}
+
+
+def test_persist_complex_types_dict_state(tmp_path):
+ """Test persisting dictionary state containing datetime, UUID, Decimal, and Path."""
+ from datetime import datetime, timezone
+ from decimal import Decimal
+ from pathlib import Path
+ import uuid
+ from typing import Any
+
+ db_path = os.path.join(tmp_path, "test_dict_flows.db")
+ persistence = SQLiteFlowPersistence(db_path)
+
+ now = datetime.now(timezone.utc)
+ uid = uuid.uuid4()
+
+ class DictFlow(Flow[Dict[str, Any]]):
+ """Flow with dictionary state."""
+
+ initial_state = dict
+
+ @start()
+ @persist(persistence)
+ def step(self):
+ """Step that populates dictionary state."""
+ self.state["id"] = "dict-uuid-1"
+ self.state["created_at"] = now
+ self.state["user_id"] = uid
+ self.state["tags"] = {"x", "y"}
+ self.state["price"] = Decimal("19.99")
+ self.state["file_path"] = Path("/tmp/data.txt")
+ self.state["nested"] = {"l1": {"l2": {"l3": {"l4": {"l5": {"l6": "deep_value"}}}}}}
+ return "done"
+
+ flow = DictFlow(persistence=persistence)
+ flow.kickoff()
+
+ saved = persistence.load_state("dict-uuid-1")
+ assert saved is not None
+ assert saved["created_at"] == now.isoformat()
+ assert saved["user_id"] == str(uid)
+ assert set(saved["tags"]) == {"x", "y"}
+ assert saved["price"] == "19.99"
+ assert saved["file_path"] == "/tmp/data.txt"
+ assert saved["nested"]["l1"]["l2"]["l3"]["l4"]["l5"]["l6"] == "deep_value"
+
+
+def test_save_pending_feedback_complex_types(tmp_path):
+ """Test saving and loading pending feedback with complex types in state."""
+ from datetime import datetime, timezone
+ import uuid
+ from crewai.flow.async_feedback.types import PendingFeedbackContext
+
+ db_path = os.path.join(tmp_path, "test_feedback_flows.db")
+ persistence = SQLiteFlowPersistence(db_path)
+
+ context = PendingFeedbackContext(
+ flow_id="test-feedback-uuid",
+ flow_class="test.TestFlow",
+ method_name="request_review",
+ method_output="draft output",
+ message="Please review",
+ )
+ now = datetime.now(timezone.utc)
+ uid = uuid.uuid4()
+ state_data = {
+ "id": "test-feedback-uuid",
+ "timestamp": now,
+ "session_id": uid,
+ "categories": {"ai", "agents"},
+ }
+
+ persistence.save_pending_feedback("test-feedback-uuid", context, state_data)
+
+ result = persistence.load_pending_feedback("test-feedback-uuid")
+ assert result is not None
+ loaded_state, loaded_context = result
+ assert loaded_context.method_name == "request_review"
+ assert loaded_state["timestamp"] == now.isoformat()
+ assert loaded_state["session_id"] == str(uid)
+ assert set(loaded_state["categories"]) == {"ai", "agents"}
+