ref: Add ruff rules RUF (#4001)

Add ruff rules RUF
This commit is contained in:
Christophe Bornet 2024-10-04 17:01:56 +02:00 • committed by GitHub
commit 63beae1833
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 196 additions and 228 deletions

View file

@ -67,7 +67,7 @@ class AsyncStreamingLLMCallbackHandleSIO(AsyncCallbackHandler):
) )
for word in rest_of_output 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 to send the response, handle potential errors.
try: try:

View file

@ -409,7 +409,7 @@ async def build_flow(
get_time_yield = time.time() get_time_yield = time.time()
client_consumed_queue.put_nowait(event_id) client_consumed_queue.put_nowait(event_id)
logger.debug( logger.debug(
f"consumed event {str(event_id)} " f"consumed event {event_id} "
f"(time in queue, {get_time - put_time:.4f}, " f"(time in queue, {get_time - put_time:.4f}, "
f"client {get_time_yield - get_time:.4f})" f"client {get_time_yield - get_time:.4f})"
) )

View file

@ -382,9 +382,9 @@ async def experimental_run_flow(
flow_id: UUID, flow_id: UUID,
inputs: list[InputValueRequest] | None = None, inputs: list[InputValueRequest] | None = None,
outputs: list[str] | None = None, outputs: list[str] | None = None,
tweaks: Annotated[Tweaks | None, Body(embed=True)] = None, # noqa: F821 tweaks: Annotated[Tweaks | None, Body(embed=True)] = None,
stream: Annotated[bool, Body(embed=True)] = False, # noqa: F821 stream: Annotated[bool, Body(embed=True)] = False,
session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821 session_id: Annotated[None | str, Body(embed=True)] = None,
api_key_user: UserRead = Depends(api_key_security), api_key_user: UserRead = Depends(api_key_security),
session_service: SessionService = Depends(get_session_service), session_service: SessionService = Depends(get_session_service),
): ):
@ -509,11 +509,11 @@ async def process(
flow_id: str, flow_id: str,
inputs: list[dict] | dict | None = None, inputs: list[dict] | dict | None = None,
tweaks: dict | None = None, tweaks: dict | None = None,
clear_cache: Annotated[bool, Body(embed=True)] = False, # noqa: F821 clear_cache: Annotated[bool, Body(embed=True)] = False,
session_id: Annotated[None | str, Body(embed=True)] = None, # noqa: F821 session_id: Annotated[None | str, Body(embed=True)] = None,
task_service: TaskService = Depends(get_task_service), task_service: TaskService = Depends(get_task_service),
api_key_user: UserRead = Depends(api_key_security), 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), session_service: SessionService = Depends(get_session_service),
): ):
""" """

View file

@ -196,7 +196,7 @@ def read_flow(
# so write an OR # so write an OR
stmt = stmt.where( stmt = stmt.where(
(Flow.user_id == current_user.id) | (Flow.user_id == None) # noqa (Flow.user_id == current_user.id) | (Flow.user_id == None) # noqa
) # noqa )
if user_flow := session.exec(stmt).first(): if user_flow := session.exec(stmt).first():
return user_flow return user_flow
raise HTTPException(status_code=404, detail="Flow not found") raise HTTPException(status_code=404, detail="Flow not found")

View file

@ -102,7 +102,7 @@ class LCAgentComponent(Component):
if self.chat_history: if self.chat_history:
input_dict["chat_history"] = data_to_messages(self.chat_history) input_dict["chat_history"] = data_to_messages(self.chat_history)
result = agent.invoke( 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 self.status = result
if "output" not in result: if "output" not in result:
@ -113,13 +113,9 @@ class LCAgentComponent(Component):
class LCToolsAgentComponent(LCAgentComponent): class LCToolsAgentComponent(LCAgentComponent):
_base_inputs = LCAgentComponent._base_inputs + [ _base_inputs = [
HandleInput( *LCAgentComponent._base_inputs,
name="tools", HandleInput(name="tools", display_name="Tools", input_types=["Tool", "BaseTool"], is_list=True),
display_name="Tools",
input_types=["Tool", "BaseTool"],
is_list=True,
),
] ]
def build_agent(self) -> AgentExecutor: def build_agent(self) -> AgentExecutor:
@ -149,7 +145,7 @@ class LCToolsAgentComponent(LCAgentComponent):
input_dict["chat_history"] = data_to_messages(self.chat_history) input_dict["chat_history"] = data_to_messages(self.chat_history)
result = runnable.invoke( 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 self.status = result
if "output" not in result: if "output" not in result:

View file

@ -56,7 +56,7 @@ def build_data_from_result_data(result_data: ResultData, get_final_results_only:
data.append(artifact) data.append(artifact)
else: else:
# Warn about unknown output type # 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 # Chat or text output
elif result_data.results: elif result_data.results:
data.append(Data(data={"result": result_data.results}, text_key="result")) data.append(Data(data={"result": result_data.results}, text_key="result"))

View file

@ -157,7 +157,10 @@ class LCModelComponent(Component):
if "prompt" in input_value: if "prompt" in input_value:
prompt = input_value.load_lc_prompt() prompt = input_value.load_lc_prompt()
if system_message: 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 system_message_added = True
runnable = prompt | runnable runnable = prompt | runnable
else: else:

View file

@ -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) new_var, invalid_chars, wrong_variables = _fix_variable(var[1:], invalid_chars, wrong_variables)
# Temporarily replace {{ and }} to avoid treating them as invalid # 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 # Remove invalid characters
for char in new_var: for char in new_var:
@ -73,7 +73,7 @@ def _fix_variable(var, invalid_chars, wrong_variables):
wrong_variables.append(var) wrong_variables.append(var)
# Restore {{ and }} # 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 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 len(custom_fields) == 1 and name == "":
# If there is only one custom field and the name is empty string # 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 # 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] old_custom_fields = custom_fields[name]
if not old_custom_fields: if not old_custom_fields:

View file

@ -76,12 +76,12 @@ class AddContentToPage(LCToolComponent):
return response.json() return response.json()
except requests.exceptions.RequestException as e: 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: if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message return error_message
except Exception as e: 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): def process_node(self, node):
blocks = [] blocks = []

View file

@ -67,7 +67,7 @@ class NotionPageCreator(LCToolComponent):
try: try:
properties = json.loads(properties_json) properties = json.loads(properties_json)
except json.JSONDecodeError as e: 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 = { headers = {
"Authorization": f"Bearer {self.notion_secret}", "Authorization": f"Bearer {self.notion_secret}",
@ -85,7 +85,7 @@ class NotionPageCreator(LCToolComponent):
response.raise_for_status() response.raise_for_status()
return response.json() return response.json()
except requests.exceptions.RequestException as e: 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: if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message return error_message

View file

@ -59,8 +59,8 @@ class NotionDatabaseProperties(LCToolComponent):
data = response.json() data = response.json()
return data.get("properties", {}) return data.get("properties", {})
except requests.exceptions.RequestException as e: 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: 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: except Exception as e:
return f"An unexpected error occurred: {str(e)}" return f"An unexpected error occurred: {e}"

View file

@ -105,7 +105,7 @@ class NotionListPages(LCToolComponent):
try: try:
query_payload = json.loads(query_json) query_payload = json.loads(query_json)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
return f"Invalid JSON format for query: {str(e)}" return f"Invalid JSON format for query: {e}"
try: try:
response = requests.post(url, headers=headers, json=query_payload) response = requests.post(url, headers=headers, json=query_payload)
@ -113,8 +113,8 @@ class NotionListPages(LCToolComponent):
results = response.json() results = response.json()
return results["results"] return results["results"]
except requests.exceptions.RequestException as e: except requests.exceptions.RequestException as e:
return f"Error querying Notion database: {str(e)}" return f"Error querying Notion database: {e}"
except KeyError: except KeyError:
return "Unexpected response format from Notion API" return "Unexpected response format from Notion API"
except Exception as e: except Exception as e:
return f"An unexpected error occurred: {str(e)}" return f"An unexpected error occurred: {e}"

View file

@ -59,12 +59,12 @@ class NotionPageContent(LCToolComponent):
blocks_data = blocks_response.json() blocks_data = blocks_response.json()
return self.parse_blocks(blocks_data.get("results", [])) return self.parse_blocks(blocks_data.get("results", []))
except requests.exceptions.RequestException as e: 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: if hasattr(e, "response") and e.response is not None:
error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}" error_message += f" Status code: {e.response.status_code}, Response: {e.response.text}"
return error_message return error_message
except Exception as e: 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: def parse_blocks(self, blocks: list) -> str:
content = "" content = ""

View file

@ -76,7 +76,7 @@ class NotionPageUpdate(LCToolComponent):
try: try:
parsed_properties = json.loads(properties) parsed_properties = json.loads(properties)
except json.JSONDecodeError as e: 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) logger.error(error_message)
return error_message return error_message
@ -94,18 +94,18 @@ class NotionPageUpdate(LCToolComponent):
logger.info(f"Successfully updated Notion page. Response: {json.dumps(updated_page)}") logger.info(f"Successfully updated Notion page. Response: {json.dumps(updated_page)}")
return updated_page return updated_page
except requests.exceptions.HTTPError as e: 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: if e.response is not None:
error_message += f"\nStatus code: {e.response.status_code}" error_message += f"\nStatus code: {e.response.status_code}"
error_message += f"\nResponse body: {e.response.text}" error_message += f"\nResponse body: {e.response.text}"
logger.error(error_message) logger.error(error_message)
return error_message return error_message
except requests.exceptions.RequestException as e: 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) logger.error(error_message)
return error_message return error_message
except Exception as e: 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) logger.error(error_message)
return error_message return error_message

View file

@ -14,7 +14,8 @@ class CSVAgentComponent(LCAgentComponent):
documentation = "https://python.langchain.com/docs/modules/agents/toolkits/csv" documentation = "https://python.langchain.com/docs/modules/agents/toolkits/csv"
name = "CSVAgent" name = "CSVAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput( HandleInput(
name="llm", name="llm",
display_name="Language Model", display_name="Language Model",

View file

@ -12,7 +12,8 @@ class HierarchicalCrewComponent(BaseCrewComponent):
documentation: str = "https://docs.crewai.com/how-to/Hierarchical/" documentation: str = "https://docs.crewai.com/how-to/Hierarchical/"
icon = "CrewAI" icon = "CrewAI"
inputs = BaseCrewComponent._base_inputs + [ inputs = [
*BaseCrewComponent._base_inputs,
HandleInput(name="agents", display_name="Agents", input_types=["Agent"], is_list=True), 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="tasks", display_name="Tasks", input_types=["HierarchicalTask"], is_list=True),
HandleInput(name="manager_llm", display_name="Manager LLM", input_types=["LanguageModel"], required=False), HandleInput(name="manager_llm", display_name="Manager LLM", input_types=["LanguageModel"], required=False),

View file

@ -15,7 +15,8 @@ class JsonAgentComponent(LCAgentComponent):
description = "Construct a json agent from an LLM and tools." description = "Construct a json agent from an LLM and tools."
name = "JsonAgent" name = "JsonAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), 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), FileInput(name="path", display_name="File Path", file_types=["json", "yaml", "yml"], required=True),
] ]

View file

@ -14,7 +14,8 @@ class OpenAIToolsAgentComponent(LCToolsAgentComponent):
beta = True beta = True
name = "OpenAIToolsAgent" name = "OpenAIToolsAgent"
inputs = LCToolsAgentComponent._base_inputs + [ inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput( HandleInput(
name="llm", name="llm",
display_name="Language Model", display_name="Language Model",

View file

@ -16,7 +16,8 @@ class OpenAPIAgentComponent(LCAgentComponent):
description = "Agent to interact with OpenAPI API." description = "Agent to interact with OpenAPI API."
name = "OpenAPIAgent" name = "OpenAPIAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), 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), 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), BoolInput(name="allow_dangerous_requests", display_name="Allow Dangerous Requests", value=False, required=True),

View file

@ -12,7 +12,8 @@ class SQLAgentComponent(LCAgentComponent):
description = "Construct an SQL agent from an LLM and tools." description = "Construct an SQL agent from an LLM and tools."
name = "SQLAgent" name = "SQLAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
MessageTextInput(name="database_uri", display_name="Database URI", required=True), MessageTextInput(name="database_uri", display_name="Database URI", required=True),
HandleInput( HandleInput(

View file

@ -11,7 +11,8 @@ class SequentialCrewComponent(BaseCrewComponent):
documentation: str = "https://docs.crewai.com/how-to/Sequential/" documentation: str = "https://docs.crewai.com/how-to/Sequential/"
icon = "CrewAI" icon = "CrewAI"
inputs = BaseCrewComponent._base_inputs + [ inputs = [
*BaseCrewComponent._base_inputs,
HandleInput(name="tasks", display_name="Tasks", input_types=["SequentialTask"], is_list=True), HandleInput(name="tasks", display_name="Tasks", input_types=["SequentialTask"], is_list=True),
] ]

View file

@ -130,9 +130,9 @@ class SequentialTaskAgentComponent(Component):
# If there's a previous task, create a list of tasks # If there's a previous task, create a list of tasks
if self.previous_task: 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: else:
tasks = [task] tasks = [task]
self.status = f"Agent: {repr(agent)}\nTask: {repr(task)}" self.status = f"Agent: {agent!r}\nTask: {task!r}"
return tasks return tasks

View file

@ -14,7 +14,8 @@ class ToolCallingAgentComponent(LCToolsAgentComponent):
beta = True beta = True
name = "ToolCallingAgent" name = "ToolCallingAgent"
inputs = LCToolsAgentComponent._base_inputs + [ inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
MultilineInput( MultilineInput(
name="system_prompt", name="system_prompt",

View file

@ -10,7 +10,8 @@ class VectorStoreAgentComponent(LCAgentComponent):
description = "Construct an agent from a Vector Store." description = "Construct an agent from a Vector Store."
name = "VectorStoreAgent" name = "VectorStoreAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
HandleInput(name="vectorstore", display_name="Vector Store", input_types=["VectorStoreInfo"], required=True), HandleInput(name="vectorstore", display_name="Vector Store", input_types=["VectorStoreInfo"], required=True),
] ]

View file

@ -10,7 +10,8 @@ class VectorStoreRouterAgentComponent(LCAgentComponent):
description = "Construct an agent from a Vector Store Router." description = "Construct an agent from a Vector Store Router."
name = "VectorStoreRouterAgent" name = "VectorStoreRouterAgent"
inputs = LCAgentComponent._base_inputs + [ inputs = [
*LCAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True),
HandleInput( HandleInput(
name="vectorstores", name="vectorstores",

View file

@ -13,7 +13,8 @@ class XMLAgentComponent(LCToolsAgentComponent):
icon = "LangChain" icon = "LangChain"
beta = True beta = True
name = "XMLAgent" name = "XMLAgent"
inputs = LCToolsAgentComponent._base_inputs + [ inputs = [
*LCToolsAgentComponent._base_inputs,
HandleInput(name="llm", display_name="Language Model", input_types=["LanguageModel"], required=True), 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), DataInput(name="chat_history", display_name="Chat History", is_list=True, advanced=True),
MultilineInput( MultilineInput(

View file

@ -54,7 +54,7 @@ class AssemblyAIGetSubtitles(Component):
transcript_id = self.transcription_result.data["id"] transcript_id = self.transcription_result.data["id"]
transcript = aai.Transcript.get_by_id(transcript_id) transcript = aai.Transcript.get_by_id(transcript_id)
except Exception as e: except Exception as e:
error = f"Getting transcription failed: {str(e)}" error = f"Getting transcription failed: {e}"
self.status = error self.status = error
return Data(data={"error": error}) return Data(data={"error": error})

View file

@ -135,7 +135,7 @@ class AssemblyAILeMUR(Component):
self.status = result self.status = result
return result return result
except Exception as e: except Exception as e:
error = f"An Error happened: {str(e)}" error = f"An Error happened: {e}"
self.status = error self.status = error
return Data(data={"error": error}) return Data(data={"error": error})

View file

@ -86,6 +86,6 @@ class AssemblyAIListTranscripts(Component):
self.status = transcripts self.status = transcripts
return transcripts return transcripts
except Exception as e: 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] self.status = [error_data]
return [error_data] return [error_data]

View file

@ -48,7 +48,7 @@ class AssemblyAITranscriptionJobPoller(Component):
try: try:
transcript = aai.Transcript.get_by_id(self.transcript_id.data["transcript_id"]) transcript = aai.Transcript.get_by_id(self.transcript_id.data["transcript_id"])
except Exception as e: except Exception as e:
error = f"Getting transcription failed: {str(e)}" error = f"Getting transcription failed: {e}"
self.status = error self.status = error
return Data(data={"error": error}) return Data(data={"error": error})

View file

@ -181,5 +181,5 @@ class AssemblyAITranscriptionJobCreator(Component):
self.status = result self.status = result
return result return result
except Exception as e: except Exception as e:
self.status = f"An error occurred: {str(e)}" self.status = f"An error occurred: {e}"
return Data(data={"error": f"An error occurred: {str(e)}"}) return Data(data={"error": f"An error occurred: {e}"})

View file

@ -41,7 +41,7 @@ class SubFlowComponent(CustomComponent):
build_config["flow_name"]["options"] = self.get_flow_names() build_config["flow_name"]["options"] = self.get_flow_names()
# Clean up the build config # Clean up the build config
for key in list(build_config.keys()): 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] del build_config[key]
if field_value is not None and field_name == "flow_name": if field_value is not None and field_name == "flow_name":
try: try:
@ -55,7 +55,7 @@ class SubFlowComponent(CustomComponent):
# Add inputs to the build config # Add inputs to the build config
build_config = self.add_inputs_to_build_config(inputs, build_config) build_config = self.add_inputs_to_build_config(inputs, build_config)
except Exception as e: 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 return build_config

View file

@ -77,7 +77,7 @@ class AzureOpenAIEmbeddingsComponent(LCModelComponent):
dimensions=self.dimensions or None, dimensions=self.dimensions or None,
) )
except Exception as e: 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 raise ValueError(msg) from e
return embeddings return embeddings

View file

@ -82,11 +82,11 @@ class CSVToDataComponent(Component):
return result return result
except csv.Error as e: except csv.Error as e:
error_message = f"CSV parsing error: {str(e)}" error_message = f"CSV parsing error: {e}"
self.status = error_message self.status = error_message
raise ValueError(error_message) from e raise ValueError(error_message) from e
except Exception as e: except Exception as e:
error_message = f"An error occurred: {str(e)}" error_message = f"An error occurred: {e}"
self.status = error_message self.status = error_message
raise ValueError(error_message) from e raise ValueError(error_message) from e

View file

@ -68,6 +68,6 @@ class CurrentDateComponent(Component):
self.status = result self.status = result
return Message(text=result) return Message(text=result)
except Exception as e: except Exception as e:
error_message = f"Error: {str(e)}" error_message = f"Error: {e}"
self.status = error_message self.status = error_message
return Message(text=error_message) return Message(text=error_message)

View file

@ -90,11 +90,11 @@ class JSONToDataComponent(Component):
return result return result
except (json.JSONDecodeError, SyntaxError, ValueError) as e: 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 self.status = error_message
raise ValueError(error_message) from e raise ValueError(error_message) from e
except Exception as e: except Exception as e:
error_message = f"An error occurred: {str(e)}" error_message = f"An error occurred: {e}"
self.status = error_message self.status = error_message
raise ValueError(error_message) from e raise ValueError(error_message) from e

View file

@ -35,6 +35,6 @@ class MessageToDataComponent(Component):
self.status = "Successfully converted Message to Data" self.status = "Successfully converted Message to Data"
return data return data
except Exception as e: 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 self.status = error_message
return Data(data={"error": error_message}) return Data(data={"error": error_message})

View file

@ -68,5 +68,5 @@ class SequentialTaskComponent(Component):
if isinstance(self.task, list) and all(isinstance(task, SequentialTask) for task in self.task): if isinstance(self.task, list) and all(isinstance(task, SequentialTask) for task in self.task):
tasks = self.task + tasks tasks = self.task + tasks
elif isinstance(self.task, SequentialTask): elif isinstance(self.task, SequentialTask):
tasks = [self.task] + tasks tasks = [self.task, *tasks]
return tasks return tasks

View file

@ -113,7 +113,7 @@ class SpiderTool(Component):
msg = f"Invalid mode: {self.mode}. Must be 'scrape' or 'crawl'." msg = f"Invalid mode: {self.mode}. Must be 'scrape' or 'crawl'."
raise ValueError(msg) raise ValueError(msg)
except Exception as e: except Exception as e:
msg = f"Error: {str(e)}" msg = f"Error: {e}"
raise Exception(msg) from e raise Exception(msg) from e
records = [] records = []

View file

@ -23,7 +23,8 @@ class AIMLModelComponent(LCModelComponent):
name = "AIMLModel" name = "AIMLModel"
documentation = "https://docs.aimlapi.com/api-reference" documentation = "https://docs.aimlapi.com/api-reference"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",

View file

@ -11,7 +11,8 @@ class AmazonBedrockComponent(LCModelComponent):
icon = "Amazon" icon = "Amazon"
name = "AmazonBedrockModel" name = "AmazonBedrockModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
DropdownInput( DropdownInput(
name="model_id", name="model_id",
display_name="Model ID", display_name="Model ID",

View file

@ -12,7 +12,8 @@ class AnthropicModelComponent(LCModelComponent):
icon = "Anthropic" icon = "Anthropic"
name = "AnthropicModel" name = "AnthropicModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",
@ -32,11 +33,7 @@ class AnthropicModelComponent(LCModelComponent):
info="https://python.langchain.com/docs/integrations/chat/anthropic", info="https://python.langchain.com/docs/integrations/chat/anthropic",
value="claude-3-5-sonnet-20240620", value="claude-3-5-sonnet-20240620",
), ),
SecretStrInput( SecretStrInput(name="anthropic_api_key", display_name="Anthropic API Key", info="Your Anthropic API key."),
name="anthropic_api_key",
display_name="Anthropic API Key",
info="Your Anthropic API key.",
),
FloatInput(name="temperature", display_name="Temperature", value=0.1), FloatInput(name="temperature", display_name="Temperature", value=0.1),
MessageTextInput( MessageTextInput(
name="anthropic_api_url", 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.", info="Endpoint of the Anthropic API. Defaults to 'https://api.anthropic.com' if not specified.",
), ),
MessageTextInput( MessageTextInput(
name="prefill", name="prefill", display_name="Prefill", info="Prefill text to guide the model's response.", advanced=True
display_name="Prefill",
info="Prefill text to guide the model's response.",
advanced=True,
), ),
HandleInput( HandleInput(
name="output_parser", name="output_parser",

View file

@ -27,7 +27,8 @@ class AzureChatOpenAIComponent(LCModelComponent):
"2024-05-13", "2024-05-13",
] ]
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
MessageTextInput( MessageTextInput(
name="azure_endpoint", name="azure_endpoint",
display_name="Azure Endpoint", display_name="Azure Endpoint",
@ -78,7 +79,7 @@ class AzureChatOpenAIComponent(LCModelComponent):
streaming=stream, streaming=stream,
) )
except Exception as e: 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 raise ValueError(msg) from e
return output # type: ignore return output # type: ignore

View file

@ -14,7 +14,8 @@ class QianfanChatEndpointComponent(LCModelComponent):
icon = "BaiduQianfan" icon = "BaiduQianfan"
name = "BaiduQianfanChatModel" name = "BaiduQianfanChatModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
DropdownInput( DropdownInput(
name="model", name="model",
display_name="Model Name", display_name="Model Name",
@ -64,9 +65,7 @@ class QianfanChatEndpointComponent(LCModelComponent):
advanced=True, advanced=True,
), ),
MessageTextInput( MessageTextInput(
name="endpoint", name="endpoint", display_name="Endpoint", info="Endpoint of the Qianfan LLM, required if custom model used."
display_name="Endpoint",
info="Endpoint of the Qianfan LLM, required if custom model used.",
), ),
HandleInput( HandleInput(
name="output_parser", name="output_parser",

View file

@ -14,7 +14,8 @@ class CohereComponent(LCModelComponent):
icon = "Cohere" icon = "Cohere"
name = "CohereModel" name = "CohereModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
SecretStrInput( SecretStrInput(
name="cohere_api_key", name="cohere_api_key",
display_name="Cohere API Key", display_name="Cohere API Key",

View file

@ -12,11 +12,10 @@ class GoogleGenerativeAIComponent(LCModelComponent):
icon = "GoogleGenerativeAI" icon = "GoogleGenerativeAI"
name = "GoogleGenerativeAIModel" name = "GoogleGenerativeAIModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_output_tokens", name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate."
display_name="Max Output Tokens",
info="The maximum number of tokens to generate.",
), ),
DropdownInput( DropdownInput(
name="model", name="model",

View file

@ -14,12 +14,9 @@ class GroqModel(LCModelComponent):
icon = "Groq" icon = "Groq"
name = "GroqModel" name = "GroqModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
SecretStrInput( *LCModelComponent._base_inputs,
name="groq_api_key", SecretStrInput(name="groq_api_key", display_name="Groq API Key", info="API key for the Groq API."),
display_name="Groq API Key",
info="API key for the Groq API.",
),
MessageTextInput( MessageTextInput(
name="groq_api_base", name="groq_api_base",
display_name="Groq API Base", display_name="Groq API Base",
@ -75,7 +72,7 @@ class GroqModel(LCModelComponent):
model_list = response.json() model_list = response.json()
return [model["id"] for model in model_list.get("data", [])] return [model["id"] for model in model_list.get("data", [])]
except requests.RequestException as e: except requests.RequestException as e:
self.status = f"Error fetching models: {str(e)}" self.status = f"Error fetching models: {e}"
return [] return []
def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None): def update_build_config(self, build_config: dict, field_value: str, field_name: str | None = None):

View file

@ -17,12 +17,9 @@ class HuggingFaceEndpointsComponent(LCModelComponent):
icon = "HuggingFace" icon = "HuggingFace"
name = "HuggingFaceModel" name = "HuggingFaceModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
StrInput( *LCModelComponent._base_inputs,
name="model_id", StrInput(name="model_id", display_name="Model ID", value="openai-community/gpt2"),
display_name="Model ID",
value="openai-community/gpt2",
),
StrInput( StrInput(
name="inference_endpoint", name="inference_endpoint",
display_name="Inference Endpoint", display_name="Inference Endpoint",

View file

@ -12,7 +12,8 @@ class MaritalkModelComponent(LCModelComponent):
description = "Generates text using Maritalk LLMs." description = "Generates text using Maritalk LLMs."
icon = "Maritalk" icon = "Maritalk"
name = "Maritalk" name = "Maritalk"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",

View file

@ -13,7 +13,8 @@ class MistralAIModelComponent(LCModelComponent):
icon = "MistralAI" icon = "MistralAI"
name = "MistralModel" name = "MistralModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",
@ -38,10 +39,8 @@ class MistralAIModelComponent(LCModelComponent):
name="mistral_api_base", name="mistral_api_base",
display_name="Mistral API Base", display_name="Mistral API Base",
advanced=True, advanced=True,
info=( info="The base URL of the Mistral API. Defaults to https://api.mistral.ai/v1. "
"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.",
"You can change this to use other APIs like JinaChat, LocalAI and Prem."
),
), ),
SecretStrInput( SecretStrInput(
name="api_key", name="api_key",

View file

@ -12,7 +12,8 @@ class NVIDIAModelComponent(LCModelComponent):
description = "Generates text using NVIDIA LLMs." description = "Generates text using NVIDIA LLMs."
icon = "NVIDIA" icon = "NVIDIA"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",

View file

@ -69,7 +69,8 @@ class ChatOllamaComponent(LCModelComponent):
msg = "Could not retrieve models. Please, make sure Ollama is running." msg = "Could not retrieve models. Please, make sure Ollama is running."
raise ValueError(msg) from e raise ValueError(msg) from e
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
StrInput( StrInput(
name="base_url", name="base_url",
display_name="Base URL", display_name="Base URL",
@ -90,17 +91,9 @@ class ChatOllamaComponent(LCModelComponent):
info="Controls the creativity of model responses.", info="Controls the creativity of model responses.",
), ),
StrInput( StrInput(
name="format", name="format", display_name="Format", info="Specify the format of the output (e.g., json).", advanced=True
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,
), ),
DictInput(name="metadata", display_name="Metadata", info="Metadata to add to the run trace.", advanced=True),
DropdownInput( DropdownInput(
name="mirostat", name="mirostat",
display_name="Mirostat", display_name="Mirostat",
@ -152,35 +145,13 @@ class ChatOllamaComponent(LCModelComponent):
info="Penalty for repetitions in generated text. (Default: 1.1)", info="Penalty for repetitions in generated text. (Default: 1.1)",
advanced=True, advanced=True,
), ),
FloatInput( FloatInput(name="tfs_z", display_name="TFS Z", info="Tail free sampling value. (Default: 1)", advanced=True),
name="tfs_z", IntInput(name="timeout", display_name="Timeout", info="Timeout for the request stream.", advanced=True),
display_name="TFS Z",
info="Tail free sampling value. (Default: 1)",
advanced=True,
),
IntInput( IntInput(
name="timeout", name="top_k", display_name="Top K", info="Limits token selection to top K. (Default: 40)", advanced=True
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.",
), ),
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( StrInput(
name="tags", name="tags",
display_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.", info="Comma-separated list of tokens to signal the model to stop generating text.",
advanced=True, advanced=True,
), ),
StrInput( StrInput(name="system", display_name="System", info="System to use for generating text.", advanced=True),
name="system", StrInput(name="template", display_name="Template", info="Template to use for generating text.", advanced=True),
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( HandleInput(
name="output_parser", name="output_parser",
display_name="Output Parser", display_name="Output Parser",

View file

@ -26,7 +26,8 @@ class OpenAIModelComponent(LCModelComponent):
icon = "OpenAI" icon = "OpenAI"
name = "OpenAIModel" name = "OpenAIModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
IntInput( IntInput(
name="max_tokens", name="max_tokens",
display_name="Max Tokens", display_name="Max Tokens",

View file

@ -14,7 +14,8 @@ class PerplexityComponent(LCModelComponent):
icon = "Perplexity" icon = "Perplexity"
name = "PerplexityModel" name = "PerplexityModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
DropdownInput( DropdownInput(
name="model_name", name="model_name",
display_name="Model Name", display_name="Model Name",
@ -31,9 +32,7 @@ class PerplexityComponent(LCModelComponent):
value="llama-3.1-sonar-small-128k-online", value="llama-3.1-sonar-small-128k-online",
), ),
IntInput( IntInput(
name="max_output_tokens", name="max_output_tokens", display_name="Max Output Tokens", info="The maximum number of tokens to generate."
display_name="Max Output Tokens",
info="The maximum number of tokens to generate.",
), ),
SecretStrInput( SecretStrInput(
name="api_key", name="api_key",

View file

@ -13,7 +13,8 @@ class ChatVertexAIComponent(LCModelComponent):
icon = "VertexAI" icon = "VertexAI"
name = "VertexAiModel" name = "VertexAiModel"
inputs = LCModelComponent._base_inputs + [ inputs = [
*LCModelComponent._base_inputs,
FileInput( FileInput(
name="credentials", name="credentials",
display_name="Credentials", display_name="Credentials",

View file

@ -78,7 +78,7 @@ class JSONCleaner(Component):
self.status = result self.status = result
return Message(text=result) return Message(text=result)
except Exception as e: except Exception as e:
msg = f"Error cleaning JSON string: {str(e)}" msg = f"Error cleaning JSON string: {e}"
raise ValueError(msg) from e raise ValueError(msg) from e
def _remove_control_characters(self, s: str) -> str: def _remove_control_characters(self, s: str) -> str:
@ -95,5 +95,5 @@ class JSONCleaner(Component):
json.loads(s) json.loads(s)
return s return s
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
msg = f"Invalid JSON string: {str(e)}" msg = f"Invalid JSON string: {e}"
raise ValueError(msg) from e raise ValueError(msg) from e

View file

@ -55,7 +55,7 @@ class PythonFunctionComponent(Component):
func = get_function(function_code) func = get_function(function_code)
return func() return func()
except Exception as e: except Exception as e:
return f"Error executing function: {str(e)}" return f"Error executing function: {e}"
def execute_function_data(self) -> list[Data]: def execute_function_data(self) -> list[Data]:
results = self.execute_function() results = self.execute_function()

View file

@ -68,14 +68,14 @@ class RunnableExecComponent(Component):
result_value = result.get(output_key) result_value = result.get(output_key)
elif len(result) == 2 and input_key in result: elif len(result) == 2 and input_key in result:
# get the other key from the result dict # 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: if other_key == output_key:
result_value = result.get(output_key) result_value = result.get(output_key)
else: else:
status += f"Warning: The output key is not '{output_key}'. The output key is '{other_key}'." status += f"Warning: The output key is not '{output_key}'. The output key is '{other_key}'."
result_value = result.get(other_key) result_value = result.get(other_key)
elif len(result) == 1: 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): elif any(k in result for k in possible_output_keys):
for key in possible_output_keys: for key in possible_output_keys:
if key in result: if key in result:

View file

@ -47,7 +47,7 @@ class SubFlowComponent(Component):
# Add inputs to the build config # Add inputs to the build config
build_config = self.add_inputs_to_build_config(inputs, build_config) build_config = self.add_inputs_to_build_config(inputs, build_config)
except Exception as e: 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 return build_config

View file

@ -86,7 +86,7 @@ class ComposioAPIComponent(LCToolComponent):
return self._process_api_key_auth(entity, app) return self._process_api_key_auth(entity, app)
return self._initiate_default_connection(entity, app) return self._initiate_default_connection(entity, app)
except Exception as exc: except Exception as exc:
logger.error(f"Authorization error: {str(exc)}") logger.error(f"Authorization error: {exc}")
return "Error" return "Error"
def _process_api_key_auth(self, entity: Any, app: str) -> str: def _process_api_key_auth(self, entity: Any, app: str) -> str:

View file

@ -69,7 +69,7 @@ class CalculatorToolComponent(LCToolComponent):
return [Data(data={"result": formatted_result})] return [Data(data={"result": formatted_result})]
except (SyntaxError, TypeError, KeyError) as e: except (SyntaxError, TypeError, KeyError) as e:
error_message = f"Invalid expression: {str(e)}" error_message = f"Invalid expression: {e}"
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]
except ZeroDivisionError: except ZeroDivisionError:
@ -77,6 +77,6 @@ class CalculatorToolComponent(LCToolComponent):
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]
except Exception as e: except Exception as e:
error_message = f"Error: {str(e)}" error_message = f"Error: {e}"
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]

View file

@ -120,7 +120,7 @@ class PythonCodeStructuredTool(LCToolComponent):
build_config["_classes"]["value"] = json.dumps(classes) build_config["_classes"]["value"] = json.dumps(classes)
build_config["tool_function"]["options"] = names build_config["tool_function"]["options"] = names
except Exception as e: 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)] build_config["tool_function"]["options"] = ["Failed to parse", str(e)]
return build_config return build_config

View file

@ -74,7 +74,7 @@ class PythonREPLToolComponent(LCToolComponent):
try: try:
return python_repl.run(code) return python_repl.run(code)
except Exception as e: except Exception as e:
return f"Error: {str(e)}" return f"Error: {e}"
tool = StructuredTool.from_function( tool = StructuredTool.from_function(
name=self.name, name=self.name,

View file

@ -75,7 +75,7 @@ class SearXNGToolComponent(LCToolComponent):
languages.append(language) languages.append(language)
build_config["language"]["options"] = languages.copy() build_config["language"]["options"] = languages.copy()
except Exception as e: 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)] build_config["categories"]["options"] = ["Failed to parse", str(e)]
return build_config return build_config
@ -113,7 +113,7 @@ class SearXNGToolComponent(LCToolComponent):
results.append(response["results"][i]) results.append(response["results"][i])
return results return results
except Exception as e: except Exception as e:
return [f"Failed to search: {str(e)}"] return [f"Failed to search: {e}"]
SearxSearch._url = self.url SearxSearch._url = self.url
SearxSearch._categories = self.categories.copy() SearxSearch._categories = self.categories.copy()

View file

@ -88,5 +88,5 @@ class SerpAPIComponent(LCToolComponent):
self.status = data_list self.status = data_list
return data_list return data_list
except Exception as e: except Exception as e:
self.status = f"Error: {str(e)}" self.status = f"Error: {e}"
return [Data(data={"error": str(e)}, text=str(e))] return [Data(data={"error": str(e)}, text=str(e))]

View file

@ -155,6 +155,6 @@ Note: Check 'Advanced' for all options.
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]
except Exception as e: except Exception as e:
error_message = f"Unexpected error: {str(e)}" error_message = f"Unexpected error: {e}"
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]

View file

@ -96,6 +96,6 @@ class YfinanceToolComponent(LCToolComponent):
return data_list return data_list
except Exception as e: except Exception as e:
error_message = f"Error retrieving data: {str(e)}" error_message = f"Error retrieving data: {e}"
self.status = error_message self.status = error_message
return [Data(data={"error": error_message})] return [Data(data={"error": error_message})]

View file

@ -427,7 +427,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
try: try:
vector_store = AstraDBVectorStore(**vector_store_kwargs) vector_store = AstraDBVectorStore(**vector_store_kwargs)
except Exception as e: except Exception as e:
msg = f"Error initializing AstraDBVectorStore: {str(e)}" msg = f"Error initializing AstraDBVectorStore: {e}"
raise ValueError(msg) from e raise ValueError(msg) from e
self._add_documents_to_vector_store(vector_store) self._add_documents_to_vector_store(vector_store)
@ -448,7 +448,7 @@ class AstraVectorStoreComponent(LCVectorStoreComponent):
try: try:
vector_store.add_documents(documents) vector_store.add_documents(documents)
except Exception as e: 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 raise ValueError(msg) from e
else: else:
logger.debug("No documents to add to the Vector Store.") 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) docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args)
except Exception as e: 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 raise ValueError(msg) from e
logger.debug(f"Retrieved documents: {len(docs)}") logger.debug(f"Retrieved documents: {len(docs)}")

View file

@ -225,7 +225,7 @@ class CassandraVectorStoreComponent(LCVectorStoreComponent):
search_type = self._map_search_type() search_type = self._map_search_type()
search_args = self._build_search_args() 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) docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args)
except KeyError as e: except KeyError as e:

View file

@ -204,7 +204,7 @@ class CassandraGraphVectorStoreComponent(LCVectorStoreComponent):
search_type = self._map_search_type() search_type = self._map_search_type()
search_args = self._build_search_args() 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) docs = vector_store.search(query=self.search_query, search_type=search_type, **search_args)
except KeyError as e: except KeyError as e:

View file

@ -198,7 +198,7 @@ class ElasticsearchVectorStoreComponent(LCVectorStoreComponent):
msg = f"Invalid search type: {self.search_type}" msg = f"Invalid search type: {self.search_type}"
raise ValueError(msg) raise ValueError(msg)
except Exception as e: except Exception as e:
logger.error(f"Search query failed: {str(e)}") logger.error(f"Search query failed: {e}")
msg = ( msg = (
"Error occurred while querying the Elasticsearch VectorStore," "Error occurred while querying the Elasticsearch VectorStore,"
" there is no Data into the VectorStore." " there is no Data into the VectorStore."

View file

@ -247,7 +247,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
try: try:
vector_store = AstraDBVectorStore(**vector_store_kwargs) vector_store = AstraDBVectorStore(**vector_store_kwargs)
except Exception as e: except Exception as e:
msg = f"Error initializing AstraDBVectorStore: {str(e)}" msg = f"Error initializing AstraDBVectorStore: {e}"
raise ValueError(msg) from e raise ValueError(msg) from e
self._add_documents_to_vector_store(vector_store) self._add_documents_to_vector_store(vector_store)
@ -267,7 +267,7 @@ class HCDVectorStoreComponent(LCVectorStoreComponent):
try: try:
vector_store.add_documents(documents) vector_store.add_documents(documents)
except Exception as e: 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 raise ValueError(msg) from e
else: else:
logger.debug("No documents to add to the Vector Store.") 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) docs = vector_store.search(query=self.search_input, search_type=search_type, **search_args)
except Exception as e: 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 raise ValueError(msg) from e
logger.debug(f"Retrieved documents: {len(docs)}") logger.debug(f"Retrieved documents: {len(docs)}")

View file

@ -124,7 +124,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try: try:
from langchain_community.vectorstores import OpenSearchVectorSearch from langchain_community.vectorstores import OpenSearchVectorSearch
except ImportError as e: 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) logger.error(error_message)
raise ImportError(error_message) from e raise ImportError(error_message) from e
@ -140,7 +140,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
ssl_show_warn=False, ssl_show_warn=False,
) )
except Exception as e: 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) logger.error(error_message)
raise RuntimeError(error_message) from e raise RuntimeError(error_message) from e
@ -167,7 +167,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try: try:
vector_store.add_documents(documents) vector_store.add_documents(documents)
except Exception as e: 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(error_message)
logger.error(f"Traceback: {traceback.format_exc()}") logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e raise RuntimeError(error_message) from e
@ -187,7 +187,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
try: try:
hybrid_query = json.loads(self.hybrid_search_query) hybrid_query = json.loads(self.hybrid_search_query)
except json.JSONDecodeError as e: 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) logger.error(error_message)
raise ValueError(error_message) from e raise ValueError(error_message) from e
@ -236,7 +236,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
raise ValueError(error_message) raise ValueError(error_message)
except Exception as e: 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(error_message)
logger.error(f"Traceback: {traceback.format_exc()}") logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e raise RuntimeError(error_message) from e
@ -259,7 +259,7 @@ class OpenSearchVectorStoreComponent(LCVectorStoreComponent):
self.status = retrieved_data self.status = retrieved_data
return retrieved_data return retrieved_data
except Exception as e: 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(error_message)
logger.error(f"Traceback: {traceback.format_exc()}") logger.error(f"Traceback: {traceback.format_exc()}")
raise RuntimeError(error_message) from e raise RuntimeError(error_message) from e

View file

@ -217,7 +217,7 @@ class DirectoryReader:
file_content = self.read_file_content(file_path) file_content = self.read_file_content(file_path)
except Exception as exc: except Exception as exc:
logger.exception(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}" return False, f"Could not read {file_path}"
if file_content is None: if file_content is None:
@ -294,7 +294,7 @@ class DirectoryReader:
file_content = self.read_file_content(file_path) file_content = self.read_file_content(file_path)
except Exception as exc: except Exception as exc:
logger.exception(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}" return False, f"Could not read {file_path}"
if file_content is None: if file_content is None:
@ -347,7 +347,7 @@ class DirectoryReader:
try: try:
output_types = await self.get_output_types_from_code_async(result_content) output_types = await self.get_output_types_from_code_async(result_content)
except Exception as exc: 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] output_types = [component_name_camelcase]
else: else:
output_types = [component_name_camelcase] output_types = [component_name_camelcase]

View file

@ -133,7 +133,7 @@ def build_invalid_menu_items(menu_item):
menu_items[component_name] = component_template menu_items[component_name] = component_template
logger.debug(f"Added {component_name} to invalid menu.") logger.debug(f"Added {component_name} to invalid menu.")
except Exception as exc: 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 return menu_items

View file

@ -273,7 +273,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
msg = "Invalid code type" msg = "Invalid code type"
raise ValueError(msg) raise ValueError(msg)
except Exception as exc: 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( raise HTTPException(
status_code=400, status_code=400,
detail={ detail={
@ -285,7 +285,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
try: try:
return custom_class(_user_id=user_id, _code=custom_component._code) return custom_class(_user_id=user_id, _code=custom_component._code)
except Exception as exc: 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: if hasattr(exc, "detail") and "traceback" in exc.detail:
logger.error(exc.detail["traceback"]) logger.error(exc.detail["traceback"])
@ -308,7 +308,7 @@ def run_build_config(
msg = "Invalid code type" msg = "Invalid code type"
raise ValueError(msg) raise ValueError(msg)
except Exception as exc: 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( raise HTTPException(
status_code=400, status_code=400,
detail={ detail={
@ -333,7 +333,7 @@ def run_build_config(
return build_config, custom_instance return build_config, custom_instance
except Exception as exc: 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: if hasattr(exc, "detail") and "traceback" in exc.detail:
logger.error(exc.detail["traceback"]) logger.error(exc.detail["traceback"])
@ -423,7 +423,7 @@ def build_custom_component_template(
raise HTTPException( raise HTTPException(
status_code=400, status_code=400,
detail={ detail={
"error": (f"Error building Component: {str(exc)}"), "error": (f"Error building Component: {exc}"),
"traceback": traceback.format_exc(), "traceback": traceback.format_exc(),
}, },
) from exc ) from exc
@ -521,8 +521,8 @@ def update_field_dict(
) )
build_config = dd_build_config build_config = dd_build_config
except Exception as exc: except Exception as exc:
logger.error(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: {str(exc)}" msg = f"Error while running update_build_config: {exc}"
raise UpdateBuildConfigError(msg) from exc raise UpdateBuildConfigError(msg) from exc
return build_config return build_config

View file

@ -452,7 +452,7 @@ class Graph:
# and run self.build_adjacency_maps(edges) to get the new predecessor map # 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 # that is not complete but we can use to update the run_predecessors
edges_set = set() edges_set = set()
for _vertex in [vertex] + successors: for _vertex in [vertex, *successors]:
edges_set.update(_vertex.edges) edges_set.update(_vertex.edges)
if _vertex.state == VertexStates.INACTIVE: if _vertex.state == VertexStates.INACTIVE:
_vertex.set_state("ACTIVE") _vertex.set_state("ACTIVE")
@ -1013,7 +1013,7 @@ class Graph:
Creates a graph from a payload. Creates a graph from a payload.
Args: Args:
payload (Dict): The payload to create the graph from.˜` payload (Dict): The payload to create the graph from.`
Returns: Returns:
Graph: The created graph. Graph: The created graph.
@ -1617,7 +1617,7 @@ class Graph:
successors_result.append([successor]) successors_result.append([successor])
if not flat and successors_result: if not flat and successors_result:
return [successors] + successors_result return [successors, *successors_result]
return successors_result return successors_result
@ -1893,7 +1893,7 @@ class Graph:
if not chat_inputs_first: if not chat_inputs_first:
return vertices_layers 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]]: 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.""" """Sorts the vertices in each layer by dependency, ensuring no vertex depends on a subsequent vertex."""

View file

@ -682,7 +682,7 @@ class Vertex:
logger.exception(e) logger.exception(e)
msg = ( msg = (
f"Params {key} ({self.params[key]}) is not a list and cannot be extended with {result}" 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 raise ValueError(msg) from e

View file

@ -161,7 +161,7 @@ def update_new_output(data):
new_source_handle["output_types"] = new_source_handle["baseClasses"] new_source_handle["output_types"] = new_source_handle["baseClasses"]
del 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 = [ intersection = [
type_ for type_ in new_source_handle["output_types"] if type_ in new_target_handle["inputTypes"] type_ for type_ in new_source_handle["output_types"] if type_ in new_target_handle["inputTypes"]
] ]

View file

@ -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 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. to the possible new key.
""" """
input_key = [ input_key = next(
key key
for key in langchain_object.input_keys for key in langchain_object.input_keys
if key not in [langchain_object.memory.memory_key, possible_new_mem_key] if key not in [langchain_object.memory.memory_key, possible_new_mem_key]
][0] )
output_key = [ output_key = next(
key key
for key in langchain_object.output_keys for key in langchain_object.output_keys
if key not in [langchain_object.memory.memory_key, possible_new_mem_key] 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")]: for key, attr in [(input_key, "input_key"), (output_key, "output_key"), (possible_new_mem_key, "memory_key")]:
try: try:

View file

@ -1,3 +1,5 @@
from __future__ import annotations
import asyncio import asyncio
import json import json
from collections.abc import AsyncIterator, Iterator from collections.abc import AsyncIterator, Iterator
@ -119,7 +121,7 @@ class Message(Data):
return AIMessage(content=text) # type: ignore return AIMessage(content=text) # type: ignore
@classmethod @classmethod
def from_lc_message(cls, lc_message: BaseMessage) -> "Message": def from_lc_message(cls, lc_message: BaseMessage) -> Message:
if lc_message.type == "human": if lc_message.type == "human":
sender = MESSAGE_SENDER_USER sender = MESSAGE_SENDER_USER
sender_name = MESSAGE_SENDER_NAME_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) return cls(text=lc_message.content, sender=sender, sender_name=sender_name)
@classmethod @classmethod
def from_data(cls, data: "Data") -> "Message": def from_data(cls, data: Data) -> Message:
""" """
Converts a BaseMessage to a Data. Converts a BaseMessage to a Data.
@ -231,7 +233,7 @@ class Message(Data):
content_dicts = await value.get_file_content_dicts() content_dicts = await value.get_file_content_dicts()
contents.extend(content_dicts) contents.extend(content_dicts)
if contents: 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 prompt_template = ChatPromptTemplate.from_messages([message]) # type: ignore

View file

@ -16,7 +16,7 @@ from sqlalchemy.exc import OperationalError
from sqlmodel import Session, SQLModel, create_engine, select, text from sqlmodel import Session, SQLModel, create_engine, select, text
from langflow.services.base import Service 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.models.user.crud import get_user_by_username
from langflow.services.database.utils import ( from langflow.services.database.utils import (
Result, Result,
@ -87,7 +87,7 @@ class DatabaseService(Service):
pragmas_list = [] pragmas_list = []
for key, val in pragmas.items() or {}: for key, val in pragmas.items() or {}:
pragmas_list.append(f"PRAGMA {key} = {val}") 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: if pragmas_list:
cursor = dbapi_connection.cursor() cursor = dbapi_connection.cursor()
try: try:

View file

@ -1,6 +1,6 @@
from collections.abc import Callable # noqa: I001 from collections.abc import Callable # noqa: I001
from enum import Enum 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 _GenericAlias # type: ignore from typing import _GenericAlias # type: ignore
from typing import _UnionGenericAlias # type: ignore from typing import _UnionGenericAlias # type: ignore

View file

@ -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["load_from_db"] = previous_value_dict.get("load_from_db", False)
template_field["value"] = previous_value_dict["value"] 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"]) file_path_value = get_file_path_value(previous_value_dict["file_path"])
if not file_path_value: if not file_path_value:
# If the file does not exist, remove the value from the template_field["value"] # If the file does not exist, remove the value from the template_field["value"]

View file

@ -155,7 +155,7 @@ def get_base_classes(cls):
result = [cls.__name__] result = [cls.__name__]
if not result: if not result:
result = [cls.__name__] result = [cls.__name__]
return list(set(result + [cls.__name__])) return list({*result, cls.__name__})
def get_default_factory(module: str, function: str): def get_default_factory(module: str, function: str):

View file

@ -190,6 +190,7 @@ select = [
"Q", "Q",
"RET", "RET",
"RSE", "RSE",
"RUF",
"SIM", "SIM",
"SLOT", "SLOT",
"T10", "T10",
@ -202,6 +203,8 @@ select = [
ignore = [ ignore = [
"COM812", # Messes with the formatter "COM812", # Messes with the formatter
"ISC001", # 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] [tool.ruff.lint.per-file-ignores]