ref: Add ruff rules for pydocstyle (D) (#4120)

Add ruff rules for pydocstyle (D)
This commit is contained in:
Christophe Bornet 2024-10-14 17:17:50 +02:00 • committed by GitHub
commit b1a79c0749
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
119 changed files with 634 additions and 1245 deletions

View file

@ -46,9 +46,7 @@ def get_number_of_workers(workers=None):
def display_results(results):
"""
Display the results of the migration.
"""
"""Display the results of the migration."""
for table_results in results:
table = Table(title=f"Migration {table_results.table_name}")
table.add_column("Name")
@ -149,10 +147,7 @@ def run(
show_default=False,
),
):
"""
Run Langflow.
"""
"""Run Langflow."""
configure(log_level=log_level, log_file=log_file)
set_var_for_macos_issue()
@ -225,9 +220,7 @@ def run(
def wait_for_server_ready(host, port):
"""
Wait for the server to become ready by polling the health endpoint.
"""
"""Wait for the server to become ready by polling the health endpoint."""
status_code = 0
while status_code != httpx.codes.OK:
try:
@ -249,16 +242,13 @@ def run_on_mac_or_linux(host, port, log_level, options, app):
def run_on_windows(host, port, log_level, options, app):
"""
Run the Langflow server on Windows.
"""
"""Run the Langflow server on Windows."""
print_banner(host, port)
run_langflow(host, port, log_level, options, app)
def is_port_in_use(port, host="localhost"):
"""
Check if a port is in use.
"""Check if a port is in use.
Args:
port (int): The port number to check.
@ -272,8 +262,7 @@ def is_port_in_use(port, host="localhost"):
def get_free_port(port):
"""
Given a used port, find a free port.
"""Given a used port, find a free port.
Args:
port (int): The port number to check.
@ -287,9 +276,7 @@ def get_free_port(port):
def get_letter_from_version(version: str):
"""
Get the letter from a pre-release version.
"""
"""Get the letter from a pre-release version."""
if "a" in version:
return "a"
if "b" in version:
@ -308,9 +295,7 @@ def build_version_notice(current_version: str, package_name: str) -> str:
def generate_pip_command(package_names, is_pre_release):
"""
Generate the pip install command based on the packages and whether it's a pre-release.
"""
"""Generate the pip install command based on the packages and whether it's a pre-release."""
base_command = "pip install"
if is_pre_release:
return f"{base_command} {' '.join(package_names)} -U --pre"
@ -369,10 +354,7 @@ def print_banner(host: str, port: int):
def run_langflow(host, port, log_level, options, app):
"""
Run Langflow server on localhost
"""
"""Run Langflow server on localhost."""
if platform.system() == "Windows":
# Run using uvicorn on MacOS and Windows
# Windows doesn't support gunicorn
@ -398,9 +380,7 @@ def superuser(
password: str = typer.Option(..., prompt=True, hide_input=True, help="Password for the superuser."),
log_level: str = typer.Option("error", help="Logging level.", envvar="LANGFLOW_LOG_LEVEL"),
):
"""
Create a superuser.
"""
"""Create a superuser."""
configure(log_level=log_level)
initialize_services()
db_service = get_db_service()
@ -432,8 +412,7 @@ def superuser(
# because now the database is stored per installation
@app.command()
def copy_db():
"""
Copy the database files to the current directory.
"""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.
@ -472,9 +451,7 @@ def migration(
help="Fix migrations. This is a destructive operation, and should only be used if you know what you are doing.",
),
):
"""
Run or test migrations.
"""
"""Run or test migrations."""
if fix and not typer.confirm(
"This will delete all data necessary to fix migrations. Are you sure you want to continue?"
):
@ -492,8 +469,7 @@ def migration(
def api_key(
log_level: str = typer.Option("error", help="Logging level."),
):
"""
Creates an API key for the default superuser if AUTO_LOGIN is enabled.
"""Creates an API key for the default superuser if AUTO_LOGIN is enabled.
Args:
log_level (str, optional): Logging level. Defaults to "error".

View file

@ -55,10 +55,10 @@ async def event_generator(request: Request):
async def stream_logs(
request: Request,
):
"""
HTTP/2 Server-Sent-Event (SSE) endpoint for streaming logs
it establishes a long-lived connection to the server and receives log messages in real-time
the client should use the head "Accept: text/event-stream"
"""HTTP/2 Server-Sent-Event (SSE) endpoint for streaming logs.
It establishes a long-lived connection to the server and receives log messages in real-time.
The client should use the header "Accept: text/event-stream".
"""
global log_buffer # noqa: PLW0602
if log_buffer.enabled() is False:

View file

@ -43,7 +43,6 @@ def remove_api_keys(flow: dict):
def build_input_keys_response(langchain_object, artifacts):
"""Build the input keys response."""
input_keys_response = {
"input_keys": dict.fromkeys(langchain_object.input_keys, ""),
"memory_keys": [],
@ -201,8 +200,7 @@ def format_exception_message(exc: Exception) -> str:
def get_top_level_vertices(graph, vertices_ids):
"""
Retrieves the top-level vertices from the given graph based on the provided vertex IDs.
"""Retrieves the top-level vertices from the given graph based on the provided vertex IDs.
Args:
graph (Graph): The graph object containing the vertices.

View file

@ -78,16 +78,17 @@ async def retrieve_vertices_order(
session=Depends(get_session),
telemetry_service: TelemetryService = Depends(get_telemetry_service),
):
"""
Retrieve the vertices order for a given flow.
"""Retrieve the vertices order for a given flow.
Args:
flow_id (str): The ID of the flow.
background_tasks (BackgroundTasks): The background tasks.
data (Optional[FlowDataRequest], optional): The flow data. Defaults to None.
stop_component_id (str, optional): The ID of the stop component. Defaults to None.
start_component_id (str, optional): The ID of the start component. Defaults to None.
chat_service (ChatService, optional): The chat service dependency. Defaults to Depends(get_chat_service).
session (Session, optional): The session dependency. Defaults to Depends(get_session).
telemetry_service (TelemetryService, optional): The telemetry service.
Returns:
VerticesOrderResponse: The response containing the ordered vertex IDs and the run ID.
@ -471,8 +472,10 @@ async def build_vertex(
vertex_id (str): The ID of the vertex to build.
background_tasks (BackgroundTasks): The background tasks dependency.
inputs (Optional[InputValueRequest], optional): The input values for the vertex. Defaults to None.
files (List[str], optional): The files to use. Defaults to None.
chat_service (ChatService, optional): The chat service dependency. Defaults to Depends(get_chat_service).
current_user (Any, optional): The current user dependency. Defaults to Depends(get_current_active_user).
telemetry_service (TelemetryService, optional): The telemetry service.
Returns:
VertexBuildResponse: The response containing the built vertex information.

View file

@ -156,9 +156,7 @@ async def simple_run_flow_task(
stream: bool = False,
api_key_user: User | None = None,
):
"""
Run a flow task as a BackgroundTask, therefore it should not throw exceptions.
"""
"""Run a flow task as a BackgroundTask, therefore it should not throw exceptions."""
try:
return await simple_run_flow(
flow=flow,
@ -180,9 +178,10 @@ async def simplified_run_flow(
api_key_user: UserRead = Depends(api_key_security),
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.
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.
@ -301,15 +300,14 @@ async def webhook_run_flow(
background_tasks: BackgroundTasks,
telemetry_service: Annotated[TelemetryService, Depends(get_telemetry_service)],
):
"""
Run a flow using a webhook request.
"""Run a flow using a webhook request.
Args:
db (Session): The database session.
flow (Flow, optional): The flow to be executed. Defaults to Depends(get_flow_by_id).
user (User): The flow user.
request (Request): The incoming HTTP request.
background_tasks (BackgroundTasks): The background tasks manager.
session_service (SessionService, optional): The session service. Defaults to Depends(get_session_service).
flow (Flow, optional): The flow to be executed. Defaults to Depends(get_flow_by_id).
telemetry_service (TelemetryService): The telemetry service.
Returns:
dict: A dictionary containing the status of the task.
@ -382,8 +380,8 @@ async def experimental_run_flow(
api_key_user: UserRead = Depends(api_key_security),
session_service: SessionService = Depends(get_session_service),
):
"""
Executes a specified flow by ID with optional input values, output selection, tweaks, and streaming capability.
"""Executes a specified flow by ID with optional input values, output selection, tweaks, and streaming capability.
This endpoint supports running flows with caching to enhance performance and efficiency.
### Parameters:
@ -511,9 +509,7 @@ async def process(
sync: Annotated[bool, Body(embed=True)] = True,
session_service: SessionService = Depends(get_session_service),
):
"""
Endpoint to process an input with a given flow_id.
"""
"""Endpoint to process an input with a given flow_id."""
# Raise a depreciation warning
logger.warning(
"The /process endpoint is deprecated and will be removed in a future version. Please use /run instead."
@ -598,8 +594,7 @@ async def custom_component_update(
code_request: UpdateCustomComponentRequest,
user: Annotated[User, Depends(get_current_active_user)],
):
"""
Update a custom component with the provided code request.
"""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.

View file

@ -137,8 +137,7 @@ def read_flows(
params: Params = Depends(),
header_flows: bool = False,
):
"""
Retrieve a list of flows with pagination support.
"""Retrieve a list of flows with pagination support.
Args:
current_user (User): The current authenticated user.
@ -149,10 +148,11 @@ def read_flows(
folder_id (UUID, optional): The folder ID. Defaults to None.
params (Params): Pagination parameters.
remove_example_flows (bool, optional): Whether to remove example flows. Defaults to False.
header_flows (bool, optional): Whether to return only specific headers of the flows. Defaults to False.
Returns:
Union[list[FlowRead], Page[FlowRead]]: A list of flows or a paginated response containing the list of flows.
"""
try:
auth_settings = settings_service.auth_settings
@ -364,12 +364,12 @@ async def delete_multiple_flows(
user: Annotated[User, Depends(get_current_active_user)],
db: Annotated[Session, Depends(get_session)],
):
"""
Delete multiple flows by their IDs.
"""Delete multiple flows by their IDs.
Args:
flow_ids (List[str]): The list of flow IDs to delete.
user (User, optional): The user making the request. Defaults to the current active user.
db (Session, optional): The database session.
Returns:
dict: A dictionary containing the number of flows deleted.
@ -441,8 +441,7 @@ def read_basic_examples(
*,
session: Session = Depends(get_session),
):
"""
Retrieve a list of basic example flows.
"""Retrieve a list of basic example flows.
Args:
session (Session): The database session.
@ -450,7 +449,6 @@ def read_basic_examples(
Returns:
list[FlowRead]: A list of basic example flows.
"""
try:
# Get the starter folder
starter_folder = session.exec(select(Folder).where(Folder.name == STARTER_FOLDER_NAME)).first()

View file

@ -28,9 +28,7 @@ def add_user(
session: Annotated[Session, Depends(get_session)],
settings_service=Depends(get_settings_service),
) -> User:
"""
Add a new user to the database.
"""
"""Add a new user to the database."""
new_user = User.model_validate(user, from_attributes=True)
try:
new_user.password = get_password_hash(user.password)
@ -52,9 +50,7 @@ def add_user(
def read_current_user(
current_user: Annotated[User, Depends(get_current_active_user)],
) -> User:
"""
Retrieve the current user's data.
"""
"""Retrieve the current user's data."""
return current_user
@ -65,9 +61,7 @@ def read_all_users(
_: Session = Depends(get_current_active_superuser),
session: Session = Depends(get_session),
) -> UsersResponse:
"""
Retrieve a list of users from the database with pagination.
"""
"""Retrieve a list of users from the database with pagination."""
query: SelectOfScalar = select(User).offset(skip).limit(limit)
users = session.exec(query).fetchall()
@ -87,10 +81,7 @@ def patch_user(
user: Annotated[User, Depends(get_current_active_user)],
session: Annotated[Session, Depends(get_session)],
) -> User:
"""
Update an existing user's data.
"""
"""Update an existing user's data."""
update_password = user_update.password is not None and user_update.password != ""
if not user.is_superuser and user_update.is_superuser:
@ -117,9 +108,7 @@ def reset_password(
user: Annotated[User, Depends(get_current_active_user)],
session: Annotated[Session, Depends(get_session)],
) -> User:
"""
Reset a user's password.
"""
"""Reset a user's password."""
if user_id != user.id:
raise HTTPException(status_code=400, detail="You can't change another user's password")
@ -141,9 +130,7 @@ def delete_user(
current_user: Annotated[User, Depends(get_current_active_superuser)],
session: Annotated[Session, Depends(get_session)],
) -> dict:
"""
Delete a user from the database.
"""
"""Delete a user from the database."""
if current_user.id == user_id:
raise HTTPException(status_code=400, detail="You can't delete your own user account")
if not current_user.is_superuser:

View file

@ -36,8 +36,7 @@ class AgentSpec(BaseModel):
def data_to_messages(data: list[Data]) -> list[BaseMessage]:
"""
Convert a list of data to a list of messages.
"""Convert a list of data to a list of messages.
Args:
data (List[Data]): The data to convert.

View file

@ -1,5 +1,4 @@
"""
This module contains constants used in the Langflow base module.
"""This module contains constants used in the Langflow base module.
Constants:
- STREAM_INFO_TEXT: A string representing the information about streaming the response from the model.

View file

@ -1,5 +1,4 @@
"""
This file contains a fix for the implementation of the `uncurl` library, which is available at https://github.com/spulec/uncurl.git.
r"""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.

View file

@ -36,12 +36,8 @@ class LCDocumentTransformerComponent(Component):
@abstractmethod
def get_data_input(self) -> Any:
"""
Get the data input.
"""
"""Get the data input."""
@abstractmethod
def build_document_transformer(self) -> BaseDocumentTransformer:
"""
Build the text splitter.
"""
"""Build the text splitter."""

View file

@ -6,8 +6,7 @@ from langflow.schema.message import Message
def build_data_from_run_outputs(run_outputs: RunOutputs) -> list[Data]:
"""
Build a list of data from the given RunOutputs.
"""Build a list of data from the given RunOutputs.
Args:
run_outputs (RunOutputs): The RunOutputs object containing the output data.
@ -26,8 +25,7 @@ def build_data_from_run_outputs(run_outputs: RunOutputs) -> list[Data]:
def build_data_from_result_data(result_data: ResultData, get_final_results_only: bool = True) -> list[Data]:
"""
Build a list of data from the given ResultData.
"""Build a list of data from the given ResultData.
Args:
result_data (ResultData): The ResultData object containing the result data.
@ -76,8 +74,7 @@ def build_data_from_result_data(result_data: ResultData, get_final_results_only:
def format_flow_output_data(data: list[Data]) -> str:
"""
Format the flow output data into a string.
"""Format the flow output data into a string.
Args:
data (List[Data]): The list of data to format.

View file

@ -27,12 +27,8 @@ class LCToolComponent(Component):
@abstractmethod
def run_model(self) -> Data | list[Data]:
"""
Run model and return the output.
"""
"""Run model and return the output."""
@abstractmethod
def build_tool(self) -> Tool | Sequence[Tool]:
"""
Build the tool.
"""
"""Build the tool."""

View file

@ -33,6 +33,4 @@ class LCChatMemoryComponent(Component):
@abstractmethod
def build_message_history(self) -> BaseChatMessageHistory:
"""
Builds the chat message history memory.
"""
"""Builds the chat message history memory."""

View file

@ -64,11 +64,10 @@ class LCModelComponent(Component):
return result
def get_result(self, runnable: LLM, stream: bool, input_value: str):
"""
Retrieves the result from the output of a Runnable object.
"""Retrieves the result from the output of a Runnable object.
Args:
output (Runnable): The output object to retrieve the result from.
runnable (Runnable): The runnable to retrieve the result from.
stream (bool): Indicates whether to use streaming or invocation mode.
input_value (str): The input value to pass to the output object.
@ -90,8 +89,7 @@ class LCModelComponent(Component):
return result
def build_status_message(self, message: AIMessage):
"""
Builds a status message from an AIMessage object.
"""Builds a status message from an AIMessage object.
Args:
message (AIMessage): The AIMessage object to build the status message from.
@ -204,6 +202,4 @@ class LCModelComponent(Component):
@abstractmethod
def build_model(self) -> LanguageModel: # type: ignore[type-var]
"""
Implement this method to build the model.
"""
"""Implement this method to build the model."""

View file

@ -6,8 +6,7 @@ from langflow.schema import Data
def data_to_string(record: Data) -> str:
"""
Convert a record to a string.
"""Convert a record to a string.
Args:
record (Data): The record to convert.
@ -19,8 +18,7 @@ def data_to_string(record: Data) -> str:
def dict_values_to_string(d: dict) -> dict:
"""
Converts the values of a dictionary to strings.
"""Converts the values of a dictionary to strings.
Args:
d (dict): The dictionary whose values need to be converted.
@ -52,8 +50,7 @@ def dict_values_to_string(d: dict) -> dict:
def document_to_string(document: Document) -> str:
"""
Convert a document to a string.
"""Convert a document to a string.
Args:
document (Document): The document to convert.

View file

@ -25,6 +25,4 @@ class LCTextSplitterComponent(LCDocumentTransformerComponent):
@abstractmethod
def build_text_splitter(self) -> TextSplitter:
"""
Build the text splitter.
"""
"""Build the text splitter."""

View file

@ -2,8 +2,7 @@ from langflow.field_typing import Tool
def build_status_from_tool(tool: Tool):
"""
Builds a status string representation of a tool.
"""Builds a status string representation of a tool.
Args:
tool (Tool): The tool object to build the status for.

View file

@ -73,7 +73,6 @@ class FlowTool(BaseTool):
def validate_inputs(self, args_names: list[dict[str, str]], args: Any, kwargs: Any):
"""Validate the inputs."""
if len(args) > 0 and len(args) != len(args_names):
msg = "Number of positional arguments does not match the number of inputs. Pass keyword arguments instead."
raise ToolException(msg)

View file

@ -15,8 +15,7 @@ if TYPE_CHECKING:
def check_cached_vector_store(f):
"""
Decorator to check for cached vector stores, and returns them if they exist.
"""Decorator to check for cached vector stores, and returns them if they exist.
Note: caching only occurs during the execution of a component - they do not persist
across separate invocations of the component. This method exists so that components with
@ -42,9 +41,7 @@ class LCVectorStoreComponent(Component):
_cached_vector_store: VectorStore | None = None
def __init_subclass__(cls, **kwargs):
"""
Enforces the check cached decorator on all subclasses
"""
"""Enforces the check cached decorator on all subclasses."""
super().__init_subclass__(**kwargs)
if hasattr(cls, "build_vector_store"):
method = cls.build_vector_store
@ -98,13 +95,14 @@ class LCVectorStoreComponent(Component):
k=10,
**kwargs,
) -> list[Data]:
"""
Search for data in the vector store based on the input value and search type.
"""Search for data in the vector store based on the input value and search type.
Args:
input_value (Text): The input value to search for.
search_type (str): The type of search to perform.
vector_store (VectorStore): The vector store to search in.
k (int): The number of results to return.
**kwargs: Additional keyword arguments to pass to the vector store search method.
Returns:
List[Data]: A list of data matching the search criteria.
@ -112,7 +110,6 @@ class LCVectorStoreComponent(Component):
Raises:
ValueError: If invalid inputs are provided.
"""
docs: list[Document] = []
if input_value and isinstance(input_value, str) and hasattr(vector_store, "search"):
docs = vector_store.search(query=input_value, search_type=search_type.lower(), k=k, **kwargs)
@ -127,9 +124,7 @@ class LCVectorStoreComponent(Component):
return cast(VectorStore, self.build_vector_store())
def build_base_retriever(self) -> Retriever: # type: ignore[type-var]
"""
Builds the BaseRetriever object.
"""
"""Builds the BaseRetriever object."""
if self._cached_vector_store is not None:
vector_store = self._cached_vector_store
else:
@ -145,9 +140,7 @@ class LCVectorStoreComponent(Component):
raise ValueError(msg)
def search_documents(self) -> list[Data]:
"""
Search for documents in the vector store.
"""
"""Search for documents in the vector store."""
search_query: str = self.search_query
if not search_query:
self.status = ""
@ -170,16 +163,12 @@ class LCVectorStoreComponent(Component):
return search_results
def get_retriever_kwargs(self):
"""
Get the retriever kwargs. Implementations can override this method to provide custom retriever kwargs.
"""
"""Get the retriever kwargs. Implementations can override this method to provide custom retriever kwargs."""
return {}
@abstractmethod
@check_cached_vector_store
def build_vector_store(self) -> VectorStore:
"""
Builds the Vector Store object.
"""
"""Builds the Vector Store object."""
msg = "build_vector_store method must be implemented."
raise NotImplementedError(msg)

Some files were not shown because too many files have changed in this diff Show more