Skip to content

Commit

Permalink
Fix union issue that Daniel was running into
Browse files Browse the repository at this point in the history
  • Loading branch information
bhancockio committed Jan 16, 2025
1 parent 3fecde4 commit baa4650
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/crewai/utilities/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -241,9 +241,13 @@ def describe_field(field_type):
origin = get_origin(field_type)
args = get_args(field_type)

if origin is Union and type(None) in args:
if origin is Union or (origin is None and len(args) > 0):
# Handle both Union and the new '|' syntax
non_none_args = [arg for arg in args if arg is not type(None)]
return f"Optional[{describe_field(non_none_args[0])}]"
if len(non_none_args) == 1:
return f"Optional[{describe_field(non_none_args[0])}]"
else:
return f"Optional[Union[{', '.join(describe_field(arg) for arg in non_none_args)}]]"
elif origin is list:
return f"List[{describe_field(args[0])}]"
elif origin is dict:
Expand All @@ -252,8 +256,10 @@ def describe_field(field_type):
return f"Dict[{key_type}, {value_type}]"
elif isinstance(field_type, type) and issubclass(field_type, BaseModel):
return generate_model_description(field_type)
else:
elif hasattr(field_type, "__name__"):
return field_type.__name__
else:
return str(field_type)

fields = model.__annotations__
field_descriptions = [
Expand Down
9 changes: 9 additions & 0 deletions tests/utilities/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -588,3 +588,12 @@ def test_converter_with_function_calling():
assert output.name == "Eve"
assert output.age == 35
instructor.to_pydantic.assert_called_once()


def test_generate_model_description_union_field():
class UnionModel(BaseModel):
field: int | str | None

description = generate_model_description(UnionModel)
expected_description = '{\n "field": int | str | None\n}'
assert description == expected_description

0 comments on commit baa4650

Please sign in to comment.