Skip to content

Commit

Permalink
ref: Use TypeError instead of ValueError when relevant (TRY004) (lang…
Browse files Browse the repository at this point in the history
…flow-ai#4045)

Use TypeError instead of ValueError when relevant (TRY004)
  • Loading branch information
cbornet authored and diogocabral committed Nov 26, 2024
1 parent 1e7ec4d commit 5443db4
Show file tree
Hide file tree
Showing 34 changed files with 56 additions and 54 deletions.
2 changes: 1 addition & 1 deletion src/backend/base/langflow/base/io/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def _stream_message(self, message: Message, message_id: str) -> str:
iterator = message.text
if not isinstance(iterator, AsyncIterator | Iterator):
msg = "The message must be an iterator or an async iterator."
raise ValueError(msg)
raise TypeError(msg)

if isinstance(iterator, AsyncIterator):
return run_until_complete(self._handle_async_iterator(iterator, message, message_id))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def convert_message_to_data(self) -> Data:
try:
if not isinstance(self.message, Message):
msg = "Input must be a Message object"
raise ValueError(msg)
raise TypeError(msg)

# Convert Message to Data
data = Data(data=self.message.data)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ async def build_executor(self) -> Message:
input_dict, status = self.get_input_dict(self.runnable, self.input_key, self.input_value)
if not isinstance(self.runnable, AgentExecutor):
msg = "The runnable must be an AgentExecutor"
raise ValueError(msg)
raise TypeError(msg)

if self.use_stream:
return self.astream_events(input_dict)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ def retrieve_documents(self) -> list[Data]:
input_text = self.query
else:
msg = f"Query type {type(self.query)} not supported."
raise ValueError(msg)
raise TypeError(msg)

documents = self_query_retriever.invoke(input=input_text, config={"callbacks": self.get_langchain_callbacks()})
data = [Data.from_document(document) for document in documents]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def get_globals(self, global_imports: str | list[str]) -> dict:
modules = global_imports
else:
msg = "global_imports must be either a string or a list"
raise ValueError(msg)
raise TypeError(msg)

for module in modules:
try:
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -441,7 +441,7 @@ def _add_documents_to_vector_store(self, vector_store):
documents.append(_input.to_lc_document())
else:
msg = "Vector Store Inputs must be Data objects."
raise ValueError(msg)
raise TypeError(msg)

if documents:
logger.debug(f"Adding {len(documents)} documents to the Vector Store.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -156,7 +156,7 @@ def _add_documents_to_vector_store(self, vector_store: "Chroma") -> None:
documents.append(_input.to_lc_document())
else:
msg = "Vector Store Inputs must be Data objects."
raise ValueError(msg)
raise TypeError(msg)

if documents and self.embedding is not None:
logger.debug(f"Adding {len(documents)} documents to the Vector Store.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def _prepare_documents(self) -> list[Document]:
else:
error_message = "Vector Store Inputs must be Data objects."
logger.error(error_message)
raise ValueError(error_message)
raise TypeError(error_message)
return documents

def _add_documents_to_vector_store(self, vector_store: "ElasticsearchStore") -> None:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/components/vectorstores/HCD.py
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ def _add_documents_to_vector_store(self, vector_store):
documents.append(_input.to_lc_document())
else:
msg = "Vector Store Inputs must be Data objects."
raise ValueError(msg)
raise TypeError(msg)

if documents:
logger.debug(f"Adding {len(documents)} documents to the Vector Store.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,7 +159,7 @@ def _add_documents_to_vector_store(self, vector_store: "OpenSearchVectorSearch")
else:
error_message = f"Expected Data object, got {type(_input)}"
logger.error(error_message)
raise ValueError(error_message)
raise TypeError(error_message)

if documents and self.embedding is not None:
logger.debug(f"Adding {len(documents)} documents to the Vector Store.")
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def build_vector_store(self) -> Qdrant:

if not isinstance(self.embedding, Embeddings):
msg = "Invalid embedding object"
raise ValueError(msg)
raise TypeError(msg)

if documents:
qdrant = Qdrant.from_documents(documents, embedding=self.embedding, **qdrant_kwargs, **server_kwargs)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -430,7 +430,7 @@ def _find_matching_output_method(self, input_name: str, value: Component):
# Ensure that the output method is a valid method name (string)
if not isinstance(output.method, str):
msg = f"Method {output.method} is not a valid output of {value.__class__.__name__}"
raise ValueError(msg)
raise TypeError(msg)
return getattr(value, output.method)

def _process_connection_or_parameter(self, key, value):
Expand Down Expand Up @@ -503,7 +503,7 @@ def _set_parameter_or_attribute(self, key, value):
f"You set {value.display_name} as value for `{key}`. "
f"You should pass one of the following: {methods}"
)
raise ValueError(msg)
raise TypeError(msg)
self._set_input_value(key, value)
self._parameters[key] = value
self._attributes[key] = value
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ def to_data(self, data: Any, keys: list[str] | None = None, silent_errors: bool
data_dict = item.copy()
else:
msg = f"Invalid data type: {type(item)}"
raise ValueError(msg)
raise TypeError(msg)

data_objects.append(Data(data=data_dict))

Expand Down
4 changes: 2 additions & 2 deletions src/backend/base/langflow/custom/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -268,7 +268,7 @@ def get_component_instance(custom_component: CustomComponent, user_id: str | UUI
custom_class = eval_custom_component_code(custom_component._code)
else:
msg = "Invalid code type"
raise ValueError(msg)
raise TypeError(msg)
except Exception as exc:
logger.exception("Error while evaluating custom component code")
raise HTTPException(
Expand Down Expand Up @@ -303,7 +303,7 @@ def run_build_config(
custom_class = eval_custom_component_code(custom_component._code)
else:
msg = "Invalid code type"
raise ValueError(msg)
raise TypeError(msg)
except Exception as exc:
logger.exception("Error while evaluating custom component code")
raise HTTPException(
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/events/event_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def __init__(self, queue: asyncio.Queue):
def _validate_callback(callback: EventCallback):
if not callable(callback):
msg = "Callback must be callable"
raise ValueError(msg)
raise TypeError(msg)
# Check if it has `self, event_type and data`
sig = inspect.signature(callback)
parameters = ["manager", "event_type", "data"]
Expand Down
8 changes: 4 additions & 4 deletions src/backend/base/langflow/graph/graph/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -248,11 +248,11 @@ def add_component_edge(self, source_id: str, output_input_tuple: tuple[str, str]
source_vertex = self.get_vertex(source_id)
if not isinstance(source_vertex, ComponentVertex):
msg = f"Source vertex {source_id} is not a component vertex."
raise ValueError(msg)
raise TypeError(msg)
target_vertex = self.get_vertex(target_id)
if not isinstance(target_vertex, ComponentVertex):
msg = f"Target vertex {target_id} is not a component vertex."
raise ValueError(msg)
raise TypeError(msg)
output_name, input_name = output_input_tuple
if source_vertex._custom_component is None:
msg = f"Source vertex {source_id} does not have a custom component."
Expand Down Expand Up @@ -661,7 +661,7 @@ async def _run(

if not isinstance(inputs.get(INPUT_FIELD_NAME, ""), str):
msg = f"Invalid input value: {inputs.get(INPUT_FIELD_NAME)}. Expected string"
raise ValueError(msg)
raise TypeError(msg)
if inputs:
self._set_inputs(input_components, inputs, input_type)
# Update all the vertices with the session_id
Expand Down Expand Up @@ -1529,7 +1529,7 @@ async def _execute_tasks(self, tasks: list[asyncio.Task], lock: asyncio.Lock) ->
vertices.append(result.vertex)
else:
msg = f"Invalid result from task {task_name}: {result}"
raise ValueError(msg)
raise TypeError(msg)

for v in vertices:
# set all executed vertices as non-runnable to not run them again.
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/graph/state/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -230,7 +230,7 @@ def create_state_model(model_name: str = "State", validate: bool = True, **kwarg
# typing.Annotated[<type>, Field(...)]
if not isinstance(value[0], type):
msg = f"Invalid type for field {name}: {type(value[0])}"
raise ValueError(msg)
raise TypeError(msg)
fields[name] = (value[0], value[1])
else:
msg = f"Invalid value type {type(value)} for field {name}"
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/graph/vertex/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -750,7 +750,7 @@ def _validate_built_object(self):
"""
if isinstance(self._built_object, UnbuiltObject):
msg = f"{self.display_name}: {self._built_object_repr()}"
raise ValueError(msg)
raise TypeError(msg)
if self._built_object is None:
message = f"{self.display_name} returned None."
if self.base_type == "custom_components":
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/graph/vertex/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -382,7 +382,7 @@ async def stream(self):
iterator = self.params.get(INPUT_FIELD_NAME, None)
if not isinstance(iterator, AsyncIterator | Iterator):
msg = "The message must be an iterator or an async iterator."
raise ValueError(msg)
raise TypeError(msg)
is_async = isinstance(iterator, AsyncIterator)
complete_message = ""
if is_async:
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/helpers/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def messages_to_text(template: str, messages: Message | list[Message]) -> str:
# If it is not a message, create one with the key "text"
if not isinstance(message, Message):
msg = "All elements in the list must be of type Message."
raise ValueError(msg)
raise TypeError(msg)
_messages.append(message)

formated_messages = [template.format(data=message.model_dump(), **message.model_dump()) for message in _messages]
Expand Down
4 changes: 2 additions & 2 deletions src/backend/base/langflow/inputs/input_mixin.py
Original file line number Diff line number Diff line change
Expand Up @@ -133,12 +133,12 @@ class FileMixin(BaseModel):
def validate_file_types(cls, v):
if not isinstance(v, list):
msg = "file_types must be a list"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
# types should be a list of extensions without the dot
for file_type in v:
if not isinstance(file_type, str):
msg = "file_types must be a list of strings"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
if file_type.startswith("."):
msg = "file_types should not start with a dot"
raise ValueError(msg)
Expand Down
10 changes: 5 additions & 5 deletions src/backend/base/langflow/inputs/inputs.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,15 +36,15 @@ def validate_value(cls, v: Any, _info):
# Check if value is a list of dicts
if not isinstance(v, list):
msg = f"TableInput value must be a list of dictionaries or Data. Value '{v}' is not a list."
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004

for item in v:
if not isinstance(item, dict | Data):
msg = (
"TableInput value must be a list of dictionaries or Data. "
f"Item '{item}' is not a dictionary or Data."
)
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return v


Expand Down Expand Up @@ -206,7 +206,7 @@ def _validate_value(v: Any, _info):
value = v
else:
msg = f"Invalid value type {type(v)}"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return value


Expand Down Expand Up @@ -462,11 +462,11 @@ def validate_value(cls, v: Any, _info):
# Check if value is a list of dicts
if not isinstance(v, list):
msg = f"MultiselectInput value must be a list. Value: '{v}'"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
for item in v:
if not isinstance(item, str):
msg = f"MultiselectInput value must be a list of strings. Item: '{item}' is not a string"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return v


Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/io/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ def create_input_schema(inputs: list["InputTypes"]) -> type[BaseModel]:
field_type = _convert_field_type_to_type[field_type]
else:
msg = f"Invalid field type: {field_type}"
raise ValueError(msg)
raise TypeError(msg)
if hasattr(input_model, "options") and isinstance(input_model.options, list) and input_model.options:
literal_string = f"Literal{input_model.options}"
# validate that the literal_string is a valid literal
Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/load/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def upload_file(file_path: str, host: str, flow_id: str, components: list[str],
tweaks[component] = {"path": response["file_path"]}
else:
msg = f"Component ID or name must be a string. Got {type(component)}"
raise ValueError(msg)
raise TypeError(msg)
return tweaks
msg = "Error uploading file"
raise ValueError(msg)
Expand Down
4 changes: 2 additions & 2 deletions src/backend/base/langflow/processing/process.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ def validate_input(
) -> list[dict[str, Any]]:
if not isinstance(graph_data, dict) or not isinstance(tweaks, dict):
msg = "graph_data and tweaks should be dictionaries"
raise ValueError(msg)
raise TypeError(msg)

nodes = graph_data.get("data", {}).get("nodes") or graph_data.get("nodes")

if not isinstance(nodes, list):
msg = "graph_data should contain a list of nodes under 'data' key or directly under 'nodes' key"
raise ValueError(msg)
raise TypeError(msg)

return nodes

Expand Down
2 changes: 1 addition & 1 deletion src/backend/base/langflow/schema/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ class Data(BaseModel):
def validate_data(cls, values):
if not isinstance(values, dict):
msg = "Data must be a dictionary"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
if not values.get("data"):
values["data"] = {}
# Any other keyword should be added to the data dictionary
Expand Down
4 changes: 2 additions & 2 deletions src/backend/base/langflow/services/chat/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ def add_pandas(self, name: str, obj: Any):
self.add(name, obj.to_csv(), "pandas", extension="csv")
else:
msg = "Object is not a pandas DataFrame or Series"
raise ValueError(msg)
raise TypeError(msg)

def add_image(self, name: str, obj: Any, extension: str = "png"):
"""
Expand All @@ -127,7 +127,7 @@ def add_image(self, name: str, obj: Any, extension: str = "png"):
self.add(name, obj, "image", extension=extension)
else:
msg = "Object is not a PIL Image"
raise ValueError(msg)
raise TypeError(msg)

def get(self, name: str):
"""
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ def validate_json(v):
return v
if not isinstance(v, dict):
msg = "Flow must be a valid JSON"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004

# data must contain nodes and edges
if "nodes" not in v:
Expand Down
8 changes: 4 additions & 4 deletions src/backend/base/langflow/services/telemetry/opentelemetry.py
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ def increment_counter(self, metric_name: str, labels: Mapping[str, str], value:
counter.add(value, labels)
else:
msg = f"Metric '{metric_name}' is not a counter"
raise ValueError(msg)
raise TypeError(msg)

def up_down_counter(self, metric_name: str, value: float, labels: Mapping[str, str]):
self.validate_labels(metric_name, labels)
Expand All @@ -217,7 +217,7 @@ def up_down_counter(self, metric_name: str, value: float, labels: Mapping[str, s
up_down_counter.add(value, labels)
else:
msg = f"Metric '{metric_name}' is not an up down counter"
raise ValueError(msg)
raise TypeError(msg)

def update_gauge(self, metric_name: str, value: float, labels: Mapping[str, str]):
self.validate_labels(metric_name, labels)
Expand All @@ -226,7 +226,7 @@ def update_gauge(self, metric_name: str, value: float, labels: Mapping[str, str]
gauge.set_value(value, labels)
else:
msg = f"Metric '{metric_name}' is not a gauge"
raise ValueError(msg)
raise TypeError(msg)

def observe_histogram(self, metric_name: str, value: float, labels: Mapping[str, str]):
self.validate_labels(metric_name, labels)
Expand All @@ -235,4 +235,4 @@ def observe_histogram(self, metric_name: str, value: float, labels: Mapping[str,
histogram.record(value, labels)
else:
msg = f"Metric '{metric_name}' is not a histogram"
raise ValueError(msg)
raise TypeError(msg)
4 changes: 2 additions & 2 deletions src/backend/base/langflow/template/field/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ def serialize_display_name(self, value, _info):
def validate_file_types(cls, value):
if not isinstance(value, list):
msg = "file_types must be a list"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return [
(f".{file_type}" if isinstance(file_type, str) and not file_type.startswith(".") else file_type)
for file_type in value
Expand All @@ -155,7 +155,7 @@ def validate_type(cls, v):
v = format_type(v)
elif not isinstance(v, str):
msg = f"type must be a string or a type, not {type(v)}"
raise ValueError(msg)
raise ValueError(msg) # noqa: TRY004
return v


Expand Down
Loading

0 comments on commit 5443db4

Please sign in to comment.