Skip to content

Commit

Permalink
Add ruff rules RUF
Browse files Browse the repository at this point in the history
  • Loading branch information
cbornet committed Oct 4, 2024
1 parent e2d907f commit b0338b7
Show file tree
Hide file tree
Showing 86 changed files with 196 additions and 228 deletions.
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/v1/callback.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/v1/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -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})"
)
Expand Down
12 changes: 6 additions & 6 deletions src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
):
Expand Down Expand Up @@ -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),
):
"""
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/api/v1/flows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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")
Expand Down
14 changes: 5 additions & 9 deletions src/backend/base/langflow/base/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/flow_processing/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
5 changes: 4 additions & 1 deletion src/backend/base/langflow/base/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions src/backend/base/langflow/base/prompts/api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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

Expand Down Expand Up @@ -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:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 = []
Expand Down
4 changes: 2 additions & 2 deletions src/backend/base/langflow/components/Notion/create_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}",
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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}"
6 changes: 3 additions & 3 deletions src/backend/base/langflow/components/Notion/list_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,16 +105,16 @@ 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)
response.raise_for_status()
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}"
Original file line number Diff line number Diff line change
Expand Up @@ -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 = ""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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

Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/agents/CSVAgent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/agents/JsonAgent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/agents/OpenAPIAgent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/agents/SQLAgent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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),
]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/agents/XMLAgent.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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})

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Loading

0 comments on commit b0338b7

Please sign in to comment.