Composio powers 1000+ toolkits, tool search, context management, authentication, and a sandboxed workbench to help you build AI agents that turn intent into action.
fix(py): fix SALESFORCE_CREATE_LEAD type error by implementing anyOf/allOf
jkomyno committed
Jan 20, 2026 at 22:39 UTC
aa216f8ea6a92ae2fe991dede95d7755667784f5
2 files changed
+258
python/composio/utils/shared.py
+49
@@ -69,6 +69,55 @@ def json_schema_to_pydantic_type(
69
# Use reduce to create Union[Type1, Type2, ...] properly
70
return reduce(lambda a, b: t.Union[a, b], cast_types) # type: ignore
71
72
+ # Handle anyOf schemas (commonly used for nullable types)
73
+ if "anyOf" in json_schema:
74
+ any_of_options = json_schema["anyOf"]
75
+ pydantic_types = [
76
+ json_schema_to_pydantic_type(option) for option in any_of_options
77
+ ]
78
+ # Filter out None/null types for the base type
79
+ # "null" type maps to t.Optional[t.Any], so we need to check for that too
80
+ null_type = PYDANTIC_TYPE_TO_PYTHON_TYPE.get("null")
81
+ has_null = any(
82
+ ptype == null_type or ptype is type(None)
83
+ for ptype in pydantic_types
84
+ if ptype is not None
85
+ )
86
+ valid_types = [
87
+ ptype
88
+ for ptype in pydantic_types
89
+ if ptype is not None and ptype is not type(None) and ptype != null_type
90
+ ]
91
+ if len(valid_types) == 0:
92
+ return str # fallback to string type
93
+ if len(valid_types) == 1:
94
+ base_type = valid_types[0]
95
+ # If null was one of the options, make it Optional
96
+ if has_null:
97
+ return t.Optional[t.cast(t.Type, base_type)] # type: ignore
98
+ return base_type
99
+ cast_types = [t.cast(t.Type, ptype) for ptype in valid_types]
100
+ union_type = reduce(lambda a, b: t.Union[a, b], cast_types) # type: ignore
101
+ # If null was one of the options, include None in the Union
102
+ if has_null:
103
+ return t.Optional[union_type] # type: ignore
104
+ return union_type
105
+
106
+ # Handle allOf schemas (usually for combining schemas)
107
+ if "allOf" in json_schema:
108
+ all_of_options = json_schema["allOf"]
109
+ # For allOf with single option, use that option's type
110
+ if len(all_of_options) == 1:
111
+ return json_schema_to_pydantic_type(all_of_options[0])
112
+ # For multiple allOf options, try to find the primary type
113
+ # Usually the first non-ref schema or the one with "type" key
114
+ for option in all_of_options:
115
+ if "type" in option:
116
+ return json_schema_to_pydantic_type(option)
117
+ # Fallback: process first option
118
+ if all_of_options:
119
+ return json_schema_to_pydantic_type(all_of_options[0])
120
+
121
# Add fallback type - string
122
if "type" not in json_schema:
123
json_schema["type"] = "string"
python/tests/test_schema_parser.py
+209
@@ -559,6 +559,89 @@ class TestJsonSchemaToPydanticType:
559
with pytest.raises(ValueError, match="Unsupported JSON schema type"):
560
json_schema_to_pydantic_type(json_schema)
561
562
+ def test_anyof_nullable_object(self):
563
+ """Test anyOf with object and null types (common for nullable fields)."""
564
+ json_schema = {
565
+ "anyOf": [{"type": "object", "additionalProperties": {}}, {"type": "null"}]
566
+ }
567
+ result = json_schema_to_pydantic_type(json_schema)
568
+ # Should return Optional[Dict], not str (to allow both dict and None)
569
+ assert hasattr(result, "__origin__")
570
+ assert result.__origin__ is t.Union
571
+ assert t.Dict in result.__args__
572
+ assert type(None) in result.__args__
573
+
574
+ def test_anyof_nullable_object_with_properties(self):
575
+ """Test anyOf with object (with properties) and null types."""
576
+ json_schema = {
577
+ "anyOf": [
578
+ {
579
+ "type": "object",
580
+ "title": "CustomFields",
581
+ "properties": {"field1": {"type": "string"}},
582
+ },
583
+ {"type": "null"},
584
+ ]
585
+ }
586
+ result = json_schema_to_pydantic_type(json_schema)
587
+ # Should return Optional[BaseModel subclass] (Union with None)
588
+ assert hasattr(result, "__origin__")
589
+ assert result.__origin__ is t.Union
590
+ # One of the args should be a BaseModel subclass
591
+ model_types = [
592
+ arg
593
+ for arg in result.__args__
594
+ if isinstance(arg, type) and issubclass(arg, BaseModel)
595
+ ]
596
+ assert len(model_types) == 1
597
+ # None should also be in the union
598
+ assert type(None) in result.__args__
599
+
600
+ def test_anyof_multiple_types(self):
601
+ """Test anyOf with multiple non-null types."""
602
+ json_schema = {
603
+ "anyOf": [{"type": "string"}, {"type": "integer"}, {"type": "object"}]
604
+ }
605
+ result = json_schema_to_pydantic_type(json_schema)
606
+ assert hasattr(result, "__origin__")
607
+ assert result.__origin__ is t.Union
608
+
609
+ def test_anyof_single_type(self):
610
+ """Test anyOf with single type returns the type directly."""
611
+ json_schema = {"anyOf": [{"type": "string"}]}
612
+ result = json_schema_to_pydantic_type(json_schema)
613
+ assert result is str
614
+ assert not hasattr(result, "__origin__")
615
+
616
+ def test_allof_single_option(self):
617
+ """Test allOf with single option."""
618
+ json_schema = {
619
+ "allOf": [
620
+ {
621
+ "type": "object",
622
+ "properties": {"name": {"type": "string"}},
623
+ "title": "Test",
624
+ }
625
+ ]
626
+ }
627
+ result = json_schema_to_pydantic_type(json_schema)
628
+ assert isinstance(result, type)
629
+ assert issubclass(result, BaseModel)
630
+
631
+ def test_allof_multiple_options_with_type(self):
632
+ """Test allOf with multiple options where one has type."""
633
+ json_schema = {
634
+ "allOf": [{"description": "Some description"}, {"type": "string"}]
635
+ }
636
+ result = json_schema_to_pydantic_type(json_schema)
637
+ assert result is str
638
+
639
+ def test_allof_empty_options(self):
640
+ """Test allOf with empty options falls back to string."""
641
+ json_schema = {"allOf": []}
642
+ result = json_schema_to_pydantic_type(json_schema)
643
+ assert result is str
644
+
645
646
class TestJsonSchemaToFieldsDict:
647
"""Test cases for json_schema_to_fields_dict function."""
@@ -755,5 +838,131 @@ class TestEdgeCases:
838
pass
839
840
841
+class TestCrewAICustomFieldsBug:
842
+ """Regression tests for PLEN-1177 - CustomFields type error with CrewAI."""
843
+
844
+ @pytest.mark.unit
845
+ @pytest.mark.schema
846
+ def test_custom_fields_object_type_preserved(self):
847
+ """
848
+ Test that CustomFields with anyOf [object, null] returns Dict, not str.
849
+
850
+ This is the exact bug scenario from PLEN-1177.
851
+ """
852
+ # Schema similar to what Salesforce tools return for CustomFields
853
+ json_schema = {
854
+ "title": "CreateLeadRequest",
855
+ "type": "object",
856
+ "properties": {
857
+ "Company": {"type": "string", "title": "Company"},
858
+ "LastName": {"type": "string", "title": "LastName"},
859
+ "CustomFields": {
860
+ "anyOf": [
861
+ {"type": "object", "additionalProperties": {}},
862
+ {"type": "null"},
863
+ ],
864
+ "default": None,
865
+ "description": "Dictionary of custom field API names and their values.",
866
+ "title": "CustomFields",
867
+ },
868
+ },
869
+ "required": ["Company", "LastName"],
870
+ }
871
+
872
+ model_class = json_schema_to_model(json_schema)
873
+
874
+ # The model should accept a dict for CustomFields
875
+ instance = model_class(
876
+ Company="Test Corp",
877
+ LastName="Smith",
878
+ CustomFields={"Custom_Field__c": "Value"},
879
+ )
880
+ assert instance.CustomFields == {"Custom_Field__c": "Value"}
881
+
882
+ # The model should also accept None
883
+ instance_none = model_class(
884
+ Company="Test Corp",
885
+ LastName="Smith",
886
+ CustomFields=None,
887
+ )
888
+ assert instance_none.CustomFields is None
889
+
890
+ @pytest.mark.unit
891
+ @pytest.mark.schema
892
+ def test_pydantic_model_json_schema_preserves_object_type(self):
893
+ """
894
+ Test that when Pydantic model is converted back to JSON schema,
895
+ the object type is preserved (not converted to string).
896
+ """
897
+ json_schema = {
898
+ "title": "TestModel",
899
+ "type": "object",
900
+ "properties": {
901
+ "custom_dict": {
902
+ "anyOf": [{"type": "object"}, {"type": "null"}],
903
+ "default": None,
904
+ }
905
+ },
906
+ }
907
+
908
+ model_class = json_schema_to_model(json_schema)
909
+ generated_schema = model_class.model_json_schema()
910
+
911
+ # The generated schema should have object type, not string
912
+ custom_dict_schema = generated_schema["properties"]["custom_dict"]
913
+
914
+ # It might be wrapped in anyOf or have direct type
915
+ if "anyOf" in custom_dict_schema:
916
+ types = [opt.get("type") for opt in custom_dict_schema["anyOf"]]
917
+ assert "object" in types
918
+ assert "string" not in types
919
+ else:
920
+ assert (
921
+ custom_dict_schema.get("type") == "object"
922
+ or custom_dict_schema.get("additionalProperties") is not None
923
+ )
924
+
925
+ @pytest.mark.unit
926
+ @pytest.mark.schema
927
+ def test_anyof_with_nested_custom_fields(self):
928
+ """
929
+ Test anyOf handling with more complex nested CustomFields scenario.
930
+ """
931
+ json_schema = {
932
+ "title": "SalesforceRequest",
933
+ "type": "object",
934
+ "properties": {
935
+ "leadData": {
936
+ "type": "object",
937
+ "title": "LeadData",
938
+ "properties": {
939
+ "Name": {"type": "string", "title": "Name"},
940
+ "CustomFields": {
941
+ "anyOf": [
942
+ {"type": "object", "additionalProperties": {}},
943
+ {"type": "null"},
944
+ ],
945
+ "default": None,
946
+ },
947
+ },
948
+ "required": ["Name"],
949
+ }
950
+ },
951
+ "required": ["leadData"],
952
+ }
953
+
954
+ model_class = json_schema_to_model(json_schema)
955
+
956
+ # Test with CustomFields as dict
957
+ instance = model_class(
958
+ leadData={"Name": "John", "CustomFields": {"Industry__c": "Tech"}}
959
+ )
960
+ assert instance.leadData.CustomFields == {"Industry__c": "Tech"}
961
+
962
+ # Test with CustomFields as None
963
+ instance_none = model_class(leadData={"Name": "John", "CustomFields": None})
964
+ assert instance_none.leadData.CustomFields is None
965
+
966
+
967
if __name__ == "__main__":
968
pytest.main([__file__, "-v"])