Skip to content

Commit

Permalink
feat: Add ruff rules for error messages (EM) (#3978)
Browse files Browse the repository at this point in the history
Add ruff rules for error messages (EM)
  • Loading branch information
cbornet authored Oct 1, 2024
1 parent e63c377 commit 1668c91
Show file tree
Hide file tree
Showing 169 changed files with 1,011 additions and 554 deletions.
3 changes: 2 additions & 1 deletion src/backend/base/langflow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,8 @@ def superuser(
if result:
typer.echo("Default folder created successfully.")
else:
raise RuntimeError("Could not create default folder.")
msg = "Could not create default folder."
raise RuntimeError(msg)
typer.echo("Superuser created successfully.")

else:
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/api/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,8 @@ async def build_graph_from_data(flow_id: str, payload: dict, **kwargs):
for vertex_id in graph._has_session_id_vertices:
vertex = graph.get_vertex(vertex_id)
if vertex is None:
raise ValueError(f"Vertex {vertex_id} not found")
msg = f"Vertex {vertex_id} not found"
raise ValueError(msg)
if not vertex._raw_params.get("session_id"):
vertex.update_raw_params({"session_id": flow_id}, overwrite=True)

Expand All @@ -150,7 +151,8 @@ async def build_graph_from_db_no_cache(flow_id: str, session: Session):
"""Build and cache the graph."""
flow: Flow | None = session.get(Flow, flow_id)
if not flow or not flow.data:
raise ValueError("Invalid flow ID")
msg = "Invalid flow ID"
raise ValueError(msg)
return await build_graph_from_data(flow_id, flow.data, flow_name=flow.name, user_id=str(flow.user_id))


Expand Down Expand Up @@ -260,4 +262,5 @@ async def cascade_delete_flow(session: Session, flow: Flow):
session.exec(delete(VertexBuildTable).where(VertexBuildTable.flow_id == flow.id)) # type: ignore
session.exec(delete(Flow).where(Flow.id == flow.id)) # type: ignore
except Exception as e:
raise RuntimeError(f"Unable to cascade delete flow: ${flow.id}", e)
msg = f"Unable to cascade delete flow: ${flow.id}"
raise RuntimeError(msg, e)
12 changes: 8 additions & 4 deletions src/backend/base/langflow/api/v1/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,8 @@ async def build_vertices(
vertex_build_response_json = vertex_build_response.model_dump_json()
build_data = json.loads(vertex_build_response_json)
except Exception as exc:
raise ValueError(f"Error serializing vertex build response: {exc}") from exc
msg = f"Error serializing vertex build response: {exc}"
raise ValueError(msg) from exc
event_manager.on_end_vertex(data={"build_data": build_data})
await client_consumed_queue.get()
if vertex_build_response.valid:
Expand Down Expand Up @@ -652,13 +653,15 @@ async def stream_vertex():
cache = await chat_service.get_cache(flow_id_str)
if not cache:
# If there's no cache
raise ValueError(f"No cache found for {flow_id_str}.")
msg = f"No cache found for {flow_id_str}."
raise ValueError(msg)
else:
graph = cache.get("result")

vertex: InterfaceVertex = graph.get_vertex(vertex_id)
if not hasattr(vertex, "stream"):
raise ValueError(f"Vertex {vertex_id} does not support streaming")
msg = f"Vertex {vertex_id} does not support streaming"
raise ValueError(msg)
if isinstance(vertex._built_result, str) and vertex._built_result:
stream_data = StreamData(
event="message",
Expand Down Expand Up @@ -691,7 +694,8 @@ async def stream_vertex():
)
yield str(stream_data)
else:
raise ValueError(f"No result found for vertex {vertex_id}")
msg = f"No result found for vertex {vertex_id}"
raise ValueError(msg)

except Exception as exc:
logger.exception(f"Error building Component: {exc}")
Expand Down
25 changes: 14 additions & 11 deletions src/backend/base/langflow/api/v1/endpoints.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,17 +94,15 @@ def validate_input_and_tweaks(input_request: SimplifiedAPIRequest):
has_input_value = value.get("input_value") is not None
input_value_is_chat = input_request.input_value is not None and input_request.input_type == "chat"
if has_input_value and input_value_is_chat:
raise InvalidChatInputException(
"If you pass an input_value to the chat input, you cannot pass a tweak with the same name."
)
msg = "If you pass an input_value to the chat input, you cannot pass a tweak with the same name."
raise InvalidChatInputException(msg)
elif "Text Input" in key or "TextInput" in key:
if isinstance(value, dict):
has_input_value = value.get("input_value") is not None
input_value_is_text = input_request.input_value is not None and input_request.input_type == "text"
if has_input_value and input_value_is_text:
raise InvalidChatInputException(
"If you pass an input_value to the text input, you cannot pass a tweak with the same name."
)
msg = "If you pass an input_value to the text input, you cannot pass a tweak with the same name."
raise InvalidChatInputException(msg)


async def simple_run_flow(
Expand All @@ -120,7 +118,8 @@ async def simple_run_flow(
user_id = api_key_user.id if api_key_user else None
flow_id_str = str(flow.id)
if flow.data is None:
raise ValueError(f"Flow {flow_id_str} has no data")
msg = f"Flow {flow_id_str} has no data"
raise ValueError(msg)
graph_data = flow.data.copy()
graph_data = process_tweaks(graph_data, input_request.tweaks or {}, stream=stream)
graph = Graph.from_payload(graph_data, flow_id=flow_id_str, user_id=str(user_id), flow_name=flow.name)
Expand Down Expand Up @@ -331,8 +330,9 @@ async def webhook_run_flow(
data = await request.body()
if not data:
logger.error("Request body is empty")
msg = "Request body is empty. You should provide a JSON payload containing the flow ID."
raise ValueError(
"Request body is empty. You should provide a JSON payload containing the flow ID.",
msg,
)

# get all webhook components in the flow
Expand Down Expand Up @@ -448,18 +448,21 @@ async def experimental_run_flow(
session_data = await session_service.load_session(session_id, flow_id=flow_id_str)
graph, artifacts = session_data if session_data else (None, None)
if graph is None:
raise ValueError(f"Session {session_id} not found")
msg = f"Session {session_id} not found"
raise ValueError(msg)
else:
# Get the flow that matches the flow_id and belongs to the user
# flow = session.query(Flow).filter(Flow.id == flow_id).filter(Flow.user_id == api_key_user.id).first()
flow = session.exec(
select(Flow).where(Flow.id == flow_id_str).where(Flow.user_id == api_key_user.id)
).first()
if flow is None:
raise ValueError(f"Flow {flow_id_str} not found")
msg = f"Flow {flow_id_str} not found"
raise ValueError(msg)

if flow.data is None:
raise ValueError(f"Flow {flow_id_str} has no data")
msg = f"Flow {flow_id_str} has no data"
raise ValueError(msg)
graph_data = flow.data
graph_data = process_tweaks(graph_data, tweaks or {})
graph = Graph.from_payload(graph_data, flow_id=flow_id_str)
Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/api/v1/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,8 @@ class ChatResponse(ChatMessage):
@classmethod
def validate_message_type(cls, v):
if v not in ["start", "stream", "end", "error", "info", "file"]:
raise ValueError("type must be start, stream, end, error, info, or file")
msg = "type must be start, stream, end, error, info, or file"
raise ValueError(msg)
return v


Expand All @@ -134,7 +135,8 @@ class FileResponse(ChatMessage):
@classmethod
def validate_data_type(cls, v):
if v not in ["image", "csv"]:
raise ValueError("data_type must be image or csv")
msg = "data_type must be image or csv"
raise ValueError(msg)
return v


Expand Down
12 changes: 8 additions & 4 deletions src/backend/base/langflow/base/agents/agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,11 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

def get_agent_kwargs(self, flatten: bool = False) -> dict:
base = {
Expand Down Expand Up @@ -102,7 +104,8 @@ async def run_agent(self, agent: AgentExecutor) -> Text:
)
self.status = result
if "output" not in result:
raise ValueError("Output key not found in result. Tried 'output'.")
msg = "Output key not found in result. Tried 'output'."
raise ValueError(msg)

return cast(str, result.get("output"))

Expand Down Expand Up @@ -148,7 +151,8 @@ async def run_agent(
)
self.status = result
if "output" not in result:
raise ValueError("Output key not found in result. Tried 'output'.")
msg = "Output key not found in result. Tried 'output'."
raise ValueError(msg)

return cast(str, result.get("output"))

Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/agents/crewai/crew.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,8 @@ def get_tasks_and_agents(self) -> tuple[list[Task], list[Agent]]:
return self.tasks, self.agents

def build_crew(self) -> Crew:
raise NotImplementedError("build_crew must be implemented in subclasses")
msg = "build_crew must be implemented in subclasses"
raise NotImplementedError(msg)

def get_task_callback(
self,
Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/chains/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/curl/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,8 @@ def parse_curl_command(curl_command):
tokens = shlex.split(normalize_newlines(curl_command))
tokens = [token for token in tokens if token and token != " "]
if tokens and "curl" not in tokens[0]:
raise ValueError("Invalid curl command")
msg = "Invalid curl command"
raise ValueError(msg)
args_template = {
"command": None,
"url": None,
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/base/data/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,8 @@ def retrieve_file_paths(
) -> list[str]:
path_obj = Path(path)
if not path_obj.exists() or not path_obj.is_dir():
raise ValueError(f"Path {path} must exist and be a directory.")
msg = f"Path {path} must exist and be a directory."
raise ValueError(msg)

def match_types(p: Path) -> bool:
return any(p.suffix == f".{t}" for t in types) if types else True
Expand Down Expand Up @@ -83,7 +84,8 @@ def partition_file_to_data(file_path: str, silent_errors: bool) -> Data | None:
elements = partition(file_path)
except Exception as e:
if not silent_errors:
raise ValueError(f"Error loading file {file_path}: {e}") from e
msg = f"Error loading file {file_path}: {e}"
raise ValueError(msg) from e
return None

# Create a Data
Expand Down Expand Up @@ -147,7 +149,8 @@ def parse_text_file_to_data(file_path: str, silent_errors: bool) -> Data | None:
text = ET.tostring(xml_element, encoding="unicode")
except Exception as e:
if not silent_errors:
raise ValueError(f"Error loading file {file_path}: {e}") from e
msg = f"Error loading file {file_path}: {e}"
raise ValueError(msg) from e
return None

record = Data(data={"file_path": file_path, "text": text})
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/base/embeddings/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,12 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

def build_embeddings(self) -> Embeddings:
raise NotImplementedError("You must implement the build_embeddings method in your class.")
msg = "You must implement the build_embeddings method in your class."
raise NotImplementedError(msg)
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/io/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,8 @@ def store_message(
flow_id=self.graph.flow_id,
)
if len(messages) > 1:
raise ValueError("Only one message can be stored at a time.")
msg = "Only one message can be stored at a time."
raise ValueError(msg)
stored_message = messages[0]
if hasattr(self, "_event_manager") and self._event_manager and stored_message.id:
if not isinstance(message.text, str):
Expand Down Expand Up @@ -55,7 +56,8 @@ async def _handle_async_iterator(self, iterator: AsyncIterator, message: Message
def _stream_message(self, message: Message, message_id: str) -> str:
iterator = message.text
if not isinstance(iterator, AsyncIterator | Iterator):
raise ValueError("The message must be an iterator or an async iterator.")
msg = "The message must be an iterator or an async iterator."
raise ValueError(msg)

if isinstance(iterator, AsyncIterator):
return run_until_complete(self._handle_async_iterator(iterator, message, message_id))
Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/langchain_utilities/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

@abstractmethod
def run_model(self) -> Data | list[Data]:
Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/memory/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,11 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

def build_base_memory(self) -> BaseChatMemory:
return ConversationBufferMemory(chat_memory=self.build_message_history())
Expand Down
9 changes: 6 additions & 3 deletions src/backend/base/langflow/base/models/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,11 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

def text_response(self) -> Message:
input_value = self.input_value
Expand Down Expand Up @@ -145,7 +147,8 @@ def get_chat_result(
):
messages: list[BaseMessage] = []
if not input_value and not system_message:
raise ValueError("The message you want to send to the model is empty.")
msg = "The message you want to send to the model is empty."
raise ValueError(msg)
system_message_added = False
if input_value:
if isinstance(input_value, Message):
Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/prompts/api_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,14 +127,16 @@ def validate_prompt(prompt_template: str, silent_errors: bool = False) -> list[s
# Check if there are invalid characters in the input_variables
input_variables = _check_input_variables(input_variables)
if any(var in _INVALID_NAMES for var in input_variables):
raise ValueError(f"Invalid input variables. None of the variables can be named {', '.join(input_variables)}. ")
msg = f"Invalid input variables. None of the variables can be named {', '.join(input_variables)}. "
raise ValueError(msg)

try:
PromptTemplate(template=prompt_template, input_variables=input_variables)
except Exception as exc:
logger.error(f"Invalid prompt: {exc}")
if not silent_errors:
raise ValueError(f"Invalid prompt: {exc}") from exc
msg = f"Invalid prompt: {exc}"
raise ValueError(msg) from exc

return input_variables

Expand Down
6 changes: 4 additions & 2 deletions src/backend/base/langflow/base/textsplitters/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,11 @@ def _validate_outputs(self):
output_names = [output.name for output in self.outputs]
for method_name in required_output_methods:
if method_name not in output_names:
raise ValueError(f"Output with name '{method_name}' must be defined.")
msg = f"Output with name '{method_name}' must be defined."
raise ValueError(msg)
elif not hasattr(self, method_name):
raise ValueError(f"Method '{method_name}' must be defined.")
msg = f"Method '{method_name}' must be defined."
raise ValueError(msg)

def build_document_transformer(self) -> BaseDocumentTransformer:
return self.build_text_splitter()
Expand Down
3 changes: 2 additions & 1 deletion src/backend/base/langflow/base/tools/component_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,8 @@ def _run(
results, _ = self.component(**kwargs)
return results
except Exception as e:
raise ToolException(f"Error running {self.name}: {e}")
msg = f"Error running {self.name}: {e}"
raise ToolException(msg)


ComponentTool.update_forward_refs()
Loading

0 comments on commit 1668c91

Please sign in to comment.