From 7b7e5cd1b4b899bc230af93f57de7c7784fb5c94 Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Tue, 1 Oct 2024 19:46:48 +0200 Subject: [PATCH] feat: Add ruff rules for return (RET) (#3981) Add ruff rules for return (RET) --- src/backend/base/langflow/__main__.py | 5 +-- .../base/langflow/api/health_check_router.py | 5 +-- src/backend/base/langflow/api/utils.py | 35 ++++++++--------- src/backend/base/langflow/api/v1/endpoints.py | 18 ++++----- src/backend/base/langflow/api/v1/files.py | 2 +- src/backend/base/langflow/api/v1/flows.py | 20 ++++------ src/backend/base/langflow/api/v1/folders.py | 6 +-- src/backend/base/langflow/api/v1/login.py | 22 +++++------ src/backend/base/langflow/api/v1/schemas.py | 3 +- .../base/langflow/api/v1/starter_projects.py | 3 +- src/backend/base/langflow/api/v1/store.py | 12 ++---- src/backend/base/langflow/api/v1/users.py | 5 +-- .../base/langflow/base/agents/agent.py | 2 +- .../base/langflow/base/chains/model.py | 2 +- src/backend/base/langflow/base/data/utils.py | 10 ++--- .../base/langflow/base/embeddings/model.py | 2 +- .../base/langchain_utilities/model.py | 2 +- .../base/langflow/base/memory/model.py | 2 +- .../base/langflow/base/models/model.py | 23 ++++++----- .../base/langflow/base/textsplitters/model.py | 2 +- .../base/langflow/base/tools/flow_tool.py | 10 ++--- .../base/langflow/base/vectorstores/model.py | 7 ++-- .../langflow/components/Notion/create_page.py | 14 +++---- .../Notion/list_database_properties.py | 8 ++-- .../components/Notion/page_content_viewer.py | 5 +-- .../components/Notion/update_page_property.py | 11 +++--- .../components/agents/HierarchicalCrew.py | 3 +- .../components/agents/SequentialCrew.py | 3 +- .../astra_assistants/create_assistant.py | 3 +- .../astra_assistants/create_thread.py | 3 +- .../astra_assistants/get_assistant.py | 3 +- .../components/astra_assistants/getenvvar.py | 4 +- .../astra_assistants/list_assistants.py | 3 +- .../components/astra_assistants/run.py | 3 +- .../base/langflow/components/data/Gmail.py | 10 ++--- .../langflow/components/data/GoogleDrive.py | 5 +-- .../components/data/GoogleDriveSearch.py | 11 +++--- .../deactivated/SelectivePassThrough.py | 13 +++---- .../documentloaders/AssemblyAIGetSubtitles.py | 5 +-- .../documentloaders/AssemblyAILeMUR.py | 17 ++++---- .../AssemblyAIPollTranscript.py | 5 +-- .../AssemblyAIStartTranscript.py | 7 ++-- .../components/documentloaders/Confluence.py | 3 +- .../components/documentloaders/GitLoader.py | 3 +- .../documentloaders/Unstructured.py | 4 +- .../embeddings/AmazonBedrockEmbeddings.py | 3 +- .../HuggingFaceInferenceAPIEmbeddings.py | 3 +- .../embeddings/util/AIMLEmbeddingsImpl.py | 3 +- .../components/helpers/ParseJSONData.py | 3 +- .../langflow/components/inputs/TextInput.py | 3 +- .../langchain_utilities/FirecrawlCrawlApi.py | 3 +- .../langchain_utilities/FirecrawlScrapeApi.py | 3 +- .../components/memories/AstraDBChatMemory.py | 3 +- .../langflow/components/models/AIMLModel.py | 4 +- .../langflow/components/models/CohereModel.py | 4 +- .../models/GoogleGenerativeAIModel.py | 4 +- .../langflow/components/models/GroqModel.py | 4 +- .../components/models/HuggingFaceModel.py | 3 +- .../langflow/components/models/Maritalk.py | 3 +- .../components/models/MistralModel.py | 4 +- .../langflow/components/models/NvidiaModel.py | 3 +- .../langflow/components/models/OllamaModel.py | 3 +- .../langflow/components/models/OpenAIModel.py | 4 +- .../components/models/PerplexityModel.py | 4 +- .../components/prompts/LangChainHubPrompt.py | 4 +- .../prototypes/ConditionalRouter.py | 18 ++++----- .../components/prototypes/PythonFunction.py | 9 ++--- .../components/prototypes/RunnableExecutor.py | 3 +- .../retrievers/MultiQueryRetriever.py | 7 +--- .../components/toolkits/ComposioAPI.py | 28 ++++++------- .../langflow/components/tools/Calculator.py | 7 ++-- .../tools/PythonCodeStructuredTool.py | 3 +- .../langflow/components/tools/SearXNGTool.py | 3 +- .../components/vectorstores/AstraDB.py | 10 ++--- .../components/vectorstores/Cassandra.py | 11 ++---- .../components/vectorstores/CassandraGraph.py | 15 +++---- .../components/vectorstores/Clickhouse.py | 3 +- .../components/vectorstores/Couchbase.py | 3 +- .../langflow/components/vectorstores/FAISS.py | 5 +-- .../langflow/components/vectorstores/HCD.py | 10 ++--- .../components/vectorstores/Milvus.py | 3 +- .../vectorstores/MongoDBAtlasVector.py | 3 +- .../components/vectorstores/Pinecone.py | 3 +- .../components/vectorstores/Qdrant.py | 3 +- .../langflow/components/vectorstores/Redis.py | 3 +- .../vectorstores/SupabaseVectorStore.py | 3 +- .../components/vectorstores/Upstash.py | 3 +- .../components/vectorstores/Vectara.py | 5 +-- .../components/vectorstores/Weaviate.py | 3 +- .../components/vectorstores/pgvector.py | 3 +- .../base/langflow/custom/attributes.py | 3 +- .../custom/code_parser/code_parser.py | 19 +++++---- .../custom/custom_component/base_component.py | 3 +- .../custom/custom_component/component.py | 12 ++---- .../custom_component/custom_component.py | 3 +- .../directory_reader/directory_reader.py | 26 ++++++------- src/backend/base/langflow/custom/utils.py | 10 ++--- src/backend/base/langflow/exceptions/api.py | 3 +- .../base/langflow/field_typing/__init__.py | 2 +- src/backend/base/langflow/graph/edge/base.py | 14 +++---- .../base/langflow/graph/graph/ascii.py | 4 +- src/backend/base/langflow/graph/graph/base.py | 39 +++++++------------ .../base/langflow/graph/graph/state_model.py | 3 +- .../base/langflow/graph/state/model.py | 4 +- src/backend/base/langflow/graph/utils.py | 11 +++--- .../base/langflow/graph/vertex/base.py | 9 ++--- .../base/langflow/graph/vertex/types.py | 16 ++++---- src/backend/base/langflow/helpers/flow.py | 10 ++--- src/backend/base/langflow/helpers/user.py | 4 +- .../base/langflow/initial_setup/setup.py | 6 +-- .../starter_projects/basic_prompting.py | 3 +- .../starter_projects/blog_writer.py | 3 +- .../starter_projects/complex_agent.py | 3 +- .../starter_projects/document_qa.py | 3 +- .../hierarchical_tasks_agent.py | 3 +- .../starter_projects/memory_chatbot.py | 3 +- .../sequential_tasks_agent.py | 4 +- .../starter_projects/vector_store_rag.py | 6 +-- src/backend/base/langflow/inputs/inputs.py | 5 +-- .../base/langflow/inputs/validators.py | 5 +-- .../langflow/interface/initialize/loading.py | 7 ++-- src/backend/base/langflow/interface/run.py | 3 +- src/backend/base/langflow/interface/types.py | 6 +-- src/backend/base/langflow/load/load.py | 6 +-- src/backend/base/langflow/load/utils.py | 18 ++++----- src/backend/base/langflow/main.py | 17 ++++---- src/backend/base/langflow/memory.py | 5 +-- .../base/langflow/processing/process.py | 3 +- src/backend/base/langflow/schema/data.py | 3 +- src/backend/base/langflow/schema/message.py | 5 +-- src/backend/base/langflow/schema/schema.py | 12 +++--- .../base/langflow/services/auth/utils.py | 25 ++++++------ .../base/langflow/services/cache/disk.py | 5 +-- .../base/langflow/services/cache/factory.py | 14 +++---- .../base/langflow/services/cache/service.py | 8 ++-- .../base/langflow/services/chat/service.py | 26 +++++++------ .../services/database/models/flow/model.py | 7 ++-- .../database/models/transactions/model.py | 3 +- .../database/models/vertex_builds/model.py | 6 +-- .../base/langflow/services/plugins/factory.py | 3 +- .../base/langflow/services/storage/factory.py | 9 ++--- .../base/langflow/services/store/schema.py | 3 +- .../base/langflow/services/store/service.py | 19 ++++----- .../services/telemetry/opentelemetry.py | 11 +++--- src/backend/base/langflow/services/utils.py | 33 +++++++--------- .../langflow/services/variable/factory.py | 3 +- .../langflow/services/variable/kubernetes.py | 15 +++---- .../services/variable/kubernetes_secrets.py | 5 +-- .../langflow/services/variable/service.py | 3 +- .../langflow/template/frontend_node/base.py | 3 +- .../base/langflow/utils/async_helpers.py | 3 +- .../utils/connection_string_parser.py | 3 +- src/backend/base/langflow/utils/util.py | 4 +- src/backend/base/langflow/utils/validate.py | 6 +-- src/backend/base/langflow/utils/version.py | 1 + src/backend/base/pyproject.toml | 1 + 156 files changed, 452 insertions(+), 670 deletions(-) diff --git a/src/backend/base/langflow/__main__.py b/src/backend/base/langflow/__main__.py index 7d7d49133..9a49ddaa3 100644 --- a/src/backend/base/langflow/__main__.py +++ b/src/backend/base/langflow/__main__.py @@ -235,7 +235,7 @@ def run_on_windows(host, port, log_level, options, app): """ print_banner(host, port) run_langflow(host, port, log_level, options, app) - return None + return def is_port_in_use(port, host="localhost"): @@ -296,8 +296,7 @@ def generate_pip_command(package_names, is_pre_release): base_command = "pip install" if is_pre_release: return f"{base_command} {' '.join(package_names)} -U --pre" - else: - return f"{base_command} {' '.join(package_names)} -U" + return f"{base_command} {' '.join(package_names)} -U" def stylize_text(text: str, to_style: str, is_prerelease: bool) -> str: diff --git a/src/backend/base/langflow/api/health_check_router.py b/src/backend/base/langflow/api/health_check_router.py index 6f0a628a4..be8c0eb78 100644 --- a/src/backend/base/langflow/api/health_check_router.py +++ b/src/backend/base/langflow/api/health_check_router.py @@ -60,6 +60,5 @@ async def health_check( if response.has_error(): raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=response.model_dump()) - else: - response.status = "ok" - return response + response.status = "ok" + return response diff --git a/src/backend/base/langflow/api/utils.py b/src/backend/base/langflow/api/utils.py index 9a8380985..7ee577149 100644 --- a/src/backend/base/langflow/api/utils.py +++ b/src/backend/base/langflow/api/utils.py @@ -100,7 +100,7 @@ async def check_langflow_version(component: StoreComponentCreate): langflow_version = get_lf_version_from_pypi() if langflow_version is None: raise HTTPException(status_code=500, detail="Unable to verify the latest version of Langflow") - elif langflow_version != component.last_tested_version: + if langflow_version != component.last_tested_version: warnings.warn( f"Your version of Langflow ({component.last_tested_version}) is outdated. " f"Please update to the latest version ({langflow_version}) and try again." @@ -117,16 +117,15 @@ def format_elapsed_time(elapsed_time: float) -> str: if elapsed_time < 1: milliseconds = int(round(elapsed_time * 1000)) return f"{milliseconds} ms" - elif elapsed_time < 60: + if elapsed_time < 60: seconds = round(elapsed_time, 2) unit = "second" if seconds == 1 else "seconds" return f"{seconds} {unit}" - else: - minutes = int(elapsed_time // 60) - seconds = round(elapsed_time % 60, 2) - minutes_unit = "minute" if minutes == 1 else "minutes" - seconds_unit = "second" if seconds == 1 else "seconds" - return f"{minutes} {minutes_unit}, {seconds} {seconds_unit}" + minutes = int(elapsed_time // 60) + seconds = round(elapsed_time % 60, 2) + minutes_unit = "minute" if minutes == 1 else "minutes" + seconds_unit = "second" if seconds == 1 else "seconds" + return f"{minutes} {minutes_unit}, {seconds} {seconds_unit}" async def build_graph_from_data(flow_id: str, payload: dict, **kwargs): @@ -231,29 +230,27 @@ def get_suggestion_message(outdated_components: list[str]) -> str: count = len(outdated_components) if count == 0: return "The flow contains no outdated components." - elif count == 1: + if count == 1: return ( "The flow contains 1 outdated component. " f"We recommend updating the following component: {outdated_components[0]}." ) - else: - components = ", ".join(outdated_components) - return ( - f"The flow contains {count} outdated components. " - f"We recommend updating the following components: {components}." - ) + components = ", ".join(outdated_components) + return ( + f"The flow contains {count} outdated components. " + f"We recommend updating the following components: {components}." + ) def parse_value(value: Any, input_type: str) -> Any: """Helper function to parse the value based on input type.""" if value == "": return value - elif input_type == "IntInput": + if input_type == "IntInput": return int(value) if value is not None else None - elif input_type == "FloatInput": + if input_type == "FloatInput": return float(value) if value is not None else None - else: - return value + return value async def cascade_delete_flow(session: Session, flow: Flow): diff --git a/src/backend/base/langflow/api/v1/endpoints.py b/src/backend/base/langflow/api/v1/endpoints.py index ad323ada5..741977770 100644 --- a/src/backend/base/langflow/api/v1/endpoints.py +++ b/src/backend/base/langflow/api/v1/endpoints.py @@ -71,11 +71,10 @@ async def get_all( try: async with Lock() as lock: - all_types_dict = await get_and_cache_all_types_dict( + return await get_and_cache_all_types_dict( settings_service=settings_service, cache_service=cache_service, force_refresh=force_refresh, lock=lock ) - return all_types_dict except Exception as exc: logger.exception(exc) raise HTTPException(status_code=500, detail=str(exc)) from exc @@ -163,13 +162,12 @@ async def simple_run_flow_task( Run a flow task as a BackgroundTask, therefore it should not throw exceptions. """ try: - result = await simple_run_flow( + return await simple_run_flow( flow=flow, input_request=input_request, stream=stream, api_key_user=api_key_user, ) - return result except Exception as exc: logger.exception(f"Error running flow {flow.id} task: {exc}") @@ -279,9 +277,8 @@ async def simplified_run_flow( raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc if "not found" in str(exc): raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc - else: - logger.exception(exc) - raise APIException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=exc, flow=flow) from exc + logger.exception(exc) + raise APIException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, exception=exc, flow=flow) from exc except InvalidChatInputException as exc: logger.error(exc) raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(exc)) from exc @@ -486,12 +483,11 @@ async def experimental_run_flow( if f"Flow {flow_id_str} not found" in str(exc): logger.error(f"Flow {flow_id_str} not found") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc - elif f"Session {session_id} not found" in str(exc): + if f"Session {session_id} not found" in str(exc): logger.error(f"Session {session_id} not found") raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(exc)) from exc - else: - logger.exception(exc) - raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc + logger.exception(exc) + raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc except Exception as exc: logger.exception(exc) raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(exc)) from exc diff --git a/src/backend/base/langflow/api/v1/files.py b/src/backend/base/langflow/api/v1/files.py index e630a3d4d..26bc8a3fe 100644 --- a/src/backend/base/langflow/api/v1/files.py +++ b/src/backend/base/langflow/api/v1/files.py @@ -105,7 +105,7 @@ async def download_image(file_name: str, flow_id: UUID, storage_service: Storage if not content_type: raise HTTPException(status_code=500, detail=f"Content type not found for extension {extension}") - elif not content_type.startswith("image"): + if not content_type.startswith("image"): raise HTTPException(status_code=500, detail=f"Content type {content_type} is not an image") file_content = await storage_service.get_file(flow_id=flow_id_str, file_name=file_name) diff --git a/src/backend/base/langflow/api/v1/flows.py b/src/backend/base/langflow/api/v1/flows.py index 7998e3582..96b0f3a07 100644 --- a/src/backend/base/langflow/api/v1/flows.py +++ b/src/backend/base/langflow/api/v1/flows.py @@ -102,7 +102,7 @@ def create_flow( # If it is a validation error, return the error message if hasattr(e, "errors"): raise HTTPException(status_code=400, detail=str(e)) from e - elif "UNIQUE constraint failed" in str(e): + if "UNIQUE constraint failed" in str(e): # Get the name of the column that failed columns = str(e).split("UNIQUE constraint failed: ")[1].split(".")[1].split("\n")[0] # UNIQUE constraint failed: flow.user_id, flow.name @@ -113,10 +113,9 @@ def create_flow( raise HTTPException( status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique" ) from e - elif isinstance(e, HTTPException): + if isinstance(e, HTTPException): raise e - else: - raise HTTPException(status_code=500, detail=str(e)) from e + raise HTTPException(status_code=500, detail=str(e)) from e @router.get("/", response_model=list[FlowRead], status_code=200) @@ -198,8 +197,7 @@ def read_flow( ) # noqa if user_flow := session.exec(stmt).first(): return user_flow - else: - raise HTTPException(status_code=404, detail="Flow not found") + raise HTTPException(status_code=404, detail="Flow not found") @router.patch("/{flow_id}", response_model=FlowRead, status_code=200) @@ -242,7 +240,7 @@ def update_flow( # If it is a validation error, return the error message if hasattr(e, "errors"): raise HTTPException(status_code=400, detail=str(e)) from e - elif "UNIQUE constraint failed" in str(e): + if "UNIQUE constraint failed" in str(e): # Get the name of the column that failed columns = str(e).split("UNIQUE constraint failed: ")[1].split(".")[1].split("\n")[0] # UNIQUE constraint failed: flow.user_id, flow.name @@ -253,10 +251,9 @@ def update_flow( raise HTTPException( status_code=400, detail=f"{column.capitalize().replace('_', ' ')} must be unique" ) from e - elif isinstance(e, HTTPException): + if isinstance(e, HTTPException): raise e - else: - raise HTTPException(status_code=500, detail=str(e)) from e + raise HTTPException(status_code=500, detail=str(e)) from e @router.delete("/{flow_id}", status_code=200) @@ -402,5 +399,4 @@ async def download_multiple_file( media_type="application/x-zip-compressed", headers={"Content-Disposition": f"attachment; filename={filename}"}, ) - else: - return flows_without_api_keys[0] + return flows_without_api_keys[0] diff --git a/src/backend/base/langflow/api/v1/folders.py b/src/backend/base/langflow/api/v1/folders.py index fba2d54b4..c00c4ec5c 100644 --- a/src/backend/base/langflow/api/v1/folders.py +++ b/src/backend/base/langflow/api/v1/folders.py @@ -89,8 +89,7 @@ def read_folders( or_(Folder.user_id == current_user.id, Folder.user_id == None) # type: ignore # noqa: E711 ) ).all() - sorted_folders = sorted(folders, key=lambda x: x.name != DEFAULT_FOLDER_NAME) - return sorted_folders + return sorted(folders, key=lambda x: x.name != DEFAULT_FOLDER_NAME) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @@ -204,8 +203,7 @@ async def download_file( ): """Download all flows from folder.""" try: - folder = session.exec(select(Folder).where(Folder.id == folder_id, Folder.user_id == current_user.id)).first() - return folder + return session.exec(select(Folder).where(Folder.id == folder_id, Folder.user_id == current_user.id)).first() except Exception as e: if "No result found" in str(e): raise HTTPException(status_code=404, detail="Folder not found") diff --git a/src/backend/base/langflow/api/v1/login.py b/src/backend/base/langflow/api/v1/login.py index 156b29583..6eac5450e 100644 --- a/src/backend/base/langflow/api/v1/login.py +++ b/src/backend/base/langflow/api/v1/login.py @@ -71,12 +71,11 @@ async def login_to_get_access_token( # Create default folder for user if it doesn't exist create_default_folder_if_it_doesnt_exist(db, user.id) return tokens - else: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Incorrect username or password", - headers={"WWW-Authenticate": "Bearer"}, - ) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Incorrect username or password", + headers={"WWW-Authenticate": "Bearer"}, + ) @router.get("/auto_login") @@ -156,12 +155,11 @@ async def refresh_token( domain=auth_settings.COOKIE_DOMAIN, ) return tokens - else: - raise HTTPException( - status_code=status.HTTP_401_UNAUTHORIZED, - detail="Invalid refresh token", - headers={"WWW-Authenticate": "Bearer"}, - ) + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, + detail="Invalid refresh token", + headers={"WWW-Authenticate": "Bearer"}, + ) @router.post("/logout") diff --git a/src/backend/base/langflow/api/v1/schemas.py b/src/backend/base/langflow/api/v1/schemas.py index 5149205e1..76911dd8c 100644 --- a/src/backend/base/langflow/api/v1/schemas.py +++ b/src/backend/base/langflow/api/v1/schemas.py @@ -287,8 +287,7 @@ class VertexBuildResponse(BaseModel): @field_serializer("data") def serialize_data(self, data: ResultDataResponse) -> dict: data_dict = data.model_dump() if isinstance(data, BaseModel) else data - truncated_data = truncate_long_strings(data_dict) - return truncated_data + return truncate_long_strings(data_dict) class VerticesBuiltResponse(BaseModel): diff --git a/src/backend/base/langflow/api/v1/starter_projects.py b/src/backend/base/langflow/api/v1/starter_projects.py index aeb20a628..25e0a9340 100644 --- a/src/backend/base/langflow/api/v1/starter_projects.py +++ b/src/backend/base/langflow/api/v1/starter_projects.py @@ -17,8 +17,7 @@ def get_starter_projects( from langflow.initial_setup.load import get_starter_projects_dump try: - flows = get_starter_projects_dump() - return flows + return get_starter_projects_dump() except Exception as exc: logger.error(exc) raise HTTPException(status_code=500, detail=str(exc)) from exc diff --git a/src/backend/base/langflow/api/v1/store.py b/src/backend/base/langflow/api/v1/store.py index b652b2020..ffa7426d7 100644 --- a/src/backend/base/langflow/api/v1/store.py +++ b/src/backend/base/langflow/api/v1/store.py @@ -29,8 +29,7 @@ def get_user_store_api_key( if not user.store_api_key: raise HTTPException(status_code=400, detail="You must have a store API key set.") try: - decrypted = auth_utils.decrypt_api_key(user.store_api_key, settings_service) - return decrypted + return auth_utils.decrypt_api_key(user.store_api_key, settings_service) except Exception as e: raise HTTPException(status_code=500, detail="Failed to decrypt API key. Please set a new one.") from e @@ -42,8 +41,7 @@ def get_optional_user_store_api_key( if not user.store_api_key: return None try: - decrypted = auth_utils.decrypt_api_key(user.store_api_key, settings_service) - return decrypted + return auth_utils.decrypt_api_key(user.store_api_key, settings_service) except Exception as e: logger.error(f"Failed to decrypt API key: {e}") return user.store_api_key @@ -82,8 +80,7 @@ async def share_component( ): try: await check_langflow_version(component) - result = await store_service.upload(store_api_key, component) - return result + return await store_service.upload(store_api_key, component) except Exception as exc: raise HTTPException(status_code=400, detail=str(exc)) @@ -97,8 +94,7 @@ async def update_shared_component( ): try: await check_langflow_version(component) - result = await store_service.update(store_api_key, component_id, component) - return result + return await store_service.update(store_api_key, component_id, component) except Exception as exc: raise HTTPException(status_code=400, detail=str(exc)) diff --git a/src/backend/base/langflow/api/v1/users.py b/src/backend/base/langflow/api/v1/users.py index 56f8f443f..e1a1a4334 100644 --- a/src/backend/base/langflow/api/v1/users.py +++ b/src/backend/base/langflow/api/v1/users.py @@ -106,8 +106,7 @@ def patch_user( if not update_password: user_update.password = user_db.password return update_user(user_db, user_update, session) - else: - raise HTTPException(status_code=404, detail="User not found") + raise HTTPException(status_code=404, detail="User not found") @router.patch("/{user_id}/reset-password", response_model=UserRead) @@ -146,7 +145,7 @@ def delete_user( """ if current_user.id == user_id: raise HTTPException(status_code=400, detail="You can't delete your own user account") - elif not current_user.is_superuser: + if not current_user.is_superuser: raise HTTPException(status_code=403, detail="Permission denied") user_db = session.exec(select(User).where(User.id == user_id)).first() diff --git a/src/backend/base/langflow/base/agents/agent.py b/src/backend/base/langflow/base/agents/agent.py index 1f1861be3..3b47e8a3a 100644 --- a/src/backend/base/langflow/base/agents/agent.py +++ b/src/backend/base/langflow/base/agents/agent.py @@ -69,7 +69,7 @@ class LCAgentComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/chains/model.py b/src/backend/base/langflow/base/chains/model.py index a8143bd98..2f907450c 100644 --- a/src/backend/base/langflow/base/chains/model.py +++ b/src/backend/base/langflow/base/chains/model.py @@ -14,6 +14,6 @@ class LCChainComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/data/utils.py b/src/backend/base/langflow/base/data/utils.py index ea7fb896e..db6453475 100644 --- a/src/backend/base/langflow/base/data/utils.py +++ b/src/backend/base/langflow/base/data/utils.py @@ -71,9 +71,7 @@ def retrieve_file_paths( glob = "**/*" if recursive else "*" paths = walk_level(path_obj, depth) if depth else path_obj.glob(glob) - file_paths = [str(p) for p in paths if p.is_file() and match_types(p) and is_not_hidden(p)] - - return file_paths + return [str(p) for p in paths if p.is_file() and match_types(p) and is_not_hidden(p)] def partition_file_to_data(file_path: str, silent_errors: bool) -> Data | None: @@ -92,8 +90,7 @@ def partition_file_to_data(file_path: str, silent_errors: bool) -> Data | None: text = "\n\n".join([str(el) for el in elements]) metadata = elements.metadata if hasattr(elements, "metadata") else {} metadata["file_path"] = file_path - record = Data(text=text, data=metadata) - return record + return Data(text=text, data=metadata) def read_text_file(file_path: str) -> str: @@ -153,8 +150,7 @@ def parse_text_file_to_data(file_path: str, silent_errors: bool) -> Data | None: raise ValueError(msg) from e return None - record = Data(data={"file_path": file_path, "text": text}) - return record + return Data(data={"file_path": file_path, "text": text}) # ! Removing unstructured dependency until diff --git a/src/backend/base/langflow/base/embeddings/model.py b/src/backend/base/langflow/base/embeddings/model.py index ac9703378..cb16b170a 100644 --- a/src/backend/base/langflow/base/embeddings/model.py +++ b/src/backend/base/langflow/base/embeddings/model.py @@ -17,7 +17,7 @@ class LCEmbeddingsModel(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/langchain_utilities/model.py b/src/backend/base/langflow/base/langchain_utilities/model.py index 3ee750a26..ae14932a4 100644 --- a/src/backend/base/langflow/base/langchain_utilities/model.py +++ b/src/backend/base/langflow/base/langchain_utilities/model.py @@ -21,7 +21,7 @@ class LCToolComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/memory/model.py b/src/backend/base/langflow/base/memory/model.py index 8c9eef0e1..38e923af8 100644 --- a/src/backend/base/langflow/base/memory/model.py +++ b/src/backend/base/langflow/base/memory/model.py @@ -24,7 +24,7 @@ class LCChatMemoryComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/models/model.py b/src/backend/base/langflow/base/models/model.py index 674673d17..85e47a277 100644 --- a/src/backend/base/langflow/base/models/model.py +++ b/src/backend/base/langflow/base/models/model.py @@ -50,7 +50,7 @@ class LCModelComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) @@ -181,18 +181,17 @@ class LCModelComponent(Component): ) if stream: return runnable.stream(inputs) # type: ignore + message = runnable.invoke(inputs) # type: ignore + result = message.content if hasattr(message, "content") else message + if isinstance(message, AIMessage): + status_message = self.build_status_message(message) + self.status = status_message + elif isinstance(result, dict): + result = json.dumps(message, indent=4) + self.status = result else: - message = runnable.invoke(inputs) # type: ignore - result = message.content if hasattr(message, "content") else message - if isinstance(message, AIMessage): - status_message = self.build_status_message(message) - self.status = status_message - elif isinstance(result, dict): - result = json.dumps(message, indent=4) - self.status = result - else: - self.status = result - return result + self.status = result + return result except Exception as e: if message := self._get_exception_message(e): raise ValueError(message) from e diff --git a/src/backend/base/langflow/base/textsplitters/model.py b/src/backend/base/langflow/base/textsplitters/model.py index 481476d71..841e66494 100644 --- a/src/backend/base/langflow/base/textsplitters/model.py +++ b/src/backend/base/langflow/base/textsplitters/model.py @@ -16,7 +16,7 @@ class LCTextSplitterComponent(LCDocumentTransformerComponent): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) diff --git a/src/backend/base/langflow/base/tools/flow_tool.py b/src/backend/base/langflow/base/tools/flow_tool.py index 02707d89a..8eb598ccb 100644 --- a/src/backend/base/langflow/base/tools/flow_tool.py +++ b/src/backend/base/langflow/base/tools/flow_tool.py @@ -30,11 +30,10 @@ class FlowTool(BaseTool): """The tool's input schema.""" if self.args_schema is not None: return self.args_schema - elif self.graph is not None: + if self.graph is not None: return build_schema_from_inputs(self.name, get_flow_inputs(self.graph)) - else: - msg = "No input schema available." - raise ToolException(msg) + msg = "No input schema available." + raise ToolException(msg) def _run( self, @@ -88,8 +87,7 @@ class FlowTool(BaseTool): def build_tweaks_dict(self, args, kwargs): args_names = get_arg_names(self.inputs) kwargs = self.validate_inputs(args_names=args_names, args=args, kwargs=kwargs) - tweaks = {arg["component_name"]: kwargs[arg["arg_name"]] for arg in args_names} - return tweaks + return {arg["component_name"]: kwargs[arg["arg_name"]] for arg in args_names} async def _arun( self, diff --git a/src/backend/base/langflow/base/vectorstores/model.py b/src/backend/base/langflow/base/vectorstores/model.py index 047cab5f3..323575ca5 100644 --- a/src/backend/base/langflow/base/vectorstores/model.py +++ b/src/backend/base/langflow/base/vectorstores/model.py @@ -84,7 +84,7 @@ class LCVectorStoreComponent(Component): if method_name not in output_names: msg = f"Output with name '{method_name}' must be defined." raise ValueError(msg) - elif not hasattr(self, method_name): + if not hasattr(self, method_name): msg = f"Method '{method_name}' must be defined." raise ValueError(msg) @@ -139,9 +139,8 @@ class LCVectorStoreComponent(Component): if self.status is None: self.status = "Retriever built successfully." return retriever - else: - msg = f"Vector Store {vector_store.__class__.__name__} does not have an as_retriever method." - raise ValueError(msg) + msg = f"Vector Store {vector_store.__class__.__name__} does not have an as_retriever method." + raise ValueError(msg) def search_documents(self) -> list[Data]: """ diff --git a/src/backend/base/langflow/components/Notion/create_page.py b/src/backend/base/langflow/components/Notion/create_page.py index 0bea9826a..d1e3abf30 100644 --- a/src/backend/base/langflow/components/Notion/create_page.py +++ b/src/backend/base/langflow/components/Notion/create_page.py @@ -45,12 +45,11 @@ class NotionPageCreator(LCToolComponent): if isinstance(result, str): # An error occurred, return it as text return Data(text=result) - else: - # Success, return the created page data - output = "Created page properties:\n" - for prop_name, prop_value in result.get("properties", {}).items(): - output += f"{prop_name}: {prop_value}\n" - return Data(text=output, data=result) + # Success, return the created page data + output = "Created page properties:\n" + for prop_name, prop_value in result.get("properties", {}).items(): + output += f"{prop_name}: {prop_value}\n" + return Data(text=output, data=result) def build_tool(self) -> Tool: return StructuredTool.from_function( @@ -84,8 +83,7 @@ class NotionPageCreator(LCToolComponent): try: response = requests.post("https://api.notion.com/v1/pages", headers=headers, json=data) response.raise_for_status() - result = response.json() - return result + return response.json() except requests.exceptions.RequestException as e: error_message = f"Failed to create Notion page. Error: {str(e)}" if hasattr(e, "response") and e.response is not None: diff --git a/src/backend/base/langflow/components/Notion/list_database_properties.py b/src/backend/base/langflow/components/Notion/list_database_properties.py index e615f58f7..393760bbe 100644 --- a/src/backend/base/langflow/components/Notion/list_database_properties.py +++ b/src/backend/base/langflow/components/Notion/list_database_properties.py @@ -36,9 +36,8 @@ class NotionDatabaseProperties(LCToolComponent): if isinstance(result, str): # An error occurred, return it as text return Data(text=result) - else: - # Success, return the properties - return Data(text=str(result), data=result) + # Success, return the properties + return Data(text=str(result), data=result) def build_tool(self) -> Tool: return StructuredTool.from_function( @@ -58,8 +57,7 @@ class NotionDatabaseProperties(LCToolComponent): response = requests.get(url, headers=headers) response.raise_for_status() data = response.json() - properties = data.get("properties", {}) - return properties + return data.get("properties", {}) except requests.exceptions.RequestException as e: return f"Error fetching Notion database properties: {str(e)}" except ValueError as e: diff --git a/src/backend/base/langflow/components/Notion/page_content_viewer.py b/src/backend/base/langflow/components/Notion/page_content_viewer.py index 231de4433..7ab1813bb 100644 --- a/src/backend/base/langflow/components/Notion/page_content_viewer.py +++ b/src/backend/base/langflow/components/Notion/page_content_viewer.py @@ -36,9 +36,8 @@ class NotionPageContent(LCToolComponent): if isinstance(result, str) and result.startswith("Error:"): # An error occurred, return it as text return Data(text=result) - else: - # Success, return the content - return Data(text=result, data={"content": result}) + # Success, return the content + return Data(text=result, data={"content": result}) def build_tool(self) -> Tool: return StructuredTool.from_function( diff --git a/src/backend/base/langflow/components/Notion/update_page_property.py b/src/backend/base/langflow/components/Notion/update_page_property.py index dab129481..76c07a717 100644 --- a/src/backend/base/langflow/components/Notion/update_page_property.py +++ b/src/backend/base/langflow/components/Notion/update_page_property.py @@ -48,12 +48,11 @@ class NotionPageUpdate(LCToolComponent): if isinstance(result, str): # An error occurred, return it as text return Data(text=result) - else: - # Success, return the updated page data - output = "Updated page properties:\n" - for prop_name, prop_value in result.get("properties", {}).items(): - output += f"{prop_name}: {prop_value}\n" - return Data(text=output, data=result) + # Success, return the updated page data + output = "Updated page properties:\n" + for prop_name, prop_value in result.get("properties", {}).items(): + output += f"{prop_name}: {prop_value}\n" + return Data(text=output, data=result) def build_tool(self) -> Tool: return StructuredTool.from_function( diff --git a/src/backend/base/langflow/components/agents/HierarchicalCrew.py b/src/backend/base/langflow/components/agents/HierarchicalCrew.py index a69a12554..ebaf9680e 100644 --- a/src/backend/base/langflow/components/agents/HierarchicalCrew.py +++ b/src/backend/base/langflow/components/agents/HierarchicalCrew.py @@ -21,7 +21,7 @@ class HierarchicalCrewComponent(BaseCrewComponent): def build_crew(self) -> Crew: tasks, agents = self.get_tasks_and_agents() - crew = Crew( + return Crew( agents=agents, tasks=tasks, process=Process.hierarchical, @@ -36,4 +36,3 @@ class HierarchicalCrewComponent(BaseCrewComponent): step_callback=self.get_step_callback(), task_callback=self.get_task_callback(), ) - return crew diff --git a/src/backend/base/langflow/components/agents/SequentialCrew.py b/src/backend/base/langflow/components/agents/SequentialCrew.py index 858be7e82..df3643337 100644 --- a/src/backend/base/langflow/components/agents/SequentialCrew.py +++ b/src/backend/base/langflow/components/agents/SequentialCrew.py @@ -20,7 +20,7 @@ class SequentialCrewComponent(BaseCrewComponent): def build_crew(self) -> Message: tasks, agents = self.get_tasks_and_agents() - crew = Crew( + return Crew( agents=agents, tasks=tasks, process=Process.sequential, @@ -33,4 +33,3 @@ class SequentialCrewComponent(BaseCrewComponent): step_callback=self.get_step_callback(), task_callback=self.get_task_callback(), ) - return crew diff --git a/src/backend/base/langflow/components/astra_assistants/create_assistant.py b/src/backend/base/langflow/components/astra_assistants/create_assistant.py index af3fb3fb2..67a3eb6b8 100644 --- a/src/backend/base/langflow/components/astra_assistants/create_assistant.py +++ b/src/backend/base/langflow/components/astra_assistants/create_assistant.py @@ -53,5 +53,4 @@ class AssistantsCreateAssistant(Component): instructions=self.instructions, model=self.model, ) - message = Message(text=assistant.id) - return message + return Message(text=assistant.id) diff --git a/src/backend/base/langflow/components/astra_assistants/create_thread.py b/src/backend/base/langflow/components/astra_assistants/create_thread.py index 3049f290a..a869c5622 100644 --- a/src/backend/base/langflow/components/astra_assistants/create_thread.py +++ b/src/backend/base/langflow/components/astra_assistants/create_thread.py @@ -28,5 +28,4 @@ class AssistantsCreateThread(Component): thread = self.client.beta.threads.create() thread_id = thread.id - message = Message(text=thread_id) - return message + return Message(text=thread_id) diff --git a/src/backend/base/langflow/components/astra_assistants/get_assistant.py b/src/backend/base/langflow/components/astra_assistants/get_assistant.py index e4d00a891..04d00cfe2 100644 --- a/src/backend/base/langflow/components/astra_assistants/get_assistant.py +++ b/src/backend/base/langflow/components/astra_assistants/get_assistant.py @@ -33,5 +33,4 @@ class AssistantsGetAssistantName(Component): assistant = self.client.beta.assistants.retrieve( assistant_id=self.assistant_id, ) - message = Message(text=assistant.name) - return message + return Message(text=assistant.name) diff --git a/src/backend/base/langflow/components/astra_assistants/getenvvar.py b/src/backend/base/langflow/components/astra_assistants/getenvvar.py index 1a9d001ee..c6c517aeb 100644 --- a/src/backend/base/langflow/components/astra_assistants/getenvvar.py +++ b/src/backend/base/langflow/components/astra_assistants/getenvvar.py @@ -27,6 +27,4 @@ class GetEnvVar(Component): if self.env_var_name not in os.environ: msg = f"Environment variable {self.env_var_name} not set" raise Exception(msg) - else: - message = Message(text=os.environ[self.env_var_name]) - return message + return Message(text=os.environ[self.env_var_name]) diff --git a/src/backend/base/langflow/components/astra_assistants/list_assistants.py b/src/backend/base/langflow/components/astra_assistants/list_assistants.py index 998f6a8ee..70b040c66 100644 --- a/src/backend/base/langflow/components/astra_assistants/list_assistants.py +++ b/src/backend/base/langflow/components/astra_assistants/list_assistants.py @@ -18,8 +18,7 @@ class AssistantsListAssistants(Component): def process_inputs(self) -> Message: assistants = self.client.beta.assistants.list().data id_list = [assistant.id for assistant in assistants] - message = Message( + return Message( # get text from list text="\n".join(id_list) ) - return message diff --git a/src/backend/base/langflow/components/astra_assistants/run.py b/src/backend/base/langflow/components/astra_assistants/run.py index ce11a9699..ebb184568 100644 --- a/src/backend/base/langflow/components/astra_assistants/run.py +++ b/src/backend/base/langflow/components/astra_assistants/run.py @@ -88,8 +88,7 @@ class AssistantsRun(Component): for part in stream.text_deltas: text += part print(part) - message = Message(text=text) - return message + return Message(text=text) except Exception as e: print(e) msg = f"Error running assistant: {e}" diff --git a/src/backend/base/langflow/components/data/Gmail.py b/src/backend/base/langflow/components/data/Gmail.py index 803b38562..eaf5c16bb 100644 --- a/src/backend/base/langflow/components/data/Gmail.py +++ b/src/backend/base/langflow/components/data/Gmail.py @@ -84,9 +84,7 @@ class GmailLoaderComponent(Component): message = re.sub(r"\s{2,}", " ", message) # Trim leading and trailing whitespace - message = message.strip() - - return message + return message.strip() def _extract_email_content(self, msg: Any) -> HumanMessage: from_email = None @@ -109,11 +107,10 @@ class GmailLoaderComponent(Component): data = base64.urlsafe_b64decode(data).decode("utf-8") pattern = re.compile(r"\r\nOn .+(\r\n)*wrote:\r\n") newest_response = re.split(pattern, data)[0] - message = HumanMessage( + return HumanMessage( content=self.clean_message_content(newest_response), additional_kwargs={"sender": from_email}, ) - return message msg = "No plain text part found in the email." raise ValueError(msg) @@ -147,8 +144,7 @@ class GmailLoaderComponent(Component): raise ValueError(msg) starter_content = self._extract_email_content(response_email) return ChatSession(messages=[starter_content, message_content]) - else: - return ChatSession(messages=[message_content]) + return ChatSession(messages=[message_content]) def lazy_load(self) -> Iterator[ChatSession]: service = build("gmail", "v1", credentials=self.creds) diff --git a/src/backend/base/langflow/components/data/GoogleDrive.py b/src/backend/base/langflow/components/data/GoogleDrive.py index 39d05eec8..3e4d50306 100644 --- a/src/backend/base/langflow/components/data/GoogleDrive.py +++ b/src/backend/base/langflow/components/data/GoogleDrive.py @@ -43,9 +43,8 @@ class GoogleDriveComponent(Component): """Load credentials from the provided creds attribute or fallback to the original method.""" if self.creds: return self.creds - else: - msg = "No credentials provided." - raise ValueError(msg) + msg = "No credentials provided." + raise ValueError(msg) class Config: arbitrary_types_allowed = True diff --git a/src/backend/base/langflow/components/data/GoogleDriveSearch.py b/src/backend/base/langflow/components/data/GoogleDriveSearch.py index 4e34a58cf..8fdba225b 100644 --- a/src/backend/base/langflow/components/data/GoogleDriveSearch.py +++ b/src/backend/base/langflow/components/data/GoogleDriveSearch.py @@ -98,16 +98,15 @@ class GoogleDriveSearchComponent(Component): """ if mime_type == "application/vnd.google-apps.document": return f"https://docs.google.com/document/d/{file_id}/edit" - elif mime_type == "application/vnd.google-apps.spreadsheet": + if mime_type == "application/vnd.google-apps.spreadsheet": return f"https://docs.google.com/spreadsheets/d/{file_id}/edit" - elif mime_type == "application/vnd.google-apps.presentation": + if mime_type == "application/vnd.google-apps.presentation": return f"https://docs.google.com/presentation/d/{file_id}/edit" - elif mime_type == "application/vnd.google-apps.drawing": + if mime_type == "application/vnd.google-apps.drawing": return f"https://docs.google.com/drawings/d/{file_id}/edit" - elif mime_type == "application/pdf": - return f"https://drive.google.com/file/d/{file_id}/view?usp=drivesdk" - else: + if mime_type == "application/pdf": return f"https://drive.google.com/file/d/{file_id}/view?usp=drivesdk" + return f"https://drive.google.com/file/d/{file_id}/view?usp=drivesdk" def search_files(self) -> dict: # Load the token information from the JSON string diff --git a/src/backend/base/langflow/components/deactivated/SelectivePassThrough.py b/src/backend/base/langflow/components/deactivated/SelectivePassThrough.py index 4a3341895..f63395b5a 100644 --- a/src/backend/base/langflow/components/deactivated/SelectivePassThrough.py +++ b/src/backend/base/langflow/components/deactivated/SelectivePassThrough.py @@ -51,13 +51,13 @@ class SelectivePassThroughComponent(Component): if operator == "equals": return input_value == comparison_value - elif operator == "not equals": + if operator == "not equals": return input_value != comparison_value - elif operator == "contains": + if operator == "contains": return comparison_value in input_value - elif operator == "starts with": + if operator == "starts with": return input_value.startswith(comparison_value) - elif operator == "ends with": + if operator == "ends with": return input_value.endswith(comparison_value) return False @@ -71,6 +71,5 @@ class SelectivePassThroughComponent(Component): if self.evaluate_condition(input_value, comparison_value, operator, case_sensitive): self.status = value_to_pass return value_to_pass - else: - self.status = "" - return "" + self.status = "" + return "" diff --git a/src/backend/base/langflow/components/documentloaders/AssemblyAIGetSubtitles.py b/src/backend/base/langflow/components/documentloaders/AssemblyAIGetSubtitles.py index 73f053b0b..19436e9e2 100644 --- a/src/backend/base/langflow/components/documentloaders/AssemblyAIGetSubtitles.py +++ b/src/backend/base/langflow/components/documentloaders/AssemblyAIGetSubtitles.py @@ -75,6 +75,5 @@ class AssemblyAIGetSubtitles(Component): self.status = result return result - else: - self.status = transcript.error - return Data(data={"error": transcript.error}) + self.status = transcript.error + return Data(data={"error": transcript.error}) diff --git a/src/backend/base/langflow/components/documentloaders/AssemblyAILeMUR.py b/src/backend/base/langflow/components/documentloaders/AssemblyAILeMUR.py index 4bfed6733..97068cf79 100644 --- a/src/backend/base/langflow/components/documentloaders/AssemblyAILeMUR.py +++ b/src/backend/base/langflow/components/documentloaders/AssemblyAILeMUR.py @@ -90,14 +90,14 @@ class AssemblyAILeMUR(Component): error = "Either a Transcription Result or Transcript IDs must be provided" self.status = error return Data(data={"error": error}) - elif self.transcription_result and self.transcription_result.data.get("error"): + if self.transcription_result and self.transcription_result.data.get("error"): # error message from the previous step self.status = self.transcription_result.data["error"] return self.transcription_result - elif self.endpoint == "task" and not self.prompt: + if self.endpoint == "task" and not self.prompt: self.status = "No prompt specified for the task endpoint" return Data(data={"error": "No prompt specified"}) - elif self.endpoint == "question-answer" and not self.questions: + if self.endpoint == "question-answer" and not self.questions: error = "No Questions were provided for the question-answer endpoint" self.status = error return Data(data={"error": error}) @@ -172,12 +172,11 @@ class AssemblyAILeMUR(Component): def get_final_model(self, model_name: str) -> aai.LemurModel: if model_name == "claude3_5_sonnet": return aai.LemurModel.claude3_5_sonnet - elif model_name == "claude3_opus": + if model_name == "claude3_opus": return aai.LemurModel.claude3_opus - elif model_name == "claude3_haiku": + if model_name == "claude3_haiku": return aai.LemurModel.claude3_haiku - elif model_name == "claude3_sonnet": + if model_name == "claude3_sonnet": return aai.LemurModel.claude3_sonnet - else: - msg = f"Model name not supported: {model_name}" - raise ValueError(msg) + msg = f"Model name not supported: {model_name}" + raise ValueError(msg) diff --git a/src/backend/base/langflow/components/documentloaders/AssemblyAIPollTranscript.py b/src/backend/base/langflow/components/documentloaders/AssemblyAIPollTranscript.py index 3b97d628f..fd4360b8d 100644 --- a/src/backend/base/langflow/components/documentloaders/AssemblyAIPollTranscript.py +++ b/src/backend/base/langflow/components/documentloaders/AssemblyAIPollTranscript.py @@ -62,6 +62,5 @@ class AssemblyAITranscriptionJobPoller(Component): data = Data(data=sorted_data) self.status = data return data - else: - self.status = transcript.error - return Data(data={"error": transcript.error}) + self.status = transcript.error + return Data(data={"error": transcript.error}) diff --git a/src/backend/base/langflow/components/documentloaders/AssemblyAIStartTranscript.py b/src/backend/base/langflow/components/documentloaders/AssemblyAIStartTranscript.py index 8ba0dce57..f474f5c58 100644 --- a/src/backend/base/langflow/components/documentloaders/AssemblyAIStartTranscript.py +++ b/src/backend/base/langflow/components/documentloaders/AssemblyAIStartTranscript.py @@ -177,10 +177,9 @@ class AssemblyAITranscriptionJobCreator(Component): if transcript.error: self.status = transcript.error return Data(data={"error": transcript.error}) - else: - result = Data(data={"transcript_id": transcript.id}) - self.status = result - return result + result = Data(data={"transcript_id": transcript.id}) + self.status = result + return result except Exception as e: self.status = f"An error occurred: {str(e)}" return Data(data={"error": f"An error occurred: {str(e)}"}) diff --git a/src/backend/base/langflow/components/documentloaders/Confluence.py b/src/backend/base/langflow/components/documentloaders/Confluence.py index a24d44676..418bfe0ad 100644 --- a/src/backend/base/langflow/components/documentloaders/Confluence.py +++ b/src/backend/base/langflow/components/documentloaders/Confluence.py @@ -66,7 +66,7 @@ class ConfluenceComponent(Component): def build_confluence(self) -> ConfluenceLoader: content_format = ContentFormat(self.content_format) - loader = ConfluenceLoader( + return ConfluenceLoader( url=self.url, username=self.username, api_key=self.api_key, @@ -75,7 +75,6 @@ class ConfluenceComponent(Component): content_format=content_format, max_pages=self.max_pages, ) - return loader def load_documents(self) -> list[Data]: confluence = self.build_confluence() diff --git a/src/backend/base/langflow/components/documentloaders/GitLoader.py b/src/backend/base/langflow/components/documentloaders/GitLoader.py index 1218b1b97..e2aaa6008 100644 --- a/src/backend/base/langflow/components/documentloaders/GitLoader.py +++ b/src/backend/base/langflow/components/documentloaders/GitLoader.py @@ -100,13 +100,12 @@ class GitLoaderComponent(Component): return False return all(f(path) for f in file_filters) - loader = GitLoader( + return GitLoader( repo_path=self.repo_path, clone_url=self.clone_url, branch=self.branch, file_filter=combined_filter, ) - return loader def load_documents(self) -> list[Data]: gitloader = self.build_gitloader() diff --git a/src/backend/base/langflow/components/documentloaders/Unstructured.py b/src/backend/base/langflow/components/documentloaders/Unstructured.py index 02081e0f1..e55cbf2d2 100644 --- a/src/backend/base/langflow/components/documentloaders/Unstructured.py +++ b/src/backend/base/langflow/components/documentloaders/Unstructured.py @@ -37,14 +37,12 @@ class UnstructuredComponent(Component): def build_unstructured(self) -> UnstructuredLoader: file_paths = [self.file] - loader = UnstructuredLoader( + return UnstructuredLoader( file_paths, api_key=self.api_key, partition_via_api=True, ) - return loader - def load_documents(self) -> list[Data]: unstructured = self.build_unstructured() diff --git a/src/backend/base/langflow/components/embeddings/AmazonBedrockEmbeddings.py b/src/backend/base/langflow/components/embeddings/AmazonBedrockEmbeddings.py index 299073510..45e52f01d 100644 --- a/src/backend/base/langflow/components/embeddings/AmazonBedrockEmbeddings.py +++ b/src/backend/base/langflow/components/embeddings/AmazonBedrockEmbeddings.py @@ -59,11 +59,10 @@ class AmazonBedrockEmbeddingsComponent(LCModelComponent): client_params["region_name"] = self.region_name boto3_client = session.client("bedrock-runtime", **client_params) - output = BedrockEmbeddings( + return BedrockEmbeddings( credentials_profile_name=self.credentials_profile_name, client=boto3_client, model_id=self.model_id, endpoint_url=self.endpoint_url, region_name=self.region_name, ) # type: ignore - return output diff --git a/src/backend/base/langflow/components/embeddings/HuggingFaceInferenceAPIEmbeddings.py b/src/backend/base/langflow/components/embeddings/HuggingFaceInferenceAPIEmbeddings.py index ccc7bec68..05419e4d5 100644 --- a/src/backend/base/langflow/components/embeddings/HuggingFaceInferenceAPIEmbeddings.py +++ b/src/backend/base/langflow/components/embeddings/HuggingFaceInferenceAPIEmbeddings.py @@ -71,8 +71,7 @@ class HuggingFaceInferenceAPIEmbeddingsComponent(LCEmbeddingsModel): def get_api_url(self) -> str: if "huggingface" in self.inference_endpoint.lower(): return f"{self.inference_endpoint}{self.model_name}" - else: - return self.inference_endpoint + return self.inference_endpoint @retry(stop=stop_after_attempt(3), wait=wait_fixed(2)) def create_huggingface_embeddings( diff --git a/src/backend/base/langflow/components/embeddings/util/AIMLEmbeddingsImpl.py b/src/backend/base/langflow/components/embeddings/util/AIMLEmbeddingsImpl.py index ef77c2835..6dfcdddd9 100644 --- a/src/backend/base/langflow/components/embeddings/util/AIMLEmbeddingsImpl.py +++ b/src/backend/base/langflow/components/embeddings/util/AIMLEmbeddingsImpl.py @@ -54,8 +54,7 @@ class AIMLEmbeddingsImpl(BaseModel, Embeddings): json=payload, ) response.raise_for_status() - result_data = response.json() - return result_data + return response.json() def embed_query(self, text: str) -> list[float]: return self.embed_documents([text])[0] diff --git a/src/backend/base/langflow/components/helpers/ParseJSONData.py b/src/backend/base/langflow/components/helpers/ParseJSONData.py index f6cf2ec64..ecb97e094 100644 --- a/src/backend/base/langflow/components/helpers/ParseJSONData.py +++ b/src/backend/base/langflow/components/helpers/ParseJSONData.py @@ -71,5 +71,4 @@ class ParseJSONDataComponent(Component): results = jq.compile(self.query).input_text(full_filter_str).all() print("results: ", results) - docs = [Data(data=value) if isinstance(value, dict) else Data(text=str(value)) for value in results] - return docs + return [Data(data=value) if isinstance(value, dict) else Data(text=str(value)) for value in results] diff --git a/src/backend/base/langflow/components/inputs/TextInput.py b/src/backend/base/langflow/components/inputs/TextInput.py index 43a2a0b36..6a2c5cb6c 100644 --- a/src/backend/base/langflow/components/inputs/TextInput.py +++ b/src/backend/base/langflow/components/inputs/TextInput.py @@ -21,7 +21,6 @@ class TextInputComponent(TextComponent): ] def text_response(self) -> Message: - message = Message( + return Message( text=self.input_value, ) - return message diff --git a/src/backend/base/langflow/components/langchain_utilities/FirecrawlCrawlApi.py b/src/backend/base/langflow/components/langchain_utilities/FirecrawlCrawlApi.py index 3c7344d8d..870321914 100644 --- a/src/backend/base/langflow/components/langchain_utilities/FirecrawlCrawlApi.py +++ b/src/backend/base/langflow/components/langchain_utilities/FirecrawlCrawlApi.py @@ -86,5 +86,4 @@ class FirecrawlCrawlApi(CustomComponent): idempotency_key, ) - records = Data(data={"results": crawl_result}) - return records + return Data(data={"results": crawl_result}) diff --git a/src/backend/base/langflow/components/langchain_utilities/FirecrawlScrapeApi.py b/src/backend/base/langflow/components/langchain_utilities/FirecrawlScrapeApi.py index 47de85fdd..48572d3e7 100644 --- a/src/backend/base/langflow/components/langchain_utilities/FirecrawlScrapeApi.py +++ b/src/backend/base/langflow/components/langchain_utilities/FirecrawlScrapeApi.py @@ -74,5 +74,4 @@ class FirecrawlScrapeApi(CustomComponent): }, ) - record = Data(data=results) - return record + return Data(data=results) diff --git a/src/backend/base/langflow/components/memories/AstraDBChatMemory.py b/src/backend/base/langflow/components/memories/AstraDBChatMemory.py index ab1544e39..ae524c6aa 100644 --- a/src/backend/base/langflow/components/memories/AstraDBChatMemory.py +++ b/src/backend/base/langflow/components/memories/AstraDBChatMemory.py @@ -59,7 +59,7 @@ class AstraDBChatMemory(LCChatMemoryComponent): ) raise ImportError(msg) - memory = AstraDBChatMessageHistory( + return AstraDBChatMessageHistory( session_id=self.session_id, collection_name=self.collection_name, token=self.token, @@ -67,4 +67,3 @@ class AstraDBChatMemory(LCChatMemoryComponent): namespace=self.namespace or None, environment=parse_api_endpoint(self.api_endpoint).environment, ) - return memory diff --git a/src/backend/base/langflow/components/models/AIMLModel.py b/src/backend/base/langflow/components/models/AIMLModel.py index 0d8894828..57a7ec886 100644 --- a/src/backend/base/langflow/components/models/AIMLModel.py +++ b/src/backend/base/langflow/components/models/AIMLModel.py @@ -84,7 +84,7 @@ class AIMLModelComponent(LCModelComponent): else: openai_api_key = aiml_api_key - model = ChatOpenAI( + return ChatOpenAI( model=model_name, temperature=temperature, api_key=openai_api_key, @@ -94,8 +94,6 @@ class AIMLModelComponent(LCModelComponent): **model_kwargs, ) - return model # type: ignore - def _get_exception_message(self, e: Exception): """ Get a message from an OpenAI exception. diff --git a/src/backend/base/langflow/components/models/CohereModel.py b/src/backend/base/langflow/components/models/CohereModel.py index 3861ca400..1dd761bf2 100644 --- a/src/backend/base/langflow/components/models/CohereModel.py +++ b/src/backend/base/langflow/components/models/CohereModel.py @@ -41,9 +41,7 @@ class CohereComponent(LCModelComponent): else: api_key = None - output = ChatCohere( + return ChatCohere( temperature=temperature or 0.75, cohere_api_key=api_key, ) - - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py b/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py index 02b5b839e..be5357b10 100644 --- a/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py +++ b/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py @@ -74,7 +74,7 @@ class GoogleGenerativeAIComponent(LCModelComponent): top_p = self.top_p n = self.n - output = ChatGoogleGenerativeAI( # type: ignore + return ChatGoogleGenerativeAI( # type: ignore model=model, max_output_tokens=max_output_tokens or None, temperature=temperature, @@ -83,5 +83,3 @@ class GoogleGenerativeAIComponent(LCModelComponent): n=n or 1, google_api_key=SecretStr(google_api_key), ) - - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/GroqModel.py b/src/backend/base/langflow/components/models/GroqModel.py index 59439c321..8770a9a10 100644 --- a/src/backend/base/langflow/components/models/GroqModel.py +++ b/src/backend/base/langflow/components/models/GroqModel.py @@ -93,7 +93,7 @@ class GroqModel(LCModelComponent): n = self.n stream = self.stream - output = ChatGroq( # type: ignore + return ChatGroq( # type: ignore model=model_name, max_tokens=max_tokens or None, temperature=temperature, @@ -102,5 +102,3 @@ class GroqModel(LCModelComponent): api_key=SecretStr(groq_api_key), streaming=stream, ) - - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/HuggingFaceModel.py b/src/backend/base/langflow/components/models/HuggingFaceModel.py index 44a9b642c..0fa037eed 100644 --- a/src/backend/base/langflow/components/models/HuggingFaceModel.py +++ b/src/backend/base/langflow/components/models/HuggingFaceModel.py @@ -51,8 +51,7 @@ class HuggingFaceEndpointsComponent(LCModelComponent): def get_api_url(self) -> str: if "huggingface" in self.inference_endpoint.lower(): return f"{self.inference_endpoint}{self.model_id}" - else: - return self.inference_endpoint + return self.inference_endpoint def create_huggingface_endpoint( self, diff --git a/src/backend/base/langflow/components/models/Maritalk.py b/src/backend/base/langflow/components/models/Maritalk.py index c11f1efbd..5e6dd9e38 100644 --- a/src/backend/base/langflow/components/models/Maritalk.py +++ b/src/backend/base/langflow/components/models/Maritalk.py @@ -51,10 +51,9 @@ class MaritalkModelComponent(LCModelComponent): model_name: str = self.model_name max_tokens = self.max_tokens - output = ChatMaritalk( + return ChatMaritalk( max_tokens=max_tokens, model=model_name, api_key=api_key, temperature=temperature or 0.1, ) - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/MistralModel.py b/src/backend/base/langflow/components/models/MistralModel.py index b92510883..ed9661c39 100644 --- a/src/backend/base/langflow/components/models/MistralModel.py +++ b/src/backend/base/langflow/components/models/MistralModel.py @@ -83,7 +83,7 @@ class MistralAIModelComponent(LCModelComponent): else: api_key = None - output = ChatMistralAI( + return ChatMistralAI( max_tokens=max_tokens or None, model_name=model_name, endpoint=mistral_api_base, @@ -96,5 +96,3 @@ class MistralAIModelComponent(LCModelComponent): random_seed=random_seed, safe_mode=safe_mode, ) - - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/NvidiaModel.py b/src/backend/base/langflow/components/models/NvidiaModel.py index 7a5387c32..c2c58d7ec 100644 --- a/src/backend/base/langflow/components/models/NvidiaModel.py +++ b/src/backend/base/langflow/components/models/NvidiaModel.py @@ -80,7 +80,7 @@ class NVIDIAModelComponent(LCModelComponent): model_name: str = self.model_name max_tokens = self.max_tokens seed = self.seed - output = ChatNVIDIA( + return ChatNVIDIA( max_tokens=max_tokens or None, model=model_name, base_url=self.base_url, @@ -88,4 +88,3 @@ class NVIDIAModelComponent(LCModelComponent): temperature=temperature or 0.1, seed=seed, ) - return output # type: ignore diff --git a/src/backend/base/langflow/components/models/OllamaModel.py b/src/backend/base/langflow/components/models/OllamaModel.py index 8b5dddb61..dede3ba7e 100644 --- a/src/backend/base/langflow/components/models/OllamaModel.py +++ b/src/backend/base/langflow/components/models/OllamaModel.py @@ -64,8 +64,7 @@ class ChatOllamaComponent(LCModelComponent): response.raise_for_status() data = response.json() - model_names = [model["name"] for model in data.get("models", [])] - return model_names + return [model["name"] for model in data.get("models", [])] except Exception as e: msg = "Could not retrieve models. Please, make sure Ollama is running." raise ValueError(msg) from e diff --git a/src/backend/base/langflow/components/models/OpenAIModel.py b/src/backend/base/langflow/components/models/OpenAIModel.py index 4a583d391..9edabf7e7 100644 --- a/src/backend/base/langflow/components/models/OpenAIModel.py +++ b/src/backend/base/langflow/components/models/OpenAIModel.py @@ -137,9 +137,9 @@ class OpenAIModelComponent(LCModelComponent): try: from openai import BadRequestError except ImportError: - return + return None if isinstance(e, BadRequestError): message = e.body.get("message") # type: ignore if message: return message - return + return None diff --git a/src/backend/base/langflow/components/models/PerplexityModel.py b/src/backend/base/langflow/components/models/PerplexityModel.py index cd6aab495..dabb671d0 100644 --- a/src/backend/base/langflow/components/models/PerplexityModel.py +++ b/src/backend/base/langflow/components/models/PerplexityModel.py @@ -79,7 +79,7 @@ class PerplexityComponent(LCModelComponent): top_p = self.top_p n = self.n - output = ChatPerplexity( + return ChatPerplexity( model=model, temperature=temperature or 0.75, pplx_api_key=api_key, @@ -88,5 +88,3 @@ class PerplexityComponent(LCModelComponent): n=n or 1, max_output_tokens=max_output_tokens, ) - - return output # type: ignore diff --git a/src/backend/base/langflow/components/prompts/LangChainHubPrompt.py b/src/backend/base/langflow/components/prompts/LangChainHubPrompt.py index dc2265a62..a4c4c6d5a 100644 --- a/src/backend/base/langflow/components/prompts/LangChainHubPrompt.py +++ b/src/backend/base/langflow/components/prompts/LangChainHubPrompt.py @@ -114,6 +114,4 @@ class LangChainHubPromptComponent(Component): raise ValueError(msg) # Pull the prompt from LangChain Hub - prompt_data = langchain.hub.pull(self.langchain_hub_prompt, api_key=self.langchain_api_key) - - return prompt_data + return langchain.hub.pull(self.langchain_hub_prompt, api_key=self.langchain_api_key) diff --git a/src/backend/base/langflow/components/prototypes/ConditionalRouter.py b/src/backend/base/langflow/components/prototypes/ConditionalRouter.py index 133a84867..2cf2d5aa2 100644 --- a/src/backend/base/langflow/components/prototypes/ConditionalRouter.py +++ b/src/backend/base/langflow/components/prototypes/ConditionalRouter.py @@ -54,13 +54,13 @@ class ConditionalRouterComponent(Component): if operator == "equals": return input_text == match_text - elif operator == "not equals": + if operator == "not equals": return input_text != match_text - elif operator == "contains": + if operator == "contains": return match_text in input_text - elif operator == "starts with": + if operator == "starts with": return input_text.startswith(match_text) - elif operator == "ends with": + if operator == "ends with": return input_text.endswith(match_text) return False @@ -69,15 +69,13 @@ class ConditionalRouterComponent(Component): if result: self.status = self.message return self.message - else: - self.stop("true_result") - return None # type: ignore + self.stop("true_result") + return None # type: ignore def false_response(self) -> Message: result = self.evaluate_condition(self.input_text, self.match_text, self.operator, self.case_sensitive) if not result: self.status = self.message return self.message - else: - self.stop("false_result") - return None # type: ignore + self.stop("false_result") + return None # type: ignore diff --git a/src/backend/base/langflow/components/prototypes/PythonFunction.py b/src/backend/base/langflow/components/prototypes/PythonFunction.py index cf37e39ce..4944ed928 100644 --- a/src/backend/base/langflow/components/prototypes/PythonFunction.py +++ b/src/backend/base/langflow/components/prototypes/PythonFunction.py @@ -43,8 +43,7 @@ class PythonFunctionComponent(Component): def get_function_callable(self) -> Callable: function_code = self.function_code self.status = function_code - func = get_function(function_code) - return func + return get_function(function_code) def execute_function(self) -> list[dotdict | str] | dotdict | str: function_code = self.function_code @@ -61,13 +60,11 @@ class PythonFunctionComponent(Component): def execute_function_data(self) -> list[Data]: results = self.execute_function() results = results if isinstance(results, list) else [results] - data = [(Data(text=x) if isinstance(x, str) else Data(**x)) for x in results] - return data + return [(Data(text=x) if isinstance(x, str) else Data(**x)) for x in results] def execute_function_message(self) -> Message: results = self.execute_function() results = results if isinstance(results, list) else [results] results_list = [str(x) for x in results] results_str = "\n".join(results_list) - data = Message(text=results_str) - return data + return Message(text=results_str) diff --git a/src/backend/base/langflow/components/prototypes/RunnableExecutor.py b/src/backend/base/langflow/components/prototypes/RunnableExecutor.py index db94363c9..4f50b0ffb 100644 --- a/src/backend/base/langflow/components/prototypes/RunnableExecutor.py +++ b/src/backend/base/langflow/components/prototypes/RunnableExecutor.py @@ -123,8 +123,7 @@ class RunnableExecComponent(Component): if self.use_stream: return self.astream_events(input_dict) - else: - result = await self.runnable.ainvoke(input_dict) + result = await self.runnable.ainvoke(input_dict) result_value, _status = self.get_output(result, self.input_key, self.output_key) status += _status status += f"\n\nOutput: {result_value}\n\nRaw Output: {result}" diff --git a/src/backend/base/langflow/components/retrievers/MultiQueryRetriever.py b/src/backend/base/langflow/components/retrievers/MultiQueryRetriever.py index 27fcd1796..5baa50025 100644 --- a/src/backend/base/langflow/components/retrievers/MultiQueryRetriever.py +++ b/src/backend/base/langflow/components/retrievers/MultiQueryRetriever.py @@ -45,8 +45,5 @@ class MultiQueryRetrieverComponent(CustomComponent): ) -> MultiQueryRetriever: if not prompt: return MultiQueryRetriever.from_llm(llm=llm, retriever=retriever, parser_key=parser_key) - else: - prompt_template = PromptTemplate.from_template(prompt) - return MultiQueryRetriever.from_llm( - llm=llm, retriever=retriever, prompt=prompt_template, parser_key=parser_key - ) + prompt_template = PromptTemplate.from_template(prompt) + return MultiQueryRetriever.from_llm(llm=llm, retriever=retriever, prompt=prompt_template, parser_key=parser_key) diff --git a/src/backend/base/langflow/components/toolkits/ComposioAPI.py b/src/backend/base/langflow/components/toolkits/ComposioAPI.py index 3c619761d..53084f21b 100644 --- a/src/backend/base/langflow/components/toolkits/ComposioAPI.py +++ b/src/backend/base/langflow/components/toolkits/ComposioAPI.py @@ -84,8 +84,7 @@ class ComposioAPIComponent(LCToolComponent): auth_schemes = toolset.client.apps.get(app).auth_schemes if auth_schemes[0].auth_mode == "API_KEY": return self._process_api_key_auth(entity, app) - else: - return self._initiate_default_connection(entity, app) + return self._initiate_default_connection(entity, app) except Exception as exc: logger.error(f"Authorization error: {str(exc)}") return "Error" @@ -108,18 +107,16 @@ class ComposioAPIComponent(LCToolComponent): if is_different_app or is_url or is_default_api_key_message: return "Enter API Key" - else: - if not is_default_api_key_message: - entity.initiate_connection( - app_name=app, - auth_mode="API_KEY", - auth_config={"api_key": self.auth_status_config}, - use_composio_auth=False, - force_new_integration=True, - ) - return f"{app} CONNECTED" - else: - return "Enter API Key" + if not is_default_api_key_message: + entity.initiate_connection( + app_name=app, + auth_mode="API_KEY", + auth_config={"api_key": self.auth_status_config}, + use_composio_auth=False, + force_new_integration=True, + ) + return f"{app} CONNECTED" + return "Enter API Key" def _initiate_default_connection(self, entity: Any, app: str) -> str: connection = entity.initiate_connection(app_name=app, use_composio_auth=True, force_new_integration=True) @@ -169,8 +166,7 @@ class ComposioAPIComponent(LCToolComponent): def build_tool(self) -> Sequence[Tool]: composio_toolset = self._build_wrapper() - composio_tools = composio_toolset.get_tools(actions=self.action_names) - return composio_tools + return composio_toolset.get_tools(actions=self.action_names) def _build_wrapper(self) -> ComposioToolSet: return ComposioToolSet(api_key=self.api_key) diff --git a/src/backend/base/langflow/components/tools/Calculator.py b/src/backend/base/langflow/components/tools/Calculator.py index a85907d31..d309c2e6b 100644 --- a/src/backend/base/langflow/components/tools/Calculator.py +++ b/src/backend/base/langflow/components/tools/Calculator.py @@ -52,12 +52,11 @@ class CalculatorToolComponent(LCToolComponent): def eval_expr(node): if isinstance(node, ast.Num): return node.n - elif isinstance(node, ast.BinOp): + if isinstance(node, ast.BinOp): return operators[type(node.op)](eval_expr(node.left), eval_expr(node.right)) - elif isinstance(node, ast.UnaryOp): + if isinstance(node, ast.UnaryOp): return operators[type(node.op)](eval_expr(node.operand)) - else: - raise TypeError(node) + raise TypeError(node) # Parse the expression and evaluate it tree = ast.parse(expression, mode="eval") diff --git a/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py b/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py index bd2af5176..db01d408b 100644 --- a/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py +++ b/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py @@ -200,14 +200,13 @@ class PythonCodeStructuredTool(LCToolComponent): if schema_fields: PythonCodeToolSchema = create_model("PythonCodeToolSchema", **schema_fields) # type: ignore - tool = StructuredTool.from_function( + return StructuredTool.from_function( func=_local[self.tool_function].run, args_schema=PythonCodeToolSchema, name=self.tool_name, description=self.tool_description, return_direct=self.return_direct, ) - return tool # type: ignore def post_code_processing(self, new_frontend_node: dict, current_frontend_node: dict): """ diff --git a/src/backend/base/langflow/components/tools/SearXNGTool.py b/src/backend/base/langflow/components/tools/SearXNGTool.py index 789a3fa98..a55daaec5 100644 --- a/src/backend/base/langflow/components/tools/SearXNGTool.py +++ b/src/backend/base/langflow/components/tools/SearXNGTool.py @@ -132,11 +132,10 @@ class SearXNGToolComponent(LCToolComponent): SearxSearchSchema = create_model("SearxSearchSchema", **schema_fields) # type: ignore - tool = StructuredTool.from_function( + return StructuredTool.from_function( func=_local["SearxSearch"].search, args_schema=SearxSearchSchema, name="searxng_search_tool", description="A tool that searches for tools using SearXNG.\nThe available categories are: " + ", ".join(self.categories), ) - return tool diff --git a/src/backend/base/langflow/components/vectorstores/AstraDB.py b/src/backend/base/langflow/components/vectorstores/AstraDB.py index 23f37027b..641d8e066 100644 --- a/src/backend/base/langflow/components/vectorstores/AstraDB.py +++ b/src/backend/base/langflow/components/vectorstores/AstraDB.py @@ -454,10 +454,9 @@ class AstraVectorStoreComponent(LCVectorStoreComponent): def _map_search_type(self): if self.search_type == "Similarity with score threshold": return "similarity_score_threshold" - elif self.search_type == "MMR (Max Marginal Relevance)": + if self.search_type == "MMR (Max Marginal Relevance)": return "mmr" - else: - return "similarity" + return "similarity" def _build_search_args(self): args = { @@ -495,9 +494,8 @@ class AstraVectorStoreComponent(LCVectorStoreComponent): logger.debug(f"Converted documents to data: {len(data)}") self.status = data return data - else: - logger.debug("No search input provided. Skipping search.") - return [] + logger.debug("No search input provided. Skipping search.") + return [] def get_retriever_kwargs(self): search_args = self._build_search_args() diff --git a/src/backend/base/langflow/components/vectorstores/Cassandra.py b/src/backend/base/langflow/components/vectorstores/Cassandra.py index f1519927a..253566b6d 100644 --- a/src/backend/base/langflow/components/vectorstores/Cassandra.py +++ b/src/backend/base/langflow/components/vectorstores/Cassandra.py @@ -212,10 +212,9 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent): def _map_search_type(self): if self.search_type == "Similarity with score threshold": return "similarity_score_threshold" - elif self.search_type == "MMR (Max Marginal Relevance)": + if self.search_type == "MMR (Max Marginal Relevance)": return "mmr" - else: - return "similarity" + return "similarity" def search_documents(self) -> list[Data]: vector_store = self.build_vector_store() @@ -239,16 +238,14 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent): "Your collection does not contain a field name 'content'." ) raise ValueError(msg) - else: - raise e + raise e logger.debug(f"Retrieved documents: {len(docs)}") data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] def _build_search_args(self): args = { diff --git a/src/backend/base/langflow/components/vectorstores/CassandraGraph.py b/src/backend/base/langflow/components/vectorstores/CassandraGraph.py index 1aa3b99ee..054105c74 100644 --- a/src/backend/base/langflow/components/vectorstores/CassandraGraph.py +++ b/src/backend/base/langflow/components/vectorstores/CassandraGraph.py @@ -187,14 +187,13 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent): def _map_search_type(self): if self.search_type == "Similarity": return "similarity" - elif self.search_type == "Similarity with score threshold": + if self.search_type == "Similarity with score threshold": return "similarity_score_threshold" - elif self.search_type == "MMR (Max Marginal Relevance)": + if self.search_type == "MMR (Max Marginal Relevance)": return "mmr" - elif self.search_type == "MMR Traversal": + if self.search_type == "MMR Traversal": return "mmr_traversal" - else: - return "traversal" + return "traversal" def search_documents(self) -> list[Data]: vector_store = self.build_vector_store() @@ -218,16 +217,14 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent): "Your collection does not contain a field name 'content'." ) raise ValueError(msg) from e - else: - raise e + raise e logger.debug(f"Retrieved documents: {len(docs)}") data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] def _build_search_args(self): args = { diff --git a/src/backend/base/langflow/components/vectorstores/Clickhouse.py b/src/backend/base/langflow/components/vectorstores/Clickhouse.py index 1dd08bc37..73fe77240 100644 --- a/src/backend/base/langflow/components/vectorstores/Clickhouse.py +++ b/src/backend/base/langflow/components/vectorstores/Clickhouse.py @@ -131,5 +131,4 @@ class ClickhouseVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Couchbase.py b/src/backend/base/langflow/components/vectorstores/Couchbase.py index 423589605..6ef111bde 100644 --- a/src/backend/base/langflow/components/vectorstores/Couchbase.py +++ b/src/backend/base/langflow/components/vectorstores/Couchbase.py @@ -103,5 +103,4 @@ class CouchbaseVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/FAISS.py b/src/backend/base/langflow/components/vectorstores/FAISS.py index f971508fe..73c11001c 100644 --- a/src/backend/base/langflow/components/vectorstores/FAISS.py +++ b/src/backend/base/langflow/components/vectorstores/FAISS.py @@ -114,6 +114,5 @@ class FaissVectorStoreComponent(LCVectorStoreComponent): logger.debug(f"Converted documents to data: {len(data)}") logger.debug(data) return data # Return the search results data - else: - logger.debug("No search input provided. Skipping search.") - return [] + logger.debug("No search input provided. Skipping search.") + return [] diff --git a/src/backend/base/langflow/components/vectorstores/HCD.py b/src/backend/base/langflow/components/vectorstores/HCD.py index 429b770e9..9a9eb083e 100644 --- a/src/backend/base/langflow/components/vectorstores/HCD.py +++ b/src/backend/base/langflow/components/vectorstores/HCD.py @@ -275,10 +275,9 @@ class HCDVectorStoreComponent(LCVectorStoreComponent): def _map_search_type(self): if self.search_type == "Similarity with score threshold": return "similarity_score_threshold" - elif self.search_type == "MMR (Max Marginal Relevance)": + if self.search_type == "MMR (Max Marginal Relevance)": return "mmr" - else: - return "similarity" + return "similarity" def _build_search_args(self): args = { @@ -315,9 +314,8 @@ class HCDVectorStoreComponent(LCVectorStoreComponent): logger.debug(f"Converted documents to data: {len(data)}") self.status = data return data - else: - logger.debug("No search input provided. Skipping search.") - return [] + logger.debug("No search input provided. Skipping search.") + return [] def get_retriever_kwargs(self): search_args = self._build_search_args() diff --git a/src/backend/base/langflow/components/vectorstores/Milvus.py b/src/backend/base/langflow/components/vectorstores/Milvus.py index 11e86db57..c55293fe3 100644 --- a/src/backend/base/langflow/components/vectorstores/Milvus.py +++ b/src/backend/base/langflow/components/vectorstores/Milvus.py @@ -119,5 +119,4 @@ class MilvusVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/MongoDBAtlasVector.py b/src/backend/base/langflow/components/vectorstores/MongoDBAtlasVector.py index 23004db1a..31fb620f5 100644 --- a/src/backend/base/langflow/components/vectorstores/MongoDBAtlasVector.py +++ b/src/backend/base/langflow/components/vectorstores/MongoDBAtlasVector.py @@ -93,5 +93,4 @@ class MongoVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Pinecone.py b/src/backend/base/langflow/components/vectorstores/Pinecone.py index 783141388..fd7ed81f3 100644 --- a/src/backend/base/langflow/components/vectorstores/Pinecone.py +++ b/src/backend/base/langflow/components/vectorstores/Pinecone.py @@ -95,5 +95,4 @@ class PineconeVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Qdrant.py b/src/backend/base/langflow/components/vectorstores/Qdrant.py index ea5221624..84e6f941f 100644 --- a/src/backend/base/langflow/components/vectorstores/Qdrant.py +++ b/src/backend/base/langflow/components/vectorstores/Qdrant.py @@ -110,5 +110,4 @@ class QdrantVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Redis.py b/src/backend/base/langflow/components/vectorstores/Redis.py index 2e346719b..66927e33a 100644 --- a/src/backend/base/langflow/components/vectorstores/Redis.py +++ b/src/backend/base/langflow/components/vectorstores/Redis.py @@ -90,5 +90,4 @@ class RedisVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/SupabaseVectorStore.py b/src/backend/base/langflow/components/vectorstores/SupabaseVectorStore.py index 9c9545baa..b5da646a6 100644 --- a/src/backend/base/langflow/components/vectorstores/SupabaseVectorStore.py +++ b/src/backend/base/langflow/components/vectorstores/SupabaseVectorStore.py @@ -76,5 +76,4 @@ class SupabaseVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Upstash.py b/src/backend/base/langflow/components/vectorstores/Upstash.py index eb1e6039e..49001a808 100644 --- a/src/backend/base/langflow/components/vectorstores/Upstash.py +++ b/src/backend/base/langflow/components/vectorstores/Upstash.py @@ -125,5 +125,4 @@ class UpstashVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Vectara.py b/src/backend/base/langflow/components/vectorstores/Vectara.py index 63ea038cb..de256cecd 100644 --- a/src/backend/base/langflow/components/vectorstores/Vectara.py +++ b/src/backend/base/langflow/components/vectorstores/Vectara.py @@ -106,6 +106,5 @@ class VectaraVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = f"Found {len(data)} results for the query: {self.search_query}" return data - else: - self.status = "No search query provided" - return [] + self.status = "No search query provided" + return [] diff --git a/src/backend/base/langflow/components/vectorstores/Weaviate.py b/src/backend/base/langflow/components/vectorstores/Weaviate.py index 2349484d9..ef01bc444 100644 --- a/src/backend/base/langflow/components/vectorstores/Weaviate.py +++ b/src/backend/base/langflow/components/vectorstores/Weaviate.py @@ -89,5 +89,4 @@ class WeaviateVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/components/vectorstores/pgvector.py b/src/backend/base/langflow/components/vectorstores/pgvector.py index f8b4d47a9..cb3c8838c 100644 --- a/src/backend/base/langflow/components/vectorstores/pgvector.py +++ b/src/backend/base/langflow/components/vectorstores/pgvector.py @@ -73,5 +73,4 @@ class PGVectorStoreComponent(LCVectorStoreComponent): data = docs_to_data(docs) self.status = data return data - else: - return [] + return [] diff --git a/src/backend/base/langflow/custom/attributes.py b/src/backend/base/langflow/custom/attributes.py index f05d8c58c..9235f0966 100644 --- a/src/backend/base/langflow/custom/attributes.py +++ b/src/backend/base/langflow/custom/attributes.py @@ -10,7 +10,7 @@ def validate_icon(value: str, *args, **kwargs): if not value.startswith(":") and not value.endswith(":"): return value - elif not value.startswith(":") or not value.endswith(":"): + if not value.startswith(":") or not value.endswith(":"): # emoji should have both starting and ending colons # so if one of them is missing, we will raise msg = f"Invalid emoji. {value} is not a valid emoji." @@ -30,6 +30,7 @@ def getattr_return_str(value): def getattr_return_bool(value): if isinstance(value, bool): return value + return None def getattr_return_list_of_str(value): diff --git a/src/backend/base/langflow/custom/code_parser/code_parser.py b/src/backend/base/langflow/custom/code_parser/code_parser.py index f5f7e59b4..7d41bcbc5 100644 --- a/src/backend/base/langflow/custom/code_parser/code_parser.py +++ b/src/backend/base/langflow/custom/code_parser/code_parser.py @@ -218,8 +218,7 @@ class CodeParser: defaults = missing_defaults + default_values - args = [self.parse_arg(arg, default) for arg, default in zip(node.args.args, defaults)] - return args + return [self.parse_arg(arg, default) for arg, default in zip(node.args.args, defaults)] def parse_varargs(self, node: ast.FunctionDef) -> list[dict[str, Any]]: """ @@ -240,8 +239,7 @@ class CodeParser: ast.unparse(default) if default else None for default in node.args.kw_defaults ] - args = [self.parse_arg(arg, default) for arg, default in zip(node.args.kwonlyargs, kw_defaults)] - return args + return [self.parse_arg(arg, default) for arg, default in zip(node.args.kwonlyargs, kw_defaults)] def parse_kwargs(self, node: ast.FunctionDef) -> list[dict[str, Any]]: """ @@ -268,20 +266,19 @@ class CodeParser: def has_return(node): if isinstance(node, ast.Return): return True - elif isinstance(node, ast.If): + if isinstance(node, ast.If): return any(has_return(child) for child in node.body) or any(has_return(child) for child in node.orelse) - elif isinstance(node, ast.Try): + if isinstance(node, ast.Try): return ( any(has_return(child) for child in node.body) or any(has_return(child) for child in node.handlers) or any(has_return(child) for child in node.finalbody) ) - elif isinstance(node, ast.For | ast.While): + if isinstance(node, ast.For | ast.While): return any(has_return(child) for child in node.body) or any(has_return(child) for child in node.orelse) - elif isinstance(node, ast.With): + if isinstance(node, ast.With): return any(has_return(child) for child in node.body) - else: - return False + return False return any(has_return(child) for child in node.body) @@ -293,6 +290,7 @@ class CodeParser: for target in stmt.targets: if isinstance(target, ast.Name): return {"name": target.id, "value": ast.unparse(stmt.value)} + return None def parse_ann_assign(self, stmt): """ @@ -305,6 +303,7 @@ class CodeParser: "value": ast.unparse(stmt.value) if stmt.value else None, "annotation": ast.unparse(stmt.annotation), } + return None def parse_function_def(self, stmt): """ diff --git a/src/backend/base/langflow/custom/custom_component/base_component.py b/src/backend/base/langflow/custom/custom_component/base_component.py index 1eb8e9663..4be0f706b 100644 --- a/src/backend/base/langflow/custom/custom_component/base_component.py +++ b/src/backend/base/langflow/custom/custom_component/base_component.py @@ -98,8 +98,7 @@ class BaseComponent: cc_class = eval_custom_component_code(self._code) component_instance = cc_class(_code=self._code) - template_config = self.get_template_config(component_instance) - return template_config + return self.get_template_config(component_instance) def build(self, *args: Any, **kwargs: Any) -> Any: raise NotImplementedError diff --git a/src/backend/base/langflow/custom/custom_component/component.py b/src/backend/base/langflow/custom/custom_component/component.py index fa670774c..ac6bf8154 100644 --- a/src/backend/base/langflow/custom/custom_component/component.py +++ b/src/backend/base/langflow/custom/custom_component/component.py @@ -318,18 +318,16 @@ class Component(CustomComponent): def _inherits_from_component(self, method: Callable): # check if the method is a method from a class that inherits from Component # and that it is an output of that class - inherits_from_component = hasattr(method, "__self__") and isinstance(method.__self__, Component) - return inherits_from_component + return hasattr(method, "__self__") and isinstance(method.__self__, Component) def _method_is_valid_output(self, method: Callable): # check if the method is a method from a class that inherits from Component # and that it is an output of that class - method_is_output = ( + return ( hasattr(method, "__self__") and isinstance(method.__self__, Component) and method.__self__.get_output_by_method(method) ) - return method_is_output def _build_error_string_from_matching_pairs(self, matching_pairs: list[tuple[Output, Input]]): text = "" @@ -558,7 +556,7 @@ class Component(CustomComponent): frontend_node.validate_component() frontend_node.set_base_classes_from_outputs() - data = { + return { "data": { "node": frontend_node.to_dict(keep_name=False), "type": self.name or self.__class__.__name__, @@ -566,7 +564,6 @@ class Component(CustomComponent): }, "id": self._id, } - return data def _validate_inputs(self, params: dict): # Params keys are the `name` attribute of the Input objects @@ -732,8 +729,7 @@ class Component(CustomComponent): self.inputs = self.template_config.get("inputs", []) if not self.inputs: return {} - build_config = {_input.name: _input.model_dump(by_alias=True, exclude_none=True) for _input in self.inputs} - return build_config + return {_input.name: _input.model_dump(by_alias=True, exclude_none=True) for _input in self.inputs} def _get_field_order(self): try: diff --git a/src/backend/base/langflow/custom/custom_component/custom_component.py b/src/backend/base/langflow/custom/custom_component/custom_component.py index b3ff427f8..b7611997a 100644 --- a/src/backend/base/langflow/custom/custom_component/custom_component.py +++ b/src/backend/base/langflow/custom/custom_component/custom_component.py @@ -531,10 +531,9 @@ class CustomComponent(BaseComponent): """ This function is called after the code validation is done. """ - frontend_node = update_frontend_node_with_template_values( + return update_frontend_node_with_template_values( frontend_node=new_frontend_node, raw_frontend_node=current_frontend_node ) - return frontend_node def get_langchain_callbacks(self) -> list[BaseCallbackHandler]: if self._tracing_service: diff --git a/src/backend/base/langflow/custom/directory_reader/directory_reader.py b/src/backend/base/langflow/custom/directory_reader/directory_reader.py index 55061c915..fe7bdb140 100644 --- a/src/backend/base/langflow/custom/directory_reader/directory_reader.py +++ b/src/backend/base/langflow/custom/directory_reader/directory_reader.py @@ -222,21 +222,20 @@ class DirectoryReader: if file_content is None: return False, f"Could not read {file_path}" - elif self.is_empty_file(file_content): + if self.is_empty_file(file_content): return False, "Empty file" - elif not self.validate_code(file_content): + if not self.validate_code(file_content): return False, "Syntax error" - elif self._is_type_hint_used_in_args("Optional", file_content) and not self._is_type_hint_imported( + if self._is_type_hint_used_in_args("Optional", file_content) and not self._is_type_hint_imported( "Optional", file_content ): return ( False, "Type hint 'Optional' is used but not imported in the code.", ) - else: - if self.compress_code_field: - file_content = str(StringCompressor(file_content).compress_string()) - return True, file_content + if self.compress_code_field: + file_content = str(StringCompressor(file_content).compress_string()) + return True, file_content def build_component_menu_list(self, file_paths): """ @@ -300,21 +299,20 @@ class DirectoryReader: if file_content is None: return False, f"Could not read {file_path}" - elif self.is_empty_file(file_content): + if self.is_empty_file(file_content): return False, "Empty file" - elif not self.validate_code(file_content): + if not self.validate_code(file_content): return False, "Syntax error" - elif self._is_type_hint_used_in_args("Optional", file_content) and not self._is_type_hint_imported( + if self._is_type_hint_used_in_args("Optional", file_content) and not self._is_type_hint_imported( "Optional", file_content ): return ( False, "Type hint 'Optional' is used but not imported in the code.", ) - else: - if self.compress_code_field: - file_content = str(StringCompressor(file_content).compress_string()) - return True, file_content + if self.compress_code_field: + file_content = str(StringCompressor(file_content).compress_string()) + return True, file_content async def get_output_types_from_code_async(self, code: str): return await asyncio.to_thread(self.get_output_types_from_code, code) diff --git a/src/backend/base/langflow/custom/utils.py b/src/backend/base/langflow/custom/utils.py index 67133f024..83945f1be 100644 --- a/src/backend/base/langflow/custom/utils.py +++ b/src/backend/base/langflow/custom/utils.py @@ -256,9 +256,8 @@ def run_build_inputs( ): """Run the build inputs of a custom component.""" try: - field_config = custom_component.build_inputs(user_id=user_id) + return custom_component.build_inputs(user_id=user_id) # add_extra_fields(frontend_node, field_config, field_config.values()) - return field_config except Exception as exc: logger.error(f"Error running build inputs: {exc}") raise HTTPException(status_code=500, detail=str(exc)) from exc @@ -269,7 +268,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI if custom_component._code is None: msg = "Code is None" raise ValueError(msg) - elif isinstance(custom_component._code, str): + if isinstance(custom_component._code, str): custom_class = eval_custom_component_code(custom_component._code) else: msg = "Invalid code type" @@ -285,8 +284,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI ) from exc try: - custom_instance = custom_class(_user_id=user_id, _code=custom_component._code) - return custom_instance + return custom_class(_user_id=user_id, _code=custom_component._code) except Exception as exc: logger.error(f"Error while instantiating custom component: {str(exc)}") if hasattr(exc, "detail") and "traceback" in exc.detail: @@ -305,7 +303,7 @@ def run_build_config( if custom_component._code is None: msg = "Code is None" raise ValueError(msg) - elif isinstance(custom_component._code, str): + if isinstance(custom_component._code, str): custom_class = eval_custom_component_code(custom_component._code) else: msg = "Invalid code type" diff --git a/src/backend/base/langflow/exceptions/api.py b/src/backend/base/langflow/exceptions/api.py index 178cbdeb7..eab4e95ed 100644 --- a/src/backend/base/langflow/exceptions/api.py +++ b/src/backend/base/langflow/exceptions/api.py @@ -31,5 +31,4 @@ class APIException(HTTPException): outdated_components = get_outdated_components(flow) if outdated_components: body["suggestion"] = get_suggestion_message(outdated_components) - excep = ExceptionBody(**body) - return excep + return ExceptionBody(**body) diff --git a/src/backend/base/langflow/field_typing/__init__.py b/src/backend/base/langflow/field_typing/__init__.py index f98d4dcee..543043f77 100644 --- a/src/backend/base/langflow/field_typing/__init__.py +++ b/src/backend/base/langflow/field_typing/__init__.py @@ -48,7 +48,7 @@ def __getattr__(name: str) -> Any: if name == "Input": return _import_input_class() return RangeSpec - elif name == "Output": + if name == "Output": return _import_output_class() # The other names should work as if they were imported from constants # Import the constants module langflow.field_typing.constants diff --git a/src/backend/base/langflow/graph/edge/base.py b/src/backend/base/langflow/graph/edge/base.py index d09a5691f..20b24816f 100644 --- a/src/backend/base/langflow/graph/edge/base.py +++ b/src/backend/base/langflow/graph/edge/base.py @@ -35,14 +35,12 @@ class Edge: "might not be a valid input." ) raise ValueError(msg) from e - else: - msg = ( - f"Field '{self._target_handle['fieldName']}' on {target.display_name} " - "might not be a valid input." - ) - raise ValueError(msg) from e - else: - raise e + msg = ( + f"Field '{self._target_handle['fieldName']}' on {target.display_name} " + "might not be a valid input." + ) + raise ValueError(msg) from e + raise e else: msg = "Target handle is not a dictionary" diff --git a/src/backend/base/langflow/graph/graph/ascii.py b/src/backend/base/langflow/graph/graph/ascii.py index 5444c87ef..d1fcdb131 100644 --- a/src/backend/base/langflow/graph/graph/ascii.py +++ b/src/backend/base/langflow/graph/graph/ascii.py @@ -181,5 +181,5 @@ def draw_graph(vertexes, edges, return_ascii=True): canvas.text(int(round(x - minx)) + 1, int(round(y - miny)) + 1, vertex.data) if return_ascii: return canvas.draws() - else: - canvas.draw() + canvas.draw() + return None diff --git a/src/backend/base/langflow/graph/graph/base.py b/src/backend/base/langflow/graph/graph/base.py index c5828959d..e0078c352 100644 --- a/src/backend/base/langflow/graph/graph/base.py +++ b/src/backend/base/langflow/graph/graph/base.py @@ -616,7 +616,7 @@ class Graph: continue # If the input_type is not any and the input_type is not in the vertex id # Example: input_type = "chat" and vertex.id = "OpenAI-19ddn" - elif input_type is not None and input_type != "any" and input_type not in vertex.id.lower(): + if input_type is not None and input_type != "any" and input_type not in vertex.id.lower(): continue if vertex is None: msg = f"Vertex {vertex_id} not found" @@ -650,7 +650,7 @@ class Graph: if input_components and not isinstance(input_components, list): msg = f"Invalid components value: {input_components}. Expected list" raise ValueError(msg) - elif input_components is None: + if input_components is None: input_components = [] if not isinstance(inputs.get(INPUT_FIELD_NAME, ""), str): @@ -1386,10 +1386,9 @@ class Graph: msg = f"No result found for vertex {vertex_id}" raise ValueError(msg) - vertex_build_result = VertexBuildResult( + return VertexBuildResult( result_dict=result_dict, params=params, valid=valid, artifacts=artifacts, vertex=vertex ) - return vertex_build_result except Exception as exc: if not isinstance(exc, ComponentBuildException): logger.exception(f"Error building Component: \n\n{exc}") @@ -1510,7 +1509,7 @@ class Graph: for t in tasks[i + 1 :]: t.cancel() raise result - elif isinstance(result, tuple) and len(result) == 5: + if isinstance(result, tuple) and len(result) == 5: vertices.append(result[4]) else: msg = f"Invalid result from task {task_name}: {result}" @@ -1527,8 +1526,7 @@ class Graph: for v in vertices: next_runnable_vertices = await self.get_next_runnable_vertices(lock, vertex=v, cache=False) results.extend(next_runnable_vertices) - no_duplicate_results = list(set(results)) - return no_duplicate_results + return list(set(results)) def topological_sort(self) -> list[Vertex]: """ @@ -1677,11 +1675,11 @@ class Graph: node_name = node_id.split("-")[0] if node_name in InterfaceComponentTypes: return InterfaceVertex - elif node_name in ["SharedState", "Notify", "Listen"]: + if node_name in ["SharedState", "Notify", "Listen"]: return StateVertex - elif node_base_type in lazy_load_vertex_dict.VERTEX_TYPE_MAP: + if node_base_type in lazy_load_vertex_dict.VERTEX_TYPE_MAP: return lazy_load_vertex_dict.VERTEX_TYPE_MAP[node_base_type] - elif node_name in lazy_load_vertex_dict.VERTEX_TYPE_MAP: + if node_name in lazy_load_vertex_dict.VERTEX_TYPE_MAP: return lazy_load_vertex_dict.VERTEX_TYPE_MAP[node_name] if node_type in lazy_load_vertex_dict.VERTEX_TYPE_MAP: @@ -1823,8 +1821,7 @@ class Graph: queue.append(predecessor) current_layer += 1 # Next layer - new_layers = self.refine_layers(layers) - return new_layers + return self.refine_layers(layers) def refine_layers(self, initial_layers): # Map each vertex to its current layer @@ -1860,9 +1857,7 @@ class Graph: refined_layers[layer_index].append(vertex_id) # Remove empty layers if any - refined_layers = [layer for layer in refined_layers if layer] - - return refined_layers + return [layer for layer in refined_layers if layer] def sort_chat_inputs_first(self, vertices_layers: list[list[str]]) -> list[list[str]]: chat_inputs_first = [] @@ -1875,9 +1870,7 @@ class Graph: if not chat_inputs_first: return vertices_layers - vertices_layers = [chat_inputs_first] + vertices_layers - - return vertices_layers + return [chat_inputs_first] + vertices_layers def sort_layer_by_dependency(self, vertices_layers: list[list[str]]) -> list[list[str]]: """Sorts the vertices in each layer by dependency, ensuring no vertex depends on a subsequent vertex.""" @@ -1894,9 +1887,7 @@ class Graph: # Build a map of each vertex to its index in the layer for quick lookup. index_map = {vertex: index for index, vertex in enumerate(layer)} # Create a sorted copy of the layer based on dependency order. - sorted_layer = sorted(layer, key=lambda vertex: self._max_dependency_index(vertex, index_map), reverse=True) - - return sorted_layer + return sorted(layer, key=lambda vertex: self._max_dependency_index(vertex, index_map), reverse=True) def _max_dependency_index(self, vertex_id: str, index_map: dict[str, int]) -> int: """Finds the highest index a given vertex's dependencies occupy in the same layer.""" @@ -1969,14 +1960,13 @@ class Graph: return any(component.value in vertex for component in InterfaceComponentTypes) # Sort each inner list so that vertices containing ChatInput or ChatOutput come first - sorted_vertices = [ + return [ sorted( inner_list, key=lambda vertex: not contains_interface_component(vertex), ) for inner_list in vertices_layers ] - return sorted_vertices def sort_by_avg_build_time(self, vertices_layers: list[list[str]]) -> list[list[str]]: """Sorts the vertices in the graph so that vertices with the lowest average build time come first.""" @@ -1989,8 +1979,7 @@ class Graph: return vertices_ids - sorted_vertices = [sort_layer_by_avg_build_time(layer) for layer in vertices_layers] - return sorted_vertices + return [sort_layer_by_avg_build_time(layer) for layer in vertices_layers] def is_vertex_runnable(self, vertex_id: str) -> bool: """Returns whether a vertex is runnable.""" diff --git a/src/backend/base/langflow/graph/graph/state_model.py b/src/backend/base/langflow/graph/graph/state_model.py index aaf8ed47e..b46dce5af 100644 --- a/src/backend/base/langflow/graph/graph/state_model.py +++ b/src/backend/base/langflow/graph/graph/state_model.py @@ -5,8 +5,7 @@ from langflow.helpers.base_model import BaseModel def camel_to_snake(camel_str: str) -> str: - snake_str = re.sub(r"(? type[BaseModel]: diff --git a/src/backend/base/langflow/graph/state/model.py b/src/backend/base/langflow/graph/state/model.py index 7bf2c94b3..6be4a9741 100644 --- a/src/backend/base/langflow/graph/state/model.py +++ b/src/backend/base/langflow/graph/state/model.py @@ -238,6 +238,4 @@ def create_state_model(model_name: str = "State", validate: bool = True, **kwarg # Create the model dynamically config_dict = ConfigDict(arbitrary_types_allowed=True, validate_assignment=True) - model = create_model(model_name, __config__=config_dict, **fields) - - return model + return create_model(model_name, __config__=config_dict, **fields) diff --git a/src/backend/base/langflow/graph/utils.py b/src/backend/base/langflow/graph/utils.py index dcad5386c..65d5845da 100644 --- a/src/backend/base/langflow/graph/utils.py +++ b/src/backend/base/langflow/graph/utils.py @@ -72,16 +72,15 @@ def serialize_field(value): if isinstance(value, list | tuple): return [serialize_field(v) for v in value] - elif isinstance(value, Document): + if isinstance(value, Document): return value.to_json() - elif isinstance(value, BaseModel): + if isinstance(value, BaseModel): return value.model_dump() - elif isinstance(value, V1BaseModel): + if isinstance(value, V1BaseModel): if hasattr(value, "to_json"): return value.to_json() - else: - return value.dict() - elif isinstance(value, str): + return value.dict() + if isinstance(value, str): return {"result": value} return value diff --git a/src/backend/base/langflow/graph/vertex/base.py b/src/backend/base/langflow/graph/vertex/base.py index 419240ab1..7231b855d 100644 --- a/src/backend/base/langflow/graph/vertex/base.py +++ b/src/backend/base/langflow/graph/vertex/base.py @@ -741,7 +741,7 @@ class Vertex: if isinstance(self._built_object, UnbuiltObject): msg = f"{self.display_name}: {self._built_object_repr()}" raise ValueError(msg) - elif self._built_object is None: + if self._built_object is None: message = f"{self.display_name} returned None." if self.base_type == "custom_components": message += " Make sure your build method returns a component." @@ -782,11 +782,11 @@ class Vertex: if self.state == VertexStates.INACTIVE: # If the vertex is inactive, return None self.build_inactive() - return + return None if self.frozen and self._built: return await self.get_requester_result(requester) - elif self._built and requester is not None: + if self._built and requester is not None: # This means that the vertex has already been built # and we are just getting the result for the requester return await self.get_requester_result(requester) @@ -812,8 +812,7 @@ class Vertex: self._finalize_build() - result = await self.get_requester_result(requester) - return result + return await self.get_requester_result(requester) async def get_requester_result(self, requester: Optional["Vertex"]): # If the requester is None, this means that diff --git a/src/backend/base/langflow/graph/vertex/types.py b/src/backend/base/langflow/graph/vertex/types.py index 2ea578a1d..24a656064 100644 --- a/src/backend/base/langflow/graph/vertex/types.py +++ b/src/backend/base/langflow/graph/vertex/types.py @@ -32,6 +32,7 @@ class CustomComponentVertex(Vertex): def _built_object_repr(self): if self.artifacts and "repr" in self.artifacts: return self.artifacts["repr"] or super()._built_object_repr() + return None class ComponentVertex(Vertex): @@ -52,6 +53,7 @@ class ComponentVertex(Vertex): def _built_object_repr(self): if self.artifacts and "repr" in self.artifacts: return self.artifacts["repr"] or super()._built_object_repr() + return None def _update_built_object_and_artifacts(self, result): """ @@ -136,12 +138,11 @@ class ComponentVertex(Vertex): if edge is None: msg = f"Edge not found between {self.display_name} and {requester.display_name}" raise ValueError(msg) - elif edge.source_handle.name not in self.results: + if edge.source_handle.name not in self.results: msg = f"Result not found for {edge.source_handle.name}. Results: {self.results}" raise ValueError(msg) - else: - msg = f"Result not found for {edge.source_handle.name} in {edge}" - raise ValueError(msg) + msg = f"Result not found for {edge.source_handle.name} in {edge}" + raise ValueError(msg) if flow_id: asyncio.create_task(log_transaction(source=self, target=requester, flow_id=str(flow_id), status="success")) return result @@ -215,8 +216,7 @@ class InterfaceVertex(ComponentVertex): if self.task_id and self.is_task: if task := self.get_task(): return str(task.info) - else: - return f"Task {self.task_id} is not running" + return f"Task {self.task_id} is not running" if self.artifacts: # dump as a yaml string if isinstance(self.artifacts, dict): @@ -230,8 +230,7 @@ class InterfaceVertex(ComponentVertex): # artifacts = {k.title().replace("_", " "): v for k, v in self.artifacts.items() if v is not None} artifact = {k.title().replace("_", " "): v for k, v in artifact.items() if v is not None} artifacts.append(artifact) - yaml_str = yaml.dump(artifacts, default_flow_style=False, allow_unicode=True) - return yaml_str + return yaml.dump(artifacts, default_flow_style=False, allow_unicode=True) return super()._built_object_repr() def _process_chat_component(self): @@ -481,6 +480,7 @@ class StateVertex(ComponentVertex): def _built_object_repr(self): if self.artifacts and "repr" in self.artifacts: return self.artifacts["repr"] or super()._built_object_repr() + return None def dict_to_codeblock(d: dict) -> str: diff --git a/src/backend/base/langflow/helpers/flow.py b/src/backend/base/langflow/helpers/flow.py index 6eeb300a9..c4802d4de 100644 --- a/src/backend/base/langflow/helpers/flow.py +++ b/src/backend/base/langflow/helpers/flow.py @@ -34,8 +34,7 @@ def list_flows(*, user_id: str | None = None) -> list[Data]: select(Flow).where(Flow.user_id == user_id).where(Flow.is_component == False) # noqa ).all() - flows_data = [flow.to_data() for flow in flows] - return flows_data + return [flow.to_data() for flow in flows] except Exception as e: msg = f"Error listing flows: {e}" raise ValueError(msg) @@ -63,8 +62,7 @@ async def load_flow( raise ValueError(msg) if tweaks: graph_data = process_tweaks(graph_data=graph_data, tweaks=tweaks) - graph = Graph.from_payload(graph_data, flow_id=flow_id, user_id=user_id) - return graph + return Graph.from_payload(graph_data, flow_id=flow_id, user_id=user_id) def find_flow(flow_name: str, user_id: str) -> str | None: @@ -273,7 +271,6 @@ def get_arg_names(inputs: list["Vertex"]) -> list[dict[str, str]]: def get_flow_by_id_or_endpoint_name(flow_id_or_name: str, user_id: UUID | None = None) -> FlowRead | None: - flow_read = None with session_scope() as session: endpoint_name = None try: @@ -287,8 +284,7 @@ def get_flow_by_id_or_endpoint_name(flow_id_or_name: str, user_id: UUID | None = flow = session.exec(stmt).first() if flow is None: raise HTTPException(status_code=404, detail=f"Flow identifier {flow_id_or_name} not found") - flow_read = FlowRead.model_validate(flow, from_attributes=True) - return flow_read + return FlowRead.model_validate(flow, from_attributes=True) def generate_unique_flow_name(flow_name, user_id, session): diff --git a/src/backend/base/langflow/helpers/user.py b/src/backend/base/langflow/helpers/user.py index d2cd6a8d9..9f3488033 100644 --- a/src/backend/base/langflow/helpers/user.py +++ b/src/backend/base/langflow/helpers/user.py @@ -9,7 +9,6 @@ from langflow.services.deps import get_db_service def get_user_by_flow_id_or_endpoint_name(flow_id_or_name: str) -> UserRead | None: - user_read = None with get_db_service().with_session() as session: try: flow_id = UUID(flow_id_or_name) @@ -25,5 +24,4 @@ def get_user_by_flow_id_or_endpoint_name(flow_id_or_name: str) -> UserRead | Non if user is None: raise HTTPException(status_code=404, detail=f"User for flow {flow_id_or_name} not found") - user_read = UserRead.model_validate(user, from_attributes=True) - return user_read + return UserRead.model_validate(user, from_attributes=True) diff --git a/src/backend/base/langflow/initial_setup/setup.py b/src/backend/base/langflow/initial_setup/setup.py index 3b28aeee1..1ad9a6688 100644 --- a/src/backend/base/langflow/initial_setup/setup.py +++ b/src/backend/base/langflow/initial_setup/setup.py @@ -460,8 +460,7 @@ def create_new_project( def get_all_flows_similar_to_project(session, folder_id): - flows = session.exec(select(Folder).where(Folder.id == folder_id)).first().flows - return flows + return session.exec(select(Folder).where(Folder.id == folder_id)).first().flows def delete_start_projects(session, folder_id): @@ -484,8 +483,7 @@ def create_starter_folder(session): session.commit() session.refresh(db_folder) return db_folder - else: - return session.exec(select(Folder).where(Folder.name == STARTER_FOLDER_NAME)).first() + return session.exec(select(Folder).where(Folder.name == STARTER_FOLDER_NAME)).first() def _is_valid_uuid(val): diff --git a/src/backend/base/langflow/initial_setup/starter_projects/basic_prompting.py b/src/backend/base/langflow/initial_setup/starter_projects/basic_prompting.py index 0f0f81ba7..0115a428c 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/basic_prompting.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/basic_prompting.py @@ -26,5 +26,4 @@ Answer: chat_output = ChatOutput() chat_output.set(input_value=openai_component.text_response) - graph = Graph(start=chat_input, end=chat_output) - return graph + return Graph(start=chat_input, end=chat_output) diff --git a/src/backend/base/langflow/initial_setup/starter_projects/blog_writer.py b/src/backend/base/langflow/initial_setup/starter_projects/blog_writer.py index e7a0f923c..813ef05fa 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/blog_writer.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/blog_writer.py @@ -45,5 +45,4 @@ Blog: chat_output = ChatOutput() chat_output.set(input_value=openai_component.text_response) - graph = Graph(start=text_input, end=chat_output) - return graph + return Graph(start=text_input, end=chat_output) diff --git a/src/backend/base/langflow/initial_setup/starter_projects/complex_agent.py b/src/backend/base/langflow/initial_setup/starter_projects/complex_agent.py index 4090fd044..f94c04dfe 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/complex_agent.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/complex_agent.py @@ -90,10 +90,9 @@ If it is just a general query (e.g a greeting) you can respond them directly.""" chat_output = ChatOutput() chat_output.set(input_value=crew_component.build_output) - graph = Graph( + return Graph( start=chat_input, end=chat_output, flow_name="Sequential Tasks Agent", description="This Agent runs tasks in a predefined sequence.", ) - return graph diff --git a/src/backend/base/langflow/initial_setup/starter_projects/document_qa.py b/src/backend/base/langflow/initial_setup/starter_projects/document_qa.py index b1d98a182..c85ce9fcb 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/document_qa.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/document_qa.py @@ -40,5 +40,4 @@ Answer: chat_output = ChatOutput() chat_output.set(input_value=openai_component.text_response) - graph = Graph(start=chat_input, end=chat_output) - return graph + return Graph(start=chat_input, end=chat_output) diff --git a/src/backend/base/langflow/initial_setup/starter_projects/hierarchical_tasks_agent.py b/src/backend/base/langflow/initial_setup/starter_projects/hierarchical_tasks_agent.py index c461c70a7..3abe720e1 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/hierarchical_tasks_agent.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/hierarchical_tasks_agent.py @@ -62,10 +62,9 @@ If it is just a general query (e.g a greeting) you can respond them directly.""" chat_output = ChatOutput() chat_output.set(input_value=crew_component.build_output) - graph = Graph( + return Graph( start=chat_input, end=chat_output, flow_name="Sequential Tasks Agent", description="This Agent runs tasks in a predefined sequence.", ) - return graph diff --git a/src/backend/base/langflow/initial_setup/starter_projects/memory_chatbot.py b/src/backend/base/langflow/initial_setup/starter_projects/memory_chatbot.py index 1b0f44b9d..412da8cab 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/memory_chatbot.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/memory_chatbot.py @@ -24,5 +24,4 @@ def memory_chatbot_graph(template: str | None = None): chat_output = ChatOutput() chat_output.set(input_value=openai_component.text_response) - graph = Graph(chat_input, chat_output) - return graph + return Graph(chat_input, chat_output) diff --git a/src/backend/base/langflow/initial_setup/starter_projects/sequential_tasks_agent.py b/src/backend/base/langflow/initial_setup/starter_projects/sequential_tasks_agent.py index 93faad877..7e1327f7d 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/sequential_tasks_agent.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/sequential_tasks_agent.py @@ -90,11 +90,9 @@ Build a fun blog post about this topic.""", chat_output.set(input_value=crew_component.build_output) # Create the graph - graph = Graph( + return Graph( start=text_input, end=chat_output, flow_name="Sequential Tasks Agent", description="This Agent runs tasks in a predefined sequence.", ) - - return graph diff --git a/src/backend/base/langflow/initial_setup/starter_projects/vector_store_rag.py b/src/backend/base/langflow/initial_setup/starter_projects/vector_store_rag.py index b8679ad21..b65857d22 100644 --- a/src/backend/base/langflow/initial_setup/starter_projects/vector_store_rag.py +++ b/src/backend/base/langflow/initial_setup/starter_projects/vector_store_rag.py @@ -24,8 +24,7 @@ def ingestion_graph(): ingest_data=text_splitter.split_text, ) - ingestion_graph = Graph(file_component, vector_store) - return ingestion_graph + return Graph(file_component, vector_store) def rag_graph(): @@ -57,8 +56,7 @@ def rag_graph(): chat_output = ChatOutput() chat_output.set(input_value=openai_component.text_response) - graph = Graph(start=chat_input, end=chat_output) - return graph + return Graph(start=chat_input, end=chat_output) def vector_store_rag_graph(): diff --git a/src/backend/base/langflow/inputs/inputs.py b/src/backend/base/langflow/inputs/inputs.py index a0dd522c9..bbc3dc773 100644 --- a/src/backend/base/langflow/inputs/inputs.py +++ b/src/backend/base/langflow/inputs/inputs.py @@ -537,6 +537,5 @@ def instantiate_input(input_type: str, data: dict) -> InputTypes: data["field_type"] = data.pop("type") if input_type_class: return input_type_class(**data) - else: - msg = f"Invalid input type: {input_type}" - raise ValueError(msg) + msg = f"Invalid input type: {input_type}" + raise ValueError(msg) diff --git a/src/backend/base/langflow/inputs/validators.py b/src/backend/base/langflow/inputs/validators.py index ac9dc12bb..18bbd3efb 100644 --- a/src/backend/base/langflow/inputs/validators.py +++ b/src/backend/base/langflow/inputs/validators.py @@ -12,9 +12,8 @@ def validate_boolean(value: bool) -> bool: return False if isinstance(value, bool): return value - else: - msg = "Value must be a boolean" - raise ValueError(msg) + msg = "Value must be a boolean" + raise ValueError(msg) CoalesceBool = Annotated[bool, PlainValidator(validate_boolean)] diff --git a/src/backend/base/langflow/interface/initialize/loading.py b/src/backend/base/langflow/interface/initialize/loading.py index 97d311cd1..7c211b024 100644 --- a/src/backend/base/langflow/interface/initialize/loading.py +++ b/src/backend/base/langflow/interface/initialize/loading.py @@ -63,11 +63,10 @@ async def get_instance_results( warnings.filterwarnings("ignore", category=PydanticDeprecatedSince20) if base_type == "custom_components": return await build_custom_component(params=custom_params, custom_component=custom_component) - elif base_type == "component": + if base_type == "component": return await build_component(params=custom_params, custom_component=custom_component) - else: - msg = f"Base type {base_type} not found." - raise ValueError(msg) + msg = f"Base type {base_type} not found." + raise ValueError(msg) def get_params(vertex_params): diff --git a/src/backend/base/langflow/interface/run.py b/src/backend/base/langflow/interface/run.py index 283c752e8..d4c58fb1f 100644 --- a/src/backend/base/langflow/interface/run.py +++ b/src/backend/base/langflow/interface/run.py @@ -15,8 +15,7 @@ def get_memory_key(langchain_object): if hasattr(langchain_object.memory, "memory_key"): memory_key = langchain_object.memory.memory_key return mem_key_dict.get(memory_key) - else: - return None # or some other default value or action + return None # or some other default value or action def update_memory_keys(langchain_object, possible_new_mem_key): diff --git a/src/backend/base/langflow/interface/types.py b/src/backend/base/langflow/interface/types.py index 8516b4941..4a63aa1eb 100644 --- a/src/backend/base/langflow/interface/types.py +++ b/src/backend/base/langflow/interface/types.py @@ -13,14 +13,12 @@ if TYPE_CHECKING: async def aget_all_types_dict(components_paths): """Get all types dictionary combining native and custom components.""" - custom_components_from_file = await abuild_custom_components(components_paths=components_paths) - return custom_components_from_file + return await abuild_custom_components(components_paths=components_paths) def get_all_types_dict(components_paths): """Get all types dictionary combining native and custom components.""" - custom_components_from_file = build_custom_components(components_paths=components_paths) - return custom_components_from_file + return build_custom_components(components_paths=components_paths) # TypeError: unhashable type: 'list' diff --git a/src/backend/base/langflow/load/load.py b/src/backend/base/langflow/load/load.py index ebf0a1951..d3b669c4b 100644 --- a/src/backend/base/langflow/load/load.py +++ b/src/backend/base/langflow/load/load.py @@ -66,8 +66,7 @@ def load_flow_from_json( if tweaks is not None: graph_data = process_tweaks(graph_data, tweaks) - graph = Graph.from_payload(graph_data) - return graph + return Graph.from_payload(graph_data) def run_flow_from_json( @@ -124,7 +123,7 @@ def run_flow_from_json( cache=cache, disable_logs=disable_logs, ) - result = run_graph( + return run_graph( graph=graph, input_value=input_value, input_type=input_type, @@ -132,4 +131,3 @@ def run_flow_from_json( output_component=output_component, fallback_to_env_vars=fallback_to_env_vars, ) - return result diff --git a/src/backend/base/langflow/load/utils.py b/src/backend/base/langflow/load/utils.py index db3112da9..5a0a678a7 100644 --- a/src/backend/base/langflow/load/utils.py +++ b/src/backend/base/langflow/load/utils.py @@ -24,9 +24,8 @@ def upload(file_path, host, flow_id): response = httpx.post(url, files={"file": file}) if response.status_code == 200 or response.status_code == 201: return response.json() - else: - msg = f"Error uploading file: {response.status_code}" - raise Exception(msg) + msg = f"Error uploading file: {response.status_code}" + raise Exception(msg) except Exception as e: msg = f"Error uploading file: {e}" raise Exception(msg) @@ -62,9 +61,8 @@ def upload_file(file_path: str, host: str, flow_id: str, components: list[str], msg = f"Component ID or name must be a string. Got {type(component)}" raise ValueError(msg) return tweaks - else: - msg = "Error uploading file" - raise ValueError(msg) + msg = "Error uploading file" + raise ValueError(msg) except Exception as e: msg = f"Error uploading file: {e}" raise ValueError(msg) @@ -89,11 +87,9 @@ def get_flow(url: str, flow_id: str): response = httpx.get(flow_url) if response.status_code == 200: json_response = response.json() - flow = FlowBase(**json_response).model_dump() - return flow - else: - msg = f"Error retrieving flow: {response.status_code}" - raise Exception(msg) + return FlowBase(**json_response).model_dump() + msg = f"Error retrieving flow: {response.status_code}" + raise Exception(msg) except Exception as e: msg = f"Error retrieving flow: {e}" raise Exception(msg) diff --git a/src/backend/base/langflow/main.py b/src/backend/base/langflow/main.py index 0dc604102..505e2cca3 100644 --- a/src/backend/base/langflow/main.py +++ b/src/backend/base/langflow/main.py @@ -59,8 +59,7 @@ class RequestCancelledMiddleware(BaseHTTPMiddleware): if cancel_task in done: return Response("Request was cancelled", status_code=499) - else: - return await handler_task + return await handler_task class JavaScriptMIMETypeMiddleware(BaseHTTPMiddleware): @@ -161,8 +160,7 @@ def create_app(): content={"detail": "Invalid multipart formatting"}, ) - response = await call_next(request) - return response + return await call_next(request) @app.middleware("http") async def flatten_query_string_lists(request: Request, call_next): @@ -203,12 +201,11 @@ def create_app(): status_code=exc.status_code, content={"message": str(exc.detail)}, ) - else: - logger.error(f"unhandled error: {exc}") - return JSONResponse( - status_code=HTTPStatus.INTERNAL_SERVER_ERROR, - content={"message": str(exc)}, - ) + logger.error(f"unhandled error: {exc}") + return JSONResponse( + status_code=HTTPStatus.INTERNAL_SERVER_ERROR, + content={"message": str(exc)}, + ) FastAPIInstrumentor.instrument_app(app) diff --git a/src/backend/base/langflow/memory.py b/src/backend/base/langflow/memory.py index ac13343ae..b76f2d4ba 100644 --- a/src/backend/base/langflow/memory.py +++ b/src/backend/base/langflow/memory.py @@ -35,7 +35,6 @@ def get_messages( Returns: List[Data]: A list of Data objects representing the retrieved messages. """ - messages_read: list[Message] = [] with session_scope() as session: stmt = select(MessageTable) if sender: @@ -55,9 +54,7 @@ def get_messages( if limit: stmt = stmt.limit(limit) messages = session.exec(stmt) - messages_read = [Message(**d.model_dump()) for d in messages] - - return messages_read + return [Message(**d.model_dump()) for d in messages] def add_messages(messages: Message | list[Message], flow_id: str | None = None): diff --git a/src/backend/base/langflow/processing/process.py b/src/backend/base/langflow/processing/process.py index 5682f7bff..90bda68f2 100644 --- a/src/backend/base/langflow/processing/process.py +++ b/src/backend/base/langflow/processing/process.py @@ -100,7 +100,7 @@ def run_graph( components.append(input_value_request.components or []) inputs_list.append({INPUT_FIELD_NAME: input_value_request.input_value}) types.append(input_value_request.type) - run_outputs = graph.run( + return graph.run( inputs_list, components, types, @@ -109,7 +109,6 @@ def run_graph( session_id="", fallback_to_env_vars=fallback_to_env_vars, ) - return run_outputs def validate_input( diff --git a/src/backend/base/langflow/schema/data.py b/src/backend/base/langflow/schema/data.py index e05ac1a22..cb22cd06c 100644 --- a/src/backend/base/langflow/schema/data.py +++ b/src/backend/base/langflow/schema/data.py @@ -39,8 +39,7 @@ class Data(BaseModel): @model_serializer(mode="plain", when_used="json") def serialize_model(self): - data = {k: v.to_json() if hasattr(v, "to_json") else v for k, v in self.data.items()} - return data + return {k: v.to_json() if hasattr(v, "to_json") else v for k, v in self.data.items()} def get_text(self): """ diff --git a/src/backend/base/langflow/schema/message.py b/src/backend/base/langflow/schema/message.py index 3b28e47d8..4012ee7c4 100644 --- a/src/backend/base/langflow/schema/message.py +++ b/src/backend/base/langflow/schema/message.py @@ -162,7 +162,7 @@ class Message(Data): def serialize_text(self, value): if isinstance(value, AsyncIterator): return "" - elif isinstance(value, Iterator): + if isinstance(value, Iterator): return "" return value @@ -205,8 +205,7 @@ class Message(Data): messages.append(AIMessage(content=message.get("content"))) self.prompt["kwargs"]["messages"] = messages - loaded_prompt = load(self.prompt) - return loaded_prompt + return load(self.prompt) @classmethod def from_lc_prompt( diff --git a/src/backend/base/langflow/schema/schema.py b/src/backend/base/langflow/schema/schema.py index 4c8b6a57d..3ad889e38 100644 --- a/src/backend/base/langflow/schema/schema.py +++ b/src/backend/base/langflow/schema/schema.py @@ -118,27 +118,27 @@ def recursive_serialize_or_str(obj): try: if isinstance(obj, dict): return {k: recursive_serialize_or_str(v) for k, v in obj.items()} - elif isinstance(obj, list): + if isinstance(obj, list): return [recursive_serialize_or_str(v) for v in obj] - elif isinstance(obj, BaseModel): + if isinstance(obj, BaseModel): if hasattr(obj, "model_dump"): obj_dict = obj.model_dump() elif hasattr(obj, "dict"): obj_dict = obj.dict() # type: ignore return {k: recursive_serialize_or_str(v) for k, v in obj_dict.items()} - elif isinstance(obj, AsyncIterator | Generator | Iterator): + if isinstance(obj, AsyncIterator | Generator | Iterator): # contain memory addresses # without consuming the iterator # return list(obj) consumes the iterator # return f"{obj}" this generates '' # it is not useful return "Unconsumed Stream" - elif hasattr(obj, "dict"): + if hasattr(obj, "dict"): return {k: recursive_serialize_or_str(v) for k, v in obj.dict().items()} - elif hasattr(obj, "model_dump"): + if hasattr(obj, "model_dump"): return {k: recursive_serialize_or_str(v) for k, v in obj.model_dump().items()} - elif issubclass(obj, BaseModel): + if issubclass(obj, BaseModel): # This a type BaseModel and not an instance of it return repr(obj) return str(obj) diff --git a/src/backend/base/langflow/services/auth/utils.py b/src/backend/base/langflow/services/auth/utils.py index 98042cae4..58a063b13 100644 --- a/src/backend/base/langflow/services/auth/utils.py +++ b/src/backend/base/langflow/services/auth/utils.py @@ -65,7 +65,7 @@ async def api_key_security( ) if isinstance(result, ApiKey): return UserRead.model_validate(result.user, from_attributes=True) - elif isinstance(result, User): + if isinstance(result, User): return UserRead.model_validate(result, from_attributes=True) msg = "Invalid result type" raise ValueError(msg) @@ -79,15 +79,14 @@ async def get_current_user( ) -> User: if token: return await get_current_user_by_jwt(token, db) - else: - user = await api_key_security(query_param, header_param, db) - if user: - return user + user = await api_key_security(query_param, header_param, db) + if user: + return user - raise HTTPException( - status_code=status.HTTP_403_FORBIDDEN, - detail="Invalid or missing API key", - ) + raise HTTPException( + status_code=status.HTTP_403_FORBIDDEN, + detail="Invalid or missing API key", + ) async def get_current_user_by_jwt( @@ -161,10 +160,9 @@ async def get_current_user_for_websocket( api_key = websocket.query_params.get("x-api-key") if token: return await get_current_user_by_jwt(token, db) - elif api_key: + if api_key: return await api_key_security(api_key, query_param, db) - else: - return None + return None def get_current_active_user(current_user: Annotated[User, Depends(get_current_user)]): @@ -363,8 +361,7 @@ def ensure_valid_key(s: str) -> bytes: def get_fernet(settings_service=Depends(get_settings_service)): SECRET_KEY: str = settings_service.auth_settings.SECRET_KEY.get_secret_value() valid_key = ensure_valid_key(SECRET_KEY) - fernet = Fernet(valid_key) - return fernet + return Fernet(valid_key) def encrypt_api_key(api_key: str, settings_service=Depends(get_settings_service)): diff --git a/src/backend/base/langflow/services/cache/disk.py b/src/backend/base/langflow/services/cache/disk.py index 901dde2fe..f53a833ce 100644 --- a/src/backend/base/langflow/services/cache/disk.py +++ b/src/backend/base/langflow/services/cache/disk.py @@ -36,9 +36,8 @@ class AsyncDiskCache(AsyncBaseCacheService, Generic[AsyncLockType]): # type: ig if time.time() - item["time"] < self.expiration_time: await asyncio.to_thread(self.cache.touch, key) # Refresh the expiry time return pickle.loads(item["value"]) if isinstance(item["value"], bytes) else item["value"] - else: - logger.info(f"Cache item for key '{key}' has expired and will be deleted.") - await self._delete(key) # Log before deleting the expired item + logger.info(f"Cache item for key '{key}' has expired and will be deleted.") + await self._delete(key) # Log before deleting the expired item return CACHE_MISS async def set(self, key, value, lock: asyncio.Lock | None = None): diff --git a/src/backend/base/langflow/services/cache/factory.py b/src/backend/base/langflow/services/cache/factory.py index 3d7887f9c..5b6e74bc7 100644 --- a/src/backend/base/langflow/services/cache/factory.py +++ b/src/backend/base/langflow/services/cache/factory.py @@ -29,17 +29,17 @@ class CacheServiceFactory(ServiceFactory): if redis_cache.is_connected(): logger.debug("Redis cache is connected") return redis_cache - else: - # do not attempt to fallback to another cache type - msg = "Failed to connect to Redis cache" - raise ConnectionError(msg) + # do not attempt to fallback to another cache type + msg = "Failed to connect to Redis cache" + raise ConnectionError(msg) - elif settings_service.settings.cache_type == "memory": + if settings_service.settings.cache_type == "memory": return ThreadingInMemoryCache(expiration_time=settings_service.settings.cache_expire) - elif settings_service.settings.cache_type == "async": + if settings_service.settings.cache_type == "async": return AsyncInMemoryCache(expiration_time=settings_service.settings.cache_expire) - elif settings_service.settings.cache_type == "disk": + if settings_service.settings.cache_type == "disk": return AsyncDiskCache( cache_dir=settings_service.settings.config_dir, expiration_time=settings_service.settings.cache_expire, ) + return None diff --git a/src/backend/base/langflow/services/cache/service.py b/src/backend/base/langflow/services/cache/service.py index 3a3056c05..dbc5bef69 100644 --- a/src/backend/base/langflow/services/cache/service.py +++ b/src/backend/base/langflow/services/cache/service.py @@ -77,8 +77,7 @@ class ThreadingInMemoryCache(CacheService, Generic[LockType]): # type: ignore else: value = item["value"] return value - else: - self.delete(key) + self.delete(key) return None def set(self, key, value, lock: Union[threading.Lock, None] = None): # noqa: UP007 @@ -353,9 +352,8 @@ class AsyncInMemoryCache(AsyncBaseCacheService, Generic[AsyncLockType]): # type if time.time() - item["time"] < self.expiration_time: self.cache.move_to_end(key) return pickle.loads(item["value"]) if isinstance(item["value"], bytes) else item["value"] - else: - logger.info(f"Cache item for key '{key}' has expired and will be deleted.") - await self._delete(key) # Log before deleting the expired item + logger.info(f"Cache item for key '{key}' has expired and will be deleted.") + await self._delete(key) # Log before deleting the expired item return CACHE_MISS async def set(self, key, value, lock: asyncio.Lock | None = None): diff --git a/src/backend/base/langflow/services/chat/service.py b/src/backend/base/langflow/services/chat/service.py index 2b2eb5825..702eab2bc 100644 --- a/src/backend/base/langflow/services/chat/service.py +++ b/src/backend/base/langflow/services/chat/service.py @@ -32,8 +32,7 @@ class ChatService(Service): """ if isinstance(self.cache_service, AsyncBaseCacheService): return self._async_cache_locks[key] - else: - return self._sync_cache_locks[key] + return self._sync_cache_locks[key] async def _perform_cache_operation( self, operation: str, key: str, data: Any = None, lock: asyncio.Lock | None = None @@ -59,17 +58,22 @@ class ChatService(Service): if isinstance(self.cache_service, AsyncBaseCacheService): if operation == "upsert": await self.cache_service.upsert(str(key), data, lock=lock) - elif operation == "get": + return None + if operation == "get": return await self.cache_service.get(key, lock=lock) - elif operation == "delete": + if operation == "delete": await self.cache_service.delete(key, lock=lock) - else: - if operation == "upsert": - self.cache_service.upsert(str(key), data, lock=lock) - elif operation == "get": - return self.cache_service.get(key, lock=lock) - elif operation == "delete": - self.cache_service.delete(key, lock=lock) + return None + return None + if operation == "upsert": + self.cache_service.upsert(str(key), data, lock=lock) + return None + if operation == "get": + return self.cache_service.get(key, lock=lock) + if operation == "delete": + self.cache_service.delete(key, lock=lock) + return None + return None async def set_cache(self, key: str, data: Any, lock: asyncio.Lock | None = None) -> bool: """ diff --git a/src/backend/base/langflow/services/database/models/flow/model.py b/src/backend/base/langflow/services/database/models/flow/model.py index 809859d31..0dbf957be 100644 --- a/src/backend/base/langflow/services/database/models/flow/model.py +++ b/src/backend/base/langflow/services/database/models/flow/model.py @@ -79,7 +79,7 @@ class FlowBase(SQLModel): if not v.startswith(":") and not v.endswith(":"): return v - elif not v.startswith(":") or not v.endswith(":"): + if not v.startswith(":") or not v.endswith(":"): # emoji should have both starting and ending colons # so if one of them is missing, we will raise msg = f"Invalid emoji. {v} is not a valid emoji." @@ -141,7 +141,7 @@ class FlowBase(SQLModel): def validate_dt(cls, v): if v is None: return v - elif isinstance(v, datetime): + if isinstance(v, datetime): return v return datetime.fromisoformat(v) @@ -167,8 +167,7 @@ class Flow(FlowBase, table=True): # type: ignore "description": serialized.pop("description"), "updated_at": serialized.pop("updated_at"), } - record = Data(data=data) - return record + return Data(data=data) __table_args__ = ( UniqueConstraint("user_id", "name", name="unique_flow_name"), diff --git a/src/backend/base/langflow/services/database/models/transactions/model.py b/src/backend/base/langflow/services/database/models/transactions/model.py index 493aec48f..210be01ea 100644 --- a/src/backend/base/langflow/services/database/models/transactions/model.py +++ b/src/backend/base/langflow/services/database/models/transactions/model.py @@ -36,8 +36,7 @@ class TransactionBase(SQLModel): @field_serializer("outputs") def serialize_outputs(self, data) -> dict: - truncated_data = truncate_long_strings(data) - return truncated_data + return truncate_long_strings(data) class TransactionTable(TransactionBase, table=True): # type: ignore diff --git a/src/backend/base/langflow/services/database/models/vertex_builds/model.py b/src/backend/base/langflow/services/database/models/vertex_builds/model.py index 69341d828..c48f3f93c 100644 --- a/src/backend/base/langflow/services/database/models/vertex_builds/model.py +++ b/src/backend/base/langflow/services/database/models/vertex_builds/model.py @@ -42,13 +42,11 @@ class VertexBuildBase(SQLModel): @field_serializer("data") def serialize_data(self, data: dict) -> dict: - truncated_data = truncate_long_strings(data) - return truncated_data + return truncate_long_strings(data) @field_serializer("artifacts") def serialize_artifacts(self, data) -> dict: - truncated_data = truncate_long_strings(data) - return truncated_data + return truncate_long_strings(data) class VertexBuildTable(VertexBuildBase, table=True): # type: ignore diff --git a/src/backend/base/langflow/services/plugins/factory.py b/src/backend/base/langflow/services/plugins/factory.py index 221d43500..586dcb0ff 100644 --- a/src/backend/base/langflow/services/plugins/factory.py +++ b/src/backend/base/langflow/services/plugins/factory.py @@ -12,5 +12,4 @@ class PluginServiceFactory(ServiceFactory): super().__init__(PluginService) def create(self, settings_service: "SettingsService"): - service = PluginService(settings_service) - return service + return PluginService(settings_service) diff --git a/src/backend/base/langflow/services/storage/factory.py b/src/backend/base/langflow/services/storage/factory.py index ae4783f1e..335772657 100644 --- a/src/backend/base/langflow/services/storage/factory.py +++ b/src/backend/base/langflow/services/storage/factory.py @@ -18,12 +18,11 @@ class StorageServiceFactory(ServiceFactory): from .local import LocalStorageService return LocalStorageService(session_service, settings_service) - elif storage_type.lower() == "s3": + if storage_type.lower() == "s3": from .s3 import S3StorageService return S3StorageService(session_service, settings_service) - else: - logger.warning(f"Storage type {storage_type} not supported. Using local storage.") - from .local import LocalStorageService + logger.warning(f"Storage type {storage_type} not supported. Using local storage.") + from .local import LocalStorageService - return LocalStorageService(session_service, settings_service) + return LocalStorageService(session_service, settings_service) diff --git a/src/backend/base/langflow/services/store/schema.py b/src/backend/base/langflow/services/store/schema.py index 45437b20b..3a2bc8fc9 100644 --- a/src/backend/base/langflow/services/store/schema.py +++ b/src/backend/base/langflow/services/store/schema.py @@ -45,8 +45,7 @@ class ListComponentResponse(BaseModel): return v if all("id" in tag and "name" in tag for tag in v): return v - else: - return [TagResponse(**tag.get("tags_id")) for tag in v if tag.get("tags_id")] + return [TagResponse(**tag.get("tags_id")) for tag in v if tag.get("tags_id")] class ListComponentResponseModel(BaseModel): diff --git a/src/backend/base/langflow/services/store/service.py b/src/backend/base/langflow/services/store/service.py index 1afb575ab..e9c4c57e5 100644 --- a/src/backend/base/langflow/services/store/service.py +++ b/src/backend/base/langflow/services/store/service.py @@ -116,9 +116,8 @@ class StoreService(Service): except HTTPStatusError as exc: if exc.response.status_code in [403, 401]: return False - else: - msg = f"Unexpected status code: {exc.response.status_code}" - raise ValueError(msg) + msg = f"Unexpected status code: {exc.response.status_code}" + raise ValueError(msg) except Exception as exc: msg = f"Unexpected error: {exc}" raise ValueError(msg) @@ -494,14 +493,12 @@ class StoreService(Service): if isinstance(result, list): return True - elif isinstance(result, int): + if isinstance(result, int): return False - else: - msg = f"Unexpected result: {result}" - raise ValueError(msg) - else: - msg = f"Unexpected status code: {response.status_code}" + msg = f"Unexpected result: {result}" raise ValueError(msg) + msg = f"Unexpected status code: {response.status_code}" + raise ValueError(msg) async def get_list_component_response_model( self, @@ -550,7 +547,7 @@ class StoreService(Service): if exc.response.status_code == 403: msg = "You are not authorized to access this public resource" raise ForbiddenError(msg) from exc - elif exc.response.status_code == 401: + if exc.response.status_code == 401: msg = "You are not authorized to access this resource. Please check your API key." raise APIKeyError(msg) from exc except Exception as exc: @@ -572,7 +569,7 @@ class StoreService(Service): if exc.response.status_code == 403: msg = "You are not authorized to access this public resource" raise ForbiddenError(msg) - elif exc.response.status_code == 401: + if exc.response.status_code == 401: msg = "You are not authorized to access this resource. Please check your API key." raise APIKeyError(msg) diff --git a/src/backend/base/langflow/services/telemetry/opentelemetry.py b/src/backend/base/langflow/services/telemetry/opentelemetry.py index 95465b2c2..614a8901b 100644 --- a/src/backend/base/langflow/services/telemetry/opentelemetry.py +++ b/src/backend/base/langflow/services/telemetry/opentelemetry.py @@ -173,27 +173,26 @@ class OpenTelemetry(metaclass=ThreadSafeSingletonMetaUsingWeakref): unit=metric.unit, description=metric.description, ) - elif metric.type == MetricType.OBSERVABLE_GAUGE: + if metric.type == MetricType.OBSERVABLE_GAUGE: return ObservableGaugeWrapper( name=metric.name, description=metric.description, unit=metric.unit, ) - elif metric.type == MetricType.UP_DOWN_COUNTER: + if metric.type == MetricType.UP_DOWN_COUNTER: return self.meter.create_up_down_counter( name=metric.name, unit=metric.unit, description=metric.description, ) - elif metric.type == MetricType.HISTOGRAM: + if metric.type == MetricType.HISTOGRAM: return self.meter.create_histogram( name=metric.name, unit=metric.unit, description=metric.description, ) - else: - msg = f"Unknown metric type: {metric.type}" - raise ValueError(msg) + msg = f"Unknown metric type: {metric.type}" + raise ValueError(msg) def validate_labels(self, metric_name: str, labels: Mapping[str, str]): reg = self._metrics_registry.get(metric_name) diff --git a/src/backend/base/langflow/services/utils.py b/src/backend/base/langflow/services/utils.py index 96ec30fce..3ead7d60f 100644 --- a/src/backend/base/langflow/services/utils.py +++ b/src/backend/base/langflow/services/utils.py @@ -22,30 +22,27 @@ def get_or_create_super_user(session: Session, username, password, is_default): if user.is_superuser: if verify_password(password, user.password): return None - else: - # Superuser exists but password is incorrect - # which means that the user has changed the - # base superuser credentials. - # This means that the user has already created - # a superuser and changed the password in the UI - # so we don't need to do anything. - logger.debug( - "Superuser exists but password is incorrect. " - "This means that the user has changed the " - "base superuser credentials." - ) - return None - else: - logger.debug("User with superuser credentials exists but is not a superuser.") + # Superuser exists but password is incorrect + # which means that the user has changed the + # base superuser credentials. + # This means that the user has already created + # a superuser and changed the password in the UI + # so we don't need to do anything. + logger.debug( + "Superuser exists but password is incorrect. " + "This means that the user has changed the " + "base superuser credentials." + ) return None + logger.debug("User with superuser credentials exists but is not a superuser.") + return None if user: if verify_password(password, user.password): msg = "User with superuser credentials exists but is not a superuser." raise ValueError(msg) - else: - msg = "Incorrect superuser credentials" - raise ValueError(msg) + msg = "Incorrect superuser credentials" + raise ValueError(msg) if is_default: logger.debug("Creating default superuser.") diff --git a/src/backend/base/langflow/services/variable/factory.py b/src/backend/base/langflow/services/variable/factory.py index 18d63bc0c..c81511244 100644 --- a/src/backend/base/langflow/services/variable/factory.py +++ b/src/backend/base/langflow/services/variable/factory.py @@ -20,5 +20,4 @@ class VariableServiceFactory(ServiceFactory): from langflow.services.variable.kubernetes import KubernetesSecretService return KubernetesSecretService(settings_service) - else: - return DatabaseVariableService(settings_service) + return DatabaseVariableService(settings_service) diff --git a/src/backend/base/langflow/services/variable/kubernetes.py b/src/backend/base/langflow/services/variable/kubernetes.py index 47400d82c..4bc670454 100644 --- a/src/backend/base/langflow/services/variable/kubernetes.py +++ b/src/backend/base/langflow/services/variable/kubernetes.py @@ -60,13 +60,11 @@ class KubernetesSecretService(VariableService, Service): if name in variables: return name, variables[name] - else: - credential_name = CREDENTIAL_TYPE + "_" + name - if credential_name in variables: - return credential_name, variables[credential_name] - else: - msg = f"user_id {user_id} variable name {name} not found." - raise ValueError(msg) + credential_name = CREDENTIAL_TYPE + "_" + name + if credential_name in variables: + return credential_name, variables[credential_name] + msg = f"user_id {user_id} variable name {name} not found." + raise ValueError(msg) def get_variable( self, @@ -147,5 +145,4 @@ class KubernetesSecretService(VariableService, Service): value=auth_utils.encrypt_api_key(value, settings_service=self.settings_service), default_fields=default_fields, ) - variable = Variable.model_validate(variable_base, from_attributes=True, update={"user_id": user_id}) - return variable + return Variable.model_validate(variable_base, from_attributes=True, update={"user_id": user_id}) diff --git a/src/backend/base/langflow/services/variable/kubernetes_secrets.py b/src/backend/base/langflow/services/variable/kubernetes_secrets.py index 6cb23b561..b270bd826 100644 --- a/src/backend/base/langflow/services/variable/kubernetes_secrets.py +++ b/src/backend/base/langflow/services/variable/kubernetes_secrets.py @@ -74,9 +74,8 @@ class KubernetesSecretManager: if e.status == 404: # Secret doesn't exist, create a new one return self.create_secret(secret_name, data) - else: - logger.error(f"Error upserting secret {secret_name}: {e}") - raise + logger.error(f"Error upserting secret {secret_name}: {e}") + raise def get_secret(self, name: str) -> dict | None: """ diff --git a/src/backend/base/langflow/services/variable/service.py b/src/backend/base/langflow/services/variable/service.py index b3eeb43ec..ab9cade98 100644 --- a/src/backend/base/langflow/services/variable/service.py +++ b/src/backend/base/langflow/services/variable/service.py @@ -87,8 +87,7 @@ class DatabaseVariableService(VariableService, Service): raise TypeError(msg) # we decrypt the value - decrypted = auth_utils.decrypt_api_key(variable.value, settings_service=self.settings_service) - return decrypted + return auth_utils.decrypt_api_key(variable.value, settings_service=self.settings_service) def get_all(self, user_id: UUID | str, session: Session = Depends(get_session)) -> list[Variable | None]: return list(session.exec(select(Variable).where(Variable.user_id == user_id)).all()) diff --git a/src/backend/base/langflow/template/frontend_node/base.py b/src/backend/base/langflow/template/frontend_node/base.py index 75f869c47..f06c8c2f5 100644 --- a/src/backend/base/langflow/template/frontend_node/base.py +++ b/src/backend/base/langflow/template/frontend_node/base.py @@ -64,8 +64,7 @@ class FrontendNode(BaseModel): def process_base_classes(self, base_classes: list[str]) -> list[str]: """Removes unwanted base classes from the list of base classes.""" - sorted_base_classes = sorted(set(base_classes), key=lambda x: x.lower()) - return sorted_base_classes + return sorted(set(base_classes), key=lambda x: x.lower()) @field_serializer("display_name") def process_display_name(self, display_name: str) -> str: diff --git a/src/backend/base/langflow/utils/async_helpers.py b/src/backend/base/langflow/utils/async_helpers.py index 25ce54451..4edd9dfb2 100644 --- a/src/backend/base/langflow/utils/async_helpers.py +++ b/src/backend/base/langflow/utils/async_helpers.py @@ -8,8 +8,7 @@ def run_until_complete(coro): if loop.is_running(): # Run the coroutine in a separate event loop in a new thread return run_in_thread(coro) - else: - return loop.run_until_complete(coro) + return loop.run_until_complete(coro) except RuntimeError: # If there's no event loop, create a new one and run the coroutine return asyncio.run(coro) diff --git a/src/backend/base/langflow/utils/connection_string_parser.py b/src/backend/base/langflow/utils/connection_string_parser.py index a67d2059e..cefb1f281 100644 --- a/src/backend/base/langflow/utils/connection_string_parser.py +++ b/src/backend/base/langflow/utils/connection_string_parser.py @@ -5,5 +5,4 @@ def transform_connection_string(connection_string): auth_part, db_url_name = connection_string.rsplit("@", 1) protocol_user, password_string = auth_part.rsplit(":", 1) encoded_password = quote(password_string) - transformed_connection_string = f"{protocol_user}:{encoded_password}@{db_url_name}" - return transformed_connection_string + return f"{protocol_user}:{encoded_password}@{db_url_name}" diff --git a/src/backend/base/langflow/utils/util.py b/src/backend/base/langflow/utils/util.py index 70cb79465..d42d12f53 100644 --- a/src/backend/base/langflow/utils/util.py +++ b/src/backend/base/langflow/utils/util.py @@ -70,6 +70,7 @@ def build_template_from_function(name: str, type_to_loader_dict: dict, add_funct "description": docs.short_description or "", "base_classes": base_classes, } + return None def build_template_from_method( @@ -131,6 +132,7 @@ def build_template_from_method( "description": docs.short_description or "", "base_classes": base_classes, } + return None def get_base_classes(cls): @@ -316,7 +318,7 @@ def get_formatted_type(key: str, _type: str) -> str: if key == "allowed_tools": return "Tool" - elif key == "max_value_length": + if key == "max_value_length": return "int" return _type diff --git a/src/backend/base/langflow/utils/validate.py b/src/backend/base/langflow/utils/validate.py index 75cf1b6f1..7ee3530fe 100644 --- a/src/backend/base/langflow/utils/validate.py +++ b/src/backend/base/langflow/utils/validate.py @@ -244,8 +244,7 @@ def compile_class_code(class_code): :param class_code: AST node of the class :return: Compiled code object of the class """ - code_obj = compile(ast.Module(body=[class_code], type_ignores=[]), "", "exec") - return code_obj + return compile(ast.Module(body=[class_code], type_ignores=[]), "", "exec") def build_class_constructor(compiled_class, exec_globals, class_name): @@ -302,8 +301,7 @@ def find_names_in_code(code, names): :param names: A list of names to check for in the code. :return: A set of names that are found in the code. """ - found_names = {name for name in names if name in code} - return found_names + return {name for name in names if name in code} def extract_function_name(code): diff --git a/src/backend/base/langflow/utils/version.py b/src/backend/base/langflow/utils/version.py index 28ff54479..262edd649 100644 --- a/src/backend/base/langflow/utils/version.py +++ b/src/backend/base/langflow/utils/version.py @@ -48,6 +48,7 @@ def _get_version_info(): if __version__ is None: msg = f"Package not found from options {package_options}" raise ValueError(msg) + return None VERSION_INFO = _get_version_info() diff --git a/src/backend/base/pyproject.toml b/src/backend/base/pyproject.toml index ce1374302..f7d3c7baf 100644 --- a/src/backend/base/pyproject.toml +++ b/src/backend/base/pyproject.toml @@ -167,6 +167,7 @@ select = [ "PD", "PIE", "Q", + "RET", "RSE", "SLOT", "T10",