diff --git a/api/.ruff.toml b/api/.ruff.toml index 84da3779bb4..e5e1f970810 100644 --- a/api/.ruff.toml +++ b/api/.ruff.toml @@ -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 diff --git a/api/app.py b/api/app.py index 7ca94d73459..8aadb4e548b 100644 --- a/api/app.py +++ b/api/app.py @@ -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: diff --git a/api/core/agent/fc_agent_runner.py b/api/core/agent/fc_agent_runner.py index e2f525588bc..a3bd64c1b2a 100644 --- a/api/core/agent/fc_agent_runner.py +++ b/api/core/agent/fc_agent_runner.py @@ -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]]]: """ diff --git a/api/core/app/app_config/easy_ui_based_app/dataset/manager.py b/api/core/app/app_config/easy_ui_based_app/dataset/manager.py index 802952b3d16..eb83051941d 100644 --- a/api/core/app/app_config/easy_ui_based_app/dataset/manager.py +++ b/api/core/app/app_config/easy_ui_based_app/dataset/manager.py @@ -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 diff --git a/api/core/app/apps/base_app_queue_manager.py b/api/core/app/apps/base_app_queue_manager.py index ea8d50b74ae..24909a79896 100644 --- a/api/core/app/apps/base_app_queue_manager.py +++ b/api/core/app/apps/base_app_queue_manager.py @@ -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: diff --git a/api/core/helper/position_helper.py b/api/core/helper/position_helper.py index 71d83bef4ad..78a1e507ec7 100644 --- a/api/core/helper/position_helper.py +++ b/api/core/helper/position_helper.py @@ -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]( diff --git a/api/core/model_manager.py b/api/core/model_manager.py index 20f681ff6ad..384a537a781 100644 --- a/api/core/model_manager.py +++ b/api/core/model_manager.py @@ -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: diff --git a/api/core/workflow/llm_environment_variable.py b/api/core/workflow/llm_environment_variable.py index aacca73a6d0..02b44a740c7 100644 --- a/api/core/workflow/llm_environment_variable.py +++ b/api/core/workflow/llm_environment_variable.py @@ -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( diff --git a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py index 0dcdcb35b36..43ebe6ca37d 100644 --- a/api/core/workflow/nodes/agent_v2/runtime_request_builder.py +++ b/api/core/workflow/nodes/agent_v2/runtime_request_builder.py @@ -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: diff --git a/api/extensions/storage/baidu_obs_storage.py b/api/extensions/storage/baidu_obs_storage.py index a4f579e551f..a0dee049d22 100644 --- a/api/extensions/storage/baidu_obs_storage.py +++ b/api/extensions/storage/baidu_obs_storage.py @@ -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): diff --git a/api/extensions/storage/clickzetta_volume/volume_permissions.py b/api/extensions/storage/clickzetta_volume/volume_permissions.py index 9d4ca689d84..1ee6a479482 100644 --- a/api/extensions/storage/clickzetta_volume/volume_permissions.py +++ b/api/extensions/storage/clickzetta_volume/volume_permissions.py @@ -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""" diff --git a/api/extensions/storage/huawei_obs_storage.py b/api/extensions/storage/huawei_obs_storage.py index 3c90baa32dc..c3cefdf5ea4 100644 --- a/api/extensions/storage/huawei_obs_storage.py +++ b/api/extensions/storage/huawei_obs_storage.py @@ -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): diff --git a/api/extensions/storage/supabase_storage.py b/api/extensions/storage/supabase_storage.py index 50c14ac2901..4a213b7662b 100644 --- a/api/extensions/storage/supabase_storage.py +++ b/api/extensions/storage/supabase_storage.py @@ -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): diff --git a/api/extensions/storage/volcengine_tos_storage.py b/api/extensions/storage/volcengine_tos_storage.py index e0a03a06c0b..3c4addff2b5 100644 --- a/api/extensions/storage/volcengine_tos_storage.py +++ b/api/extensions/storage/volcengine_tos_storage.py @@ -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): diff --git a/api/libs/helper.py b/api/libs/helper.py index 355ddfc2a07..abb02d2ca4a 100644 --- a/api/libs/helper.py +++ b/api/libs/helper.py @@ -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) diff --git a/api/providers/trace/trace-tencent/src/dify_trace_tencent/client.py b/api/providers/trace/trace-tencent/src/dify_trace_tencent/client.py index c616de5724b..a628ce4bb51 100644 --- a/api/providers/trace/trace-tencent/src/dify_trace_tencent/client.py +++ b/api/providers/trace/trace-tencent/src/dify_trace_tencent/client.py @@ -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""" diff --git a/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py b/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py index 3a1a638b979..ae8e7f287b9 100644 --- a/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py +++ b/api/providers/vdb/vdb-baidu/src/dify_vdb_baidu/baidu_vector.py @@ -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]): diff --git a/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py b/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py index cbacb33f9db..30974156ab9 100644 --- a/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py +++ b/api/providers/vdb/vdb-tencent/src/dify_vdb_tencent/tencent_vector.py @@ -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]): diff --git a/api/providers/vdb/vdb-vikingdb/src/dify_vdb_vikingdb/vikingdb_vector.py b/api/providers/vdb/vdb-vikingdb/src/dify_vdb_vikingdb/vikingdb_vector.py index 96eecf77ffd..e0bbc8d6243 100644 --- a/api/providers/vdb/vdb-vikingdb/src/dify_vdb_vikingdb/vikingdb_vector.py +++ b/api/providers/vdb/vdb-vikingdb/src/dify_vdb_vikingdb/vikingdb_vector.py @@ -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]): diff --git a/api/services/knowledge/dataset_service.py b/api/services/knowledge/dataset_service.py index bc4ab0bc671..045d817b021 100644 --- a/api/services/knowledge/dataset_service.py +++ b/api/services/knowledge/dataset_service.py @@ -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): diff --git a/api/services/retention/workflow_run/archive_bundle_index.py b/api/services/retention/workflow_run/archive_bundle_index.py index 8eb9723a7f8..6a1025dd005 100644 --- a/api/services/retention/workflow_run/archive_bundle_index.py +++ b/api/services/retention/workflow_run/archive_bundle_index.py @@ -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( diff --git a/api/services/telemetry_service.py b/api/services/telemetry_service.py index adf3565cc0e..530885165e0 100644 --- a/api/services/telemetry_service.py +++ b/api/services/telemetry_service.py @@ -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: diff --git a/api/services/variable_truncator.py b/api/services/variable_truncator.py index 78e917b052a..1266111e89e 100644 --- a/api/services/variable_truncator.py +++ b/api/services/variable_truncator.py @@ -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]]: """ diff --git a/api/services/workflow/node_output_inspector_service.py b/api/services/workflow/node_output_inspector_service.py index b972330484b..65f2b97d938 100644 --- a/api/services/workflow/node_output_inspector_service.py +++ b/api/services/workflow/node_output_inspector_service.py @@ -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"} diff --git a/api/services/workflow_draft_variable_service.py b/api/services/workflow_draft_variable_service.py index 28bea6e3a90..e0acab10def 100644 --- a/api/services/workflow_draft_variable_service.py +++ b/api/services/workflow_draft_variable_service.py @@ -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) diff --git a/api/tests/unit_tests/core/test_model_manager.py b/api/tests/unit_tests/core/test_model_manager.py index cab6013f033..fd275b71404 100644 --- a/api/tests/unit_tests/core/test_model_manager.py +++ b/api/tests/unit_tests/core/test_model_manager.py @@ -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)