From 63beae1833922bb42606723476f84c9c430d6653 Mon Sep 17 00:00:00 2001 From: Christophe Bornet Date: Fri, 4 Oct 2024 17:01:56 +0200 Subject: [PATCH] ref: Add ruff rules RUF (#4001) Add ruff rules RUF --- src/backend/base/langflow/api/v1/callback.py | 2 +- src/backend/base/langflow/api/v1/chat.py | 2 +- src/backend/base/langflow/api/v1/endpoints.py | 12 ++-- src/backend/base/langflow/api/v1/flows.py | 2 +- .../base/langflow/base/agents/agent.py | 14 ++--- .../langflow/base/flow_processing/utils.py | 2 +- .../base/langflow/base/models/model.py | 5 +- .../base/langflow/base/prompts/api_utils.py | 6 +- .../components/Notion/add_content_to_page.py | 4 +- .../langflow/components/Notion/create_page.py | 4 +- .../Notion/list_database_properties.py | 6 +- .../langflow/components/Notion/list_pages.py | 6 +- .../components/Notion/page_content_viewer.py | 4 +- .../components/Notion/update_page_property.py | 8 +-- .../langflow/components/agents/CSVAgent.py | 3 +- .../components/agents/HierarchicalCrew.py | 3 +- .../langflow/components/agents/JsonAgent.py | 3 +- .../components/agents/OpenAIToolsAgent.py | 3 +- .../components/agents/OpenAPIAgent.py | 3 +- .../langflow/components/agents/SQLAgent.py | 3 +- .../components/agents/SequentialCrew.py | 3 +- .../components/agents/SequentialTaskAgent.py | 4 +- .../components/agents/ToolCallingAgent.py | 3 +- .../components/agents/VectorStoreAgent.py | 3 +- .../agents/VectorStoreRouterAgent.py | 3 +- .../langflow/components/agents/XMLAgent.py | 3 +- .../assemblyai/AssemblyAIGetSubtitles.py | 2 +- .../components/assemblyai/AssemblyAILeMUR.py | 2 +- .../assemblyai/AssemblyAIListTranscripts.py | 2 +- .../assemblyai/AssemblyAIPollTranscript.py | 2 +- .../assemblyai/AssemblyAIStartTranscript.py | 4 +- .../components/deactivated/SubFlow.py | 4 +- .../embeddings/AzureOpenAIEmbeddings.py | 2 +- .../langflow/components/helpers/CSVtoData.py | 4 +- .../components/helpers/CurrentDate.py | 2 +- .../langflow/components/helpers/JSONtoData.py | 4 +- .../components/helpers/MessageToData.py | 2 +- .../components/helpers/SequentialTask.py | 2 +- .../langchain_utilities/SpiderTool.py | 2 +- .../langflow/components/models/AIMLModel.py | 3 +- .../components/models/AmazonBedrockModel.py | 3 +- .../components/models/AnthropicModel.py | 14 ++--- .../components/models/AzureOpenAIModel.py | 5 +- .../models/BaiduQianfanChatModel.py | 7 +-- .../langflow/components/models/CohereModel.py | 3 +- .../models/GoogleGenerativeAIModel.py | 7 +-- .../langflow/components/models/GroqModel.py | 11 ++-- .../components/models/HuggingFaceModel.py | 9 +-- .../langflow/components/models/Maritalk.py | 3 +- .../components/models/MistralModel.py | 9 ++- .../langflow/components/models/NvidiaModel.py | 3 +- .../langflow/components/models/OllamaModel.py | 61 ++++--------------- .../langflow/components/models/OpenAIModel.py | 3 +- .../components/models/PerplexityModel.py | 7 +-- .../components/models/VertexAiModel.py | 3 +- .../components/prototypes/JSONCleaner.py | 4 +- .../components/prototypes/PythonFunction.py | 2 +- .../components/prototypes/RunnableExecutor.py | 4 +- .../langflow/components/prototypes/SubFlow.py | 2 +- .../components/toolkits/ComposioAPI.py | 2 +- .../langflow/components/tools/Calculator.py | 4 +- .../tools/PythonCodeStructuredTool.py | 2 +- .../components/tools/PythonREPLTool.py | 2 +- .../langflow/components/tools/SearXNGTool.py | 4 +- .../base/langflow/components/tools/SerpAPI.py | 2 +- .../components/tools/TavilyAISearch.py | 2 +- .../langflow/components/tools/YfinanceTool.py | 2 +- .../components/vectorstores/AstraDB.py | 6 +- .../components/vectorstores/Cassandra.py | 2 +- .../components/vectorstores/CassandraGraph.py | 2 +- .../components/vectorstores/Elasticsearch.py | 2 +- .../langflow/components/vectorstores/HCD.py | 6 +- .../components/vectorstores/OpenSearch.py | 12 ++-- .../directory_reader/directory_reader.py | 6 +- .../langflow/custom/directory_reader/utils.py | 2 +- src/backend/base/langflow/custom/utils.py | 14 ++--- src/backend/base/langflow/graph/graph/base.py | 8 +-- .../base/langflow/graph/vertex/base.py | 2 +- .../base/langflow/initial_setup/setup.py | 2 +- src/backend/base/langflow/interface/run.py | 8 +-- src/backend/base/langflow/schema/message.py | 8 ++- .../langflow/services/database/service.py | 4 +- .../base/langflow/template/field/base.py | 2 +- src/backend/base/langflow/template/utils.py | 2 +- src/backend/base/langflow/utils/util.py | 2 +- src/backend/base/pyproject.toml | 3 + 86 files changed, 196 insertions(+), 228 deletions(-) diff --git a/src/backend/base/langflow/api/v1/callback.py b/src/backend/base/langflow/api/v1/callback.py index a075e482e..8c3b262b0 100644 --- a/src/backend/base/langflow/api/v1/callback.py +++ b/src/backend/base/langflow/api/v1/callback.py @@ -67,7 +67,7 @@ class AsyncStreamingLLMCallbackHandleSIO(AsyncCallbackHandler): ) for word in rest_of_output ] - resps = [resp] + rest_of_resps + resps = [resp, *rest_of_resps] # Try to send the response, handle potential errors. try: diff --git a/src/backend/base/langflow/api/v1/chat.py b/src/backend/base/langflow/api/v1/chat.py index 03b0d5978..751b61f46 100644 --- a/src/backend/base/langflow/api/v1/chat.py +++ b/src/backend/base/langflow/api/v1/chat.py @@ -409,7 +409,7 @@ async def build_flow( get_time_yield = time.time() client_consumed_queue.put_nowait(event_id) logger.debug( - f"consumed event {str(event_id)} " + f"consumed event {event_id} " f"(time in queue, {get_time - put_time:.4f}, " f"client {get_time_yield - get_time:.4f})" ) diff --git a/src/backend/base/langflow/api/v1/endpoints.py b/src/backend/base/langflow/api/v1/endpoints.py index 7f5e06a48..1038940f5 100644 --- a/src/backend/base/langflow/api/v1/endpoints.py +++ b/src/backend/base/langflow/api/v1/endpoints.py @@ -382,9 +382,9 @@ async def experimental_run_flow( flow_id: UUID, inputs: list[InputValueRequest] | None = None, outputs: list[str] | None = None, - tweaks: Annotated[Tweaks | None, Body(embed=True)] = None, # noqa: F821 - stream: Annotated[bool, Body(embed=True)] = False, # noqa: F821 - session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821 + tweaks: Annotated[Tweaks | None, Body(embed=True)] = None, + stream: Annotated[bool, Body(embed=True)] = False, + session_id: Annotated[None | str, Body(embed=True)] = None, api_key_user: UserRead = Depends(api_key_security), session_service: SessionService = Depends(get_session_service), ): @@ -509,11 +509,11 @@ async def process( flow_id: str, inputs: list[dict] | dict | None = None, tweaks: dict | None = None, - clear_cache: Annotated[bool, Body(embed=True)] = False, # noqa: F821 - session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821 + clear_cache: Annotated[bool, Body(embed=True)] = False, + session_id: Annotated[None | str, Body(embed=True)] = None, task_service: TaskService = Depends(get_task_service), api_key_user: UserRead = Depends(api_key_security), - sync: Annotated[bool, Body(embed=True)] = True, # noqa: F821 + sync: Annotated[bool, Body(embed=True)] = True, session_service: SessionService = Depends(get_session_service), ): """ diff --git a/src/backend/base/langflow/api/v1/flows.py b/src/backend/base/langflow/api/v1/flows.py index f955fe372..b88b5fd99 100644 --- a/src/backend/base/langflow/api/v1/flows.py +++ b/src/backend/base/langflow/api/v1/flows.py @@ -196,7 +196,7 @@ def read_flow( # so write an OR stmt = stmt.where( (Flow.user_id == current_user.id) | (Flow.user_id == None) # noqa - ) # noqa + ) if user_flow := session.exec(stmt).first(): return user_flow raise HTTPException(status_code=404, detail="Flow not found") diff --git a/src/backend/base/langflow/base/agents/agent.py b/src/backend/base/langflow/base/agents/agent.py index c149ef9e3..2e8e3be22 100644 --- a/src/backend/base/langflow/base/agents/agent.py +++ b/src/backend/base/langflow/base/agents/agent.py @@ -102,7 +102,7 @@ class LCAgentComponent(Component): if self.chat_history: input_dict["chat_history"] = data_to_messages(self.chat_history) result = agent.invoke( - input_dict, config={"callbacks": [AgentAsyncHandler(self.log)] + self.get_langchain_callbacks()} + input_dict, config={"callbacks": [AgentAsyncHandler(self.log), *self.get_langchain_callbacks()]} ) self.status = result if "output" not in result: @@ -113,13 +113,9 @@ class LCAgentComponent(Component): class LCToolsAgentComponent(LCAgentComponent): - _base_inputs = LCAgentComponent._base_inputs + [ - HandleInput( - name="tools", - display_name="Tools", - input_types=["Tool", "BaseTool"], - is_list=True, - ), + _base_inputs = [ + *LCAgentComponent._base_inputs, + HandleInput(name="tools", display_name="Tools", input_types=["Tool", "BaseTool"], is_list=True), ] def build_agent(self) -> AgentExecutor: @@ -149,7 +145,7 @@ class LCToolsAgentComponent(LCAgentComponent): input_dict["chat_history"] = data_to_messages(self.chat_history) result = runnable.invoke( - input_dict, config={"callbacks": [AgentAsyncHandler(self.log)] + self.get_langchain_callbacks()} + input_dict, config={"callbacks": [AgentAsyncHandler(self.log), *self.get_langchain_callbacks()]} ) self.status = result if "output" not in result: diff --git a/src/backend/base/langflow/base/flow_processing/utils.py b/src/backend/base/langflow/base/flow_processing/utils.py index 8ed275f09..2b640a81c 100644 --- a/src/backend/base/langflow/base/flow_processing/utils.py +++ b/src/backend/base/langflow/base/flow_processing/utils.py @@ -56,7 +56,7 @@ def build_data_from_result_data(result_data: ResultData, get_final_results_only: data.append(artifact) else: # Warn about unknown output type - logger.warning(f"Unable to build record output from unknown ResultData.artifact: {str(artifact)}") + logger.warning(f"Unable to build record output from unknown ResultData.artifact: {artifact}") # Chat or text output elif result_data.results: data.append(Data(data={"result": result_data.results}, text_key="result")) diff --git a/src/backend/base/langflow/base/models/model.py b/src/backend/base/langflow/base/models/model.py index f5cec67a9..5434a1d08 100644 --- a/src/backend/base/langflow/base/models/model.py +++ b/src/backend/base/langflow/base/models/model.py @@ -157,7 +157,10 @@ class LCModelComponent(Component): if "prompt" in input_value: prompt = input_value.load_lc_prompt() if system_message: - prompt.messages = [SystemMessage(content=system_message)] + prompt.messages + prompt.messages = [ + SystemMessage(content=system_message), + *prompt.messages, # type: ignore[has-type] + ] system_message_added = True runnable = prompt | runnable else: diff --git a/src/backend/base/langflow/base/prompts/api_utils.py b/src/backend/base/langflow/base/prompts/api_utils.py index 7c55eb4f1..02101f055 100644 --- a/src/backend/base/langflow/base/prompts/api_utils.py +++ b/src/backend/base/langflow/base/prompts/api_utils.py @@ -62,7 +62,7 @@ def _fix_variable(var, invalid_chars, wrong_variables): new_var, invalid_chars, wrong_variables = _fix_variable(var[1:], invalid_chars, wrong_variables) # Temporarily replace {{ and }} to avoid treating them as invalid - new_var = new_var.replace("{{", "ᴛᴇᴍᴘᴏᴘᴇɴ").replace("}}", "ᴛᴇᴍᴘᴄʟᴏsᴇ") + new_var = new_var.replace("{{", "ᴛᴇᴍᴘᴏᴘᴇɴ").replace("}}", "ᴛᴇᴍᴘᴄʟᴏsᴇ") # noqa: RUF001 # Remove invalid characters for char in new_var: @@ -73,7 +73,7 @@ def _fix_variable(var, invalid_chars, wrong_variables): wrong_variables.append(var) # Restore {{ and }} - new_var = new_var.replace("ᴛᴇᴍᴘᴏᴘᴇɴ", "{{").replace("ᴛᴇᴍᴘᴄʟᴏsᴇ", "}}") + new_var = new_var.replace("ᴛᴇᴍᴘᴏᴘᴇɴ", "{{").replace("ᴛᴇᴍᴘᴄʟᴏsᴇ", "}}") # noqa: RUF001 return new_var, invalid_chars, wrong_variables @@ -146,7 +146,7 @@ def get_old_custom_fields(custom_fields, name): if len(custom_fields) == 1 and name == "": # If there is only one custom field and the name is empty string # then we are dealing with the first prompt request after the node was created - name = list(custom_fields.keys())[0] + name = next(iter(custom_fields.keys())) old_custom_fields = custom_fields[name] if not old_custom_fields: diff --git a/src/backend/base/langflow/components/Notion/add_content_to_page.py b/src/backend/base/langflow/components/Notion/add_content_to_page.py index c88c10a6b..d7410737f 100644 --- a/src/backend/base/langflow/components/Notion/add_content_to_page.py +++ b/src/backend/base/langflow/components/Notion/add_content_to_page.py @@ -76,12 +76,12 @@ class AddContentToPage(LCToolComponent): return response.json() except requests.exceptions.RequestException as e: - error_message = f"Error: Failed to add content to Notion page. {str(e)}" + error_message = f"Error: Failed to add content to Notion page. {e}" if hasattr(e, "response") and e.response is not None: error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" return error_message except Exception as e: - return f"Error: An unexpected error occurred while adding content to Notion page. {str(e)}" + return f"Error: An unexpected error occurred while adding content to Notion page. {e}" def process_node(self, node): blocks = [] diff --git a/src/backend/base/langflow/components/Notion/create_page.py b/src/backend/base/langflow/components/Notion/create_page.py index d1e3abf30..f35f6306c 100644 --- a/src/backend/base/langflow/components/Notion/create_page.py +++ b/src/backend/base/langflow/components/Notion/create_page.py @@ -67,7 +67,7 @@ class NotionPageCreator(LCToolComponent): try: properties = json.loads(properties_json) except json.JSONDecodeError as e: - return f"Invalid properties format. Please provide a valid JSON string. Error: {str(e)}" + return f"Invalid properties format. Please provide a valid JSON string. Error: {e}" headers = { "Authorization": f"Bearer {self.notion_secret}", @@ -85,7 +85,7 @@ class NotionPageCreator(LCToolComponent): response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: - error_message = f"Failed to create Notion page. Error: {str(e)}" + error_message = f"Failed to create Notion page. Error: {e}" if hasattr(e, "response") and e.response is not None: error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" return error_message 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 393760bbe..acdd4b09b 100644 --- a/src/backend/base/langflow/components/Notion/list_database_properties.py +++ b/src/backend/base/langflow/components/Notion/list_database_properties.py @@ -59,8 +59,8 @@ class NotionDatabaseProperties(LCToolComponent): data = response.json() return data.get("properties", {}) except requests.exceptions.RequestException as e: - return f"Error fetching Notion database properties: {str(e)}" + return f"Error fetching Notion database properties: {e}" except ValueError as e: - return f"Error parsing Notion API response: {str(e)}" + return f"Error parsing Notion API response: {e}" except Exception as e: - return f"An unexpected error occurred: {str(e)}" + return f"An unexpected error occurred: {e}" diff --git a/src/backend/base/langflow/components/Notion/list_pages.py b/src/backend/base/langflow/components/Notion/list_pages.py index 9d47c9635..a8cb846ca 100644 --- a/src/backend/base/langflow/components/Notion/list_pages.py +++ b/src/backend/base/langflow/components/Notion/list_pages.py @@ -105,7 +105,7 @@ class NotionListPages(LCToolComponent): try: query_payload = json.loads(query_json) except json.JSONDecodeError as e: - return f"Invalid JSON format for query: {str(e)}" + return f"Invalid JSON format for query: {e}" try: response = requests.post(url, headers=headers, json=query_payload) @@ -113,8 +113,8 @@ class NotionListPages(LCToolComponent): results = response.json() return results["results"] except requests.exceptions.RequestException as e: - return f"Error querying Notion database: {str(e)}" + return f"Error querying Notion database: {e}" except KeyError: return "Unexpected response format from Notion API" except Exception as e: - return f"An unexpected error occurred: {str(e)}" + return f"An unexpected error occurred: {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 7ab1813bb..6e3b853eb 100644 --- a/src/backend/base/langflow/components/Notion/page_content_viewer.py +++ b/src/backend/base/langflow/components/Notion/page_content_viewer.py @@ -59,12 +59,12 @@ class NotionPageContent(LCToolComponent): blocks_data = blocks_response.json() return self.parse_blocks(blocks_data.get("results", [])) except requests.exceptions.RequestException as e: - error_message = f"Error: Failed to retrieve Notion page content. {str(e)}" + error_message = f"Error: Failed to retrieve Notion page content. {e}" if hasattr(e, "response") and e.response is not None: error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" return error_message except Exception as e: - return f"Error: An unexpected error occurred while retrieving Notion page content. {str(e)}" + return f"Error: An unexpected error occurred while retrieving Notion page content. {e}" def parse_blocks(self, blocks: list) -> str: content = "" 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 76c07a717..40a4ff06b 100644 --- a/src/backend/base/langflow/components/Notion/update_page_property.py +++ b/src/backend/base/langflow/components/Notion/update_page_property.py @@ -76,7 +76,7 @@ class NotionPageUpdate(LCToolComponent): try: parsed_properties = json.loads(properties) except json.JSONDecodeError as e: - error_message = f"Invalid JSON format for properties: {str(e)}" + error_message = f"Invalid JSON format for properties: {e}" logger.error(error_message) return error_message @@ -94,18 +94,18 @@ class NotionPageUpdate(LCToolComponent): logger.info(f"Successfully updated Notion page. Response: {json.dumps(updated_page)}") return updated_page except requests.exceptions.HTTPError as e: - error_message = f"HTTP Error occurred: {str(e)}" + error_message = f"HTTP Error occurred: {e}" if e.response is not None: error_message += f"\nStatus code: {e.response.status_code}" error_message += f"\nResponse body: {e.response.text}" logger.error(error_message) return error_message except requests.exceptions.RequestException as e: - error_message = f"An error occurred while making the request: {str(e)}" + error_message = f"An error occurred while making the request: {e}" logger.error(error_message) return error_message except Exception as e: - error_message = f"An unexpected error occurred: {str(e)}" + error_message = f"An unexpected error occurred: {e}" logger.error(error_message) return error_message diff --git a/src/backend/base/langflow/components/agents/CSVAgent.py b/src/backend/base/langflow/components/agents/CSVAgent.py index c84590fd9..b638a7f76 100644 --- a/src/backend/base/langflow/components/agents/CSVAgent.py +++ b/src/backend/base/langflow/components/agents/CSVAgent.py @@ -14,7 +14,8 @@ class CSVAgentComponent(LCAgentComponent): documentation = "https://python.langchain.com/docs/modules/agents/toolkits/csv" name = "CSVAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput( name="llm", display_name="Language Model", diff --git a/src/backend/base/langflow/components/agents/HierarchicalCrew.py b/src/backend/base/langflow/components/agents/HierarchicalCrew.py index ebaf9680e..e2267bd43 100644 --- a/src/backend/base/langflow/components/agents/HierarchicalCrew.py +++ b/src/backend/base/langflow/components/agents/HierarchicalCrew.py @@ -12,7 +12,8 @@ class HierarchicalCrewComponent(BaseCrewComponent): documentation: str = "https://docs.crewai.com/how-to/Hierarchical/" icon = "CrewAI" - inputs = BaseCrewComponent._base_inputs + [ + inputs = [ + *BaseCrewComponent._base_inputs, HandleInput(name="agents", display_name="Agents", input_types=["Agent"], is_list=True), HandleInput(name="tasks", display_name="Tasks", input_types=["HierarchicalTask"], is_list=True), HandleInput(name="manager_llm", display_name="Manager LLM", input_types=["LanguageModel"], required=False), diff --git a/src/backend/base/langflow/components/agents/JsonAgent.py b/src/backend/base/langflow/components/agents/JsonAgent.py index 38010d871..da6d64aae 100644 --- a/src/backend/base/langflow/components/agents/JsonAgent.py +++ b/src/backend/base/langflow/components/agents/JsonAgent.py @@ -15,7 +15,8 @@ class JsonAgentComponent(LCAgentComponent): description = "Construct a json agent from an LLM and tools." name = "JsonAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), FileInput(name="path", display_name="File Path", file_types=["json", "yaml", "yml"], required=True), ] diff --git a/src/backend/base/langflow/components/agents/OpenAIToolsAgent.py b/src/backend/base/langflow/components/agents/OpenAIToolsAgent.py index 20a6c2e24..e9b925db0 100644 --- a/src/backend/base/langflow/components/agents/OpenAIToolsAgent.py +++ b/src/backend/base/langflow/components/agents/OpenAIToolsAgent.py @@ -14,7 +14,8 @@ class OpenAIToolsAgentComponent(LCToolsAgentComponent): beta = True name = "OpenAIToolsAgent" - inputs = LCToolsAgentComponent._base_inputs + [ + inputs = [ + *LCToolsAgentComponent._base_inputs, HandleInput( name="llm", display_name="Language Model", diff --git a/src/backend/base/langflow/components/agents/OpenAPIAgent.py b/src/backend/base/langflow/components/agents/OpenAPIAgent.py index 50c76c423..1880e8813 100644 --- a/src/backend/base/langflow/components/agents/OpenAPIAgent.py +++ b/src/backend/base/langflow/components/agents/OpenAPIAgent.py @@ -16,7 +16,8 @@ class OpenAPIAgentComponent(LCAgentComponent): description = "Agent to interact with OpenAPI API." name = "OpenAPIAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), FileInput(name="path", display_name="File Path", file_types=["json", "yaml", "yml"], required=True), BoolInput(name="allow_dangerous_requests", display_name="Allow Dangerous Requests", value=False, required=True), diff --git a/src/backend/base/langflow/components/agents/SQLAgent.py b/src/backend/base/langflow/components/agents/SQLAgent.py index f44c86abd..bb0f52c91 100644 --- a/src/backend/base/langflow/components/agents/SQLAgent.py +++ b/src/backend/base/langflow/components/agents/SQLAgent.py @@ -12,7 +12,8 @@ class SQLAgentComponent(LCAgentComponent): description = "Construct an SQL agent from an LLM and tools." name = "SQLAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), MessageTextInput(name="database_uri", display_name="Database URI", required=True), HandleInput( diff --git a/src/backend/base/langflow/components/agents/SequentialCrew.py b/src/backend/base/langflow/components/agents/SequentialCrew.py index df3643337..cbe172f5b 100644 --- a/src/backend/base/langflow/components/agents/SequentialCrew.py +++ b/src/backend/base/langflow/components/agents/SequentialCrew.py @@ -11,7 +11,8 @@ class SequentialCrewComponent(BaseCrewComponent): documentation: str = "https://docs.crewai.com/how-to/Sequential/" icon = "CrewAI" - inputs = BaseCrewComponent._base_inputs + [ + inputs = [ + *BaseCrewComponent._base_inputs, HandleInput(name="tasks", display_name="Tasks", input_types=["SequentialTask"], is_list=True), ] diff --git a/src/backend/base/langflow/components/agents/SequentialTaskAgent.py b/src/backend/base/langflow/components/agents/SequentialTaskAgent.py index 1890f1c76..c2f3442a9 100644 --- a/src/backend/base/langflow/components/agents/SequentialTaskAgent.py +++ b/src/backend/base/langflow/components/agents/SequentialTaskAgent.py @@ -130,9 +130,9 @@ class SequentialTaskAgentComponent(Component): # If there's a previous task, create a list of tasks if self.previous_task: - tasks = self.previous_task + [task] if isinstance(self.previous_task, list) else [self.previous_task, task] + tasks = [*self.previous_task, task] if isinstance(self.previous_task, list) else [self.previous_task, task] else: tasks = [task] - self.status = f"Agent: {repr(agent)}\nTask: {repr(task)}" + self.status = f"Agent: {agent!r}\nTask: {task!r}" return tasks diff --git a/src/backend/base/langflow/components/agents/ToolCallingAgent.py b/src/backend/base/langflow/components/agents/ToolCallingAgent.py index 7abb58b9b..3701d31cc 100644 --- a/src/backend/base/langflow/components/agents/ToolCallingAgent.py +++ b/src/backend/base/langflow/components/agents/ToolCallingAgent.py @@ -14,7 +14,8 @@ class ToolCallingAgentComponent(LCToolsAgentComponent): beta = True name = "ToolCallingAgent" - inputs = LCToolsAgentComponent._base_inputs + [ + inputs = [ + *LCToolsAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), MultilineInput( name="system_prompt", diff --git a/src/backend/base/langflow/components/agents/VectorStoreAgent.py b/src/backend/base/langflow/components/agents/VectorStoreAgent.py index 41aff7212..86f38b313 100644 --- a/src/backend/base/langflow/components/agents/VectorStoreAgent.py +++ b/src/backend/base/langflow/components/agents/VectorStoreAgent.py @@ -10,7 +10,8 @@ class VectorStoreAgentComponent(LCAgentComponent): description = "Construct an agent from a Vector Store." name = "VectorStoreAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput(name="vectorstore", display_name="Vector Store", input_types=["VectorStoreInfo"], required=True), ] diff --git a/src/backend/base/langflow/components/agents/VectorStoreRouterAgent.py b/src/backend/base/langflow/components/agents/VectorStoreRouterAgent.py index bef7f0ada..efea4e08e 100644 --- a/src/backend/base/langflow/components/agents/VectorStoreRouterAgent.py +++ b/src/backend/base/langflow/components/agents/VectorStoreRouterAgent.py @@ -10,7 +10,8 @@ class VectorStoreRouterAgentComponent(LCAgentComponent): description = "Construct an agent from a Vector Store Router." name = "VectorStoreRouterAgent" - inputs = LCAgentComponent._base_inputs + [ + inputs = [ + *LCAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput( name="vectorstores", diff --git a/src/backend/base/langflow/components/agents/XMLAgent.py b/src/backend/base/langflow/components/agents/XMLAgent.py index 54447b22c..5e31b4d13 100644 --- a/src/backend/base/langflow/components/agents/XMLAgent.py +++ b/src/backend/base/langflow/components/agents/XMLAgent.py @@ -13,7 +13,8 @@ class XMLAgentComponent(LCToolsAgentComponent): icon = "LangChain" beta = True name = "XMLAgent" - inputs = LCToolsAgentComponent._base_inputs + [ + inputs = [ + *LCToolsAgentComponent._base_inputs, HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), DataInput(name="chat_history", display_name="Chat History", is_list=True, advanced=True), MultilineInput( diff --git a/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py b/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py index 19436e9e2..4a7992e58 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py @@ -54,7 +54,7 @@ class AssemblyAIGetSubtitles(Component): transcript_id = self.transcription_result.data["id"] transcript = aai.Transcript.get_by_id(transcript_id) except Exception as e: - error = f"Getting transcription failed: {str(e)}" + error = f"Getting transcription failed: {e}" self.status = error return Data(data={"error": error}) diff --git a/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py b/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py index 97068cf79..bd4c80465 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py @@ -135,7 +135,7 @@ class AssemblyAILeMUR(Component): self.status = result return result except Exception as e: - error = f"An Error happened: {str(e)}" + error = f"An Error happened: {e}" self.status = error return Data(data={"error": error}) diff --git a/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py b/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py index 832fcbceb..b19517d05 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py @@ -86,6 +86,6 @@ class AssemblyAIListTranscripts(Component): self.status = transcripts return transcripts except Exception as e: - error_data = Data(data={"error": f"An error occurred: {str(e)}"}) + error_data = Data(data={"error": f"An error occurred: {e}"}) self.status = [error_data] return [error_data] diff --git a/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py b/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py index fd4360b8d..05526f27d 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py @@ -48,7 +48,7 @@ class AssemblyAITranscriptionJobPoller(Component): try: transcript = aai.Transcript.get_by_id(self.transcript_id.data["transcript_id"]) except Exception as e: - error = f"Getting transcription failed: {str(e)}" + error = f"Getting transcription failed: {e}" self.status = error return Data(data={"error": error}) diff --git a/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py b/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py index f474f5c58..62f2f55a0 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py @@ -181,5 +181,5 @@ class AssemblyAITranscriptionJobCreator(Component): 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)}"}) + self.status = f"An error occurred: {e}" + return Data(data={"error": f"An error occurred: {e}"}) diff --git a/src/backend/base/langflow/components/deactivated/SubFlow.py b/src/backend/base/langflow/components/deactivated/SubFlow.py index a2ddbc49e..15173ce66 100644 --- a/src/backend/base/langflow/components/deactivated/SubFlow.py +++ b/src/backend/base/langflow/components/deactivated/SubFlow.py @@ -41,7 +41,7 @@ class SubFlowComponent(CustomComponent): build_config["flow_name"]["options"] = self.get_flow_names() # Clean up the build config for key in list(build_config.keys()): - if key not in self.field_order + ["code", "_type", "get_final_results_only"]: + if key not in [*self.field_order, "code", "_type", "get_final_results_only"]: del build_config[key] if field_value is not None and field_name == "flow_name": try: @@ -55,7 +55,7 @@ class SubFlowComponent(CustomComponent): # Add inputs to the build config build_config = self.add_inputs_to_build_config(inputs, build_config) except Exception as e: - logger.error(f"Error getting flow {field_value}: {str(e)}") + logger.error(f"Error getting flow {field_value}: {e}") return build_config diff --git a/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py b/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py index d5c742c02..cf6fabd91 100644 --- a/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py +++ b/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py @@ -77,7 +77,7 @@ class AzureOpenAIEmbeddingsComponent(LCModelComponent): dimensions=self.dimensions or None, ) except Exception as e: - msg = f"Could not connect to AzureOpenAIEmbeddings API: {str(e)}" + msg = f"Could not connect to AzureOpenAIEmbeddings API: {e}" raise ValueError(msg) from e return embeddings diff --git a/src/backend/base/langflow/components/helpers/CSVtoData.py b/src/backend/base/langflow/components/helpers/CSVtoData.py index 7356133dc..968b5f7a4 100644 --- a/src/backend/base/langflow/components/helpers/CSVtoData.py +++ b/src/backend/base/langflow/components/helpers/CSVtoData.py @@ -82,11 +82,11 @@ class CSVToDataComponent(Component): return result except csv.Error as e: - error_message = f"CSV parsing error: {str(e)}" + error_message = f"CSV parsing error: {e}" self.status = error_message raise ValueError(error_message) from e except Exception as e: - error_message = f"An error occurred: {str(e)}" + error_message = f"An error occurred: {e}" self.status = error_message raise ValueError(error_message) from e diff --git a/src/backend/base/langflow/components/helpers/CurrentDate.py b/src/backend/base/langflow/components/helpers/CurrentDate.py index 915ae07c2..32ed6a84d 100644 --- a/src/backend/base/langflow/components/helpers/CurrentDate.py +++ b/src/backend/base/langflow/components/helpers/CurrentDate.py @@ -68,6 +68,6 @@ class CurrentDateComponent(Component): self.status = result return Message(text=result) except Exception as e: - error_message = f"Error: {str(e)}" + error_message = f"Error: {e}" self.status = error_message return Message(text=error_message) diff --git a/src/backend/base/langflow/components/helpers/JSONtoData.py b/src/backend/base/langflow/components/helpers/JSONtoData.py index 62482501e..50719899e 100644 --- a/src/backend/base/langflow/components/helpers/JSONtoData.py +++ b/src/backend/base/langflow/components/helpers/JSONtoData.py @@ -90,11 +90,11 @@ class JSONToDataComponent(Component): return result except (json.JSONDecodeError, SyntaxError, ValueError) as e: - error_message = f"Invalid JSON or Python literal: {str(e)}" + error_message = f"Invalid JSON or Python literal: {e}" self.status = error_message raise ValueError(error_message) from e except Exception as e: - error_message = f"An error occurred: {str(e)}" + error_message = f"An error occurred: {e}" self.status = error_message raise ValueError(error_message) from e diff --git a/src/backend/base/langflow/components/helpers/MessageToData.py b/src/backend/base/langflow/components/helpers/MessageToData.py index bc13f9fbc..02ff11aed 100644 --- a/src/backend/base/langflow/components/helpers/MessageToData.py +++ b/src/backend/base/langflow/components/helpers/MessageToData.py @@ -35,6 +35,6 @@ class MessageToDataComponent(Component): self.status = "Successfully converted Message to Data" return data except Exception as e: - error_message = f"Error converting Message to Data: {str(e)}" + error_message = f"Error converting Message to Data: {e}" self.status = error_message return Data(data={"error": error_message}) diff --git a/src/backend/base/langflow/components/helpers/SequentialTask.py b/src/backend/base/langflow/components/helpers/SequentialTask.py index 7048a68c7..81add12c6 100644 --- a/src/backend/base/langflow/components/helpers/SequentialTask.py +++ b/src/backend/base/langflow/components/helpers/SequentialTask.py @@ -68,5 +68,5 @@ class SequentialTaskComponent(Component): if isinstance(self.task, list) and all(isinstance(task, SequentialTask) for task in self.task): tasks = self.task + tasks elif isinstance(self.task, SequentialTask): - tasks = [self.task] + tasks + tasks = [self.task, *tasks] return tasks diff --git a/src/backend/base/langflow/components/langchain_utilities/SpiderTool.py b/src/backend/base/langflow/components/langchain_utilities/SpiderTool.py index 7b7800414..8592fa908 100644 --- a/src/backend/base/langflow/components/langchain_utilities/SpiderTool.py +++ b/src/backend/base/langflow/components/langchain_utilities/SpiderTool.py @@ -113,7 +113,7 @@ class SpiderTool(Component): msg = f"Invalid mode: {self.mode}. Must be 'scrape' or 'crawl'." raise ValueError(msg) except Exception as e: - msg = f"Error: {str(e)}" + msg = f"Error: {e}" raise Exception(msg) from e records = [] diff --git a/src/backend/base/langflow/components/models/AIMLModel.py b/src/backend/base/langflow/components/models/AIMLModel.py index 1cf9d25cb..5e4c8edbe 100644 --- a/src/backend/base/langflow/components/models/AIMLModel.py +++ b/src/backend/base/langflow/components/models/AIMLModel.py @@ -23,7 +23,8 @@ class AIMLModelComponent(LCModelComponent): name = "AIMLModel" documentation = "https://docs.aimlapi.com/api-reference" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", diff --git a/src/backend/base/langflow/components/models/AmazonBedrockModel.py b/src/backend/base/langflow/components/models/AmazonBedrockModel.py index 92ebd5a86..1816be570 100644 --- a/src/backend/base/langflow/components/models/AmazonBedrockModel.py +++ b/src/backend/base/langflow/components/models/AmazonBedrockModel.py @@ -11,7 +11,8 @@ class AmazonBedrockComponent(LCModelComponent): icon = "Amazon" name = "AmazonBedrockModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, DropdownInput( name="model_id", display_name="Model ID", diff --git a/src/backend/base/langflow/components/models/AnthropicModel.py b/src/backend/base/langflow/components/models/AnthropicModel.py index c846c3d2e..e71cc2fd6 100644 --- a/src/backend/base/langflow/components/models/AnthropicModel.py +++ b/src/backend/base/langflow/components/models/AnthropicModel.py @@ -12,7 +12,8 @@ class AnthropicModelComponent(LCModelComponent): icon = "Anthropic" name = "AnthropicModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", @@ -32,11 +33,7 @@ class AnthropicModelComponent(LCModelComponent): info="https://python.langchain.com/docs/integrations/chat/anthropic", value="claude-3-5-sonnet-20240620", ), - SecretStrInput( - name="anthropic_api_key", - display_name="Anthropic API Key", - info="Your Anthropic API key.", - ), + SecretStrInput(name="anthropic_api_key", display_name="Anthropic API Key", info="Your Anthropic API key."), FloatInput(name="temperature", display_name="Temperature", value=0.1), MessageTextInput( name="anthropic_api_url", @@ -45,10 +42,7 @@ class AnthropicModelComponent(LCModelComponent): info="Endpoint of the Anthropic API. Defaults to 'https://api.anthropic.com' if not specified.", ), MessageTextInput( - name="prefill", - display_name="Prefill", - info="Prefill text to guide the model's response.", - advanced=True, + name="prefill", display_name="Prefill", info="Prefill text to guide the model's response.", advanced=True ), HandleInput( name="output_parser", diff --git a/src/backend/base/langflow/components/models/AzureOpenAIModel.py b/src/backend/base/langflow/components/models/AzureOpenAIModel.py index a5ff32d57..ac42b22b3 100644 --- a/src/backend/base/langflow/components/models/AzureOpenAIModel.py +++ b/src/backend/base/langflow/components/models/AzureOpenAIModel.py @@ -27,7 +27,8 @@ class AzureChatOpenAIComponent(LCModelComponent): "2024-05-13", ] - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, MessageTextInput( name="azure_endpoint", display_name="Azure Endpoint", @@ -78,7 +79,7 @@ class AzureChatOpenAIComponent(LCModelComponent): streaming=stream, ) except Exception as e: - msg = f"Could not connect to AzureOpenAI API: {str(e)}" + msg = f"Could not connect to AzureOpenAI API: {e}" raise ValueError(msg) from e return output # type: ignore diff --git a/src/backend/base/langflow/components/models/BaiduQianfanChatModel.py b/src/backend/base/langflow/components/models/BaiduQianfanChatModel.py index 8003f5ca4..c7aa591df 100644 --- a/src/backend/base/langflow/components/models/BaiduQianfanChatModel.py +++ b/src/backend/base/langflow/components/models/BaiduQianfanChatModel.py @@ -14,7 +14,8 @@ class QianfanChatEndpointComponent(LCModelComponent): icon = "BaiduQianfan" name = "BaiduQianfanChatModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, DropdownInput( name="model", display_name="Model Name", @@ -64,9 +65,7 @@ class QianfanChatEndpointComponent(LCModelComponent): advanced=True, ), MessageTextInput( - name="endpoint", - display_name="Endpoint", - info="Endpoint of the Qianfan LLM, required if custom model used.", + name="endpoint", display_name="Endpoint", info="Endpoint of the Qianfan LLM, required if custom model used." ), HandleInput( name="output_parser", diff --git a/src/backend/base/langflow/components/models/CohereModel.py b/src/backend/base/langflow/components/models/CohereModel.py index 8ccf0922a..60d5ba3ca 100644 --- a/src/backend/base/langflow/components/models/CohereModel.py +++ b/src/backend/base/langflow/components/models/CohereModel.py @@ -14,7 +14,8 @@ class CohereComponent(LCModelComponent): icon = "Cohere" name = "CohereModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, SecretStrInput( name="cohere_api_key", display_name="Cohere API Key", diff --git a/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py b/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py index bca14f4e9..7fb872f12 100644 --- a/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py +++ b/src/backend/base/langflow/components/models/GoogleGenerativeAIModel.py @@ -12,11 +12,10 @@ class GoogleGenerativeAIComponent(LCModelComponent): icon = "GoogleGenerativeAI" name = "GoogleGenerativeAIModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( - name="max_output_tokens", - display_name="Max Output Tokens", - info="The maximum number of tokens to generate.", + name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate." ), DropdownInput( name="model", diff --git a/src/backend/base/langflow/components/models/GroqModel.py b/src/backend/base/langflow/components/models/GroqModel.py index 8770a9a10..73ff7a090 100644 --- a/src/backend/base/langflow/components/models/GroqModel.py +++ b/src/backend/base/langflow/components/models/GroqModel.py @@ -14,12 +14,9 @@ class GroqModel(LCModelComponent): icon = "Groq" name = "GroqModel" - inputs = LCModelComponent._base_inputs + [ - SecretStrInput( - name="groq_api_key", - display_name="Groq API Key", - info="API key for the Groq API.", - ), + inputs = [ + *LCModelComponent._base_inputs, + SecretStrInput(name="groq_api_key", display_name="Groq API Key", info="API key for the Groq API."), MessageTextInput( name="groq_api_base", display_name="Groq API Base", @@ -75,7 +72,7 @@ class GroqModel(LCModelComponent): model_list = response.json() return [model["id"] for model in model_list.get("data", [])] except requests.RequestException as e: - self.status = f"Error fetching models: {str(e)}" + self.status = f"Error fetching models: {e}" return [] def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None): diff --git a/src/backend/base/langflow/components/models/HuggingFaceModel.py b/src/backend/base/langflow/components/models/HuggingFaceModel.py index 0fa037eed..63da512cc 100644 --- a/src/backend/base/langflow/components/models/HuggingFaceModel.py +++ b/src/backend/base/langflow/components/models/HuggingFaceModel.py @@ -17,12 +17,9 @@ class HuggingFaceEndpointsComponent(LCModelComponent): icon = "HuggingFace" name = "HuggingFaceModel" - inputs = LCModelComponent._base_inputs + [ - StrInput( - name="model_id", - display_name="Model ID", - value="openai-community/gpt2", - ), + inputs = [ + *LCModelComponent._base_inputs, + StrInput(name="model_id", display_name="Model ID", value="openai-community/gpt2"), StrInput( name="inference_endpoint", display_name="Inference Endpoint", diff --git a/src/backend/base/langflow/components/models/Maritalk.py b/src/backend/base/langflow/components/models/Maritalk.py index 5e6dd9e38..80b37d2de 100644 --- a/src/backend/base/langflow/components/models/Maritalk.py +++ b/src/backend/base/langflow/components/models/Maritalk.py @@ -12,7 +12,8 @@ class MaritalkModelComponent(LCModelComponent): description = "Generates text using Maritalk LLMs." icon = "Maritalk" name = "Maritalk" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", diff --git a/src/backend/base/langflow/components/models/MistralModel.py b/src/backend/base/langflow/components/models/MistralModel.py index 611bf58cf..86fd3e1c7 100644 --- a/src/backend/base/langflow/components/models/MistralModel.py +++ b/src/backend/base/langflow/components/models/MistralModel.py @@ -13,7 +13,8 @@ class MistralAIModelComponent(LCModelComponent): icon = "MistralAI" name = "MistralModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", @@ -38,10 +39,8 @@ class MistralAIModelComponent(LCModelComponent): name="mistral_api_base", display_name="Mistral API Base", advanced=True, - info=( - "The base URL of the Mistral API. Defaults to https://api.mistral.ai/v1. " - "You can change this to use other APIs like JinaChat, LocalAI and Prem." - ), + info="The base URL of the Mistral API. Defaults to https://api.mistral.ai/v1. " + "You can change this to use other APIs like JinaChat, LocalAI and Prem.", ), SecretStrInput( name="api_key", diff --git a/src/backend/base/langflow/components/models/NvidiaModel.py b/src/backend/base/langflow/components/models/NvidiaModel.py index 89b568aa2..6e6fff6b1 100644 --- a/src/backend/base/langflow/components/models/NvidiaModel.py +++ b/src/backend/base/langflow/components/models/NvidiaModel.py @@ -12,7 +12,8 @@ class NVIDIAModelComponent(LCModelComponent): description = "Generates text using NVIDIA LLMs." icon = "NVIDIA" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", diff --git a/src/backend/base/langflow/components/models/OllamaModel.py b/src/backend/base/langflow/components/models/OllamaModel.py index dede3ba7e..a5bdaa880 100644 --- a/src/backend/base/langflow/components/models/OllamaModel.py +++ b/src/backend/base/langflow/components/models/OllamaModel.py @@ -69,7 +69,8 @@ class ChatOllamaComponent(LCModelComponent): msg = "Could not retrieve models. Please, make sure Ollama is running." raise ValueError(msg) from e - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, StrInput( name="base_url", display_name="Base URL", @@ -90,17 +91,9 @@ class ChatOllamaComponent(LCModelComponent): info="Controls the creativity of model responses.", ), StrInput( - name="format", - display_name="Format", - info="Specify the format of the output (e.g., json).", - advanced=True, - ), - DictInput( - name="metadata", - display_name="Metadata", - info="Metadata to add to the run trace.", - advanced=True, + name="format", display_name="Format", info="Specify the format of the output (e.g., json).", advanced=True ), + DictInput(name="metadata", display_name="Metadata", info="Metadata to add to the run trace.", advanced=True), DropdownInput( name="mirostat", display_name="Mirostat", @@ -152,35 +145,13 @@ class ChatOllamaComponent(LCModelComponent): info="Penalty for repetitions in generated text. (Default: 1.1)", advanced=True, ), - FloatInput( - name="tfs_z", - display_name="TFS Z", - info="Tail free sampling value. (Default: 1)", - advanced=True, - ), + FloatInput(name="tfs_z", display_name="TFS Z", info="Tail free sampling value. (Default: 1)", advanced=True), + IntInput(name="timeout", display_name="Timeout", info="Timeout for the request stream.", advanced=True), IntInput( - name="timeout", - display_name="Timeout", - info="Timeout for the request stream.", - advanced=True, - ), - IntInput( - name="top_k", - display_name="Top K", - info="Limits token selection to top K. (Default: 40)", - advanced=True, - ), - FloatInput( - name="top_p", - display_name="Top P", - info="Works together with top-k. (Default: 0.9)", - advanced=True, - ), - BoolInput( - name="verbose", - display_name="Verbose", - info="Whether to print out response text.", + name="top_k", display_name="Top K", info="Limits token selection to top K. (Default: 40)", advanced=True ), + FloatInput(name="top_p", display_name="Top P", info="Works together with top-k. (Default: 0.9)", advanced=True), + BoolInput(name="verbose", display_name="Verbose", info="Whether to print out response text."), StrInput( name="tags", display_name="Tags", @@ -193,18 +164,8 @@ class ChatOllamaComponent(LCModelComponent): info="Comma-separated list of tokens to signal the model to stop generating text.", advanced=True, ), - StrInput( - name="system", - display_name="System", - info="System to use for generating text.", - advanced=True, - ), - StrInput( - name="template", - display_name="Template", - info="Template to use for generating text.", - advanced=True, - ), + StrInput(name="system", display_name="System", info="System to use for generating text.", advanced=True), + StrInput(name="template", display_name="Template", info="Template to use for generating text.", advanced=True), HandleInput( name="output_parser", display_name="Output Parser", diff --git a/src/backend/base/langflow/components/models/OpenAIModel.py b/src/backend/base/langflow/components/models/OpenAIModel.py index 6d585af3d..e849c349d 100644 --- a/src/backend/base/langflow/components/models/OpenAIModel.py +++ b/src/backend/base/langflow/components/models/OpenAIModel.py @@ -26,7 +26,8 @@ class OpenAIModelComponent(LCModelComponent): icon = "OpenAI" name = "OpenAIModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, IntInput( name="max_tokens", display_name="Max Tokens", diff --git a/src/backend/base/langflow/components/models/PerplexityModel.py b/src/backend/base/langflow/components/models/PerplexityModel.py index dabb671d0..a1adc50e2 100644 --- a/src/backend/base/langflow/components/models/PerplexityModel.py +++ b/src/backend/base/langflow/components/models/PerplexityModel.py @@ -14,7 +14,8 @@ class PerplexityComponent(LCModelComponent): icon = "Perplexity" name = "PerplexityModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, DropdownInput( name="model_name", display_name="Model Name", @@ -31,9 +32,7 @@ class PerplexityComponent(LCModelComponent): value="llama-3.1-sonar-small-128k-online", ), IntInput( - name="max_output_tokens", - display_name="Max Output Tokens", - info="The maximum number of tokens to generate.", + name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate." ), SecretStrInput( name="api_key", diff --git a/src/backend/base/langflow/components/models/VertexAiModel.py b/src/backend/base/langflow/components/models/VertexAiModel.py index 2c7beee2b..638d9eb6d 100644 --- a/src/backend/base/langflow/components/models/VertexAiModel.py +++ b/src/backend/base/langflow/components/models/VertexAiModel.py @@ -13,7 +13,8 @@ class ChatVertexAIComponent(LCModelComponent): icon = "VertexAI" name = "VertexAiModel" - inputs = LCModelComponent._base_inputs + [ + inputs = [ + *LCModelComponent._base_inputs, FileInput( name="credentials", display_name="Credentials", diff --git a/src/backend/base/langflow/components/prototypes/JSONCleaner.py b/src/backend/base/langflow/components/prototypes/JSONCleaner.py index 6f98b44c5..f3426d07c 100644 --- a/src/backend/base/langflow/components/prototypes/JSONCleaner.py +++ b/src/backend/base/langflow/components/prototypes/JSONCleaner.py @@ -78,7 +78,7 @@ class JSONCleaner(Component): self.status = result return Message(text=result) except Exception as e: - msg = f"Error cleaning JSON string: {str(e)}" + msg = f"Error cleaning JSON string: {e}" raise ValueError(msg) from e def _remove_control_characters(self, s: str) -> str: @@ -95,5 +95,5 @@ class JSONCleaner(Component): json.loads(s) return s except json.JSONDecodeError as e: - msg = f"Invalid JSON string: {str(e)}" + msg = f"Invalid JSON string: {e}" raise ValueError(msg) from e diff --git a/src/backend/base/langflow/components/prototypes/PythonFunction.py b/src/backend/base/langflow/components/prototypes/PythonFunction.py index 4944ed928..0105ed1d0 100644 --- a/src/backend/base/langflow/components/prototypes/PythonFunction.py +++ b/src/backend/base/langflow/components/prototypes/PythonFunction.py @@ -55,7 +55,7 @@ class PythonFunctionComponent(Component): func = get_function(function_code) return func() except Exception as e: - return f"Error executing function: {str(e)}" + return f"Error executing function: {e}" def execute_function_data(self) -> list[Data]: results = self.execute_function() diff --git a/src/backend/base/langflow/components/prototypes/RunnableExecutor.py b/src/backend/base/langflow/components/prototypes/RunnableExecutor.py index 2c251e446..804481b42 100644 --- a/src/backend/base/langflow/components/prototypes/RunnableExecutor.py +++ b/src/backend/base/langflow/components/prototypes/RunnableExecutor.py @@ -68,14 +68,14 @@ class RunnableExecComponent(Component): result_value = result.get(output_key) elif len(result) == 2 and input_key in result: # get the other key from the result dict - other_key = [k for k in result if k != input_key][0] + other_key = next(k for k in result if k != input_key) if other_key == output_key: result_value = result.get(output_key) else: status += f"Warning: The output key is not '{output_key}'. The output key is '{other_key}'." result_value = result.get(other_key) elif len(result) == 1: - result_value = list(result.values())[0] + result_value = next(iter(result.values())) elif any(k in result for k in possible_output_keys): for key in possible_output_keys: if key in result: diff --git a/src/backend/base/langflow/components/prototypes/SubFlow.py b/src/backend/base/langflow/components/prototypes/SubFlow.py index 22b6b668e..03b77e262 100644 --- a/src/backend/base/langflow/components/prototypes/SubFlow.py +++ b/src/backend/base/langflow/components/prototypes/SubFlow.py @@ -47,7 +47,7 @@ class SubFlowComponent(Component): # Add inputs to the build config build_config = self.add_inputs_to_build_config(inputs, build_config) except Exception as e: - logger.error(f"Error getting flow {field_value}: {str(e)}") + logger.error(f"Error getting flow {field_value}: {e}") return build_config diff --git a/src/backend/base/langflow/components/toolkits/ComposioAPI.py b/src/backend/base/langflow/components/toolkits/ComposioAPI.py index 53084f21b..f9fb811ef 100644 --- a/src/backend/base/langflow/components/toolkits/ComposioAPI.py +++ b/src/backend/base/langflow/components/toolkits/ComposioAPI.py @@ -86,7 +86,7 @@ class ComposioAPIComponent(LCToolComponent): return self._process_api_key_auth(entity, app) return self._initiate_default_connection(entity, app) except Exception as exc: - logger.error(f"Authorization error: {str(exc)}") + logger.error(f"Authorization error: {exc}") return "Error" def _process_api_key_auth(self, entity: Any, app: str) -> str: diff --git a/src/backend/base/langflow/components/tools/Calculator.py b/src/backend/base/langflow/components/tools/Calculator.py index d309c2e6b..ac27e9099 100644 --- a/src/backend/base/langflow/components/tools/Calculator.py +++ b/src/backend/base/langflow/components/tools/Calculator.py @@ -69,7 +69,7 @@ class CalculatorToolComponent(LCToolComponent): return [Data(data={"result": formatted_result})] except (SyntaxError, TypeError, KeyError) as e: - error_message = f"Invalid expression: {str(e)}" + error_message = f"Invalid expression: {e}" self.status = error_message return [Data(data={"error": error_message})] except ZeroDivisionError: @@ -77,6 +77,6 @@ class CalculatorToolComponent(LCToolComponent): self.status = error_message return [Data(data={"error": error_message})] except Exception as e: - error_message = f"Error: {str(e)}" + error_message = f"Error: {e}" self.status = error_message return [Data(data={"error": error_message})] diff --git a/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py b/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py index 295eb2004..c27632619 100644 --- a/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py +++ b/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py @@ -120,7 +120,7 @@ class PythonCodeStructuredTool(LCToolComponent): build_config["_classes"]["value"] = json.dumps(classes) build_config["tool_function"]["options"] = names except Exception as e: - self.status = f"Failed to extract names: {str(e)}" + self.status = f"Failed to extract names: {e}" build_config["tool_function"]["options"] = ["Failed to parse", str(e)] return build_config diff --git a/src/backend/base/langflow/components/tools/PythonREPLTool.py b/src/backend/base/langflow/components/tools/PythonREPLTool.py index 1b4040b0a..eb501cfd6 100644 --- a/src/backend/base/langflow/components/tools/PythonREPLTool.py +++ b/src/backend/base/langflow/components/tools/PythonREPLTool.py @@ -74,7 +74,7 @@ class PythonREPLToolComponent(LCToolComponent): try: return python_repl.run(code) except Exception as e: - return f"Error: {str(e)}" + return f"Error: {e}" tool = StructuredTool.from_function( name=self.name, diff --git a/src/backend/base/langflow/components/tools/SearXNGTool.py b/src/backend/base/langflow/components/tools/SearXNGTool.py index 8d7016ccc..a6a4bb3f0 100644 --- a/src/backend/base/langflow/components/tools/SearXNGTool.py +++ b/src/backend/base/langflow/components/tools/SearXNGTool.py @@ -75,7 +75,7 @@ class SearXNGToolComponent(LCToolComponent): languages.append(language) build_config["language"]["options"] = languages.copy() except Exception as e: - self.status = f"Failed to extract names: {str(e)}" + self.status = f"Failed to extract names: {e}" build_config["categories"]["options"] = ["Failed to parse", str(e)] return build_config @@ -113,7 +113,7 @@ class SearXNGToolComponent(LCToolComponent): results.append(response["results"][i]) return results except Exception as e: - return [f"Failed to search: {str(e)}"] + return [f"Failed to search: {e}"] SearxSearch._url = self.url SearxSearch._categories = self.categories.copy() diff --git a/src/backend/base/langflow/components/tools/SerpAPI.py b/src/backend/base/langflow/components/tools/SerpAPI.py index 9fea66ff5..6adef8a9e 100644 --- a/src/backend/base/langflow/components/tools/SerpAPI.py +++ b/src/backend/base/langflow/components/tools/SerpAPI.py @@ -88,5 +88,5 @@ class SerpAPIComponent(LCToolComponent): self.status = data_list return data_list except Exception as e: - self.status = f"Error: {str(e)}" + self.status = f"Error: {e}" return [Data(data={"error": str(e)}, text=str(e))] diff --git a/src/backend/base/langflow/components/tools/TavilyAISearch.py b/src/backend/base/langflow/components/tools/TavilyAISearch.py index 577e16d65..e2ae170a6 100644 --- a/src/backend/base/langflow/components/tools/TavilyAISearch.py +++ b/src/backend/base/langflow/components/tools/TavilyAISearch.py @@ -155,6 +155,6 @@ Note: Check 'Advanced' for all options. self.status = error_message return [Data(data={"error": error_message})] except Exception as e: - error_message = f"Unexpected error: {str(e)}" + error_message = f"Unexpected error: {e}" self.status = error_message return [Data(data={"error": error_message})] diff --git a/src/backend/base/langflow/components/tools/YfinanceTool.py b/src/backend/base/langflow/components/tools/YfinanceTool.py index b32850e98..53305d660 100644 --- a/src/backend/base/langflow/components/tools/YfinanceTool.py +++ b/src/backend/base/langflow/components/tools/YfinanceTool.py @@ -96,6 +96,6 @@ class YfinanceToolComponent(LCToolComponent): return data_list except Exception as e: - error_message = f"Error retrieving data: {str(e)}" + error_message = f"Error retrieving data: {e}" self.status = error_message return [Data(data={"error": error_message})] diff --git a/src/backend/base/langflow/components/vectorstores/AstraDB.py b/src/backend/base/langflow/components/vectorstores/AstraDB.py index c7ebb77fa..cfcef1fa4 100644 --- a/src/backend/base/langflow/components/vectorstores/AstraDB.py +++ b/src/backend/base/langflow/components/vectorstores/AstraDB.py @@ -427,7 +427,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent): try: vector_store = AstraDBVectorStore(**vector_store_kwargs) except Exception as e: - msg = f"Error initializing AstraDBVectorStore: {str(e)}" + msg = f"Error initializing AstraDBVectorStore: {e}" raise ValueError(msg) from e self._add_documents_to_vector_store(vector_store) @@ -448,7 +448,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent): try: vector_store.add_documents(documents) except Exception as e: - msg = f"Error adding documents to AstraDBVectorStore: {str(e)}" + msg = f"Error adding documents to AstraDBVectorStore: {e}" raise ValueError(msg) from e else: logger.debug("No documents to add to the Vector Store.") @@ -487,7 +487,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent): docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args) except Exception as e: - msg = f"Error performing search in AstraDBVectorStore: {str(e)}" + msg = f"Error performing search in AstraDBVectorStore: {e}" raise ValueError(msg) from e logger.debug(f"Retrieved documents: {len(docs)}") diff --git a/src/backend/base/langflow/components/vectorstores/Cassandra.py b/src/backend/base/langflow/components/vectorstores/Cassandra.py index 19ab2eb18..c4abfe4c7 100644 --- a/src/backend/base/langflow/components/vectorstores/Cassandra.py +++ b/src/backend/base/langflow/components/vectorstores/Cassandra.py @@ -225,7 +225,7 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent): search_type = self._map_search_type() search_args = self._build_search_args() - logger.debug(f"Search args: {str(search_args)}") + logger.debug(f"Search args: {search_args}") docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args) except KeyError as e: diff --git a/src/backend/base/langflow/components/vectorstores/CassandraGraph.py b/src/backend/base/langflow/components/vectorstores/CassandraGraph.py index 557da2c24..402e54b3d 100644 --- a/src/backend/base/langflow/components/vectorstores/CassandraGraph.py +++ b/src/backend/base/langflow/components/vectorstores/CassandraGraph.py @@ -204,7 +204,7 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent): search_type = self._map_search_type() search_args = self._build_search_args() - logger.debug(f"Search args: {str(search_args)}") + logger.debug(f"Search args: {search_args}") docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args) except KeyError as e: diff --git a/src/backend/base/langflow/components/vectorstores/Elasticsearch.py b/src/backend/base/langflow/components/vectorstores/Elasticsearch.py index 2412b415d..ee98771d9 100644 --- a/src/backend/base/langflow/components/vectorstores/Elasticsearch.py +++ b/src/backend/base/langflow/components/vectorstores/Elasticsearch.py @@ -198,7 +198,7 @@ class ElasticsearchVectorStoreComponent(LCVectorStoreComponent): msg = f"Invalid search type: {self.search_type}" raise ValueError(msg) except Exception as e: - logger.error(f"Search query failed: {str(e)}") + logger.error(f"Search query failed: {e}") msg = ( "Error occurred while querying the Elasticsearch VectorStore," " there is no Data into the VectorStore." diff --git a/src/backend/base/langflow/components/vectorstores/HCD.py b/src/backend/base/langflow/components/vectorstores/HCD.py index 78580d877..679f376d7 100644 --- a/src/backend/base/langflow/components/vectorstores/HCD.py +++ b/src/backend/base/langflow/components/vectorstores/HCD.py @@ -247,7 +247,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent): try: vector_store = AstraDBVectorStore(**vector_store_kwargs) except Exception as e: - msg = f"Error initializing AstraDBVectorStore: {str(e)}" + msg = f"Error initializing AstraDBVectorStore: {e}" raise ValueError(msg) from e self._add_documents_to_vector_store(vector_store) @@ -267,7 +267,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent): try: vector_store.add_documents(documents) except Exception as e: - msg = f"Error adding documents to AstraDBVectorStore: {str(e)}" + msg = f"Error adding documents to AstraDBVectorStore: {e}" raise ValueError(msg) from e else: logger.debug("No documents to add to the Vector Store.") @@ -305,7 +305,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent): docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args) except Exception as e: - msg = f"Error performing search in AstraDBVectorStore: {str(e)}" + msg = f"Error performing search in AstraDBVectorStore: {e}" raise ValueError(msg) from e logger.debug(f"Retrieved documents: {len(docs)}") diff --git a/src/backend/base/langflow/components/vectorstores/OpenSearch.py b/src/backend/base/langflow/components/vectorstores/OpenSearch.py index 8e351724d..649989e23 100644 --- a/src/backend/base/langflow/components/vectorstores/OpenSearch.py +++ b/src/backend/base/langflow/components/vectorstores/OpenSearch.py @@ -124,7 +124,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): try: from langchain_community.vectorstores import OpenSearchVectorSearch except ImportError as e: - error_message = f"Failed to import required modules: {str(e)}" + error_message = f"Failed to import required modules: {e}" logger.error(error_message) raise ImportError(error_message) from e @@ -140,7 +140,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): ssl_show_warn=False, ) except Exception as e: - error_message = f"Failed to create OpenSearchVectorSearch instance: {str(e)}" + error_message = f"Failed to create OpenSearchVectorSearch instance: {e}" logger.error(error_message) raise RuntimeError(error_message) from e @@ -167,7 +167,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): try: vector_store.add_documents(documents) except Exception as e: - error_message = f"Error adding documents to Vector Store: {str(e)}" + error_message = f"Error adding documents to Vector Store: {e}" logger.error(error_message) logger.error(f"Traceback: {traceback.format_exc()}") raise RuntimeError(error_message) from e @@ -187,7 +187,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): try: hybrid_query = json.loads(self.hybrid_search_query) except json.JSONDecodeError as e: - error_message = f"Invalid hybrid search query JSON: {str(e)}" + error_message = f"Invalid hybrid search query JSON: {e}" logger.error(error_message) raise ValueError(error_message) from e @@ -236,7 +236,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): raise ValueError(error_message) except Exception as e: - error_message = f"Error during search: {str(e)}" + error_message = f"Error during search: {e}" logger.error(error_message) logger.error(f"Traceback: {traceback.format_exc()}") raise RuntimeError(error_message) from e @@ -259,7 +259,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent): self.status = retrieved_data return retrieved_data except Exception as e: - error_message = f"Error during document search: {str(e)}" + error_message = f"Error during document search: {e}" logger.error(error_message) logger.error(f"Traceback: {traceback.format_exc()}") raise RuntimeError(error_message) from e 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 42092e3c1..bbd18ceb7 100644 --- a/src/backend/base/langflow/custom/directory_reader/directory_reader.py +++ b/src/backend/base/langflow/custom/directory_reader/directory_reader.py @@ -217,7 +217,7 @@ class DirectoryReader: file_content = self.read_file_content(file_path) except Exception as exc: logger.exception(exc) - logger.error(f"Error while reading file {file_path}: {str(exc)}") + logger.error(f"Error while reading file {file_path}: {exc}") return False, f"Could not read {file_path}" if file_content is None: @@ -294,7 +294,7 @@ class DirectoryReader: file_content = self.read_file_content(file_path) except Exception as exc: logger.exception(exc) - logger.error(f"Error while reading file {file_path}: {str(exc)}") + logger.error(f"Error while reading file {file_path}: {exc}") return False, f"Could not read {file_path}" if file_content is None: @@ -347,7 +347,7 @@ class DirectoryReader: try: output_types = await self.get_output_types_from_code_async(result_content) except Exception as exc: - logger.error(f"Error while getting output types from code: {str(exc)}") + logger.error(f"Error while getting output types from code: {exc}") output_types = [component_name_camelcase] else: output_types = [component_name_camelcase] diff --git a/src/backend/base/langflow/custom/directory_reader/utils.py b/src/backend/base/langflow/custom/directory_reader/utils.py index 331b72d2a..9bb963f46 100644 --- a/src/backend/base/langflow/custom/directory_reader/utils.py +++ b/src/backend/base/langflow/custom/directory_reader/utils.py @@ -133,7 +133,7 @@ def build_invalid_menu_items(menu_item): menu_items[component_name] = component_template logger.debug(f"Added {component_name} to invalid menu.") except Exception as exc: - logger.exception(f"Error while creating custom component [{component_name}]: {str(exc)}") + logger.exception(f"Error while creating custom component [{component_name}]: {exc}") return menu_items diff --git a/src/backend/base/langflow/custom/utils.py b/src/backend/base/langflow/custom/utils.py index c5b78e59e..45ca553c5 100644 --- a/src/backend/base/langflow/custom/utils.py +++ b/src/backend/base/langflow/custom/utils.py @@ -273,7 +273,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI msg = "Invalid code type" raise ValueError(msg) except Exception as exc: - logger.error(f"Error while evaluating custom component code: {str(exc)}") + logger.error(f"Error while evaluating custom component code: {exc}") raise HTTPException( status_code=400, detail={ @@ -285,7 +285,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI try: 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)}") + logger.error(f"Error while instantiating custom component: {exc}") if hasattr(exc, "detail") and "traceback" in exc.detail: logger.error(exc.detail["traceback"]) @@ -308,7 +308,7 @@ def run_build_config( msg = "Invalid code type" raise ValueError(msg) except Exception as exc: - logger.error(f"Error while evaluating custom component code: {str(exc)}") + logger.error(f"Error while evaluating custom component code: {exc}") raise HTTPException( status_code=400, detail={ @@ -333,7 +333,7 @@ def run_build_config( return build_config, custom_instance except Exception as exc: - logger.error(f"Error while building field config: {str(exc)}") + logger.error(f"Error while building field config: {exc}") if hasattr(exc, "detail") and "traceback" in exc.detail: logger.error(exc.detail["traceback"]) @@ -423,7 +423,7 @@ def build_custom_component_template( raise HTTPException( status_code=400, detail={ - "error": (f"Error building Component: {str(exc)}"), + "error": (f"Error building Component: {exc}"), "traceback": traceback.format_exc(), }, ) from exc @@ -521,8 +521,8 @@ def update_field_dict( ) build_config = dd_build_config except Exception as exc: - logger.error(f"Error while running update_build_config: {str(exc)}") - msg = f"Error while running update_build_config: {str(exc)}" + logger.error(f"Error while running update_build_config: {exc}") + msg = f"Error while running update_build_config: {exc}" raise UpdateBuildConfigError(msg) from exc return build_config diff --git a/src/backend/base/langflow/graph/graph/base.py b/src/backend/base/langflow/graph/graph/base.py index 07839b472..84a116f63 100644 --- a/src/backend/base/langflow/graph/graph/base.py +++ b/src/backend/base/langflow/graph/graph/base.py @@ -452,7 +452,7 @@ class Graph: # and run self.build_adjacency_maps(edges) to get the new predecessor map # that is not complete but we can use to update the run_predecessors edges_set = set() - for _vertex in [vertex] + successors: + for _vertex in [vertex, *successors]: edges_set.update(_vertex.edges) if _vertex.state == VertexStates.INACTIVE: _vertex.set_state("ACTIVE") @@ -1013,7 +1013,7 @@ class Graph: Creates a graph from a payload. Args: - payload (Dict): The payload to create the graph from.˜` + payload (Dict): The payload to create the graph from.` Returns: Graph: The created graph. @@ -1617,7 +1617,7 @@ class Graph: successors_result.append([successor]) if not flat and successors_result: - return [successors] + successors_result + return [successors, *successors_result] return successors_result @@ -1893,7 +1893,7 @@ class Graph: if not chat_inputs_first: return vertices_layers - return [chat_inputs_first] + 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.""" diff --git a/src/backend/base/langflow/graph/vertex/base.py b/src/backend/base/langflow/graph/vertex/base.py index f0e4f2b80..1b6677767 100644 --- a/src/backend/base/langflow/graph/vertex/base.py +++ b/src/backend/base/langflow/graph/vertex/base.py @@ -682,7 +682,7 @@ class Vertex: logger.exception(e) msg = ( f"Params {key} ({self.params[key]}) is not a list and cannot be extended with {result}" - f"Error building Component {self.display_name}: \n\n{str(e)}" + f"Error building Component {self.display_name}: \n\n{e}" ) raise ValueError(msg) from e diff --git a/src/backend/base/langflow/initial_setup/setup.py b/src/backend/base/langflow/initial_setup/setup.py index abbbeffa5..9f440b027 100644 --- a/src/backend/base/langflow/initial_setup/setup.py +++ b/src/backend/base/langflow/initial_setup/setup.py @@ -161,7 +161,7 @@ def update_new_output(data): new_source_handle["output_types"] = new_source_handle["baseClasses"] del new_source_handle["baseClasses"] - if "inputTypes" in new_target_handle and new_target_handle["inputTypes"]: + if new_target_handle.get("inputTypes"): intersection = [ type_ for type_ in new_source_handle["output_types"] if type_ in new_target_handle["inputTypes"] ] diff --git a/src/backend/base/langflow/interface/run.py b/src/backend/base/langflow/interface/run.py index e65b9d450..6cd54f3b2 100644 --- a/src/backend/base/langflow/interface/run.py +++ b/src/backend/base/langflow/interface/run.py @@ -24,17 +24,17 @@ def update_memory_keys(langchain_object, possible_new_mem_key): object's memory attribute to exclude the current memory key and the possible new key. It then sets the memory key to the possible new key. """ - input_key = [ + input_key = next( key for key in langchain_object.input_keys if key not in [langchain_object.memory.memory_key, possible_new_mem_key] - ][0] + ) - output_key = [ + output_key = next( key for key in langchain_object.output_keys if key not in [langchain_object.memory.memory_key, possible_new_mem_key] - ][0] + ) for key, attr in [(input_key, "input_key"), (output_key, "output_key"), (possible_new_mem_key, "memory_key")]: try: diff --git a/src/backend/base/langflow/schema/message.py b/src/backend/base/langflow/schema/message.py index fb501d7b0..01a5b7973 100644 --- a/src/backend/base/langflow/schema/message.py +++ b/src/backend/base/langflow/schema/message.py @@ -1,3 +1,5 @@ +from __future__ import annotations + import asyncio import json from collections.abc import AsyncIterator, Iterator @@ -119,7 +121,7 @@ class Message(Data): return AIMessage(content=text) # type: ignore @classmethod - def from_lc_message(cls, lc_message: BaseMessage) -> "Message": + def from_lc_message(cls, lc_message: BaseMessage) -> Message: if lc_message.type == "human": sender = MESSAGE_SENDER_USER sender_name = MESSAGE_SENDER_NAME_USER @@ -136,7 +138,7 @@ class Message(Data): return cls(text=lc_message.content, sender=sender, sender_name=sender_name) @classmethod - def from_data(cls, data: "Data") -> "Message": + def from_data(cls, data: Data) -> Message: """ Converts a BaseMessage to a Data. @@ -231,7 +233,7 @@ class Message(Data): content_dicts = await value.get_file_content_dicts() contents.extend(content_dicts) if contents: - message = HumanMessage(content=[{"type": "text", "text": text}] + contents) + message = HumanMessage(content=[{"type": "text", "text": text}, *contents]) prompt_template = ChatPromptTemplate.from_messages([message]) # type: ignore diff --git a/src/backend/base/langflow/services/database/service.py b/src/backend/base/langflow/services/database/service.py index c018bdc38..9f0f6f073 100644 --- a/src/backend/base/langflow/services/database/service.py +++ b/src/backend/base/langflow/services/database/service.py @@ -16,7 +16,7 @@ from sqlalchemy.exc import OperationalError from sqlmodel import Session, SQLModel, create_engine, select, text from langflow.services.base import Service -from langflow.services.database import models # noqa +from langflow.services.database import models from langflow.services.database.models.user.crud import get_user_by_username from langflow.services.database.utils import ( Result, @@ -87,7 +87,7 @@ class DatabaseService(Service): pragmas_list = [] for key, val in pragmas.items() or {}: pragmas_list.append(f"PRAGMA {key} = {val}") - logger.info(f"sqlite connection, setting pragmas: {str(pragmas_list)}") + logger.info(f"sqlite connection, setting pragmas: {pragmas_list}") if pragmas_list: cursor = dbapi_connection.cursor() try: diff --git a/src/backend/base/langflow/template/field/base.py b/src/backend/base/langflow/template/field/base.py index c48b8ab63..5ff3682c2 100644 --- a/src/backend/base/langflow/template/field/base.py +++ b/src/backend/base/langflow/template/field/base.py @@ -1,6 +1,6 @@ from collections.abc import Callable # noqa: I001 from enum import Enum -from typing import Any # noqa +from typing import Any from typing import GenericAlias # type: ignore from typing import _GenericAlias # type: ignore from typing import _UnionGenericAlias # type: ignore diff --git a/src/backend/base/langflow/template/utils.py b/src/backend/base/langflow/template/utils.py index b9aef4d3d..36f088b38 100644 --- a/src/backend/base/langflow/template/utils.py +++ b/src/backend/base/langflow/template/utils.py @@ -41,7 +41,7 @@ def update_template_field(new_template, key, previous_value_dict): template_field["load_from_db"] = previous_value_dict.get("load_from_db", False) template_field["value"] = previous_value_dict["value"] - if "file_path" in previous_value_dict and previous_value_dict["file_path"]: + if previous_value_dict.get("file_path"): file_path_value = get_file_path_value(previous_value_dict["file_path"]) if not file_path_value: # If the file does not exist, remove the value from the template_field["value"] diff --git a/src/backend/base/langflow/utils/util.py b/src/backend/base/langflow/utils/util.py index 3839aaaad..ff845114c 100644 --- a/src/backend/base/langflow/utils/util.py +++ b/src/backend/base/langflow/utils/util.py @@ -155,7 +155,7 @@ def get_base_classes(cls): result = [cls.__name__] if not result: result = [cls.__name__] - return list(set(result + [cls.__name__])) + return list({*result, cls.__name__}) def get_default_factory(module: str, function: str): diff --git a/src/backend/base/pyproject.toml b/src/backend/base/pyproject.toml index 2df390eb3..13e7db2ef 100644 --- a/src/backend/base/pyproject.toml +++ b/src/backend/base/pyproject.toml @@ -190,6 +190,7 @@ select = [ "Q", "RET", "RSE", + "RUF", "SIM", "SLOT", "T10", @@ -202,6 +203,8 @@ select = [ ignore = [ "COM812", # Messes with the formatter "ISC001", # Messes with the formatter + "RUF006", # TODO (Store a reference to the return value of `asyncio.create_task`) + "RUF012", # TODO (Mutable class attributes should be annotated with `typing.ClassVar`) ] [tool.ruff.lint.per-file-ignores]