mirror of
https://github.com/langgenius/dify.git
synced 2026-10-16 15:35:32 +08:00
ci: enable Ruff SIM103 (#44110)
Co-authored-by: Codex <codex@openai.com>
This commit is contained in:
@@ -72,7 +72,6 @@ ignore = [
|
||||
"N815", # mixed-case-variable-in-class-scope
|
||||
"PT011", # pytest-raises-too-broad
|
||||
"SIM102", # collapsible-if
|
||||
"SIM103", # needless-bool
|
||||
"SIM105", # suppressible-exception
|
||||
"SIM108", # if-else-block-instead-of-if-exp
|
||||
"SIM117", # multiple-with-statements
|
||||
|
||||
+1
-3
@@ -35,9 +35,7 @@ logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def is_db_command() -> bool:
|
||||
if len(sys.argv) > 1 and sys.argv[0].endswith("flask") and sys.argv[1] == "db":
|
||||
return True
|
||||
return False
|
||||
return bool(len(sys.argv) > 1 and sys.argv[0].endswith("flask") and sys.argv[1] == "db")
|
||||
|
||||
|
||||
def log_startup_banner(host: str, port: int) -> None:
|
||||
|
||||
@@ -427,17 +427,13 @@ class FunctionCallAgentRunner(BaseAgentRunner):
|
||||
"""
|
||||
Check if there is any tool call in llm result chunk
|
||||
"""
|
||||
if llm_result_chunk.delta.message.tool_calls:
|
||||
return True
|
||||
return False
|
||||
return bool(llm_result_chunk.delta.message.tool_calls)
|
||||
|
||||
def check_blocking_tool_calls(self, llm_result: LLMResult) -> bool:
|
||||
"""
|
||||
Check if there is any blocking tool call in llm result
|
||||
"""
|
||||
if llm_result.message.tool_calls:
|
||||
return True
|
||||
return False
|
||||
return bool(llm_result.message.tool_calls)
|
||||
|
||||
def extract_tool_calls(self, llm_result_chunk: LLMResultChunk) -> list[tuple[str, str, dict[str, Any]]]:
|
||||
"""
|
||||
|
||||
@@ -295,7 +295,4 @@ class DatasetConfigManager:
|
||||
if not dataset:
|
||||
return False
|
||||
|
||||
if dataset.tenant_id != tenant_id:
|
||||
return False
|
||||
|
||||
return True
|
||||
return dataset.tenant_id == tenant_id
|
||||
|
||||
@@ -238,10 +238,7 @@ class AppQueueManager(ABC):
|
||||
)
|
||||
return False
|
||||
|
||||
if result is not None:
|
||||
return True
|
||||
|
||||
return False
|
||||
return result is not None
|
||||
|
||||
@classmethod
|
||||
def _generate_task_belong_cache_key(cls, task_id: str) -> str:
|
||||
|
||||
@@ -86,11 +86,8 @@ def is_filtered[T](
|
||||
|
||||
name = name_func(data)
|
||||
|
||||
if name in exclude_set: # exclude_set is prioritized
|
||||
return True
|
||||
if include_set and name not in include_set: # filter out only if include_set is not empty
|
||||
return True
|
||||
return False
|
||||
# Exclusions take priority; a nonempty include set filters all other names.
|
||||
return name in exclude_set or bool(include_set and name not in include_set)
|
||||
|
||||
|
||||
def sort_by_position_map[T](
|
||||
|
||||
@@ -995,9 +995,7 @@ class ModelManager:
|
||||
model_schema = model_type_instance.get_model_schema(model, model_instance.credentials)
|
||||
if not model_schema:
|
||||
return False
|
||||
if model_schema.features and ModelFeature.VISION in model_schema.features:
|
||||
return True
|
||||
return False
|
||||
return bool(model_schema.features and ModelFeature.VISION in model_schema.features)
|
||||
|
||||
|
||||
class LBModelManager:
|
||||
|
||||
@@ -80,14 +80,12 @@ def should_resolve_llm_model_selector(selector: object) -> bool:
|
||||
|
||||
if selector is None:
|
||||
return False
|
||||
if (
|
||||
return not (
|
||||
isinstance(selector, Sequence)
|
||||
and not isinstance(selector, str | bytes)
|
||||
and len(selector) > 0
|
||||
and selector[0] != ENVIRONMENT_VARIABLE_NODE_ID
|
||||
):
|
||||
return False
|
||||
return True
|
||||
)
|
||||
|
||||
|
||||
def resolve_llm_model_config(
|
||||
|
||||
@@ -1012,9 +1012,7 @@ def _cli_tool_enabled(item: object) -> bool:
|
||||
return False
|
||||
if data.get("pre_authorized") is False or _permission_denied(data):
|
||||
return False
|
||||
if _dangerous_without_acknowledgement(data):
|
||||
return False
|
||||
return True
|
||||
return not _dangerous_without_acknowledgement(data)
|
||||
|
||||
|
||||
def _shell_cli_tool(item: object) -> DifyShellCliToolConfig | None:
|
||||
|
||||
@@ -55,9 +55,7 @@ class BaiduObsStorage(BaseStorage):
|
||||
@override
|
||||
def exists(self, filename):
|
||||
res = self.client.get_object_meta_data(bucket_name=self.bucket_name, key=filename)
|
||||
if res is None:
|
||||
return False
|
||||
return True
|
||||
return res is not None
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
|
||||
@@ -557,10 +557,7 @@ class VolumePermissionManager:
|
||||
return True
|
||||
|
||||
# Check Windows drive path
|
||||
if len(file_path) >= 2 and file_path[1] == ":":
|
||||
return True
|
||||
|
||||
return False
|
||||
return bool(len(file_path) >= 2 and file_path[1] == ":")
|
||||
|
||||
def _is_sensitive_path(self, file_path: str) -> bool:
|
||||
"""Check if path is sensitive path"""
|
||||
|
||||
@@ -45,9 +45,7 @@ class HuaweiObsStorage(BaseStorage):
|
||||
@override
|
||||
def exists(self, filename):
|
||||
res = self._get_meta(filename)
|
||||
if res is None:
|
||||
return False
|
||||
return True
|
||||
return res is not None
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
|
||||
@@ -53,9 +53,7 @@ class SupabaseStorage(BaseStorage):
|
||||
@override
|
||||
def exists(self, filename):
|
||||
result = self.client.storage.from_(self.bucket_name).list(path=filename)
|
||||
if len(result) > 0:
|
||||
return True
|
||||
return False
|
||||
return len(result) > 0
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
|
||||
@@ -62,9 +62,7 @@ class VolcengineTosStorage(BaseStorage):
|
||||
if not self.bucket_name:
|
||||
return False
|
||||
res = self.client.head_object(bucket=self.bucket_name, key=filename)
|
||||
if res.status_code != 200:
|
||||
return False
|
||||
return True
|
||||
return res.status_code == 200
|
||||
|
||||
@override
|
||||
def delete(self, filename: str):
|
||||
|
||||
+1
-3
@@ -632,9 +632,7 @@ class RateLimiter:
|
||||
self._redis_client.zremrangebyscore(key, "-inf", window_start_time)
|
||||
attempts = self._redis_client.zcard(key)
|
||||
|
||||
if attempts and int(attempts) >= self.max_attempts:
|
||||
return True
|
||||
return False
|
||||
return bool(attempts and int(attempts) >= self.max_attempts)
|
||||
|
||||
def increment_rate_limit(self, email: str):
|
||||
key = self._get_key(email)
|
||||
|
||||
@@ -504,9 +504,7 @@ class TencentTraceClient:
|
||||
|
||||
except Exception:
|
||||
logger.exception("[Tencent APM] API check failed")
|
||||
if "127.0.0.1" in self.endpoint or "localhost" in self.endpoint:
|
||||
return True
|
||||
return False
|
||||
return bool("127.0.0.1" in self.endpoint or "localhost" in self.endpoint)
|
||||
|
||||
def get_project_url(self) -> str:
|
||||
"""Get project console URL"""
|
||||
|
||||
@@ -123,9 +123,7 @@ class BaiduVector(BaseVector):
|
||||
@override
|
||||
def text_exists(self, id: str) -> bool:
|
||||
res = self._db.table(self._collection_name).query(primary_key={VDBField.PRIMARY_KEY: id})
|
||||
if res and res.code == 0:
|
||||
return True
|
||||
return False
|
||||
return bool(res and res.code == 0)
|
||||
|
||||
@override
|
||||
def delete_by_ids(self, ids: list[str]):
|
||||
|
||||
@@ -229,9 +229,7 @@ class TencentVector(BaseVector):
|
||||
docs = self._client.query(
|
||||
database_name=self._client_config.database, collection_name=self.collection_name, document_ids=[id]
|
||||
)
|
||||
if docs and len(docs) > 0:
|
||||
return True
|
||||
return False
|
||||
return bool(docs and len(docs) > 0)
|
||||
|
||||
@override
|
||||
def delete_by_ids(self, ids: list[str]):
|
||||
|
||||
@@ -146,9 +146,7 @@ class VikingDBVector(BaseVector):
|
||||
def text_exists(self, id: str) -> bool:
|
||||
docs = self._client.get_collection(self._collection_name).fetch_data(id)
|
||||
not_exists_str = "data does not exist"
|
||||
if docs is not None and not_exists_str not in docs.fields.get("message", ""):
|
||||
return True
|
||||
return False
|
||||
return bool(docs is not None and not_exists_str not in docs.fields.get("message", ""))
|
||||
|
||||
@override
|
||||
def delete_by_ids(self, ids: list[str]):
|
||||
|
||||
@@ -513,10 +513,7 @@ class DatasetService:
|
||||
model_schema = text_embedding_model.get_model_schema(model_instance.model_name, model_instance.credentials)
|
||||
if not model_schema:
|
||||
raise ValueError("Model schema not found")
|
||||
if model_schema.features and ModelFeature.VISION in model_schema.features:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return bool(model_schema.features and ModelFeature.VISION in model_schema.features)
|
||||
except LLMBadRequestError:
|
||||
raise ValueError("No Model available. Please configure a valid provider in the Settings -> Model Provider.")
|
||||
|
||||
@@ -1934,10 +1931,7 @@ class DocumentService:
|
||||
|
||||
@staticmethod
|
||||
def check_archived(document):
|
||||
if document.archived:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
return bool(document.archived)
|
||||
|
||||
@staticmethod
|
||||
def delete_document(document, session: Session):
|
||||
|
||||
@@ -302,9 +302,7 @@ class WorkflowRunArchiveBundleIndexBackfill:
|
||||
return False
|
||||
if year is not None and _extract_key_part(key, "year") != f"{year:04d}":
|
||||
return False
|
||||
if month is not None and _extract_key_part(key, "month") != f"{month:02d}":
|
||||
return False
|
||||
return True
|
||||
return not (month is not None and _extract_key_part(key, "month") != f"{month:02d}")
|
||||
|
||||
@staticmethod
|
||||
def _validate_manifest_scope(
|
||||
|
||||
@@ -135,10 +135,7 @@ class CommunityTelemetryService:
|
||||
if setup.instance_id is None:
|
||||
return False
|
||||
|
||||
if setup.last_heartbeat_at is not None and setup.last_heartbeat_at.date() >= now.date():
|
||||
return False
|
||||
|
||||
return True
|
||||
return not (setup.last_heartbeat_at is not None and setup.last_heartbeat_at.date() >= now.date())
|
||||
|
||||
@staticmethod
|
||||
def _format_datetime(value: datetime) -> str:
|
||||
|
||||
@@ -140,20 +140,15 @@ class VariableTruncator(BaseTruncator):
|
||||
|
||||
@staticmethod
|
||||
def _segment_need_truncation(segment: Segment) -> bool:
|
||||
if isinstance(
|
||||
segment,
|
||||
(NoneSegment, FloatSegment, IntegerSegment, FileSegment, BooleanSegment, ArrayFileSegment),
|
||||
):
|
||||
return False
|
||||
return True
|
||||
return not isinstance(
|
||||
segment, (NoneSegment, FloatSegment, IntegerSegment, FileSegment, BooleanSegment, ArrayFileSegment)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _json_value_needs_truncation(value: Any) -> bool:
|
||||
if value is None:
|
||||
return False
|
||||
if isinstance(value, (bool, int, float)):
|
||||
return False
|
||||
return True
|
||||
return not isinstance(value, (bool, int, float))
|
||||
|
||||
@override
|
||||
def truncate(self, segment: Segment) -> TruncationResult:
|
||||
@@ -309,9 +304,7 @@ class VariableTruncator(BaseTruncator):
|
||||
qa_chunks = m.get(_QAKeys.QA_CHUNKS)
|
||||
if qa_chunks is None:
|
||||
return False
|
||||
if not isinstance(qa_chunks, list):
|
||||
return False
|
||||
return True
|
||||
return isinstance(qa_chunks, list)
|
||||
|
||||
@classmethod
|
||||
def _maybe_parent_child_structure(cls, m: Mapping[str, Any]) -> bool:
|
||||
@@ -323,10 +316,7 @@ class VariableTruncator(BaseTruncator):
|
||||
parent_child_chunks = m.get(_PCKeys.PARENT_CHILD_CHUNKS)
|
||||
if parent_child_chunks is None:
|
||||
return False
|
||||
if not isinstance(parent_child_chunks, list):
|
||||
return False
|
||||
|
||||
return True
|
||||
return isinstance(parent_child_chunks, list)
|
||||
|
||||
def _truncate_object(self, mapping: Mapping[str, Any], target_size: int) -> _PartResult[Mapping[str, Any]]:
|
||||
"""
|
||||
|
||||
@@ -798,6 +798,4 @@ def _is_passing(result: Mapping[str, Any]) -> bool:
|
||||
"""A check-result row is "passing" when its ``status`` is the ready/passed
|
||||
sentinel emitted by the type-checker / output-check executor."""
|
||||
status = result.get("status")
|
||||
if status in {"ready", "passed", "not_produced"}:
|
||||
return True
|
||||
return False
|
||||
return status in {"ready", "passed", "not_produced"}
|
||||
|
||||
@@ -906,10 +906,8 @@ class DraftVariableSaver:
|
||||
)
|
||||
|
||||
def _should_save_output_variables_for_draft(self) -> bool:
|
||||
if self._enclosing_node_id is not None and self._node_type != BuiltinNodeTypes.VARIABLE_ASSIGNER:
|
||||
# Currently we do not save output variables for nodes inside loop or iteration.
|
||||
return False
|
||||
return True
|
||||
# Save nested output variables only for variable assigners.
|
||||
return self._enclosing_node_id is None or self._node_type == BuiltinNodeTypes.VARIABLE_ASSIGNER
|
||||
|
||||
def _build_from_variable_assigner_mapping(self, process_data: Mapping[str, Any]) -> list[WorkflowDraftVariable]:
|
||||
draft_vars: list[WorkflowDraftVariable] = []
|
||||
@@ -1183,17 +1181,13 @@ class DraftVariableSaver:
|
||||
def _should_variable_be_editable(node_id: str, name: str) -> bool:
|
||||
if node_id in (CONVERSATION_VARIABLE_NODE_ID, ENVIRONMENT_VARIABLE_NODE_ID):
|
||||
return False
|
||||
if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
|
||||
return False
|
||||
return True
|
||||
return not (node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name))
|
||||
|
||||
@staticmethod
|
||||
def _should_variable_be_visible(node_id: str, node_type: NodeType, name: str) -> bool:
|
||||
if node_type == BuiltinNodeTypes.IF_ELSE:
|
||||
return False
|
||||
if node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name):
|
||||
return False
|
||||
return True
|
||||
return not (node_id == SYSTEM_VARIABLE_NODE_ID and not is_system_variable_editable(name))
|
||||
|
||||
def _should_variable_be_saved(self, name: str) -> bool:
|
||||
exclude_var_names = self._EXCLUDE_VARIABLE_NAMES_MAPPING.get(self._node_type)
|
||||
|
||||
@@ -44,10 +44,7 @@ def lb_model_manager():
|
||||
lb_model_manager.cooldown = MagicMock(return_value=None)
|
||||
|
||||
def is_cooldown(config: ModelLoadBalancingConfiguration):
|
||||
if config.id == "id1":
|
||||
return True
|
||||
|
||||
return False
|
||||
return config.id == "id1"
|
||||
|
||||
lb_model_manager.in_cooldown = MagicMock(side_effect=is_cooldown)
|
||||
|
||||
|
||||
Reference in New Issue
Block a user