From 7b93eb13859e08f4862644bd244cefc5c7462113 Mon Sep 17 00:00:00 2001 From: Gabriel Luiz Freitas Almeida Date: Sat, 22 Jun 2024 15:31:29 -0300 Subject: [PATCH] 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. --- .../base/langflow/template/field/base.py | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/backend/base/langflow/template/field/base.py b/src/backend/base/langflow/template/field/base.py index 2fe1a7a9d..e82576230 100644 --- a/src/backend/base/langflow/template/field/base.py +++ b/src/backend/base/langflow/template/field/base.py @@ -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=[])