Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion api/.ruff.toml
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,6 @@ ignore = [
"SIM102", # collapsible-if
"SIM103", # needless-bool
"SIM105", # suppressible-exception
"SIM108", # if-else-block-instead-of-if-exp
"SIM117", # multiple-with-statements
"TID252", # allow relative imports from parent modules
]
Expand Down
5 changes: 1 addition & 4 deletions api/controllers/common/agent_access.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,6 @@ def resolve_agent_access_filter(
if has_agent_list_permission(override.permission_keys)
}

if whitelist_scope.unrestricted:
accessible_agent_ids = permission_agent_ids
else:
accessible_agent_ids = set(whitelist_scope.resource_ids)
accessible_agent_ids = permission_agent_ids if whitelist_scope.unrestricted else set(whitelist_scope.resource_ids)

return AgentAccessFilter(accessible_agent_ids=accessible_agent_ids)
5 changes: 1 addition & 4 deletions api/controllers/common/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,7 @@

def decode_remote_url(url: str, query_string: bytes | str = b"") -> str:
decoded_url = urllib.parse.unquote(url)
if isinstance(query_string, bytes):
raw_query = query_string.decode()
else:
raw_query = query_string
raw_query = query_string.decode() if isinstance(query_string, bytes) else query_string
if not raw_query:
return decoded_url

Expand Down
5 changes: 1 addition & 4 deletions api/controllers/console/app/wraps.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,10 +117,7 @@ def decorated_view(*args: P.args, **kwargs: P.kwargs) -> R:
app_mode = AppMode.value_of(app_model.mode)

if mode is not None:
if isinstance(mode, list):
modes = mode
else:
modes = [mode]
modes = mode if isinstance(mode, list) else [mode]

if app_mode not in modes:
mode_values = {m.value for m in modes}
Expand Down
5 changes: 1 addition & 4 deletions api/controllers/openapi/workflow_events.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,10 +125,7 @@ def _generate_finished_events() -> Generator[str]:
else:
msg_generator = MessageGenerator()
generator: BaseAppGenerator
if app_mode == AppMode.ADVANCED_CHAT:
generator = AdvancedChatAppGenerator()
else:
generator = WorkflowAppGenerator()
generator = AdvancedChatAppGenerator() if app_mode == AppMode.ADVANCED_CHAT else WorkflowAppGenerator()

include_state_snapshot = query.include_state_snapshot
continue_on_pause = query.continue_on_pause
Expand Down
5 changes: 1 addition & 4 deletions api/core/file/remote_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,10 +143,7 @@ def _parse_signed_file_path(path: str) -> _SignedFileUrl | None:
upload_match = _UPLOAD_FILE_PATH_PATTERN.match(path)
if upload_match:
preview_kind: Literal["file-preview", "image-preview"]
if upload_match.group("preview_kind") == "image-preview":
preview_kind = "image-preview"
else:
preview_kind = "file-preview"
preview_kind = "image-preview" if upload_match.group("preview_kind") == "image-preview" else "file-preview"

return _SignedFileUrl(
file_id=upload_match.group("file_id"),
Expand Down
10 changes: 2 additions & 8 deletions api/core/llm_generator/llm_generator.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,7 @@ def _normalize_completion_params(completion_params: dict[str, object]) -> tuple[
"""
normalized_parameters = dict(completion_params)
stop_value = normalized_parameters.pop("stop", [])
if isinstance(stop_value, list) and all(isinstance(item, str) for item in stop_value):
stop = stop_value
else:
stop = []
stop = stop_value if isinstance(stop_value, list) and all(isinstance(item, str) for item in stop_value) else []

for token_limit_key in ("max_tokens", "max_output_tokens"):
token_limit = normalized_parameters.get(token_limit_key)
Expand Down Expand Up @@ -276,10 +273,7 @@ def generate_conversation_name(
answer = query
else:
output = result_dict.get("Your Output")
if isinstance(output, str) and output.strip():
answer = output.strip()
else:
answer = query
answer = output.strip() if isinstance(output, str) and output.strip() else query

name = answer.strip()

Expand Down
5 changes: 1 addition & 4 deletions api/core/memory/token_buffer_memory.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,10 +217,7 @@ def load_history(
# fetch limited messages, and return reversed
stmt = select(Message).where(Message.conversation_id == conversation.id).order_by(Message.created_at.desc())

if message_limit and message_limit > 0:
message_limit = min(message_limit, 500)
else:
message_limit = 500
message_limit = min(message_limit, 500) if message_limit and message_limit > 0 else 500

msg_limit_stmt = stmt.limit(message_limit)

Expand Down
5 changes: 1 addition & 4 deletions api/core/moderation/output_moderation.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,10 +55,7 @@ def moderation_completion(self, completion: str, public_event: bool = False) ->
if not result or not result.flagged:
return completion, False

if result.action == ModerationAction.DIRECT_OUTPUT:
final_output = result.preset_response
else:
final_output = result.text
final_output = result.preset_response if result.action == ModerationAction.DIRECT_OUTPUT else result.text

if public_event:
self.queue_manager.publish(
Expand Down
5 changes: 1 addition & 4 deletions api/core/plugin/impl/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -187,10 +187,7 @@ def _prepare_request(
data if isinstance(data, (bytes, str, dict)) or data is None else None
)
if isinstance(data, dict):
if prepared_headers.get("Content-Type") == "application/json":
prepared_data = json.dumps(data)
else:
prepared_data = data
prepared_data = json.dumps(data) if prepared_headers.get("Content-Type") == "application/json" else data

return str(url), prepared_headers, prepared_data, params, files

Expand Down
5 changes: 1 addition & 4 deletions api/core/rag/datasource/retrieval_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -671,10 +671,7 @@ def format_retrieval_documents(cls, session: Session, documents: list[Document])
child_chunk_details: list[ChildChunkDetail] = []
for child_chunk in child_chunks:
child_document: Document | None = doc_to_document_map.get(child_chunk.index_node_id)
if child_document:
child_score = child_document.metadata.get("score", 0.0)
else:
child_score = 0.0
child_score = child_document.metadata.get("score", 0.0) if child_document else 0.0
child_chunk_detail: ChildChunkDetail = {
"id": child_chunk.id,
"content": child_chunk.content,
Expand Down
5 changes: 1 addition & 4 deletions api/core/rag/extractor/blob/blob.py
Original file line number Diff line number Diff line change
Expand Up @@ -109,10 +109,7 @@ def from_path(
Returns:
Blob instance
"""
if mime_type is None and guess_type:
_mimetype = mimetypes.guess_type(path)[0]
else:
_mimetype = mime_type
_mimetype = mimetypes.guess_type(path)[0] if mime_type is None and guess_type else mime_type
# We do not load the data immediately, instead we treat the blob as a
# reference to the underlying data.
return cls(data=None, mimetype=_mimetype, encoding=encoding, path=path)
Expand Down
5 changes: 1 addition & 4 deletions api/core/rag/extractor/extract_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,10 +96,7 @@ def load_from_url(cls, url: str, return_text: bool = False) -> list[Document] |
if filename_match:
filename = unquote(filename_match.group(1))
match = re.search(r"\.(\w+)$", filename)
if match:
suffix = "." + match.group(1)
else:
suffix = ""
suffix = "." + match.group(1) if match else ""
# https://stackoverflow.com/questions/26541416/generate-temporary-file-names-without-creating-actual-file-in-python#comment90414256_26541521
# Generate a temporary filename under the created temp_dir and ensure the directory exists
file_path = f"{temp_dir}/{next(tempfile._get_candidate_names())}{suffix}" # type: ignore
Expand Down
5 changes: 1 addition & 4 deletions api/core/rag/extractor/notion_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,10 +127,7 @@ def _get_notion_database_data(
# join them all so no part of the value is dropped.
value = "".join(segment.get("plain_text", "") for segment in property_value[type])
elif type in {"select", "status"}:
if property_value[type]:
value = property_value[type]["name"]
else:
value = ""
value = property_value[type]["name"] if property_value[type] else ""
else:
value = property_value[type]
data[property_name] = value
Expand Down
10 changes: 2 additions & 8 deletions api/core/rag/retrieval/dataset_retrieval.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,10 +470,7 @@ def retrieve(
planning_strategy = PlanningStrategy.ROUTER
available_datasets = self._get_available_datasets(tenant_id, dataset_ids)

if inputs:
inputs = {key: str(value) for key, value in inputs.items()}
else:
inputs = {}
inputs = {key: str(value) for key, value in inputs.items()} if inputs else {}
available_datasets_ids = [dataset.id for dataset in available_datasets]
metadata_filter_document_ids, metadata_condition = self.get_metadata_filter_condition(
session,
Expand Down Expand Up @@ -566,10 +563,7 @@ def retrieve(
segment_content = sign_segment_content(segment, session=session)

# If summary exists, prepend it to the content
if record.summary:
final_content = f"{record.summary}\n{segment_content}"
else:
final_content = segment_content
final_content = f"{record.summary}\n{segment_content}" if record.summary else segment_content

document_context_list.append(
DocumentContext(
Expand Down
15 changes: 3 additions & 12 deletions api/core/rag/splitter/fixed_text_splitter.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,10 +41,7 @@ def __init__(self, fixed_separator: str = "\n\n", separators: list[str] | None =
@override
def split_text(self, text: str) -> list[str]:
"""Split incoming text and return chunks."""
if self._fixed_separator:
chunks = text.split(self._fixed_separator)
else:
chunks = [text]
chunks = text.split(self._fixed_separator) if self._fixed_separator else [text]

final_chunks = []
chunks_lengths = self._length_function(chunks)
Expand Down Expand Up @@ -74,18 +71,12 @@ def recursive_split_text(self, text: str) -> list[str]:

# Now that we have the separator, split the text
if separator:
if separator == " ":
splits = re.split(r" +", text)
else:
splits = text.split(separator)
splits = re.split(r" +", text) if separator == " " else text.split(separator)
if self._keep_separator:
splits = [s + separator for s in splits[:-1]] + splits[-1:]
else:
splits = list(text)
if separator == "\n":
splits = [s for s in splits if s != ""]
else:
splits = [s for s in splits if (s not in {"", "\n"})]
splits = [s for s in splits if s != ""] if separator == "\n" else [s for s in splits if s not in {"", "\n"}]
_good_splits = []
_good_splits_lengths = [] # cache the lengths of the splits
_separator = "" if self._keep_separator else separator
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,7 @@ def _run(self, session: Session, query: str) -> str:
self.retrieve_config.metadata_filtering_conditions,
self.inputs,
)
if metadata_filter_document_ids:
document_ids_filter = metadata_filter_document_ids.get(dataset.id, [])
else:
document_ids_filter = None
document_ids_filter = metadata_filter_document_ids.get(dataset.id, []) if metadata_filter_document_ids else None
if dataset.provider == "external":
results: list[RetrievalDocument] = []
external_documents = ExternalDatasetService.fetch_external_knowledge_retrieval(
Expand Down Expand Up @@ -183,10 +180,7 @@ def _run(self, session: Session, query: str) -> str:
segment_content = sign_segment_content(segment, session=session)

# If summary exists, prepend it to the content
if record.summary:
final_content = f"{record.summary}\n{segment_content}"
else:
final_content = segment_content
final_content = f"{record.summary}\n{segment_content}" if record.summary else segment_content

document_context_list.append(
DocumentContext(
Expand Down
5 changes: 1 addition & 4 deletions api/core/tools/utils/web_reader_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,10 +70,7 @@ def get_url(url: str, user_agent: str | None = None) -> str:

# Detect encoding using charset_normalizer
detected_encoding = charset_normalizer.from_bytes(response.content).best()
if detected_encoding:
encoding = detected_encoding.encoding
else:
encoding = "utf-8"
encoding = detected_encoding.encoding if detected_encoding else "utf-8"
if encoding:
try:
content = response.content.decode(encoding)
Expand Down
5 changes: 1 addition & 4 deletions api/enterprise/telemetry/exporter.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,7 @@ def _parse_otlp_headers(raw: str) -> dict[str, str]:
def _datetime_to_ns(dt: datetime) -> int:
"""Convert a datetime to nanoseconds since epoch (OTEL convention)."""
# Ensure we always interpret naive datetimes as UTC instead of local time.
if dt.tzinfo is None:
dt = dt.replace(tzinfo=UTC)
else:
dt = dt.astimezone(UTC)
dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
return int(dt.timestamp() * 1_000_000_000)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -220,10 +220,7 @@ def get_node_last_execution(
# For each id, select the row with max log_version
deduplicated_results = []
for rows in id_to_results.values():
if len(rows) > 1:
max_row = max(rows, key=lambda x: int(x.get("log_version", 0)))
else:
max_row = rows[0]
max_row = max(rows, key=lambda x: int(x.get("log_version", 0))) if len(rows) > 1 else rows[0]
deduplicated_results.append(max_row)
else:
# For PG mode, results are already deduplicated by the SQL query
Expand Down Expand Up @@ -325,10 +322,7 @@ def get_executions_by_workflow_run(

# For each id, select the row with max log_version
for rows in id_to_results.values():
if len(rows) > 1:
max_row = max(rows, key=lambda x: int(x.get("log_version", 0)))
else:
max_row = rows[0]
max_row = max(rows, key=lambda x: int(x.get("log_version", 0))) if len(rows) > 1 else rows[0]

model = _dict_to_workflow_node_execution_model(max_row)
if model and model.id: # Ensure model is valid
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -191,11 +191,8 @@ def _get_volume_sql_prefix(self, dataset_id: str | None = None) -> str:

# Only use TABLE VOLUME for actual dataset-specific paths
# like "dataset_12345/file.pdf" or paths with dataset_ prefix
if dataset_id:
table_name = f"{self._config.table_prefix}{dataset_id}"
else:
# Default table name for generic operations
table_name = "default_dataset"
# Default table name for generic operations
table_name = f"{self._config.table_prefix}{dataset_id}" if dataset_id else "default_dataset"
return f"TABLE VOLUME {table_name}"
elif self._config.volume_type == "external":
return f"VOLUME {self._config.volume_name}"
Expand Down Expand Up @@ -517,10 +514,7 @@ def scan(self, path: str, files: bool = True, directories: bool = False) -> list
else:
sql = f"LIST {volume_prefix} SUBDIRECTORY '{self._config.dify_prefix}'"
else:
if path:
sql = f"LIST {volume_prefix} SUBDIRECTORY '{path}'"
else:
sql = f"LIST {volume_prefix}"
sql = f"LIST {volume_prefix} SUBDIRECTORY '{path}'" if path else f"LIST {volume_prefix}"

rows = self._execute_sql(sql, fetch=True)

Expand Down
5 changes: 1 addition & 4 deletions api/libs/broadcast_channel/redis/streams_channel.py
Original file line number Diff line number Diff line change
Expand Up @@ -202,10 +202,7 @@ def receive(self, timeout: float | None = 0.1) -> bytes | None:
self._start_if_needed()

try:
if timeout is None:
item = self._queue.get()
else:
item = self._queue.get(timeout=timeout)
item = self._queue.get() if timeout is None else self._queue.get(timeout=timeout)
except queue.Empty:
return None

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -262,13 +262,10 @@ def search_by_vector(self, query_vector: list[float], **kwargs: Any) -> list[Doc
try:
distance = float(record["distance"])
# Convert distance to similarity score
if self.distance_function == "cosine":
# For cosine distance: similarity = 1 - distance
similarity = 1.0 - distance
else:
# For euclidean distance: use inverse relationship
# similarity = 1 / (1 + distance)
similarity = 1.0 / (1.0 + distance)
# For cosine distance: similarity = 1 - distance
# For euclidean distance: use inverse relationship
# similarity = 1 / (1 + distance)
similarity = 1.0 - distance if self.distance_function == "cosine" else 1.0 / (1.0 + distance)

metadata = parse_metadata_json(record["meta"])
metadata["score"] = similarity
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -531,10 +531,7 @@ def search_by_vector(self, query_vector: list[float], **kwargs: Any) -> list[Doc
for obj in res.objects:
properties = dict(obj.properties or {})
text = properties.pop(Field.TEXT_KEY.value, "")
if obj.metadata and obj.metadata.distance is not None:
distance = obj.metadata.distance
else:
distance = 1.0
distance = obj.metadata.distance if obj.metadata and obj.metadata.distance is not None else 1.0
score = 1.0 - distance

if score > score_threshold:
Expand Down
5 changes: 1 addition & 4 deletions api/repositories/app/console_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -774,10 +774,7 @@ def update_app(cls, app: App, args: AppUpdateArguments, *, account_id: str, sess
app.name = args["name"]
app.description = args["description"]
icon_type = args.get("icon_type")
if icon_type is None:
resolved_icon_type = app.icon_type
else:
resolved_icon_type = IconType(icon_type)
resolved_icon_type = app.icon_type if icon_type is None else IconType(icon_type)

app.icon_type = resolved_icon_type
app.icon = args["icon"]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,7 @@ def _map_human_input_content(
display_in_ui = bool(form_definition.display_in_ui)

submitted = form.submitted_at is not None or form.status == HumanInputFormStatus.SUBMITTED
if not submitted:
form_token = self._resolve_form_token(recipients_by_form_id.get(form.id, []))
else:
form_token = None
form_token = self._resolve_form_token(recipients_by_form_id.get(form.id, [])) if not submitted else None
form_definition_domain_model = HumanInputFormDefinition(
form_id=form.id,
node_id=form.node_id,
Expand Down
Loading
Loading