diff --git a/src/backend/base/langflow/api/v1/callback.py b/src/backend/base/langflow/api/v1/callback.py index a075e482ee5..8c3b262b0d6 100644 --- a/src/backend/base/langflow/api/v1/callback.py +++ b/src/backend/base/langflow/api/v1/callback.py @@ -67,7 +67,7 @@ async def on_tool_end(self, output: str, **kwargs: Any) -> Any: ) 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 03b0d597800..751b61f4660 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 consume_and_yield(queue: asyncio.Queue, client_consumed_queue: asyncio 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 7f5e06a48c5..1038940f50b 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 f955fe37233..b88b5fd990b 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 c149ef9e359..2e8e3be220e 100644 --- a/src/backend/base/langflow/base/agents/agent.py +++ b/src/backend/base/langflow/base/agents/agent.py @@ -102,7 +102,7 @@ async def run_agent(self, agent: AgentExecutor) -> Text: 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 @@ async def run_agent(self, agent: AgentExecutor) -> Text: 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 @@ async def run_agent( 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 8ed275f0936..2b640a81c67 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 f5cec67a9eb..5434a1d0878 100644 --- a/src/backend/base/langflow/base/models/model.py +++ b/src/backend/base/langflow/base/models/model.py @@ -157,7 +157,10 @@ def get_chat_result( 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 7c55eb4f129..02101f05574 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 c88c10a6b86..d7410737feb 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 @@ def _add_content_to_page(self, markdown_text: str, block_id: str) -> dict[str, A 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 d1e3abf3052..f35f6306cd7 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 @@ def _create_notion_page(self, database_id: str, properties_json: str) -> dict[st 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 @@ def _create_notion_page(self, database_id: str, properties_json: str) -> dict[st 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 393760bbed2..acdd4b09b27 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 @@ def _fetch_database_properties(self, database_id: str) -> dict | str: 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 9d47c96358a..a8cb846ca32 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 @@ def _query_notion_database(self, database_id: str, query_json: str | None = None 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 @@ def _query_notion_database(self, database_id: str, query_json: str | None = None 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 7ab1813bbee..6e3b853eb89 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 @@ def _retrieve_page_content(self, page_id: str) -> str: 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 76c07a717b9..40a4ff06b5d 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 @@ def _update_notion_page(self, page_id: str, properties: str | dict[str, Any]) -> 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 @@ def _update_notion_page(self, page_id: str, properties: str | dict[str, Any]) -> 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 c84590fd9d1..b638a7f769c 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 ebaf9680ed4..e2267bd4396 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 38010d8719f..da6d64aaeb9 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 20a6c2e243a..e9b925db007 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 50c76c423f1..1880e881336 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 f44c86abd99..bb0f52c917a 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 df36433379d..cbe172f5baf 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 1890f1c76e2..c2f3442a985 100644 --- a/src/backend/base/langflow/components/agents/SequentialTaskAgent.py +++ b/src/backend/base/langflow/components/agents/SequentialTaskAgent.py @@ -130,9 +130,9 @@ def build_agent_and_task(self) -> list[SequentialTask]: # 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 7abb58b9b7f..3701d31cc53 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 41aff7212d4..86f38b31363 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 bef7f0ada38..efea4e08e67 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 54447b22c35..5e31b4d1310 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 19436e9e215..4a7992e5803 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIGetSubtitles.py @@ -54,7 +54,7 @@ def get_subtitles(self) -> Data: 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 97068cf79a1..bd4c80465e4 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAILeMUR.py @@ -135,7 +135,7 @@ def run_lemur(self) -> Data: 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 832fcbceb6c..b19517d05f2 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIListTranscripts.py @@ -86,6 +86,6 @@ def convert_page_to_data_list(page): 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 fd4360b8df9..05526f27d90 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIPollTranscript.py @@ -48,7 +48,7 @@ def poll_transcription_job(self) -> Data: 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 f474f5c589a..62f2f55a0eb 100644 --- a/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py +++ b/src/backend/base/langflow/components/assemblyai/AssemblyAIStartTranscript.py @@ -181,5 +181,5 @@ def create_transcription_job(self) -> Data: 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 a2ddbc49eab..15173ce66c2 100644 --- a/src/backend/base/langflow/components/deactivated/SubFlow.py +++ b/src/backend/base/langflow/components/deactivated/SubFlow.py @@ -41,7 +41,7 @@ def update_build_config(self, build_config: dotdict, field_value: Any, field_nam 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 @@ def update_build_config(self, build_config: dotdict, field_value: Any, field_nam # 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 d5c742c02bd..cf6fabd91e8 100644 --- a/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py +++ b/src/backend/base/langflow/components/embeddings/AzureOpenAIEmbeddings.py @@ -77,7 +77,7 @@ def build_embeddings(self) -> Embeddings: 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 7356133dc68..968b5f7a483 100644 --- a/src/backend/base/langflow/components/helpers/CSVtoData.py +++ b/src/backend/base/langflow/components/helpers/CSVtoData.py @@ -82,11 +82,11 @@ def load_csv_to_data(self) -> list[Data]: 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 915ae07c224..32ed6a84dad 100644 --- a/src/backend/base/langflow/components/helpers/CurrentDate.py +++ b/src/backend/base/langflow/components/helpers/CurrentDate.py @@ -68,6 +68,6 @@ def get_current_date(self) -> Message: 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 62482501eec..50719899eb6 100644 --- a/src/backend/base/langflow/components/helpers/JSONtoData.py +++ b/src/backend/base/langflow/components/helpers/JSONtoData.py @@ -90,11 +90,11 @@ def convert_json_to_data(self) -> Data | list[Data]: 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 bc13f9fbc55..02ff11aedef 100644 --- a/src/backend/base/langflow/components/helpers/MessageToData.py +++ b/src/backend/base/langflow/components/helpers/MessageToData.py @@ -35,6 +35,6 @@ def convert_message_to_data(self) -> Data: 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 7048a68c778..81add12c689 100644 --- a/src/backend/base/langflow/components/helpers/SequentialTask.py +++ b/src/backend/base/langflow/components/helpers/SequentialTask.py @@ -68,5 +68,5 @@ def build_task(self) -> list[SequentialTask]: 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 7b780041400..8592fa90845 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 @@ def crawl(self) -> list[Data]: 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 1cf9d25cbcf..5e4c8edbe03 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 92ebd5a86a1..1816be5709a 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 c846c3d2ed2..e71cc2fd627 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 a5ff32d57c4..ac42b22b344 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 @@ def build_model(self) -> LanguageModel: # type: ignore[type-var] 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 8003f5ca4fa..c7aa591dfbb 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 8ccf0922a6f..60d5ba3cae3 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 bca14f4e92d..7fb872f1252 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 8770a9a104d..73ff7a090d7 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 @@ def get_models(self) -> list[str]: 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 0fa037eed19..63da512ccde 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 5e6dd9e387c..80b37d2de98 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 611bf58cf32..86fd3e1c7c3 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 89b568aa262..6e6fff6b196 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 dede3ba7eed..a5bdaa8806f 100644 --- a/src/backend/base/langflow/components/models/OllamaModel.py +++ b/src/backend/base/langflow/components/models/OllamaModel.py @@ -69,7 +69,8 @@ def get_model(self, base_url_value: str) -> list[str]: 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 @@ def get_model(self, base_url_value: str) -> list[str]: 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 @@ def get_model(self, base_url_value: str) -> list[str]: 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 @@ def get_model(self, base_url_value: str) -> list[str]: 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 6d585af3da2..e849c349d55 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 dabb671d0cd..a1adc50e2d4 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 2c7beee2baf..638d9eb6de3 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 6f98b44c5e9..f3426d07cdb 100644 --- a/src/backend/base/langflow/components/prototypes/JSONCleaner.py +++ b/src/backend/base/langflow/components/prototypes/JSONCleaner.py @@ -78,7 +78,7 @@ def clean_json(self) -> Message: 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 @@ def _validate_json(self, s: str) -> str: 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 4944ed928c2..0105ed1d0f5 100644 --- a/src/backend/base/langflow/components/prototypes/PythonFunction.py +++ b/src/backend/base/langflow/components/prototypes/PythonFunction.py @@ -55,7 +55,7 @@ def execute_function(self) -> list[dotdict | str] | dotdict | str: 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 2c251e446f7..804481b4256 100644 --- a/src/backend/base/langflow/components/prototypes/RunnableExecutor.py +++ b/src/backend/base/langflow/components/prototypes/RunnableExecutor.py @@ -68,14 +68,14 @@ def get_output(self, result, input_key, output_key): 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 22b6b668e53..03b77e262de 100644 --- a/src/backend/base/langflow/components/prototypes/SubFlow.py +++ b/src/backend/base/langflow/components/prototypes/SubFlow.py @@ -47,7 +47,7 @@ def update_build_config(self, build_config: dotdict, field_value: Any, field_nam # 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 53084f21b4e..f9fb811ef9f 100644 --- a/src/backend/base/langflow/components/toolkits/ComposioAPI.py +++ b/src/backend/base/langflow/components/toolkits/ComposioAPI.py @@ -86,7 +86,7 @@ def _handle_authorization_failure(self, toolset: ComposioToolSet, entity: Any, a 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 d309c2e6bdd..ac27e9099e7 100644 --- a/src/backend/base/langflow/components/tools/Calculator.py +++ b/src/backend/base/langflow/components/tools/Calculator.py @@ -69,7 +69,7 @@ def eval_expr(node): 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 @@ def eval_expr(node): 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 295eb2004e9..c27632619a8 100644 --- a/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py +++ b/src/backend/base/langflow/components/tools/PythonCodeStructuredTool.py @@ -120,7 +120,7 @@ def update_build_config(self, build_config: dotdict, field_value: Any, field_nam 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 1b4040b0aca..eb501cfd6e6 100644 --- a/src/backend/base/langflow/components/tools/PythonREPLTool.py +++ b/src/backend/base/langflow/components/tools/PythonREPLTool.py @@ -74,7 +74,7 @@ def run_python_code(code: str) -> str: 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 8d7016ccc7a..a6a4bb3f0d2 100644 --- a/src/backend/base/langflow/components/tools/SearXNGTool.py +++ b/src/backend/base/langflow/components/tools/SearXNGTool.py @@ -75,7 +75,7 @@ def update_build_config(self, build_config: dotdict, field_value: Any, field_nam 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 @@ def search(query: str, categories: Sequence[str] = ()) -> list: 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 9fea66ff503..6adef8a9ed6 100644 --- a/src/backend/base/langflow/components/tools/SerpAPI.py +++ b/src/backend/base/langflow/components/tools/SerpAPI.py @@ -88,5 +88,5 @@ def run_model(self) -> list[Data]: 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 577e16d6562..e2ae170a694 100644 --- a/src/backend/base/langflow/components/tools/TavilyAISearch.py +++ b/src/backend/base/langflow/components/tools/TavilyAISearch.py @@ -155,6 +155,6 @@ def _tavily_search( 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 b32850e9862..53305d66058 100644 --- a/src/backend/base/langflow/components/tools/YfinanceTool.py +++ b/src/backend/base/langflow/components/tools/YfinanceTool.py @@ -96,6 +96,6 @@ def _yahoo_finance_tool( 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 c7ebb77fa06..cfcef1fa4c8 100644 --- a/src/backend/base/langflow/components/vectorstores/AstraDB.py +++ b/src/backend/base/langflow/components/vectorstores/AstraDB.py @@ -427,7 +427,7 @@ def build_vector_store(self, vectorize_options=None): 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 @@ def _add_documents_to_vector_store(self, vector_store): 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 @@ def search_documents(self, vector_store=None) -> list[Data]: 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 19ab2eb1869..c4abfe4c703 100644 --- a/src/backend/base/langflow/components/vectorstores/Cassandra.py +++ b/src/backend/base/langflow/components/vectorstores/Cassandra.py @@ -225,7 +225,7 @@ def search_documents(self) -> list[Data]: 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 557da2c2487..402e54b3d16 100644 --- a/src/backend/base/langflow/components/vectorstores/CassandraGraph.py +++ b/src/backend/base/langflow/components/vectorstores/CassandraGraph.py @@ -204,7 +204,7 @@ def search_documents(self) -> list[Data]: 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 2412b415daa..ee98771d9a6 100644 --- a/src/backend/base/langflow/components/vectorstores/Elasticsearch.py +++ b/src/backend/base/langflow/components/vectorstores/Elasticsearch.py @@ -198,7 +198,7 @@ def search(self, query: str | None = None) -> list[dict[str, Any]]: 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 78580d87778..679f376d782 100644 --- a/src/backend/base/langflow/components/vectorstores/HCD.py +++ b/src/backend/base/langflow/components/vectorstores/HCD.py @@ -247,7 +247,7 @@ def build_vector_store(self): 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 @@ def _add_documents_to_vector_store(self, vector_store): 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 @@ def search_documents(self) -> list[Data]: 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 8e351724d0b..649989e2349 100644 --- a/src/backend/base/langflow/components/vectorstores/OpenSearch.py +++ b/src/backend/base/langflow/components/vectorstores/OpenSearch.py @@ -124,7 +124,7 @@ def build_vector_store(self) -> OpenSearchVectorSearch: 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 @@ def build_vector_store(self) -> OpenSearchVectorSearch: 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 @@ def _add_documents_to_vector_store(self, vector_store: "OpenSearchVectorSearch") 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 @@ def search(self, query: str | None = None) -> list[dict[str, Any]]: 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 @@ def search(self, query: str | None = None) -> list[dict[str, Any]]: 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 @@ def search_documents(self) -> list[Data]: 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 42092e3c151..bbd18ceb7bd 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 @@ def process_file(self, file_path): 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 @@ async def process_file_async(self, file_path): 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 @@ async def abuild_component_menu_list(self, file_paths): 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 331b72d2a8d..9bb963f462c 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 c5b78e59ecf..45ca553c504 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 07839b47261..84a116f639d 100644 --- a/src/backend/base/langflow/graph/graph/base.py +++ b/src/backend/base/langflow/graph/graph/base.py @@ -452,7 +452,7 @@ def activate_state_vertices(self, name: str, caller: str): # 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 @@ def from_payload( 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 @@ def get_all_successors(self, vertex: Vertex, recursive=True, flat=True, visited= 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 @@ def sort_chat_inputs_first(self, vertices_layers: list[list[str]]) -> list[list[ 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 f0e4f2b801a..1b667776757 100644 --- a/src/backend/base/langflow/graph/vertex/base.py +++ b/src/backend/base/langflow/graph/vertex/base.py @@ -682,7 +682,7 @@ async def _build_list_of_vertices_and_update_params( 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 abbbeffa544..9f440b027ce 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 e65b9d45017..6cd54f3b2e0 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 fb501d7b01c..01a5b797389 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 @@ def to_lc_message( 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 @@ def from_lc_message(cls, lc_message: BaseMessage) -> "Message": 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 @@ async def from_template_and_variables(cls, template: str, **variables): 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 c018bdc38a4..9f0f6f073f8 100644 --- a/src/backend/base/langflow/services/database/service.py +++ b/src/backend/base/langflow/services/database/service.py @@ -16,7 +16,7 @@ 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 @@ def on_connection(self, dbapi_connection, connection_record): 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 c48b8ab63ed..5ff3682c28f 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 b9aef4d3de5..36f088b389d 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 3839aaaad87..ff845114c0a 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 2df390eb3c4..13e7db2efbd 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]