feat: Add ruff rules for error messages (EM) (#3978)

Add ruff rules for error messages (EM)
This commit is contained in:
Christophe Bornet 2024-10-01 17:38:32 +02:00 • committed by GitHub
commit 1668c91433
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
169 changed files with 1011 additions and 554 deletions

View file

@ -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:

View file

@ -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)
@ -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))
@ -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)

View file

@ -340,7 +340,8 @@ async def build_flow(
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:
@ -652,13 +653,15 @@ async def build_vertex_stream(
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",
@ -691,7 +694,8 @@ async def build_vertex_stream(
)
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}")

View file

@ -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(
@ -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)
@ -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
@ -448,7 +448,8 @@ 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()
@ -456,10 +457,12 @@ async def experimental_run_flow(
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)

View file

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

View file

@ -67,9 +67,11 @@ class LCAgentComponent(Component):
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 = {
@ -102,7 +104,8 @@ class LCAgentComponent(Component):
)
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"))
@ -148,7 +151,8 @@ class LCToolsAgentComponent(LCAgentComponent):
)
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"))

View file

@ -46,7 +46,8 @@ class BaseCrewComponent(Component):
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,

View file

@ -12,6 +12,8 @@ class LCChainComponent(Component):
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)

View file

@ -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,

View file

@ -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
@ -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
@ -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})

View file

@ -15,9 +15,12 @@ class LCEmbeddingsModel(Component):
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)

View file

@ -22,7 +22,8 @@ class ChatComponent(Component):
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):
@ -55,7 +56,8 @@ class ChatComponent(Component):
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))

View file

@ -19,9 +19,11 @@ class LCToolComponent(Component):
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]:

View file

@ -22,9 +22,11 @@ class LCChatMemoryComponent(Component):
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())

View file

@ -48,9 +48,11 @@ class LCModelComponent(Component):
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
@ -145,7 +147,8 @@ class LCModelComponent(Component):
):
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):

View file

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

View file

@ -14,9 +14,11 @@ class LCTextSplitterComponent(LCDocumentTransformerComponent):
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()

View file

@ -35,7 +35,8 @@ class ComponentTool(BaseTool):
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()

View file

@ -33,7 +33,8 @@ class FlowTool(BaseTool):
elif self.graph is not None:
return build_schema_from_inputs(self.name, get_flow_inputs(self.graph))
else:
raise ToolException("No input schema available.")
msg = "No input schema available."
raise ToolException(msg)
def _run(
self,
@ -45,9 +46,8 @@ class FlowTool(BaseTool):
if len(args_names) == len(args):
kwargs = {arg["arg_name"]: arg_value for arg, arg_value in zip(args_names, args)}
elif len(args_names) != len(args) and len(args) != 0:
raise ToolException(
"Number of arguments does not match the number of inputs. Pass keyword arguments instead."
)
msg = "Number of arguments does not match the number of inputs. Pass keyword arguments instead."
raise ToolException(msg)
tweaks = {arg["component_name"]: kwargs[arg["arg_name"]] for arg in args_names}
run_outputs = run_until_complete(
@ -72,16 +72,16 @@ class FlowTool(BaseTool):
"""Validate the inputs."""
if len(args) > 0 and len(args) != len(args_names):
raise ToolException(
"Number of positional arguments does not match the number of inputs. Pass keyword arguments instead."
)
msg = "Number of positional arguments does not match the number of inputs. Pass keyword arguments instead."
raise ToolException(msg)
if len(args) == len(args_names):
kwargs = {arg_name["arg_name"]: arg_value for arg_name, arg_value in zip(args_names, args)}
missing_args = [arg["arg_name"] for arg in args_names if arg["arg_name"] not in kwargs]
if missing_args:
raise ToolException(f"Missing required arguments: {', '.join(missing_args)}")
msg = f"Missing required arguments: {', '.join(missing_args)}"
raise ToolException(msg)
return kwargs

View file

@ -47,10 +47,11 @@ class LCVectorStoreComponent(Component):
if hasattr(cls, "build_vector_store"):
method = cls.build_vector_store
if not hasattr(method, "_is_cached_vector_store_checked"):
raise TypeError(
msg = (
f"The method 'build_vector_store' in class {cls.__name__} "
"must be decorated with @check_cached_vector_store"
)
raise TypeError(msg)
trace_type = "retriever"
outputs = [
@ -81,9 +82,11 @@ class LCVectorStoreComponent(Component):
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 search_with_vector_store(
self,
@ -112,7 +115,8 @@ class LCVectorStoreComponent(Component):
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)
else:
raise ValueError("Invalid inputs provided.")
msg = "Invalid inputs provided."
raise ValueError(msg)
data = docs_to_data(docs)
self.status = data
return data
@ -136,7 +140,8 @@ class LCVectorStoreComponent(Component):
self.status = "Retriever built successfully."
return retriever
else:
raise ValueError(f"Vector Store {vector_store.__class__.__name__} does not have an as_retriever method.")
msg = f"Vector Store {vector_store.__class__.__name__} does not have an as_retriever method."
raise ValueError(msg)
def search_documents(self) -> list[Data]:
"""
@ -175,4 +180,5 @@ class LCVectorStoreComponent(Component):
"""
Builds the Vector Store object.
"""
raise NotImplementedError("build_vector_store method must be implemented.")
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