Skip to content

Commit

Permalink
feat: Add ruff rules for pycodestyle Errors (E) (langflow-ai#3947)
Browse files Browse the repository at this point in the history
Add ruff rules for pycodestyle Errors (E)
  • Loading branch information
cbornet authored and diogocabral committed Nov 26, 2024
1 parent 306ab62 commit 0f41c71
Show file tree
Hide file tree
Showing 69 changed files with 282 additions and 126 deletions.
15 changes: 11 additions & 4 deletions src/backend/base/langflow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def set_var_for_macos_issue():
import os

os.environ["OBJC_DISABLE_INITIALIZE_FORK_SAFETY"] = "YES"
# https://stackoverflow.com/questions/75747888/uwsgi-segmentation-fault-with-flask-python-app-behind-nginx-after-running-for-2 # noqa
# https://stackoverflow.com/questions/75747888/uwsgi-segmentation-fault-with-flask-python-app-behind-nginx-after-running-for-2 # noqa: E501
os.environ["no_proxy"] = "*" # to avoid error with gunicorn
logger.debug("Set OBJC_DISABLE_INITIALIZE_FORK_SAFETY to YES to avoid error")

Expand Down Expand Up @@ -336,8 +336,14 @@ def print_banner(host: str, port: int):
styled_package_name = stylize_text(package_name, package_name, any("pre-release" in notice for notice in notices))

title = f"[bold]Welcome to :chains: {styled_package_name}[/bold]\n"
info_text = "Collaborate, and contribute at our [bold][link=https://github.com/langflow-ai/langflow]GitHub Repo[/link][/bold] :star2:"
telemetry_text = "We collect anonymous usage data to improve Langflow.\nYou can opt-out by setting [bold]DO_NOT_TRACK=true[/bold] in your environment."
info_text = (
"Collaborate, and contribute at our "
"[bold][link=https://github.com/langflow-ai/langflow]GitHub Repo[/link][/bold] :star2:"
)
telemetry_text = (
"We collect anonymous usage data to improve Langflow.\n"
"You can opt-out by setting [bold]DO_NOT_TRACK=true[/bold] in your environment."
)
access_link = f"Access [link=http://{host}:{port}]http://{host}:{port}[/link]"

panel_content = "\n\n".join([title, *styled_notices, info_text, telemetry_text, access_link])
Expand Down Expand Up @@ -411,7 +417,8 @@ def copy_db():
"""
Copy the database files to the current directory.
This function copies the 'langflow.db' and 'langflow-pre.db' files from the cache directory to the current directory.
This function copies the 'langflow.db' and 'langflow-pre.db' files from the cache directory to the current
directory.
If the files exist in the cache directory, they will be copied to the same directory as this script (__main__.py).
Returns:
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/api/health_check_router.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ class HealthResponse(BaseModel):
chat: str = "error check the server logs"
db: str = "error check the server logs"
"""
Do not send exceptions and detailed error messages to the client because it might contain credentials and other sensitive server information.
Do not send exceptions and detailed error messages to the client because it might contain credentials and other
sensitive server information.
"""

def has_error(self) -> bool:
Expand Down
10 changes: 8 additions & 2 deletions src/backend/base/langflow/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,10 +230,16 @@ def get_suggestion_message(outdated_components: list[str]) -> str:
if count == 0:
return "The flow contains no outdated components."
elif count == 1:
return f"The flow contains 1 outdated component. We recommend updating the following component: {outdated_components[0]}."
return (
"The flow contains 1 outdated component. "
f"We recommend updating the following component: {outdated_components[0]}."
)
else:
components = ", ".join(outdated_components)
return f"The flow contains {count} outdated components. We recommend updating the following components: {components}."
return (
f"The flow contains {count} outdated components. "
f"We recommend updating the following components: {components}."
)


def parse_value(value: Any, input_type: str) -> Any:
Expand Down
4 changes: 3 additions & 1 deletion src/backend/base/langflow/api/v1/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -411,7 +411,9 @@ 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)} (time in queue, {get_time - put_time:.4f}, client {get_time_yield - get_time:.4f})"
f"consumed event {str(event_id)} "
f"(time in queue, {get_time - put_time:.4f}, "
f"client {get_time_yield - get_time:.4f})"
)

asyncio_queue: asyncio.Queue = asyncio.Queue()
Expand Down
67 changes: 46 additions & 21 deletions src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,31 +186,44 @@ async def simplified_run_flow(
telemetry_service: TelemetryService = Depends(get_telemetry_service),
):
"""
Executes a specified flow by ID with input customization, performance enhancements through caching, and optional data streaming.
Executes a specified flow by ID with input customization, performance enhancements through caching, and optional
data streaming.
### Parameters:
- `db` (Session): Database session for executing queries.
- `flow_id_or_name` (str): ID or endpoint name of the flow to run.
- `input_request` (SimplifiedAPIRequest): Request object containing input values, types, output selection, tweaks, and session ID.
- `input_request` (SimplifiedAPIRequest): Request object containing input values, types, output selection, tweaks,
and session ID.
- `api_key_user` (User): User object derived from the provided API key, used for authentication.
- `session_service` (SessionService): Service for managing flow sessions, essential for session reuse and caching.
### SimplifiedAPIRequest:
- `input_value` (Optional[str], default=""): Input value to pass to the flow.
- `input_type` (Optional[Literal["chat", "text", "any"]], default="chat"): Type of the input value, determining how the input is interpreted.
- `output_type` (Optional[Literal["chat", "text", "any", "debug"]], default="chat"): Desired type of output, affecting which components' outputs are included in the response. If set to "debug", all outputs are returned.
- `output_component` (Optional[str], default=None): Specific component output to retrieve. If provided, only the output of the specified component is returned. This overrides the `output_type` parameter.
- `tweaks` (Optional[Tweaks], default=None): Adjustments to the flow's behavior, allowing for custom execution parameters.
- `session_id` (Optional[str], default=None): An identifier for reusing session data, aiding in performance for subsequent requests.
- `input_type` (Optional[Literal["chat", "text", "any"]], default="chat"): Type of the input value,
determining how the input is interpreted.
- `output_type` (Optional[Literal["chat", "text", "any", "debug"]], default="chat"): Desired type of output,
affecting which components' outputs are included in the response. If set to "debug", all outputs are returned.
- `output_component` (Optional[str], default=None): Specific component output to retrieve. If provided,
only the output of the specified component is returned. This overrides the `output_type` parameter.
- `tweaks` (Optional[Tweaks], default=None): Adjustments to the flow's behavior, allowing for custom execution
parameters.
- `session_id` (Optional[str], default=None): An identifier for reusing session data, aiding in performance for
subsequent requests.
### Tweaks
A dictionary of tweaks to customize the flow execution. The tweaks can be used to modify the flow's parameters and components. Tweaks can be overridden by the input values.
You can use Component's `id` or Display Name as key to tweak a specific component (e.g., `{"Component Name": {"parameter_name": "value"}}`).
You can also use the parameter name as key to tweak all components with that parameter (e.g., `{"parameter_name": "value"}`).
A dictionary of tweaks to customize the flow execution.
The tweaks can be used to modify the flow's parameters and components.
Tweaks can be overridden by the input values.
You can use Component's `id` or Display Name as key to tweak a specific component
(e.g., `{"Component Name": {"parameter_name": "value"}}`).
You can also use the parameter name as key to tweak all components with that parameter
(e.g., `{"parameter_name": "value"}`).
### Returns:
- A `RunResponse` object containing the execution results, including selected (or all, based on `output_type`) outputs of the flow and the session ID, facilitating result retrieval and further interactions in a session context.
- A `RunResponse` object containing the execution results, including selected (or all, based on `output_type`)
outputs of the flow and the session ID, facilitating result retrieval and further interactions in a session
context.
### Raises:
- HTTPException: 404 if the specified flow ID curl -X 'POST' \
Expand All @@ -231,7 +244,9 @@ async def simplified_run_flow(
}'
```
This endpoint provides a powerful interface for executing flows with enhanced flexibility and efficiency, supporting a wide range of applications by allowing for dynamic input and output configuration along with performance optimizations through session management and caching.
This endpoint provides a powerful interface for executing flows with enhanced flexibility and efficiency,
supporting a wide range of applications by allowing for dynamic input and output configuration along with
performance optimizations through session management and caching.
"""
if flow is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Flow not found")
Expand Down Expand Up @@ -382,19 +397,27 @@ async def experimental_run_flow(
### Parameters:
- `flow_id` (str): The unique identifier of the flow to be executed.
- `inputs` (List[InputValueRequest], optional): A list of inputs specifying the input values and components for the flow. Each input can target specific components and provide custom values.
- `outputs` (List[str], optional): A list of output names to retrieve from the executed flow. If not provided, all outputs are returned.
- `tweaks` (Optional[Tweaks], optional): A dictionary of tweaks to customize the flow execution. The tweaks can be used to modify the flow's parameters and components. Tweaks can be overridden by the input values.
- `inputs` (List[InputValueRequest], optional): A list of inputs specifying the input values and components
for the flow. Each input can target specific components and provide custom values.
- `outputs` (List[str], optional): A list of output names to retrieve from the executed flow.
If not provided, all outputs are returned.
- `tweaks` (Optional[Tweaks], optional): A dictionary of tweaks to customize the flow execution.
The tweaks can be used to modify the flow's parameters and components.
Tweaks can be overridden by the input values.
- `stream` (bool, optional): Specifies whether the results should be streamed. Defaults to False.
- `session_id` (Union[None, str], optional): An optional session ID to utilize existing session data for the flow execution.
- `session_id` (Union[None, str], optional): An optional session ID to utilize existing session data for the flow
execution.
- `api_key_user` (User): The user associated with the current API key. Automatically resolved from the API key.
- `session_service` (SessionService): The session service object for managing flow sessions.
### Returns:
A `RunResponse` object containing the selected outputs (or all if not specified) of the executed flow and the session ID. The structure of the response accommodates multiple inputs, providing a nested list of outputs for each input.
A `RunResponse` object containing the selected outputs (or all if not specified) of the executed flow
and the session ID.
The structure of the response accommodates multiple inputs, providing a nested list of outputs for each input.
### Raises:
HTTPException: Indicates issues with finding the specified flow, invalid input formats, or internal errors during flow execution.
HTTPException: Indicates issues with finding the specified flow, invalid input formats, or internal errors during
flow execution.
### Example usage:
```json
Expand All @@ -412,8 +435,9 @@ async def experimental_run_flow(
}
```
This endpoint facilitates complex flow executions with customized inputs, outputs, and configurations, catering to diverse application requirements.
"""
This endpoint facilitates complex flow executions with customized inputs, outputs, and configurations,
catering to diverse application requirements.
""" # noqa: E501
try:
flow_id_str = str(flow_id)
if outputs is None:
Expand Down Expand Up @@ -582,7 +606,8 @@ async def custom_component_update(
Update a custom component with the provided code request.
This endpoint generates the CustomComponentFrontendNode normally but then runs the `update_build_config` method
on the latest version of the template. This ensures that every time it runs, it has the latest version of the template.
on the latest version of the template.
This ensures that every time it runs, it has the latest version of the template.
Args:
code_request (CustomComponentRequest): The code request containing the updated code for the custom component.
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/api/v1/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,8 @@ class InputValueRequest(BaseModel):
input_value: str | None = None
type: InputType | None = Field(
"any",
description="Defines on which components the input value should be applied. 'any' applies to all input components.",
description="Defines on which components the input value should be applied. "
"'any' applies to all input components.",
)

# add an example
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/agents/default_prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,4 +20,4 @@
{chat_history}
Question: {input}
{agent_scratchpad}"""
{agent_scratchpad}""" # noqa: E501
9 changes: 6 additions & 3 deletions src/backend/base/langflow/base/curl/parse.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
"""
This file contains a fix for the implementation of the `uncurl` library, which is available at https://github.com/spulec/uncurl.git.
The `uncurl` library provides a way to parse and convert cURL commands into Python requests. However, there are some issues with the original implementation that this file aims to fix.
The `uncurl` library provides a way to parse and convert cURL commands into Python requests.
However, there are some issues with the original implementation that this file aims to fix.
The `parse_context` function in this file takes a cURL command as input and returns a `ParsedContext` object, which contains the parsed information from the cURL command, such as the HTTP method, URL, headers, cookies, etc.
The `parse_context` function in this file takes a cURL command as input and returns a `ParsedContext` object,
which contains the parsed information from the cURL command, such as the HTTP method, URL, headers, cookies, etc.
The `normalize_newlines` function is a helper function that replaces the line continuation character ("\") followed by a newline with a space.
The `normalize_newlines` function is a helper function that replaces the line continuation character ("\")
followed by a newline with a space.
"""
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/io/text.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ def build_config(self):
"data_template": {
"display_name": "Data Template",
"multiline": True,
"info": "Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.",
"info": "Template to convert Data to Text. "
"If left empty, it will be dynamically set to the Data's text key.",
"advanced": True,
},
}
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/memory/memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ def build_config(self):
"data_template": {
"display_name": "Data Template",
"multiline": True,
"info": "Template to convert Data to Text. If left empty, it will be dynamically set to the Data's text key.",
"info": "Template to convert Data to Text. "
"If left empty, it will be dynamically set to the Data's text key.",
"advanced": True,
},
}
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/tools/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ def build_status_from_tool(tool: Tool):
tool (Tool): The tool object to build the status for.
Returns:
str: The status string representation of the tool, including its name, description, arguments (if any), and args_schema (if any).
str: The status string representation of the tool, including its name, description, arguments (if any),
and args_schema (if any).
"""
description_repr = repr(tool.description).strip("'")
args_str = "\n".join(
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/vectorstores/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,8 @@ def __init_subclass__(cls, **kwargs):
method = cls.build_vector_store
if not hasattr(method, "_is_cached_vector_store_checked"):
raise TypeError(
f"The method 'build_vector_store' in class {cls.__name__} must be decorated with @check_cached_vector_store"
f"The method 'build_vector_store' in class {cls.__name__} "
"must be decorated with @check_cached_vector_store"
)

trace_type = "retriever"
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/Notion/create_page.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,8 @@ def run_model(self) -> Data:
def build_tool(self) -> Tool:
return StructuredTool.from_function(
name="create_notion_page",
description="Create a new page in a Notion database. IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
description="Create a new page in a Notion database. "
"IMPORTANT: Use the tool to check the Database properties for more details before using this tool.",
func=self._create_notion_page,
args_schema=self.NotionPageCreatorSchema,
)
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/components/Notion/list_pages.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ class NotionListPages(LCToolComponent):
"Query a Notion database with filtering and sorting. "
"The input should be a JSON string containing the 'filter' and 'sorts' objects. "
"Example input:\n"
'{"filter": {"property": "Status", "select": {"equals": "Done"}}, "sorts": [{"timestamp": "created_time", "direction": "descending"}]}'
'{"filter": {"property": "Status", "select": {"equals": "Done"}}, '
'"sorts": [{"timestamp": "created_time", "direction": "descending"}]}'
)
documentation: str = "https://docs.langflow.org/integrations/notion/list-pages"
icon = "NotionDirectoryLoader"
Expand All @@ -37,15 +38,17 @@ class NotionListPages(LCToolComponent):
MultilineInput(
name="query_json",
display_name="Database query (JSON)",
info="A JSON string containing the filters and sorts that will be used for querying the database. Leave empty for no filters or sorts.",
info="A JSON string containing the filters and sorts that will be used for querying the database. "
"Leave empty for no filters or sorts.",
),
]

class NotionListPagesSchema(BaseModel):
database_id: str = Field(..., description="The ID of the Notion database to query.")
query_json: str | None = Field(
default="",
description="A JSON string containing the filters and sorts for querying the database. Leave empty for no filters or sorts.",
description="A JSON string containing the filters and sorts for querying the database. "
"Leave empty for no filters or sorts.",
)

def run_model(self) -> list[Data]:
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/components/Notion/search.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,8 @@ def run_model(self) -> list[Data]:
def build_tool(self) -> Tool:
return StructuredTool.from_function(
name="notion_search",
description="Search Notion pages and databases. Input should include the search query and optionally filter type and sort direction.",
description="Search Notion pages and databases. "
"Input should include the search query and optionally filter type and sort direction.",
func=self._search_notion,
args_schema=self.NotionSearchSchema,
)
Expand Down
Loading

0 comments on commit 0f41c71

Please sign in to comment.