chore: Update langflow template field base.py

Refactor langflow template field base.py to improve code readability and maintainability.

- Import additional types from langflow.helpers.custom and langflow.type_extraction.type_extraction modules.
- Add field_validator method to validate field_type.
- Convert type to string if it is a type instance.
- Raise ValueError if type is not a string or a type instance.
This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-06-22 15:31:29 -03:00
commit 7b93eb1385

View file

@ -1,11 +1,12 @@
from enum import Enum
from typing import Optional # type: ignore
from typing import Any, Callable, Union
from typing import Any, Callable, GenericAlias, Optional, Union, _GenericAlias, _UnionGenericAlias # type: ignore
from pydantic import BaseModel, ConfigDict, Field, field_serializer, field_validator, model_serializer, model_validator
from langflow.field_typing import Text
from langflow.field_typing.range_spec import RangeSpec
from langflow.helpers.custom import format_type
from langflow.type_extraction.type_extraction import post_process_type
class UndefinedType(Enum):
@ -139,6 +140,19 @@ class Input(BaseModel):
for file_type in value
]
@field_validator("field_type", mode="before")
@classmethod
def validate_type(cls, v):
# If the user passes CustomComponent as a type insteado of "CustomComponent" we need to convert it to a string
# this should be done for all types
# How to check if v is a type?
if isinstance(v, (type, _GenericAlias, GenericAlias, _UnionGenericAlias)):
v = post_process_type(v)[0]
v = format_type(v)
elif not isinstance(v, str):
raise ValueError(f"type must be a string or a type, not {type(v)}")
return v
class Output(BaseModel):
types: Optional[list[str]] = Field(default=[])