Refactor custom component field ordering

This commit is contained in:
Gabriel Luiz Freitas Almeida 2024-02-11 13:04:13 -03:00
commit aabaf513e4

View file

@ -7,8 +7,6 @@ from typing import Any, Dict, List, Optional, Union
from uuid import UUID
from fastapi import HTTPException
from loguru import logger
from langflow.field_typing.range_spec import RangeSpec
from langflow.interface.custom.code_parser.utils import extract_inner_type
from langflow.interface.custom.custom_component import CustomComponent
@ -21,6 +19,7 @@ from langflow.interface.importing.utils import eval_custom_component_code
from langflow.template.field.base import TemplateField
from langflow.template.frontend_node.custom_components import CustomComponentFrontendNode
from langflow.utils.util import get_base_classes
from loguru import logger
def add_output_types(frontend_node: CustomComponentFrontendNode, return_types: List[str]):
@ -52,7 +51,10 @@ def reorder_fields(frontend_node: CustomComponentFrontendNode, field_order: List
# Create a dictionary for O(1) lookup time.
field_dict = {field.name: field for field in frontend_node.template.fields}
reordered_fields = [field_dict[name] for name in field_order if name in field_dict]
# Add any fields that are not in the field_order list
for field in frontend_node.template.fields:
if field.name not in field_order:
reordered_fields.append(field)
frontend_node.template.fields = reordered_fields
@ -206,7 +208,8 @@ def run_build_config(custom_component: CustomComponent, user_id: Optional[Union[
) from exc
try:
build_config: Dict = custom_class(user_id=user_id).build_config()
custom_instance = custom_class(user_id=user_id)
build_config: Dict = custom_instance.build_config()
for field_name, field in build_config.items():
# Allow user to build TemplateField as well
@ -220,7 +223,7 @@ def run_build_config(custom_component: CustomComponent, user_id: Optional[Union[
except Exception as exc:
logger.error(f"Error while getting build_config: {str(exc)}")
return build_config
return build_config, custom_instance
except Exception as exc:
logger.error(f"Error while building field config: {str(exc)}")
@ -291,7 +294,7 @@ def build_custom_component_template(
logger.debug("Built base frontend node")
logger.debug("Updated attributes")
field_config = run_build_config(custom_component, user_id=user_id, update_field=update_field)
field_config, custom_instance = run_build_config(custom_component, user_id=user_id, update_field=update_field)
logger.debug("Built field config")
entrypoint_args = custom_component.get_function_entrypoint_args
@ -303,7 +306,7 @@ def build_custom_component_template(
add_output_types(frontend_node, custom_component.get_function_entrypoint_return_type)
logger.debug("Added base classes")
reorder_fields(frontend_node, custom_component.field_order)
reorder_fields(frontend_node, custom_instance._get_field_order())
return frontend_node.to_dict(add_name=False)
except Exception as exc: