mirror of
https://github.com/langgenius/dify.git
synced 2026-11-10 21:35:45 +08:00
ci: enable Ruff B904 (#44121)
Co-authored-by: Codex <codex@openai.com> Co-authored-by: hjlarry <hjlarry@163.com>
This commit is contained in:
138 files changed
+883
-872
No files matched your search
+1
-2
@@ -59,7 +59,6 @@ select = [
|
||||
|
||||
ignore = [
|
||||
"B901", # allow return in yield
|
||||
"B904", # raise-without-from-inside-except
|
||||
"N815", # mixed-case-variable-in-class-scope
|
||||
"SIM102", # collapsible-if
|
||||
"SIM117", # multiple-with-statements
|
||||
@@ -84,4 +83,4 @@ msg = "Use Pydantic payload/query models instead of reqparse."
|
||||
msg = "Use Pydantic payload/query models instead of reqparse."
|
||||
|
||||
[lint.isort]
|
||||
known-first-party = ["graphon"]
|
||||
known-first-party = ["graphon"]
|
||||
@@ -159,7 +159,7 @@ def upgrade_db():
|
||||
except Exception as e:
|
||||
logger.exception("Failed to execute database migration")
|
||||
click.echo(click.style(f"Database migration failed: {e}", fg="red"))
|
||||
raise SystemExit(1)
|
||||
raise SystemExit(1) from e
|
||||
finally:
|
||||
status = "successful" if migration_succeeded else "failed"
|
||||
lock.release_safely(status=status)
|
||||
|
||||
@@ -38,7 +38,7 @@ class NacosSettingsSource(RemoteSettingsSource):
|
||||
try:
|
||||
return parse_config(content)
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Failed to parse config: {e}")
|
||||
raise RuntimeError(f"Failed to parse config: {e}") from e
|
||||
|
||||
@override
|
||||
def get_field_value(self, field: FieldInfo, field_name: str) -> tuple[Any, str, bool]:
|
||||
|
||||
@@ -153,27 +153,27 @@ def _transcribe_audio_to_text(
|
||||
end_user=None,
|
||||
)
|
||||
return dump_response(AudioTranscriptResponse, response)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except NoAudioUploadedServiceError:
|
||||
raise NoAudioUploadedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except NoAudioUploadedServiceError as caught_error:
|
||||
raise NoAudioUploadedError() from caught_error
|
||||
except AudioTooLargeServiceError as e:
|
||||
raise AudioTooLargeError(str(e))
|
||||
except UnsupportedAudioTypeServiceError:
|
||||
raise UnsupportedAudioTypeError()
|
||||
except ProviderNotSupportSpeechToTextServiceError:
|
||||
raise ProviderNotSupportSpeechToTextError()
|
||||
except SpeechToTextDisabledServiceError:
|
||||
raise SpeechToTextDisabledError()
|
||||
raise AudioTooLargeError(str(e)) from e
|
||||
except UnsupportedAudioTypeServiceError as caught_error:
|
||||
raise UnsupportedAudioTypeError() from caught_error
|
||||
except ProviderNotSupportSpeechToTextServiceError as caught_error:
|
||||
raise ProviderNotSupportSpeechToTextError() from caught_error
|
||||
except SpeechToTextDisabledServiceError as caught_error:
|
||||
raise SpeechToTextDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError:
|
||||
@@ -314,19 +314,19 @@ def _text_to_speech(*, payload: TextToSpeechPayload, app_model: App, session: Se
|
||||
message_ref=message_ref,
|
||||
is_draft=True,
|
||||
)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except ProviderNotSupportTextToSpeechServiceError:
|
||||
raise ProviderNotSupportTextToSpeechError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderNotSupportTextToSpeechServiceError as caught_error:
|
||||
raise ProviderNotSupportTextToSpeechError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except HTTPException:
|
||||
raise
|
||||
except ValueError:
|
||||
@@ -431,18 +431,18 @@ def _get_text_to_speech_voices(*, tenant_id: str, language: str):
|
||||
|
||||
return dump_response(TextToSpeechVoiceListResponse, response)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("Failed to handle get request to TextModesApi")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/text-to-audio/voices")
|
||||
|
||||
@@ -188,26 +188,26 @@ class CompletionMessageApi(Resource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/completion-messages/<string:task_id>/stop")
|
||||
@@ -567,30 +567,30 @@ def _generate_chat_message(
|
||||
invoke_from=InvokeFrom.DEBUGGER,
|
||||
streaming=streaming,
|
||||
)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except CompletionRequestError:
|
||||
raise
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
def _generate_chat_message_response(
|
||||
|
||||
@@ -217,8 +217,8 @@ class CompletionConversationDetailApi(Resource):
|
||||
|
||||
try:
|
||||
ConversationService.delete(app_model, conversation_id_str, current_user, session=session)
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
return "", 204
|
||||
|
||||
@@ -385,8 +385,8 @@ class ChatConversationDetailApi(Resource):
|
||||
|
||||
try:
|
||||
ConversationService.delete(app_model, conversation_id_str, current_user, session=session)
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
return "", 204
|
||||
|
||||
|
||||
@@ -277,13 +277,13 @@ class RuleGenerateApi(Resource):
|
||||
try:
|
||||
rules = LLMGenerator.generate_rule_config(tenant_id=current_tenant_id, args=req_data)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
|
||||
return dump_response(RuleGenerateResponse, rules)
|
||||
|
||||
@@ -313,13 +313,13 @@ class RuleCodeGenerateApi(Resource):
|
||||
args=req_data,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
|
||||
return code_result
|
||||
|
||||
@@ -353,13 +353,13 @@ class RuleStructuredOutputGenerateApi(Resource):
|
||||
args=req_data,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
|
||||
return structured_output
|
||||
|
||||
@@ -466,13 +466,13 @@ class InstructionGenerateApi(Resource):
|
||||
)
|
||||
return {"error": "incompatible parameters"}, 400
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
|
||||
|
||||
@console_ns.route("/instruction-generate/template")
|
||||
@@ -578,13 +578,13 @@ class WorkflowGenerateApi(Resource):
|
||||
else None,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
|
||||
return dump_response(WorkflowGenerateResponse, result)
|
||||
|
||||
|
||||
@@ -403,8 +403,8 @@ def _list_chat_messages(
|
||||
user=current_user,
|
||||
session=session,
|
||||
)
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
else:
|
||||
conversation = session.scalar(
|
||||
select(Conversation)
|
||||
@@ -529,25 +529,25 @@ def _get_message_suggested_questions(
|
||||
raise AppUnavailableError() from exc
|
||||
except SuggestedQuestionsActorNotFoundError as exc:
|
||||
raise Unauthorized("Account no longer exists") from exc
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message not found")
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation not found")
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message not found") from caught_error
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation not found") from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
except SuggestedQuestionsAfterAnswerDisabledError:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError()
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except SuggestedQuestionsAfterAnswerDisabledError as caught_error:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError() from caught_error
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
return dump_response(SuggestedQuestionsResponse, {"data": questions})
|
||||
|
||||
|
||||
@@ -660,8 +660,8 @@ class DraftWorkflowApi(Resource):
|
||||
elif "text/plain" in content_type:
|
||||
try:
|
||||
args_model = SyncDraftWorkflowPayload.model_validate_json(request.data)
|
||||
except (ValueError, ValidationError):
|
||||
raise InvalidArgumentError("Invalid JSON data")
|
||||
except (ValueError, ValidationError) as caught_error:
|
||||
raise InvalidArgumentError("Invalid JSON data") from caught_error
|
||||
else:
|
||||
abort(415)
|
||||
|
||||
@@ -703,10 +703,10 @@ class DraftWorkflowApi(Resource):
|
||||
preserve_environment_variables=True,
|
||||
graph_only=args_model.is_collaborative,
|
||||
)
|
||||
except WorkflowHashNotEqualError:
|
||||
raise DraftWorkflowNotSync()
|
||||
except WorkflowHashNotEqualError as caught_error:
|
||||
raise DraftWorkflowNotSync() from caught_error
|
||||
except VariableError as e:
|
||||
raise InvalidArgumentError(description=str(e))
|
||||
raise InvalidArgumentError(description=str(e)) from e
|
||||
|
||||
return dump_response(
|
||||
SyncDraftWorkflowResponse,
|
||||
@@ -758,17 +758,17 @@ class AdvancedChatDraftWorkflowRunApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/advanced-chat/workflows/draft/iteration/nodes/<string:node_id>/run")
|
||||
@@ -809,15 +809,15 @@ class AdvancedChatDraftRunIterationNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/workflows/draft/iteration/nodes/<string:node_id>/run")
|
||||
@@ -858,15 +858,15 @@ class WorkflowDraftRunIterationNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/advanced-chat/workflows/draft/loop/nodes/<string:node_id>/run")
|
||||
@@ -902,15 +902,15 @@ class AdvancedChatDraftRunLoopNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/workflows/draft/loop/nodes/<string:node_id>/run")
|
||||
@@ -950,15 +950,15 @@ class WorkflowDraftRunLoopNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
class HumanInputFormPreviewPayload(BaseModel):
|
||||
@@ -1207,7 +1207,7 @@ class DraftWorkflowRunApi(Resource):
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
|
||||
|
||||
@console_ns.route("/apps/<uuid:app_id>/workflow-runs/tasks/<string:task_id>/stop")
|
||||
@@ -1421,8 +1421,8 @@ class DefaultBlockConfigApi(Resource):
|
||||
if args.q:
|
||||
try:
|
||||
filters = json.loads(args.q)
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Invalid filters")
|
||||
except json.JSONDecodeError as caught_error:
|
||||
raise ValueError("Invalid filters") from caught_error
|
||||
|
||||
# Get default block configs
|
||||
workflow_service = WorkflowService()
|
||||
@@ -1674,7 +1674,7 @@ class WorkflowByIdApi(Resource):
|
||||
except DraftWorkflowDeletionError as e:
|
||||
abort(400, description=str(e))
|
||||
except ValueError as e:
|
||||
raise NotFound(str(e))
|
||||
raise NotFound(str(e)) from e
|
||||
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id=app_model.tenant_id,
|
||||
@@ -1781,7 +1781,7 @@ class DraftWorkflowTriggerRunApi(Resource):
|
||||
)
|
||||
)
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except PluginInvokeError as e:
|
||||
return jsonable_encoder({"status": "error", "error": e.to_user_friendly_error()}), 400
|
||||
except Exception as e:
|
||||
@@ -1937,7 +1937,7 @@ class DraftWorkflowTriggerRunAllApi(Resource):
|
||||
)
|
||||
return helper.compact_generate_response(response)
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except Exception:
|
||||
logger.exception("Error running draft workflow trigger run-all")
|
||||
return jsonable_encoder(
|
||||
|
||||
@@ -98,7 +98,7 @@ class DatasetsHitTestingBase:
|
||||
try:
|
||||
DatasetService.check_dataset_permission(dataset, current_user, session)
|
||||
except services.errors.base.NoPermissionError as e:
|
||||
raise Forbidden(str(e))
|
||||
raise Forbidden(str(e)) from e
|
||||
|
||||
return dataset
|
||||
|
||||
@@ -140,23 +140,23 @@ class DatasetsHitTestingBase:
|
||||
"query": {"content": query["content"]},
|
||||
"records": DatasetsHitTestingBase._prepare_hit_testing_records(response.get("records", [])),
|
||||
}
|
||||
except services.errors.index.IndexNotInitializedError:
|
||||
raise DatasetNotInitializedError()
|
||||
except services.errors.index.IndexNotInitializedError as caught_error:
|
||||
raise DatasetNotInitializedError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
except LLMBadRequestError:
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except LLMBadRequestError as caught_error:
|
||||
raise ProviderNotInitializeError(
|
||||
"No Embedding Model or Reranking Model available. Please configure a valid provider "
|
||||
"in the Settings -> Model Provider."
|
||||
)
|
||||
) from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise ValueError(str(e))
|
||||
except Exception:
|
||||
raise ValueError(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.exception("Hit testing failed.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
@@ -325,7 +325,7 @@ class DatasourceAuth(Resource):
|
||||
name=req_data.name,
|
||||
)
|
||||
except CredentialsValidateFailedError as ex:
|
||||
raise ValueError(str(ex))
|
||||
raise ValueError(str(ex)) from ex
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json"), 200
|
||||
|
||||
@console_ns.response(
|
||||
|
||||
@@ -93,8 +93,8 @@ class CreateRagPipelineDatasetApi(Resource):
|
||||
db.session(),
|
||||
)
|
||||
db.session.commit()
|
||||
except services.errors.dataset.DatasetNameDuplicateError:
|
||||
raise DatasetNameDuplicateError()
|
||||
except services.errors.dataset.DatasetNameDuplicateError as caught_error:
|
||||
raise DatasetNameDuplicateError() from caught_error
|
||||
|
||||
if dify_config.RBAC_ENABLED and dataset_id is not None:
|
||||
enterprise_rbac_service.RBACService.DatasetAccess.replace_whitelist(
|
||||
|
||||
@@ -276,8 +276,8 @@ class DraftRagPipelineApi(Resource):
|
||||
elif "text/plain" in content_type:
|
||||
try:
|
||||
payload = DraftWorkflowSyncPayload.model_validate_json(request.data)
|
||||
except (ValueError, ValidationError):
|
||||
raise InvalidArgumentError("Invalid JSON data")
|
||||
except (ValueError, ValidationError) as caught_error:
|
||||
raise InvalidArgumentError("Invalid JSON data") from caught_error
|
||||
else:
|
||||
abort(415)
|
||||
rag_pipeline_service = RagPipelineService(db.session())
|
||||
@@ -302,8 +302,8 @@ class DraftRagPipelineApi(Resource):
|
||||
conversation_variables=conversation_variables,
|
||||
rag_pipeline_variables=payload.rag_pipeline_variables or [],
|
||||
)
|
||||
except WorkflowHashNotEqualError:
|
||||
raise DraftWorkflowNotSync()
|
||||
except WorkflowHashNotEqualError as caught_error:
|
||||
raise DraftWorkflowNotSync() from caught_error
|
||||
|
||||
return {
|
||||
"result": "success",
|
||||
@@ -342,15 +342,15 @@ class RagPipelineDraftRunIterationNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logging.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflows/draft/loop/nodes/<string:node_id>/run")
|
||||
@@ -383,15 +383,15 @@ class RagPipelineDraftRunLoopNodeApi(Resource):
|
||||
)
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logging.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflows/draft/run")
|
||||
@@ -429,7 +429,7 @@ class DraftRagPipelineRunApi(Resource):
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
|
||||
|
||||
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflows/published/run")
|
||||
@@ -466,7 +466,7 @@ class PublishedRagPipelineRunApi(Resource):
|
||||
|
||||
return helper.compact_generate_response(response)
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
|
||||
|
||||
@console_ns.route("/rag/pipelines/<uuid:pipeline_id>/workflows/published/datasource/nodes/<string:node_id>/run")
|
||||
@@ -697,8 +697,8 @@ class DefaultRagPipelineBlockConfigApi(Resource):
|
||||
if req_data.q:
|
||||
try:
|
||||
filters = json.loads(req_data.q)
|
||||
except json.JSONDecodeError:
|
||||
raise ValueError("Invalid filters")
|
||||
except json.JSONDecodeError as caught_error:
|
||||
raise ValueError("Invalid filters") from caught_error
|
||||
|
||||
# Get default block configs
|
||||
rag_pipeline_service = RagPipelineService(db.session())
|
||||
@@ -859,7 +859,7 @@ class RagPipelineByIdApi(Resource):
|
||||
except DraftWorkflowDeletionError as e:
|
||||
abort(400, description=str(e))
|
||||
except ValueError as e:
|
||||
raise NotFound(str(e))
|
||||
raise NotFound(str(e)) from e
|
||||
|
||||
WorkflowAgentRetirementService.retire_unowned(
|
||||
tenant_id=pipeline.tenant_id,
|
||||
|
||||
@@ -48,13 +48,13 @@ class WebsiteCrawlApi(Resource):
|
||||
try:
|
||||
api_request = WebsiteCrawlApiRequest.from_args(req_data.model_dump())
|
||||
except ValueError as e:
|
||||
raise WebsiteCrawlError(str(e))
|
||||
raise WebsiteCrawlError(str(e)) from e
|
||||
|
||||
# Crawl URL using typed request
|
||||
try:
|
||||
result = WebsiteService(providers=application_services().data_sources.providers).crawl_url(api_request)
|
||||
except Exception as e:
|
||||
raise WebsiteCrawlError(str(e))
|
||||
raise WebsiteCrawlError(str(e)) from e
|
||||
return result, 200
|
||||
|
||||
|
||||
@@ -76,7 +76,7 @@ class WebsiteCrawlStatusApi(Resource):
|
||||
try:
|
||||
api_request = WebsiteCrawlStatusApiRequest.from_args(req_data.model_dump(), job_id)
|
||||
except ValueError as e:
|
||||
raise WebsiteCrawlError(str(e))
|
||||
raise WebsiteCrawlError(str(e)) from e
|
||||
|
||||
# Get crawl status using typed request
|
||||
try:
|
||||
@@ -84,5 +84,5 @@ class WebsiteCrawlStatusApi(Resource):
|
||||
api_request
|
||||
)
|
||||
except Exception as e:
|
||||
raise WebsiteCrawlError(str(e))
|
||||
raise WebsiteCrawlError(str(e)) from e
|
||||
return result, 200
|
||||
@@ -123,26 +123,26 @@ class CompletionApi(Resource):
|
||||
raise NotFoundError("Installed app not found") from None
|
||||
except AccountNotFoundError:
|
||||
raise UnauthorizedError("Account no longer exists.") from None
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFoundError("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFoundError("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route(
|
||||
@@ -213,28 +213,28 @@ class ChatApi(Resource):
|
||||
raise NotFoundError("Installed app not found") from None
|
||||
except AccountNotFoundError:
|
||||
raise UnauthorizedError("Account no longer exists.") from None
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFoundError("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFoundError("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route(
|
||||
|
||||
@@ -74,8 +74,8 @@ class SavedMessageListApi(Resource):
|
||||
actor=SavedMessageActor.account(request_context.account_id),
|
||||
message_id=str(req_data.message_id),
|
||||
)
|
||||
except MessageNotExistsError:
|
||||
raise NotFoundError("Message Not Exists.")
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFoundError("Message Not Exists.") from caught_error
|
||||
|
||||
return ResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
|
||||
@@ -585,20 +585,20 @@ class TrialAppWorkflowRunApi(Resource):
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as error:
|
||||
raise AppUnavailableError() from error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except (AppInvokeQuotaExceededError, InvokeRateLimitError) as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/trial-apps/<uuid:app_id>/workflows/tasks/<string:task_id>/stop")
|
||||
@@ -661,30 +661,30 @@ class TrialChatApi(Resource):
|
||||
raise AppUnavailableError() from error
|
||||
except AccountNotFoundError as error:
|
||||
raise UnauthorizedError("Account no longer exists.") from error
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFoundError("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFoundError("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except (AgentAppGeneratorError, AgentAppNotPublishedError):
|
||||
raise AppUnavailableError() from None
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except (AppInvokeQuotaExceededError, InvokeRateLimitError) as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route(
|
||||
@@ -742,23 +742,23 @@ class TrialMessageSuggestedQuestionApi(Resource):
|
||||
raise AppUnavailableError() from error
|
||||
except SuggestedQuestionsActorNotFoundError as error:
|
||||
raise UnauthorizedError("Account no longer exists.") from error
|
||||
except MessageNotExistsError:
|
||||
raise NotFoundError("Message not found")
|
||||
except ConversationNotExistsError:
|
||||
raise NotFoundError("Conversation not found")
|
||||
except SuggestedQuestionsAfterAnswerDisabledError:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError()
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFoundError("Message not found") from caught_error
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFoundError("Conversation not found") from caught_error
|
||||
except SuggestedQuestionsAfterAnswerDisabledError as caught_error:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
except Exception:
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
return dump_response(SuggestedQuestionsResponse, {"data": questions})
|
||||
|
||||
@@ -920,28 +920,28 @@ class TrialCompletionApi(Resource):
|
||||
raise AppUnavailableError() from error
|
||||
except AccountNotFoundError as error:
|
||||
raise UnauthorizedError("Account no longer exists.") from error
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFoundError("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFoundError("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except (AppInvokeQuotaExceededError, InvokeRateLimitError) as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/trial-apps/<uuid:app_id>/site")
|
||||
|
||||
@@ -80,20 +80,20 @@ class InstalledAppWorkflowRunApi(Resource):
|
||||
except AccountNotFoundError:
|
||||
raise UnauthorizedError("Account no longer exists.") from None
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/installed-apps/<uuid:installed_app_id>/workflows/tasks/<string:task_id>/stop")
|
||||
|
||||
@@ -223,8 +223,8 @@ class SnippetDraftWorkflowApi(Resource):
|
||||
account=current_user,
|
||||
input_fields=req_data.input_fields,
|
||||
)
|
||||
except WorkflowHashNotEqualError:
|
||||
raise DraftWorkflowNotSync()
|
||||
except WorkflowHashNotEqualError as caught_error:
|
||||
raise DraftWorkflowNotSync() from caught_error
|
||||
except ValueError as e:
|
||||
raise InvalidArgumentError(str(e)) from e
|
||||
|
||||
@@ -502,11 +502,11 @@ class SnippetWorkflowByIdApi(Resource):
|
||||
workflow_id=workflow_id,
|
||||
)
|
||||
except WorkflowInUseError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except DraftWorkflowDeletionError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except ValueError as e:
|
||||
raise NotFound(str(e))
|
||||
raise NotFound(str(e)) from e
|
||||
|
||||
return None, 204
|
||||
|
||||
@@ -745,9 +745,9 @@ class SnippetDraftRunIterationNodeApi(Resource):
|
||||
return helper.compact_generate_response(response)
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/snippets/<uuid:snippet_id>/workflows/draft/loop/nodes/<string:node_id>/run")
|
||||
@@ -796,9 +796,9 @@ class SnippetDraftRunLoopNodeApi(Resource):
|
||||
return helper.compact_generate_response(response)
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/snippets/<uuid:snippet_id>/workflows/draft/run")
|
||||
@@ -840,9 +840,9 @@ class SnippetDraftWorkflowRunApi(Resource):
|
||||
return helper.compact_generate_response(response)
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@console_ns.route("/snippets/<uuid:snippet_id>/workflow-runs/tasks/<string:task_id>/stop")
|
||||
|
||||
@@ -238,7 +238,7 @@ class ModelProviderCredentialApi(Resource):
|
||||
credential_name=args.name,
|
||||
)
|
||||
except CredentialsValidateFailedError as ex:
|
||||
raise ValueError(str(ex))
|
||||
raise ValueError(str(ex)) from ex
|
||||
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json"), 201
|
||||
|
||||
@@ -263,7 +263,7 @@ class ModelProviderCredentialApi(Resource):
|
||||
credential_name=args.name,
|
||||
)
|
||||
except CredentialsValidateFailedError as ex:
|
||||
raise ValueError(str(ex))
|
||||
raise ValueError(str(ex)) from ex
|
||||
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
|
||||
@@ -427,7 +427,7 @@ class ModelProviderModelCredentialApi(Resource):
|
||||
req_data.model,
|
||||
req_data.model_type,
|
||||
)
|
||||
raise ValueError(str(ex))
|
||||
raise ValueError(str(ex)) from ex
|
||||
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json"), 201
|
||||
|
||||
@@ -454,7 +454,7 @@ class ModelProviderModelCredentialApi(Resource):
|
||||
credential_name=req_data.name,
|
||||
)
|
||||
except CredentialsValidateFailedError as ex:
|
||||
raise ValueError(str(ex))
|
||||
raise ValueError(str(ex)) from ex
|
||||
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
|
||||
@@ -624,8 +624,8 @@ class PluginCategoryListApi(Resource):
|
||||
|
||||
try:
|
||||
plugin_category = PluginCategory(category)
|
||||
except ValueError:
|
||||
raise InvalidArgumentError("invalid plugin category")
|
||||
except ValueError as caught_error:
|
||||
raise InvalidArgumentError("invalid plugin category") from caught_error
|
||||
|
||||
try:
|
||||
plugins = PluginService.list_by_category(
|
||||
@@ -810,7 +810,7 @@ class PluginUploadFromBundleApi(Resource):
|
||||
try:
|
||||
response = PluginService.upload_bundle(tenant_id, content)
|
||||
except PluginDaemonClientSideError as e:
|
||||
raise ValueError(e)
|
||||
raise ValueError(e) from e
|
||||
|
||||
return jsonable_encoder(response)
|
||||
|
||||
|
||||
@@ -511,7 +511,7 @@ class TriggerSubscriptionUpdateApi(Resource):
|
||||
)
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json")
|
||||
except ValueError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.exception("Error updating subscription", exc_info=e)
|
||||
raise
|
||||
@@ -547,7 +547,7 @@ class TriggerSubscriptionDeleteApi(Resource):
|
||||
)
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json")
|
||||
except ValueError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.exception("Error deleting provider credential", exc_info=e)
|
||||
raise
|
||||
@@ -782,7 +782,7 @@ class TriggerOAuthClientManageApi(Resource):
|
||||
return dump_response(SimpleResultResponse, result)
|
||||
|
||||
except ValueError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.exception("Error configuring OAuth client", exc_info=e)
|
||||
raise
|
||||
@@ -808,7 +808,7 @@ class TriggerOAuthClientManageApi(Resource):
|
||||
)
|
||||
return dump_response(SimpleResultResponse, result)
|
||||
except ValueError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
except Exception as e:
|
||||
logger.exception("Error removing OAuth client", exc_info=e)
|
||||
raise
|
||||
|
||||
@@ -183,8 +183,8 @@ class GrantedRemoteFileUploadApi(Resource):
|
||||
raise FileTooLargeError(exc.description) from exc
|
||||
except services.errors.file.BlockedFileExtensionError as exc:
|
||||
raise BlockedFileExtensionError(exc.description) from exc
|
||||
except services.errors.file.UnsupportedFileTypeError:
|
||||
raise UnsupportedFileTypeError()
|
||||
except services.errors.file.UnsupportedFileTypeError as caught_error:
|
||||
raise UnsupportedFileTypeError() from caught_error
|
||||
return _remote_granted_file_response(upload_file), 201
|
||||
|
||||
|
||||
@@ -214,7 +214,7 @@ class ProducedFileApi(Resource):
|
||||
mimetype=upload.mimetype,
|
||||
)
|
||||
except services.errors.file.FileTooLargeError as exc:
|
||||
raise FileTooLargeError(exc.description)
|
||||
raise FileTooLargeError(exc.description) from exc
|
||||
except EndUserNotFoundError as exc:
|
||||
raise GrantedFileNotFoundError() from exc
|
||||
|
||||
@@ -354,11 +354,11 @@ def _store_upload(
|
||||
except EndUserNotFoundError as exc:
|
||||
raise GrantedFileNotFoundError() from exc
|
||||
except services.errors.file.FileTooLargeError as exc:
|
||||
raise FileTooLargeError(exc.description)
|
||||
raise FileTooLargeError(exc.description) from exc
|
||||
except services.errors.file.BlockedFileExtensionError as exc:
|
||||
raise BlockedFileExtensionError(exc.description) from exc
|
||||
except services.errors.file.UnsupportedFileTypeError:
|
||||
raise UnsupportedFileTypeError()
|
||||
except services.errors.file.UnsupportedFileTypeError as caught_error:
|
||||
raise UnsupportedFileTypeError() from caught_error
|
||||
|
||||
|
||||
def _grant_context(grant: FileGrantClaims) -> FileGrantContext:
|
||||
|
||||
@@ -227,7 +227,7 @@ class MCPAppApi(Resource):
|
||||
try:
|
||||
return self._convert_user_input_form(raw_user_input_form)
|
||||
except ValidationError as e:
|
||||
raise MCPRequestError(mcp_types.INVALID_PARAMS, f"Invalid user_input_form: {str(e)}")
|
||||
raise MCPRequestError(mcp_types.INVALID_PARAMS, f"Invalid user_input_form: {str(e)}") from e
|
||||
|
||||
def _convert_user_input_form(self, raw_form: list[dict[str, Any]]) -> list[VariableEntity]:
|
||||
"""Convert raw user input form to VariableEntity objects"""
|
||||
|
||||
@@ -99,41 +99,41 @@ def _translate_service_errors() -> Generator[None]:
|
||||
try:
|
||||
yield
|
||||
except WorkflowNotFoundError as ex:
|
||||
raise NotFound(str(ex))
|
||||
raise NotFound(str(ex)) from ex
|
||||
except (IsDraftWorkflowError, WorkflowIdFormatError) as ex:
|
||||
raise BadRequest(str(ex))
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError:
|
||||
raise TriggerWorkflowServiceModeUnavailableError()
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
raise BadRequest(str(ex)) from ex
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
|
||||
raise TriggerWorkflowServiceModeUnavailableError() from caught_error
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
except AppInvokeQuotaExceededError:
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except AppInvokeQuotaExceededError as caught_error:
|
||||
# App concurrency limit. Without this it falls through to the bare `except Exception`
|
||||
# below and surfaces as a 500. Render as the canonical 429 (code "too_many_requests");
|
||||
# the source message is dropped since it carries internal detail (client_id / limits).
|
||||
raise TooManyRequests()
|
||||
raise TooManyRequests() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
except ValueError:
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as caught_error:
|
||||
logger.warning("run input refused by the service.", exc_info=True)
|
||||
raise BadRequest(_INVALID_RUN_INPUT)
|
||||
raise BadRequest(_INVALID_RUN_INPUT) from caught_error
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
_RUN_GUARDS: Final = (
|
||||
|
||||
@@ -94,8 +94,8 @@ def _require_uuid(value: str, *, not_found: type[OpenApiError]) -> str:
|
||||
a UUID-typed database column and fail as a 500."""
|
||||
try:
|
||||
return str(UUID(value))
|
||||
except ValueError:
|
||||
raise not_found()
|
||||
except ValueError as e:
|
||||
raise not_found() from e
|
||||
|
||||
|
||||
def _require_run(ctx: Context, run_id: str) -> WorkflowRun:
|
||||
|
||||
@@ -75,10 +75,10 @@ def load_workspace_role(ctx: Context) -> TenantAccountRole:
|
||||
def _path_param(ctx: Context, name: str) -> str:
|
||||
try:
|
||||
return ctx.view_args[name]
|
||||
except KeyError:
|
||||
except KeyError as caught_error:
|
||||
raise RouteContractError(
|
||||
f"{name} is not a path parameter of this route: the requirement asking for it does not belong here"
|
||||
)
|
||||
) from caught_error
|
||||
|
||||
|
||||
def _fetch_app(ctx: Context) -> App:
|
||||
@@ -86,8 +86,8 @@ def _fetch_app(ctx: Context) -> App:
|
||||
try:
|
||||
# Canonical dashed form, so a bare-hex path parameter names the same app.
|
||||
app_id = str(uuid.UUID(raw))
|
||||
except ValueError:
|
||||
raise NotFound("app not found")
|
||||
except ValueError as caught_error:
|
||||
raise NotFound("app not found") from caught_error
|
||||
app = AppService.get_app_by_id(app_id, ctx.session)
|
||||
if not app or app.status != AppStatus.NORMAL:
|
||||
raise NotFound("app not found")
|
||||
@@ -118,8 +118,8 @@ def _workspace_from_request(ctx: Context) -> Tenant:
|
||||
raise NotFound("workspace not found")
|
||||
try:
|
||||
uuid.UUID(workspace_id)
|
||||
except ValueError:
|
||||
raise NotFound("workspace not found")
|
||||
except ValueError as caught_error:
|
||||
raise NotFound("workspace not found") from caught_error
|
||||
tenant = application_services().workspaces.identity.get_workspace(workspace_id)
|
||||
if tenant is None or tenant.status == TenantStatus.ARCHIVE:
|
||||
raise NotFound("workspace not found")
|
||||
|
||||
@@ -53,11 +53,11 @@ class AuthRouter:
|
||||
|
||||
try:
|
||||
auth = authenticate_resource_token(token) if is_resource_token else get_authenticator().authenticate(token)
|
||||
except InvalidBearerError:
|
||||
except InvalidBearerError as caught_error:
|
||||
# One answer for every rejection reason - unknown prefix, no live row,
|
||||
# expired - so a caller cannot probe which one it hit. Same reasoning as
|
||||
# the 404-not-403 elsewhere on this surface.
|
||||
raise Unauthorized("invalid bearer")
|
||||
raise Unauthorized("invalid bearer") from caught_error
|
||||
subject = subject_from_auth(auth)
|
||||
pipeline = pipeline_for_subject(subject)
|
||||
|
||||
|
||||
@@ -194,8 +194,8 @@ class OpenApiWorkflowHumanInputFormSubmitApi(Resource):
|
||||
submission_user_id=submission_user_id,
|
||||
submission_end_user_id=submission_end_user_id,
|
||||
)
|
||||
except FormNotFoundError:
|
||||
raise HumanInputFormNotFound()
|
||||
except FormNotFoundError as caught_error:
|
||||
raise HumanInputFormNotFound() from caught_error
|
||||
|
||||
if form.workflow_run_id is None:
|
||||
return FormSubmitResponse()
|
||||
|
||||
@@ -173,15 +173,15 @@ class WorkspaceMembersApi(Resource):
|
||||
role=body.role,
|
||||
)
|
||||
except AccountAlreadyInTenantError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except InvalidWorkspaceMemberRoleError as exc:
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except NoPermissionError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
except SeatsLimitExceededError:
|
||||
raise BadRequest("licensed seats limit exceeded")
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except SeatsLimitExceededError as caught_error:
|
||||
raise BadRequest("licensed seats limit exceeded") from caught_error
|
||||
except AccountRegisterError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
|
||||
return _invitation_response(invitation)
|
||||
|
||||
@@ -217,11 +217,11 @@ class WorkspaceMemberApi(Resource):
|
||||
except AccountNotFoundError:
|
||||
raise NotFound("member not found") from None
|
||||
except CannotOperateSelfError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except NoPermissionError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except MemberNotInTenantError as exc:
|
||||
raise NotFound(str(exc))
|
||||
raise NotFound(str(exc)) from exc
|
||||
|
||||
return MemberActionResponse()
|
||||
|
||||
@@ -252,13 +252,13 @@ class WorkspaceMemberApi(Resource):
|
||||
except AccountNotFoundError:
|
||||
raise NotFound("member not found") from None
|
||||
except CannotOperateSelfError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except NoPermissionError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except MemberNotInTenantError as exc:
|
||||
raise NotFound(str(exc))
|
||||
raise NotFound(str(exc)) from exc
|
||||
except RoleAlreadyAssignedError as exc:
|
||||
raise BadRequest(str(exc))
|
||||
raise BadRequest(str(exc)) from exc
|
||||
except InvalidWorkspaceMemberRoleError as exc:
|
||||
raise BadRequest(str(exc)) from exc
|
||||
|
||||
|
||||
@@ -129,32 +129,32 @@ class AudioApi(Resource):
|
||||
)
|
||||
|
||||
return dump_response(AudioTranscriptResponse, response)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except NoAudioUploadedServiceError:
|
||||
raise NoAudioUploadedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except NoAudioUploadedServiceError as caught_error:
|
||||
raise NoAudioUploadedError() from caught_error
|
||||
except AudioTooLargeServiceError as e:
|
||||
raise AudioTooLargeError(str(e))
|
||||
except UnsupportedAudioTypeServiceError:
|
||||
raise UnsupportedAudioTypeError()
|
||||
except ProviderNotSupportSpeechToTextServiceError:
|
||||
raise ProviderNotSupportSpeechToTextError()
|
||||
except SpeechToTextDisabledServiceError:
|
||||
raise SpeechToTextDisabledError()
|
||||
raise AudioTooLargeError(str(e)) from e
|
||||
except UnsupportedAudioTypeServiceError as caught_error:
|
||||
raise UnsupportedAudioTypeError() from caught_error
|
||||
except ProviderNotSupportSpeechToTextServiceError as caught_error:
|
||||
raise ProviderNotSupportSpeechToTextError() from caught_error
|
||||
except SpeechToTextDisabledServiceError as caught_error:
|
||||
raise SpeechToTextDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
register_schema_model(service_api_ns, TextToAudioPayload)
|
||||
@@ -231,19 +231,19 @@ class TextApi(Resource):
|
||||
end_user=end_user.external_user_id,
|
||||
message_ref=message_ref,
|
||||
)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
@@ -262,28 +262,28 @@ class CompletionApi(Resource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except AgentAppNotPublishedError:
|
||||
raise AgentNotPublishedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except AgentAppNotPublishedError as caught_error:
|
||||
raise AgentNotPublishedError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/completion-messages/<string:task_id>/stop")
|
||||
@@ -453,35 +453,35 @@ class ChatApi(Resource):
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except WorkflowNotFoundError as ex:
|
||||
raise NotFound(str(ex))
|
||||
raise NotFound(str(ex)) from ex
|
||||
except IsDraftWorkflowError as ex:
|
||||
raise BadRequest(str(ex))
|
||||
raise BadRequest(str(ex)) from ex
|
||||
except WorkflowIdFormatError as ex:
|
||||
raise BadRequest(str(ex))
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
raise BadRequest(str(ex)) from ex
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except AgentAppNotPublishedError:
|
||||
raise AgentNotPublishedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except AgentAppNotPublishedError as caught_error:
|
||||
raise AgentNotPublishedError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/chat-messages/<string:task_id>/stop")
|
||||
|
||||
@@ -220,8 +220,8 @@ class ConversationApi(Resource):
|
||||
return ConversationInfiniteScrollPagination(
|
||||
limit=pagination.limit, has_more=pagination.has_more, data=conversations
|
||||
).model_dump(mode="json")
|
||||
except services.errors.conversation.LastConversationNotExistsError:
|
||||
raise NotFound("Last Conversation Not Exists.")
|
||||
except services.errors.conversation.LastConversationNotExistsError as caught_error:
|
||||
raise NotFound("Last Conversation Not Exists.") from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/conversations/<uuid:conversation_id>")
|
||||
@@ -259,8 +259,8 @@ class ConversationDetailApi(Resource):
|
||||
|
||||
try:
|
||||
ConversationService.delete(app_model, conversation_id_str, end_user, session=db.session())
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
return "", 204
|
||||
|
||||
|
||||
@@ -312,8 +312,8 @@ class ConversationRenameApi(Resource):
|
||||
app_model, conversation_id_str, end_user, payload.name, payload.auto_generate, session=session
|
||||
)
|
||||
return dump_response(SimpleConversation, ConversationResponseSource(conversation, session=session))
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/conversations/<uuid:conversation_id>/variables")
|
||||
@@ -373,8 +373,8 @@ class ConversationVariablesApi(Resource):
|
||||
session=db.session(),
|
||||
)
|
||||
return dump_response(ConversationVariableInfiniteScrollPaginationResponse, pagination)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/conversations/<uuid:conversation_id>/variables/<uuid:variable_id>")
|
||||
@@ -439,9 +439,9 @@ class ConversationVariableDetailApi(Resource):
|
||||
app_model, conversation_id_str, variable_id_str, end_user, payload.value, session=db.session()
|
||||
)
|
||||
return dump_response(ConversationVariableResponse, variable)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationVariableNotExistsError:
|
||||
raise NotFound("Conversation Variable Not Exists.")
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationVariableNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Variable Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationVariableTypeMismatchError as e:
|
||||
raise BadRequest(str(e))
|
||||
raise BadRequest(str(e)) from e
|
||||
@@ -197,7 +197,7 @@ class WorkflowHumanInputFormApi(Resource):
|
||||
form_data=payload.inputs,
|
||||
submission_end_user_id=end_user.id,
|
||||
)
|
||||
except FormNotFoundError:
|
||||
raise NotFound("Form not found")
|
||||
except FormNotFoundError as caught_error:
|
||||
raise NotFound("Form not found") from caught_error
|
||||
|
||||
return {}, 200
|
||||
@@ -129,10 +129,10 @@ class MessageListApi(Resource):
|
||||
return MessageInfiniteScrollPagination(
|
||||
limit=pagination.limit, has_more=pagination.has_more, data=items
|
||||
).model_dump(mode="json")
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except FirstMessageNotExistsError:
|
||||
raise NotFound("First Message Not Exists.")
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except FirstMessageNotExistsError as caught_error:
|
||||
raise NotFound("First Message Not Exists.") from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/messages/<uuid:message_id>/feedbacks")
|
||||
@@ -179,8 +179,8 @@ class MessageFeedbackApi(Resource):
|
||||
content=payload.content,
|
||||
session=db.session(),
|
||||
)
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message Not Exists.")
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message Not Exists.") from caught_error
|
||||
|
||||
return ResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
@@ -278,12 +278,12 @@ class MessageSuggestedApi(Resource):
|
||||
invoke_from=InvokeFrom.SERVICE_API,
|
||||
session=db.session(),
|
||||
)
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message Not Exists.")
|
||||
except SuggestedQuestionsAfterAnswerDisabledError:
|
||||
raise BadRequest("Suggested Questions Is Disabled.")
|
||||
except Exception:
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message Not Exists.") from caught_error
|
||||
except SuggestedQuestionsAfterAnswerDisabledError as caught_error:
|
||||
raise BadRequest("Suggested Questions Is Disabled.") from caught_error
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
return SimpleResultStringListResponse(result="success", data=questions).model_dump(mode="json")
|
||||
@@ -383,23 +383,23 @@ class WorkflowRunApi(Resource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError:
|
||||
raise TriggerWorkflowServiceModeUnavailableError()
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
|
||||
raise TriggerWorkflowServiceModeUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/workflows/<string:workflow_id>/run")
|
||||
@@ -525,29 +525,29 @@ class WorkflowRunByIdApi(Resource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError:
|
||||
raise TriggerWorkflowServiceModeUnavailableError()
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
|
||||
raise TriggerWorkflowServiceModeUnavailableError() from caught_error
|
||||
except WorkflowNotFoundError as ex:
|
||||
raise NotFound(str(ex))
|
||||
raise NotFound(str(ex)) from ex
|
||||
except IsDraftWorkflowError as ex:
|
||||
raise BadRequest(str(ex))
|
||||
raise BadRequest(str(ex)) from ex
|
||||
except WorkflowIdFormatError as ex:
|
||||
raise BadRequest(str(ex))
|
||||
raise BadRequest(str(ex)) from ex
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/workflows/tasks/<string:task_id>/stop")
|
||||
|
||||
@@ -556,8 +556,8 @@ class DatasetListApi(DatasetApiResource):
|
||||
retrieval_model=payload.retrieval_model,
|
||||
summary_index_setting=payload.summary_index_setting,
|
||||
)
|
||||
except services.errors.dataset.DatasetNameDuplicateError:
|
||||
raise DatasetNameDuplicateError()
|
||||
except services.errors.dataset.DatasetNameDuplicateError as caught_error:
|
||||
raise DatasetNameDuplicateError() from caught_error
|
||||
|
||||
if dify_config.RBAC_ENABLED:
|
||||
enterprise_rbac_service.RBACService.DatasetAccess.replace_whitelist(
|
||||
@@ -612,7 +612,7 @@ class DatasetApi(DatasetApiResource):
|
||||
try:
|
||||
DatasetService.check_dataset_permission(dataset, current_user, session)
|
||||
except services.errors.base.NoPermissionError as e:
|
||||
raise Forbidden(str(e))
|
||||
raise Forbidden(str(e)) from e
|
||||
data = _dump_service_dataset_detail(load_dataset_detail(dataset, session=session))
|
||||
# check embedding setting
|
||||
assert isinstance(current_user, Account)
|
||||
@@ -792,8 +792,8 @@ class DatasetApi(DatasetApiResource):
|
||||
return "", 204
|
||||
else:
|
||||
raise NotFound("Dataset not found.")
|
||||
except services.errors.dataset.DatasetInUseError:
|
||||
raise DatasetInUseError()
|
||||
except services.errors.dataset.DatasetInUseError as caught_error:
|
||||
raise DatasetInUseError() from caught_error
|
||||
|
||||
|
||||
@service_api_ns.route("/datasets/<uuid:dataset_id>/documents/status/<string:action>")
|
||||
@@ -870,7 +870,7 @@ class DocumentStatusApi(DatasetApiResource):
|
||||
try:
|
||||
DatasetService.check_dataset_permission(dataset, current_user, session)
|
||||
except services.errors.base.NoPermissionError as e:
|
||||
raise Forbidden(str(e))
|
||||
raise Forbidden(str(e)) from e
|
||||
|
||||
# Check dataset model setting
|
||||
DatasetService.check_dataset_model_setting(dataset)
|
||||
@@ -882,9 +882,9 @@ class DocumentStatusApi(DatasetApiResource):
|
||||
try:
|
||||
DocumentService.batch_update_document_status(dataset, document_ids, action, current_user, session)
|
||||
except services.errors.document.DocumentIndexingError as e:
|
||||
raise InvalidActionError(str(e))
|
||||
raise InvalidActionError(str(e)) from e
|
||||
except ValueError as e:
|
||||
raise InvalidActionError(str(e))
|
||||
raise InvalidActionError(str(e)) from e
|
||||
|
||||
return SimpleResultResponse(result="success").model_dump(mode="json"), 200
|
||||
|
||||
|
||||
@@ -463,7 +463,7 @@ def _create_document_by_text(session: Session, tenant_id: str, dataset_id: UUID)
|
||||
session=session,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
document = documents[0]
|
||||
|
||||
return document, batch
|
||||
@@ -527,7 +527,7 @@ def _update_document_by_text(
|
||||
session=session,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
document = documents[0]
|
||||
|
||||
return document, batch
|
||||
@@ -830,7 +830,7 @@ class DocumentAddByFileApi(DatasetApiResource):
|
||||
default_file_size_limit=FeatureService.get_knowledge_file_size_limit(tenant_id),
|
||||
)
|
||||
except services.errors.file.FileTooLargeError as file_too_large_error:
|
||||
raise FileTooLargeError(file_too_large_error.description)
|
||||
raise FileTooLargeError(file_too_large_error.description) from file_too_large_error
|
||||
data_source = {
|
||||
"type": "upload_file",
|
||||
"info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
|
||||
@@ -856,7 +856,7 @@ class DocumentAddByFileApi(DatasetApiResource):
|
||||
session=session,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
document = documents[0]
|
||||
return _document_and_batch_response(document, batch, session=session), 200
|
||||
|
||||
@@ -910,9 +910,9 @@ def _update_document_by_file(
|
||||
default_file_size_limit=FeatureService.get_knowledge_file_size_limit(tenant_id),
|
||||
)
|
||||
except services.errors.file.FileTooLargeError as file_too_large_error:
|
||||
raise FileTooLargeError(file_too_large_error.description)
|
||||
except services.errors.file.UnsupportedFileTypeError:
|
||||
raise UnsupportedFileTypeError()
|
||||
raise FileTooLargeError(file_too_large_error.description) from file_too_large_error
|
||||
except services.errors.file.UnsupportedFileTypeError as caught_error:
|
||||
raise UnsupportedFileTypeError() from caught_error
|
||||
data_source = {
|
||||
"type": "upload_file",
|
||||
"info_list": {"data_source_type": "upload_file", "file_info_list": {"file_ids": [upload_file.id]}},
|
||||
@@ -937,7 +937,7 @@ def _update_document_by_file(
|
||||
session=session,
|
||||
)
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
document = documents[0]
|
||||
return document, document.batch
|
||||
|
||||
|
||||
@@ -330,7 +330,7 @@ class PipelineRunApi(DatasetApiResource):
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except Exception as ex:
|
||||
raise PipelineRunError(description=str(ex))
|
||||
raise PipelineRunError(description=str(ex)) from ex
|
||||
|
||||
|
||||
@service_api_ns.route("/datasets/pipeline/file-upload")
|
||||
@@ -403,8 +403,8 @@ class KnowledgebasePipelineFileUploadApi(DatasetApiResource):
|
||||
default_file_size_limit=FeatureService.get_knowledge_file_size_limit(tenant_id),
|
||||
)
|
||||
except services.errors.file.FileTooLargeError as file_too_large_error:
|
||||
raise FileTooLargeError(file_too_large_error.description)
|
||||
except services.errors.file.UnsupportedFileTypeError:
|
||||
raise UnsupportedFileTypeError()
|
||||
raise FileTooLargeError(file_too_large_error.description) from file_too_large_error
|
||||
except services.errors.file.UnsupportedFileTypeError as caught_error:
|
||||
raise UnsupportedFileTypeError() from caught_error
|
||||
|
||||
return dump_response(PipelineUploadFileResponse, upload_file), 201
|
||||
@@ -219,12 +219,12 @@ class SegmentApi(DatasetApiResource):
|
||||
model_type=ModelType.TEXT_EMBEDDING,
|
||||
model=dataset.embedding_model,
|
||||
)
|
||||
except LLMBadRequestError:
|
||||
except LLMBadRequestError as caught_error:
|
||||
raise ProviderNotInitializeError(
|
||||
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
||||
)
|
||||
) from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
# validate args
|
||||
try:
|
||||
payload = SegmentCreatePayload.model_validate(service_api_ns.payload or {})
|
||||
@@ -319,12 +319,12 @@ class SegmentApi(DatasetApiResource):
|
||||
model_type=ModelType.TEXT_EMBEDDING,
|
||||
model=dataset.embedding_model,
|
||||
)
|
||||
except LLMBadRequestError:
|
||||
except LLMBadRequestError as caught_error:
|
||||
raise ProviderNotInitializeError(
|
||||
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
||||
)
|
||||
) from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
|
||||
segments, total = SegmentService.get_segments(
|
||||
session=session,
|
||||
@@ -461,12 +461,12 @@ class DatasetSegmentApi(DatasetApiResource):
|
||||
model_type=ModelType.TEXT_EMBEDDING,
|
||||
model=dataset.embedding_model,
|
||||
)
|
||||
except LLMBadRequestError:
|
||||
except LLMBadRequestError as caught_error:
|
||||
raise ProviderNotInitializeError(
|
||||
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
||||
)
|
||||
) from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
segment_id_str = str(segment_id)
|
||||
_, segment = _get_segment_for_document(session, dataset, document, segment_id_str)
|
||||
|
||||
@@ -620,12 +620,12 @@ class ChildChunkApi(DatasetApiResource):
|
||||
model_type=ModelType.TEXT_EMBEDDING,
|
||||
model=dataset.embedding_model,
|
||||
)
|
||||
except LLMBadRequestError:
|
||||
except LLMBadRequestError as caught_error:
|
||||
raise ProviderNotInitializeError(
|
||||
"No Embedding Model available. Please configure a valid provider in the Settings -> Model Provider."
|
||||
)
|
||||
) from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
|
||||
try:
|
||||
child_chunk = SegmentService.create_child_chunk(
|
||||
@@ -638,7 +638,7 @@ class ChildChunkApi(DatasetApiResource):
|
||||
mutations=application_services().knowledge.segments.mutations,
|
||||
)
|
||||
except ChildChunkIndexingServiceError as e:
|
||||
raise ChildChunkIndexingError(str(e))
|
||||
raise ChildChunkIndexingError(str(e)) from e
|
||||
|
||||
return dump_response(ChildChunkDetailResponse, {"data": child_chunk}), 200
|
||||
|
||||
@@ -780,7 +780,7 @@ class DatasetChildChunkApi(DatasetApiResource):
|
||||
child_chunk, dataset, session, mutations=application_services().knowledge.segments.mutations
|
||||
)
|
||||
except ChildChunkDeleteIndexServiceError as e:
|
||||
raise ChildChunkDeleteIndexError(str(e))
|
||||
raise ChildChunkDeleteIndexError(str(e)) from e
|
||||
|
||||
return "", 204
|
||||
|
||||
@@ -861,6 +861,6 @@ class DatasetChildChunkApi(DatasetApiResource):
|
||||
mutations=application_services().knowledge.segments.mutations,
|
||||
)
|
||||
except ChildChunkIndexingServiceError as e:
|
||||
raise ChildChunkIndexingError(str(e))
|
||||
raise ChildChunkIndexingError(str(e)) from e
|
||||
|
||||
return dump_response(ChildChunkDetailResponse, {"data": child_chunk}), 200
|
||||
@@ -90,7 +90,7 @@ def handle_webhook(webhook_id: str):
|
||||
}
|
||||
), 429
|
||||
except ValueError as error:
|
||||
raise NotFound(str(error))
|
||||
raise NotFound(str(error)) from error
|
||||
except RequestEntityTooLarge:
|
||||
raise
|
||||
except Exception as e:
|
||||
@@ -161,7 +161,7 @@ def handle_webhook_debug(webhook_id: str):
|
||||
return jsonify(response_data), status_code
|
||||
|
||||
except ValueError as e:
|
||||
raise NotFound(str(e))
|
||||
raise NotFound(str(e)) from e
|
||||
except RequestEntityTooLarge:
|
||||
raise
|
||||
except Exception:
|
||||
|
||||
@@ -101,32 +101,32 @@ class AudioApi(WebApiResource):
|
||||
)
|
||||
|
||||
return dump_response(AudioToTextResponse, response)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except NoAudioUploadedServiceError:
|
||||
raise NoAudioUploadedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except NoAudioUploadedServiceError as caught_error:
|
||||
raise NoAudioUploadedError() from caught_error
|
||||
except AudioTooLargeServiceError as e:
|
||||
raise AudioTooLargeError(str(e))
|
||||
except UnsupportedAudioTypeServiceError:
|
||||
raise UnsupportedAudioTypeError()
|
||||
except ProviderNotSupportSpeechToTextServiceError:
|
||||
raise ProviderNotSupportSpeechToTextError()
|
||||
except SpeechToTextDisabledServiceError:
|
||||
raise SpeechToTextDisabledError()
|
||||
raise AudioTooLargeError(str(e)) from e
|
||||
except UnsupportedAudioTypeServiceError as caught_error:
|
||||
raise UnsupportedAudioTypeError() from caught_error
|
||||
except ProviderNotSupportSpeechToTextServiceError as caught_error:
|
||||
raise ProviderNotSupportSpeechToTextError() from caught_error
|
||||
except SpeechToTextDisabledServiceError as caught_error:
|
||||
raise SpeechToTextDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("Failed to handle post request to AudioApi")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
@web_ns.route("/text-to-audio")
|
||||
@@ -175,19 +175,19 @@ class TextApi(WebApiResource):
|
||||
end_user=end_user.external_user_id,
|
||||
message_ref=message_ref,
|
||||
)
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("Failed to handle post request to TextApi")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
@@ -142,28 +142,28 @@ class CompletionApi(WebApiResource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except AgentAppNotPublishedError:
|
||||
raise AgentNotPublishedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except AgentAppNotPublishedError as caught_error:
|
||||
raise AgentNotPublishedError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
@web_ns.route("/completion-messages/<string:task_id>/stop")
|
||||
@@ -254,30 +254,30 @@ class ChatApi(WebApiResource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except services.errors.conversation.ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except services.errors.conversation.ConversationCompletedError:
|
||||
raise ConversationCompletedError()
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError:
|
||||
except services.errors.conversation.ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except services.errors.conversation.ConversationCompletedError as caught_error:
|
||||
raise ConversationCompletedError() from caught_error
|
||||
except services.errors.app_model_config.AppModelConfigBrokenError as caught_error:
|
||||
logger.exception("App model config broken.")
|
||||
raise AppUnavailableError()
|
||||
except AgentAppNotPublishedError:
|
||||
raise AgentNotPublishedError()
|
||||
raise AppUnavailableError() from caught_error
|
||||
except AgentAppNotPublishedError as caught_error:
|
||||
raise AgentNotPublishedError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as e:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from e
|
||||
|
||||
|
||||
@web_ns.route("/chat-messages/<string:task_id>/stop")
|
||||
|
||||
@@ -95,8 +95,8 @@ class ConversationListApi(WebApiResource):
|
||||
has_more=pagination.has_more,
|
||||
data=conversations,
|
||||
).model_dump(mode="json")
|
||||
except LastConversationNotExistsError:
|
||||
raise NotFound("Last Conversation Not Exists.")
|
||||
except LastConversationNotExistsError as caught_error:
|
||||
raise NotFound("Last Conversation Not Exists.") from caught_error
|
||||
|
||||
|
||||
@web_ns.route("/conversations/<uuid:c_id>")
|
||||
@@ -122,8 +122,8 @@ class ConversationApi(WebApiResource):
|
||||
conversation_id = str(c_id)
|
||||
try:
|
||||
ConversationService.delete(app_model, conversation_id, end_user, session=db.session())
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
return "", 204
|
||||
|
||||
|
||||
@@ -173,8 +173,8 @@ class ConversationRenameApi(WebApiResource):
|
||||
.validate_python(ConversationResponseSource(conversation, session=session), from_attributes=True)
|
||||
.model_dump(mode="json")
|
||||
)
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
|
||||
@web_ns.route("/conversations/<uuid:c_id>/pin")
|
||||
@@ -202,8 +202,8 @@ class ConversationPinApi(WebApiResource):
|
||||
|
||||
try:
|
||||
WebConversationService.pin(app_model, conversation_id, end_user, db.session())
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
|
||||
return ResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
|
||||
@@ -139,8 +139,8 @@ class HumanInputFormUploadTokenApi(Resource):
|
||||
|
||||
try:
|
||||
token = application_services().human_input_file_uploads.issue_upload_token(form_token)
|
||||
except FormNotFoundError:
|
||||
raise NotFoundError("Form not found")
|
||||
except FormNotFoundError as caught_error:
|
||||
raise NotFoundError("Form not found") from caught_error
|
||||
|
||||
return HumanInputUploadTokenResponse(
|
||||
upload_token=token.upload_token, expires_at=to_timestamp(token.expires_at)
|
||||
@@ -271,8 +271,8 @@ class HumanInputFormApi(Resource):
|
||||
form_data=payload.inputs,
|
||||
submission_end_user_id=None,
|
||||
)
|
||||
except FormNotFoundError:
|
||||
raise NotFoundError("Form not found")
|
||||
except FormNotFoundError as caught_error:
|
||||
raise NotFoundError("Form not found") from caught_error
|
||||
|
||||
return HumanInputFormSubmitResponse().model_dump(mode="json"), 200
|
||||
|
||||
|
||||
@@ -99,10 +99,10 @@ class MessageListApi(WebApiResource):
|
||||
has_more=pagination.has_more,
|
||||
data=items,
|
||||
).model_dump(mode="json")
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation Not Exists.")
|
||||
except FirstMessageNotExistsError:
|
||||
raise NotFound("First Message Not Exists.")
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation Not Exists.") from caught_error
|
||||
except FirstMessageNotExistsError as caught_error:
|
||||
raise NotFound("First Message Not Exists.") from caught_error
|
||||
|
||||
|
||||
@web_ns.route("/messages/<uuid:message_id>/feedbacks")
|
||||
@@ -145,8 +145,8 @@ class MessageFeedbackApi(WebApiResource):
|
||||
content=payload.content,
|
||||
session=db.session(),
|
||||
)
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message Not Exists.")
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message Not Exists.") from caught_error
|
||||
|
||||
return ResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
@@ -204,23 +204,23 @@ class MessageMoreLikeThisApi(WebApiResource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message Not Exists.")
|
||||
except MoreLikeThisDisabledError:
|
||||
raise AppMoreLikeThisDisabledError()
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message Not Exists.") from caught_error
|
||||
except MoreLikeThisDisabledError as caught_error:
|
||||
raise AppMoreLikeThisDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@web_ns.route("/messages/<uuid:message_id>/suggested-questions")
|
||||
@@ -263,22 +263,22 @@ class MessageSuggestedQuestionApi(WebApiResource):
|
||||
session=db.session(),
|
||||
)
|
||||
# questions is a list of strings, not a list of Message objects
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message not found")
|
||||
except ConversationNotExistsError:
|
||||
raise NotFound("Conversation not found")
|
||||
except SuggestedQuestionsAfterAnswerDisabledError:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError()
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message not found") from caught_error
|
||||
except ConversationNotExistsError as caught_error:
|
||||
raise NotFound("Conversation not found") from caught_error
|
||||
except SuggestedQuestionsAfterAnswerDisabledError as caught_error:
|
||||
raise AppSuggestedQuestionsAfterAnswerDisabledError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
except Exception:
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
return SuggestedQuestionsResponse(data=questions).model_dump(mode="json")
|
||||
@@ -80,8 +80,8 @@ class SavedMessageListApi(WebApiResource):
|
||||
actor=SavedMessageActor.end_user(end_user.id),
|
||||
message_id=payload.message_id,
|
||||
)
|
||||
except MessageNotExistsError:
|
||||
raise NotFound("Message Not Exists.")
|
||||
except MessageNotExistsError as caught_error:
|
||||
raise NotFound("Message Not Exists.") from caught_error
|
||||
|
||||
return ResultResponse(result="success").model_dump(mode="json")
|
||||
|
||||
|
||||
@@ -92,23 +92,23 @@ class WorkflowRunApi(WebApiResource):
|
||||
|
||||
# response-contract:ignore compact_generate_response
|
||||
return helper.compact_generate_response(response)
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError:
|
||||
raise TriggerWorkflowServiceModeUnavailableError()
|
||||
except TriggerWorkflowServiceModeUnavailableServiceError as caught_error:
|
||||
raise TriggerWorkflowServiceModeUnavailableError() from caught_error
|
||||
except ProviderTokenNotInitError as ex:
|
||||
raise ProviderNotInitializeError(ex.description)
|
||||
except QuotaExceededError:
|
||||
raise ProviderQuotaExceededError()
|
||||
except ModelCurrentlyNotSupportError:
|
||||
raise ProviderModelCurrentlyNotSupportError()
|
||||
raise ProviderNotInitializeError(ex.description) from ex
|
||||
except QuotaExceededError as caught_error:
|
||||
raise ProviderQuotaExceededError() from caught_error
|
||||
except ModelCurrentlyNotSupportError as caught_error:
|
||||
raise ProviderModelCurrentlyNotSupportError() from caught_error
|
||||
except InvokeError as e:
|
||||
raise CompletionRequestError(e.description)
|
||||
raise CompletionRequestError(e.description) from e
|
||||
except InvokeRateLimitError as ex:
|
||||
raise InvokeRateLimitHttpError(ex.description)
|
||||
raise InvokeRateLimitHttpError(ex.description) from ex
|
||||
except ValueError as e:
|
||||
raise e
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("internal server error.")
|
||||
raise InternalServerError()
|
||||
raise InternalServerError() from caught_error
|
||||
|
||||
|
||||
@web_ns.route("/workflows/tasks/<string:task_id>/stop")
|
||||
|
||||
@@ -104,16 +104,16 @@ def decode_jwt_token(app_code: str | None = None, user_id: str | None = None) ->
|
||||
except Unauthorized as e:
|
||||
if webapp_auth_enabled:
|
||||
if not app_code:
|
||||
raise Unauthorized("Please re-login to access the web app.")
|
||||
raise Unauthorized("Please re-login to access the web app.") from e
|
||||
app_id = resolve_web_app_id(app_code)
|
||||
app_web_auth_enabled = (
|
||||
EnterpriseService.WebAppAuth.get_app_access_mode_by_id(app_id=app_id).access_mode
|
||||
!= WebAppAccessMode.PUBLIC
|
||||
)
|
||||
if app_web_auth_enabled:
|
||||
raise WebAppAuthRequiredError()
|
||||
raise WebAppAuthRequiredError() from e
|
||||
|
||||
raise Unauthorized(e.description)
|
||||
raise Unauthorized(e.description) from e
|
||||
|
||||
|
||||
def _validate_webapp_token(decoded, app_web_auth_enabled: bool, system_webapp_auth_enabled: bool):
|
||||
|
||||
@@ -268,8 +268,8 @@ class DatasetConfigManager:
|
||||
|
||||
try:
|
||||
uuid.UUID(tool_item["id"])
|
||||
except ValueError:
|
||||
raise ValueError("id in dataset must be of UUID type")
|
||||
except ValueError as caught_error:
|
||||
raise ValueError("id in dataset must be of UUID type") from caught_error
|
||||
|
||||
if not cls.is_dataset_exists(tenant_id, tool_item["id"], session):
|
||||
raise ValueError("Dataset ID does not exist, please check your permission.")
|
||||
|
||||
@@ -28,7 +28,7 @@ class MoreLikeThisConfigManager:
|
||||
def validate_and_set_defaults(cls, config: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:
|
||||
try:
|
||||
return AppConfigModel.model_validate(config).model_dump(), ["more_like_this"]
|
||||
except ValidationError:
|
||||
except ValidationError as caught_error:
|
||||
raise ValueError(
|
||||
"more_like_this must be of dict type and enabled in more_like_this must be of boolean type"
|
||||
)
|
||||
) from caught_error
|
||||
@@ -789,7 +789,7 @@ class AdvancedChatAppGenerator(MessageBasedAppGenerator):
|
||||
return generate_task_pipeline.process()
|
||||
except ValueError as e:
|
||||
if len(e.args) > 0 and e.args[0] == "I/O operation on closed file.": # ignore this error
|
||||
raise GenerateTaskStoppedError()
|
||||
raise GenerateTaskStoppedError() from e
|
||||
else:
|
||||
logger.exception("Failed to process generate task pipeline, conversation_id: %s", conversation.id)
|
||||
raise e
|
||||
@@ -223,8 +223,8 @@ class AgentChatAppConfigManager(BaseAppConfigManager):
|
||||
|
||||
try:
|
||||
uuid.UUID(tool_item["id"])
|
||||
except ValueError:
|
||||
raise ValueError("id in dataset must be of UUID type")
|
||||
except ValueError as caught_error:
|
||||
raise ValueError("id in dataset must be of UUID type") from caught_error
|
||||
|
||||
if not DatasetConfigManager.is_dataset_exists(tenant_id, tool_item["id"], session):
|
||||
raise ValueError("Dataset ID does not exist, please check your permission.")
|
||||
|
||||
@@ -250,8 +250,10 @@ class BaseAppGenerator:
|
||||
return float(value)
|
||||
else:
|
||||
return int(value)
|
||||
except ValueError:
|
||||
raise ValueError(f"{variable_entity.variable} in input form must be a valid number")
|
||||
except ValueError as caught_error:
|
||||
raise ValueError(
|
||||
f"{variable_entity.variable} in input form must be a valid number"
|
||||
) from caught_error
|
||||
case _:
|
||||
raise TypeError(f"expected value type int, float or str, got {type(value)}, value: {value}")
|
||||
|
||||
|
||||
@@ -80,7 +80,7 @@ class MessageBasedAppGenerator(BaseAppGenerator):
|
||||
return generate_task_pipeline.process()
|
||||
except ValueError as e:
|
||||
if len(e.args) > 0 and e.args[0] == "I/O operation on closed file.": # ignore this error
|
||||
raise GenerateTaskStoppedError()
|
||||
raise GenerateTaskStoppedError() from e
|
||||
else:
|
||||
logger.exception("Failed to handle response, conversation_id: %s", conversation.id)
|
||||
raise e
|
||||
|
||||
@@ -692,7 +692,7 @@ class PipelineGenerator(BaseAppGenerator):
|
||||
return generate_task_pipeline.process()
|
||||
except ValueError as e:
|
||||
if len(e.args) > 0 and e.args[0] == "I/O operation on closed file.": # ignore this error
|
||||
raise GenerateTaskStoppedError()
|
||||
raise GenerateTaskStoppedError() from e
|
||||
else:
|
||||
logger.exception(
|
||||
"Fails to process generate task pipeline, task_id: %r",
|
||||
|
||||
@@ -735,7 +735,7 @@ class WorkflowAppGenerator(BaseAppGenerator):
|
||||
return generate_task_pipeline.process()
|
||||
except ValueError as e:
|
||||
if len(e.args) > 0 and e.args[0] == "I/O operation on closed file.": # ignore this error
|
||||
raise GenerateTaskStoppedError()
|
||||
raise GenerateTaskStoppedError() from e
|
||||
else:
|
||||
logger.exception(
|
||||
"Fails to process generate task pipeline, task_id: %s", application_generate_entity.task_id
|
||||
|
||||
@@ -102,8 +102,8 @@ class DatasourceFileManager:
|
||||
response = remote_fetcher.make_request("GET", file_url)
|
||||
response.raise_for_status()
|
||||
blob = response.content
|
||||
except httpx.TimeoutException:
|
||||
raise ValueError(f"timeout when downloading file from {file_url}")
|
||||
except httpx.TimeoutException as caught_error:
|
||||
raise ValueError(f"timeout when downloading file from {file_url}") from caught_error
|
||||
|
||||
mimetype = (
|
||||
guess_type(file_url)[0]
|
||||
|
||||
@@ -84,7 +84,7 @@ class ApiExternalDataTool(ExternalDataTool):
|
||||
# request api
|
||||
requestor = APIBasedExtensionRequestor(api_endpoint=api_based_extension.api_endpoint, api_key=api_key)
|
||||
except Exception as e:
|
||||
raise ValueError(f"[External data tool] API query failed, variable: {self.variable}, error: {e}")
|
||||
raise ValueError(f"[External data tool] API query failed, variable: {self.variable}, error: {e}") from e
|
||||
|
||||
response_json = requestor.request(
|
||||
point=APIBasedExtensionPoint.APP_EXTERNAL_DATA_TOOL_QUERY,
|
||||
|
||||
@@ -119,7 +119,7 @@ class CodeExecutor:
|
||||
"Failed to execute code, which is likely a network issue,"
|
||||
" please check if the sandbox service is running."
|
||||
f" ( Error: {str(e)} )"
|
||||
)
|
||||
) from e
|
||||
|
||||
try:
|
||||
response_data = response.json()
|
||||
|
||||
@@ -54,12 +54,12 @@ class TemplateTransformer(ABC):
|
||||
result_str = cls.extract_result_str_from_response(response)
|
||||
result = json.loads(result_str)
|
||||
except json.JSONDecodeError as e:
|
||||
raise ValueError(f"Failed to parse JSON response: {str(e)}.")
|
||||
raise ValueError(f"Failed to parse JSON response: {str(e)}.") from e
|
||||
except ValueError as e:
|
||||
# Re-raise ValueError from extract_result_str_from_response
|
||||
raise e
|
||||
except Exception as e:
|
||||
raise ValueError(f"Unexpected error during response transformation: {str(e)}")
|
||||
raise ValueError(f"Unexpected error during response transformation: {str(e)}") from e
|
||||
|
||||
if not isinstance(result, dict):
|
||||
raise ValueError(f"Result must be a dict, got {type(result).__name__}")
|
||||
|
||||
@@ -66,8 +66,8 @@ def check_moderation(tenant_id: str, model_config: ModelConfigWithCredentialsEnt
|
||||
|
||||
if moderation_result is True:
|
||||
return True
|
||||
except Exception:
|
||||
except Exception as caught_error:
|
||||
logger.exception("Fails to check moderation, provider_name: %s", provider_name)
|
||||
raise InvokeBadRequestError("Rate limit exceeded, please try again later.")
|
||||
raise InvokeBadRequestError("Rate limit exceeded, please try again later.") from caught_error
|
||||
|
||||
return False
|
||||
@@ -27,4 +27,6 @@ class RuleConfigGeneratorOutputParser:
|
||||
raise ValueError("Expected 'opening_statement' to be a str.")
|
||||
return parsed
|
||||
except Exception as e:
|
||||
raise OutputParserError(f"Parsing text\n{text}\n of rule config generator raised following error:\n{e}")
|
||||
raise OutputParserError(
|
||||
f"Parsing text\n{text}\n of rule config generator raised following error:\n{e}"
|
||||
) from e
|
||||
@@ -291,7 +291,7 @@ def _parse_structured_output(result_text: str) -> Mapping[str, Any]:
|
||||
if not isinstance(parsed, dict):
|
||||
raise OutputParserError(f"Failed to parse structured output: {result_text}")
|
||||
structured_output = parsed
|
||||
except ValidationError:
|
||||
except ValidationError as caught_error:
|
||||
# if the result_text is not a valid json, try to repair it
|
||||
temp_parsed = json_repair.loads(result_text)
|
||||
if isinstance(temp_parsed, list) and result_text.lstrip().lower().startswith("<think"):
|
||||
@@ -320,7 +320,7 @@ def _parse_structured_output(result_text: str) -> Mapping[str, Any]:
|
||||
# handle reasoning model like deepseek-r1 got '<think>\n\n</think>\n' prefix
|
||||
temp_parsed = next((item for item in temp_parsed if isinstance(item, dict)), {})
|
||||
case _:
|
||||
raise OutputParserError(f"Failed to parse structured output: {result_text}")
|
||||
raise OutputParserError(f"Failed to parse structured output: {result_text}") from caught_error
|
||||
structured_output = cast(dict, temp_parsed)
|
||||
return structured_output
|
||||
|
||||
|
||||
@@ -235,7 +235,7 @@ def _retrieve_redis_state(state_key: str) -> OAuthCallbackState:
|
||||
|
||||
return oauth_state
|
||||
except ValidationError as e:
|
||||
raise ValueError(f"Invalid state parameter: {str(e)}")
|
||||
raise ValueError(f"Invalid state parameter: {str(e)}") from e
|
||||
|
||||
|
||||
def handle_callback(state_key: str, authorization_code: str) -> tuple[OAuthCallbackState, OAuthTokens]:
|
||||
@@ -611,7 +611,7 @@ def auth(
|
||||
try:
|
||||
full_information = register_client(server_url, server_metadata, client_metadata)
|
||||
except RequestError as e:
|
||||
raise ValueError(f"Could not register OAuth client: {e}")
|
||||
raise ValueError(f"Could not register OAuth client: {e}") from e
|
||||
|
||||
# Return action to save client information
|
||||
actions.append(
|
||||
@@ -654,7 +654,7 @@ def auth(
|
||||
# RequestError: HTTP request failed
|
||||
# ValueError: Invalid response data
|
||||
# KeyError: Missing required fields in response
|
||||
raise ValueError(f"Client credentials flow failed: {e}")
|
||||
raise ValueError(f"Client credentials flow failed: {e}") from e
|
||||
|
||||
# Exchange authorization code for tokens (Authorization Code flow)
|
||||
if authorization_code is not None:
|
||||
@@ -672,7 +672,7 @@ def auth(
|
||||
raise ValueError("Missing code_verifier or redirect_uri in state data")
|
||||
|
||||
except (json.JSONDecodeError, ValueError) as e:
|
||||
raise ValueError(f"Invalid state parameter: {e}")
|
||||
raise ValueError(f"Invalid state parameter: {e}") from e
|
||||
|
||||
tokens = exchange_authorization(
|
||||
server_url,
|
||||
@@ -719,7 +719,7 @@ def auth(
|
||||
# RequestError: HTTP request failed
|
||||
# ValueError: Invalid response data
|
||||
# KeyError: Missing required fields in response
|
||||
raise ValueError(f"Could not refresh OAuth tokens: {e}")
|
||||
raise ValueError(f"Could not refresh OAuth tokens: {e}") from e
|
||||
|
||||
# Start new authorization flow (only for authorization code flow)
|
||||
authorization_url, code_verifier = start_authorization(
|
||||
|
||||
@@ -208,8 +208,8 @@ class SSETransport:
|
||||
"""
|
||||
try:
|
||||
status = status_queue.get(timeout=1)
|
||||
except queue.Empty:
|
||||
raise ValueError("failed to get endpoint URL")
|
||||
except queue.Empty as caught_error:
|
||||
raise ValueError("failed to get endpoint URL") from caught_error
|
||||
|
||||
match status:
|
||||
case _StatusReady():
|
||||
@@ -295,8 +295,8 @@ def sse_client(
|
||||
|
||||
except httpx.HTTPStatusError as exc:
|
||||
if exc.response.status_code == 401:
|
||||
raise MCPAuthError(response=exc.response)
|
||||
raise MCPConnectionError()
|
||||
raise MCPAuthError(response=exc.response) from exc
|
||||
raise MCPConnectionError() from exc
|
||||
except httpx.RequestError as exc:
|
||||
# Transport-level failures (refused connection, DNS, protocol errors, timeouts)
|
||||
# must keep the MCP error contract: MCPClient only falls back to streamable
|
||||
|
||||
@@ -152,7 +152,7 @@ class MCPClient:
|
||||
self._exit_stack.close()
|
||||
except Exception as e:
|
||||
logger.exception("Error during cleanup")
|
||||
raise ValueError(f"Error during cleanup: {e}")
|
||||
raise ValueError(f"Error during cleanup: {e}") from e
|
||||
finally:
|
||||
self._session = None
|
||||
self._initialized = False
|
||||
@@ -147,9 +147,9 @@ class BasePluginClient:
|
||||
|
||||
try:
|
||||
response = _httpx_client.request(**request_kwargs)
|
||||
except httpx.RequestError:
|
||||
except httpx.RequestError as caught_error:
|
||||
logger.exception("Request to Plugin Daemon Service failed")
|
||||
raise PluginDaemonInnerError(code=-500, message="Request to Plugin Daemon Service failed")
|
||||
raise PluginDaemonInnerError(code=-500, message="Request to Plugin Daemon Service failed") from caught_error
|
||||
|
||||
return response
|
||||
|
||||
@@ -254,9 +254,9 @@ class BasePluginClient:
|
||||
line = line[5:].strip()
|
||||
if line:
|
||||
yield line
|
||||
except httpx.RequestError:
|
||||
except httpx.RequestError as caught_error:
|
||||
logger.exception("Stream request to Plugin Daemon Service failed")
|
||||
raise PluginDaemonInnerError(code=-500, message="Request to Plugin Daemon Service failed")
|
||||
raise PluginDaemonInnerError(code=-500, message="Request to Plugin Daemon Service failed") from caught_error
|
||||
|
||||
def _stream_request_with_model[T: BaseModel | dict[str, Any] | list[Any] | bool | str](
|
||||
self,
|
||||
@@ -310,9 +310,9 @@ class BasePluginClient:
|
||||
except httpx.HTTPStatusError as e:
|
||||
logger.exception("Failed to request plugin daemon, status: %s, url: %s", e.response.status_code, path)
|
||||
if e.response.status_code < 500:
|
||||
raise PluginDaemonClientSideError(description=str(e))
|
||||
raise PluginDaemonClientSideError(description=str(e)) from e
|
||||
else:
|
||||
raise PluginDaemonInternalServerError(description=str(e))
|
||||
raise PluginDaemonInternalServerError(description=str(e)) from e
|
||||
except Exception as e:
|
||||
msg = f"Failed to request plugin daemon, url: {path}"
|
||||
logger.exception("Failed to request plugin daemon, url: %s", path)
|
||||
@@ -362,16 +362,16 @@ class BasePluginClient:
|
||||
for line in self._stream_request(method, path, params, headers, data, files):
|
||||
try:
|
||||
rep = PluginDaemonBasicResponse[type_].model_validate_json(line) # type: ignore
|
||||
except (ValueError, TypeError):
|
||||
except (ValueError, TypeError) as caught_error:
|
||||
# TODO modify this when line_data has code and message
|
||||
try:
|
||||
line_data = json.loads(line)
|
||||
except (ValueError, TypeError):
|
||||
raise ValueError(line)
|
||||
except (ValueError, TypeError) as caught_error_inner:
|
||||
raise ValueError(line) from caught_error_inner
|
||||
# If the dictionary contains the `error` key, use its value as the argument
|
||||
# for `ValueError`.
|
||||
# Otherwise, use the `line` to provide better contextual information about the error.
|
||||
raise ValueError(line_data.get("error", line))
|
||||
raise ValueError(line_data.get("error", line)) from caught_error
|
||||
|
||||
if rep.code != 0:
|
||||
if rep.code == -500:
|
||||
|
||||
@@ -215,7 +215,7 @@ class PluginModelClient(BasePluginClient):
|
||||
try:
|
||||
yield from response
|
||||
except PluginDaemonInnerError as e:
|
||||
raise ValueError(e.message + str(e.code))
|
||||
raise ValueError(e.message + str(e.code)) from e
|
||||
|
||||
def start_llm_polling(
|
||||
self,
|
||||
@@ -615,7 +615,7 @@ class PluginModelClient(BasePluginClient):
|
||||
hex_str = result.result
|
||||
yield TTSAudioChunk(binascii.unhexlify(hex_str), mime_type=result.mime_type)
|
||||
except PluginDaemonInnerError as e:
|
||||
raise ValueError(e.message + str(e.code))
|
||||
raise ValueError(e.message + str(e.code)) from e
|
||||
|
||||
def get_tts_model_voices(
|
||||
self,
|
||||
|
||||
@@ -40,7 +40,7 @@ class OAuthHandler(BasePluginClient):
|
||||
return resp
|
||||
raise ValueError("No response received from plugin daemon for authorization URL request.")
|
||||
except Exception as e:
|
||||
raise ValueError(f"Error getting authorization URL: {e}")
|
||||
raise ValueError(f"Error getting authorization URL: {e}") from e
|
||||
|
||||
def get_credentials(
|
||||
self,
|
||||
@@ -82,7 +82,7 @@ class OAuthHandler(BasePluginClient):
|
||||
return resp
|
||||
raise ValueError("No response received from plugin daemon for authorization URL request.")
|
||||
except Exception as e:
|
||||
raise ValueError(f"Error getting credentials: {e}")
|
||||
raise ValueError(f"Error getting credentials: {e}") from e
|
||||
|
||||
def refresh_credentials(
|
||||
self,
|
||||
@@ -117,7 +117,7 @@ class OAuthHandler(BasePluginClient):
|
||||
return resp
|
||||
raise ValueError("No response received from plugin daemon for refresh credentials request.")
|
||||
except Exception as e:
|
||||
raise ValueError(f"Error refreshing credentials: {e}")
|
||||
raise ValueError(f"Error refreshing credentials: {e}") from e
|
||||
|
||||
def _convert_request_to_raw_data(self, request: Request) -> bytes:
|
||||
"""
|
||||
|
||||
@@ -111,7 +111,7 @@ class FirecrawlApp:
|
||||
storage.delete(file_key)
|
||||
storage.save(file_key, json.dumps(url_data_list).encode("utf-8"))
|
||||
except Exception as e:
|
||||
raise Exception(f"Error saving crawl data: {e}")
|
||||
raise Exception(f"Error saving crawl data: {e}") from e
|
||||
return self._format_crawl_status_response("completed", crawl_status_response, url_data_list)
|
||||
else:
|
||||
return self._format_crawl_status_response(
|
||||
|
||||
@@ -44,8 +44,8 @@ def detect_file_encodings(file_path: str, timeout: int = 5, sample_size: int = 1
|
||||
future = executor.submit(read_and_detect, file_path)
|
||||
try:
|
||||
encodings = future.result(timeout=timeout)
|
||||
except concurrent.futures.TimeoutError:
|
||||
raise TimeoutError(f"Timeout reached while detecting encoding for {file_path}")
|
||||
except concurrent.futures.TimeoutError as caught_error:
|
||||
raise TimeoutError(f"Timeout reached while detecting encoding for {file_path}") from caught_error
|
||||
|
||||
if all(encoding.encoding is None for encoding in encodings):
|
||||
raise RuntimeError(f"Could not detect encoding for {file_path}")
|
||||
|
||||
@@ -42,7 +42,9 @@ class TextExtractor(BaseExtractor):
|
||||
f"Decode failed: {self._file_path}, all detected encodings failed. Original error: {e}"
|
||||
)
|
||||
else:
|
||||
raise RuntimeError(f"Decode failed: {self._file_path}, specified encoding failed. Original error: {e}")
|
||||
raise RuntimeError(
|
||||
f"Decode failed: {self._file_path}, specified encoding failed. Original error: {e}"
|
||||
) from e
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"Error loading {self._file_path}") from e
|
||||
|
||||
|
||||
@@ -139,7 +139,7 @@ class QAIndexProcessor(BaseIndexProcessor):
|
||||
raise ValueError("The CSV file is empty.")
|
||||
|
||||
except Exception as e:
|
||||
raise ValueError(str(e))
|
||||
raise ValueError(str(e)) from e
|
||||
return text_docs
|
||||
|
||||
@override
|
||||
|
||||
@@ -142,10 +142,10 @@ class TextSplitter(BaseDocumentTransformer, ABC):
|
||||
def _huggingface_tokenizer_length(text: str) -> int:
|
||||
return len(tokenizer.encode(text))
|
||||
|
||||
except ImportError:
|
||||
except ImportError as caught_error:
|
||||
raise ValueError(
|
||||
"Could not import transformers python package. Please install it with `pip install transformers`."
|
||||
)
|
||||
) from caught_error
|
||||
return cls(length_function=lambda x: [_huggingface_tokenizer_length(text) for text in x], **kwargs)
|
||||
|
||||
@override
|
||||
@@ -198,12 +198,12 @@ class TokenTextSplitter(TextSplitter):
|
||||
super().__init__(**kwargs)
|
||||
try:
|
||||
import tiktoken
|
||||
except ImportError:
|
||||
except ImportError as caught_error:
|
||||
raise ImportError(
|
||||
"Could not import tiktoken python package. "
|
||||
"This is needed in order to for TokenTextSplitter. "
|
||||
"Please install it with `pip install tiktoken`."
|
||||
)
|
||||
) from caught_error
|
||||
|
||||
if model_name is not None:
|
||||
enc = tiktoken.encoding_for_model(model_name)
|
||||
|
||||
@@ -33,7 +33,7 @@ class BuiltinToolProviderController(ToolProviderController[ToolProviderEntity, B
|
||||
try:
|
||||
provider_yaml = load_yaml_file_cached(yaml_path)
|
||||
except Exception as e:
|
||||
raise ToolProviderNotFoundError(f"can not load provider yaml for {provider}: {e}")
|
||||
raise ToolProviderNotFoundError(f"can not load provider yaml for {provider}: {e}") from e
|
||||
|
||||
if "credentials_for_provider" in provider_yaml and provider_yaml["credentials_for_provider"] is not None:
|
||||
# set credentials name
|
||||
|
||||
@@ -34,4 +34,4 @@ class SimpleCode(BuiltinTool):
|
||||
result = CodeExecutor.execute_code(language, "", code)
|
||||
yield self.create_text_message(result)
|
||||
except Exception as e:
|
||||
raise ToolInvokeError(str(e))
|
||||
raise ToolInvokeError(str(e)) from e
|
||||
@@ -59,4 +59,4 @@ class LocaltimeToTimestampTool(BuiltinTool):
|
||||
timestamp = int(converted_localtime.timestamp())
|
||||
return timestamp
|
||||
except Exception as e:
|
||||
raise ToolInvokeError(str(e))
|
||||
raise ToolInvokeError(str(e)) from e
|
||||
@@ -49,4 +49,4 @@ class TimestampToLocaltimeTool(BuiltinTool):
|
||||
local_time = datetime.fromtimestamp(timestamp, local_tz)
|
||||
return local_time
|
||||
except Exception as e:
|
||||
raise ToolInvokeError(str(e))
|
||||
raise ToolInvokeError(str(e)) from e
|
||||
@@ -53,4 +53,4 @@ class TimezoneConversionTool(BuiltinTool):
|
||||
converted_datetime = datetime_with_tz.astimezone(output_timezone)
|
||||
return converted_datetime.strftime(time_format)
|
||||
except Exception as e:
|
||||
raise ToolInvokeError(str(e))
|
||||
raise ToolInvokeError(str(e)) from e
|
||||
@@ -40,4 +40,4 @@ class WebscraperTool(BuiltinTool):
|
||||
# return full webpage
|
||||
yield self.create_text_message(result)
|
||||
except Exception as e:
|
||||
raise ToolInvokeError(str(e))
|
||||
raise ToolInvokeError(str(e)) from e
|
||||
@@ -231,7 +231,7 @@ class ToolEngine:
|
||||
yield from tool.invoke(session, user_id, tool_parameters, conversation_id, app_id, message_id)
|
||||
except Exception as e:
|
||||
meta.error = str(e)
|
||||
raise ToolEngineInvokeError(meta)
|
||||
raise ToolEngineInvokeError(meta) from e
|
||||
finally:
|
||||
ended_at = datetime.now(UTC)
|
||||
meta.time_cost = (ended_at - started_at).total_seconds()
|
||||
|
||||
@@ -116,8 +116,8 @@ class ToolFileManager:
|
||||
response = remote_fetcher.make_request("GET", file_url)
|
||||
response.raise_for_status()
|
||||
blob = response.content
|
||||
except httpx.TimeoutException:
|
||||
raise ValueError(f"timeout when downloading file from {file_url}")
|
||||
except httpx.TimeoutException as caught_error:
|
||||
raise ValueError(f"timeout when downloading file from {file_url}") from caught_error
|
||||
|
||||
mimetype = (
|
||||
guess_type(file_url)[0]
|
||||
|
||||
@@ -891,8 +891,8 @@ class ToolManager:
|
||||
provider = mcp_service.get_provider_by_persisted_reference(
|
||||
id_or_server_identifier=provider_id, tenant_id=tenant_id
|
||||
)
|
||||
except ValueError:
|
||||
raise ToolProviderNotFoundError(f"mcp provider {provider_id} not found")
|
||||
except ValueError as caught_error:
|
||||
raise ToolProviderNotFoundError(f"mcp provider {provider_id} not found") from caught_error
|
||||
|
||||
controller = MCPToolProviderController.from_db(provider)
|
||||
|
||||
@@ -1044,8 +1044,8 @@ class ToolManager:
|
||||
id_or_server_identifier=provider_id, tenant_id=tenant_id
|
||||
)
|
||||
return cast(EmojiIconDict | str, mcp_provider.provider_icon)
|
||||
except ValueError:
|
||||
raise ToolProviderNotFoundError(f"mcp provider {provider_id} not found")
|
||||
except ValueError as caught_error:
|
||||
raise ToolProviderNotFoundError(f"mcp provider {provider_id} not found") from caught_error
|
||||
except Exception:
|
||||
return {"background": "#252525", "content": "\ud83d\ude01"}
|
||||
|
||||
|
||||
@@ -149,17 +149,17 @@ class ModelInvocationUtils:
|
||||
callbacks=[],
|
||||
)
|
||||
except InvokeRateLimitError as e:
|
||||
raise InvokeModelError(f"Invoke rate limit error: {e}")
|
||||
raise InvokeModelError(f"Invoke rate limit error: {e}") from e
|
||||
except InvokeBadRequestError as e:
|
||||
raise InvokeModelError(f"Invoke bad request error: {e}")
|
||||
raise InvokeModelError(f"Invoke bad request error: {e}") from e
|
||||
except InvokeConnectionError as e:
|
||||
raise InvokeModelError(f"Invoke connection error: {e}")
|
||||
except InvokeAuthorizationError:
|
||||
raise InvokeModelError("Invoke authorization error")
|
||||
raise InvokeModelError(f"Invoke connection error: {e}") from e
|
||||
except InvokeAuthorizationError as e:
|
||||
raise InvokeModelError("Invoke authorization error") from e
|
||||
except InvokeServerUnavailableError as e:
|
||||
raise InvokeModelError(f"Invoke server unavailable error: {e}")
|
||||
raise InvokeModelError(f"Invoke server unavailable error: {e}") from e
|
||||
except Exception as e:
|
||||
raise InvokeModelError(f"Invoke error: {e}")
|
||||
raise InvokeModelError(f"Invoke error: {e}") from e
|
||||
|
||||
# update tool model invoke
|
||||
tool_model_invoke.model_response = str(response.message.content)
|
||||
|
||||
@@ -369,8 +369,8 @@ class ApiBasedToolSchemaParser:
|
||||
api = openai_plugin["api"]
|
||||
api_url = api["url"]
|
||||
api_type = api["type"]
|
||||
except JSONDecodeError:
|
||||
raise ToolProviderNotFoundError("Invalid openai plugin json.")
|
||||
except JSONDecodeError as caught_error:
|
||||
raise ToolProviderNotFoundError("Invalid openai plugin json.") from caught_error
|
||||
|
||||
if api_type != "openapi":
|
||||
raise ToolNotSupportedError("Only openapi is supported now.")
|
||||
|
||||
@@ -311,7 +311,7 @@ class WorkflowEntry:
|
||||
node.node_type,
|
||||
node.version(),
|
||||
)
|
||||
raise WorkflowNodeRunFailedError(node=node, err_msg=str(e))
|
||||
raise WorkflowNodeRunFailedError(node=node, err_msg=str(e)) from e
|
||||
return node, generator
|
||||
|
||||
@staticmethod
|
||||
@@ -452,7 +452,7 @@ class WorkflowEntry:
|
||||
node.node_type,
|
||||
node.version(),
|
||||
)
|
||||
raise WorkflowNodeRunFailedError(node=node, err_msg=str(e))
|
||||
raise WorkflowNodeRunFailedError(node=node, err_msg=str(e)) from e
|
||||
|
||||
@staticmethod
|
||||
def handle_special_values(value: Mapping[str, Any] | None) -> Mapping[str, Any] | None:
|
||||
|
||||
@@ -72,7 +72,7 @@ class AwsS3Storage(BaseStorage):
|
||||
data: bytes = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].read()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found")
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
return data
|
||||
@@ -84,9 +84,9 @@ class AwsS3Storage(BaseStorage):
|
||||
yield from response["Body"].iter_chunks()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("file not found")
|
||||
raise FileNotFoundError("file not found") from ex
|
||||
elif "reached max retries" in str(ex):
|
||||
raise ValueError("please do not request the same file too frequently")
|
||||
raise ValueError("please do not request the same file too frequently") from ex
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
@@ -33,7 +33,7 @@ class OracleOCIStorage(BaseStorage):
|
||||
data: bytes = self.client.get_object(Bucket=self.bucket_name, Key=filename)["Body"].read()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found")
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
return data
|
||||
@@ -45,7 +45,7 @@ class OracleOCIStorage(BaseStorage):
|
||||
yield from response["Body"].iter_chunks()
|
||||
except ClientError as ex:
|
||||
if ex.response.get("Error", {}).get("Code") == "NoSuchKey":
|
||||
raise FileNotFoundError("File not found")
|
||||
raise FileNotFoundError("File not found") from ex
|
||||
else:
|
||||
raise
|
||||
|
||||
|
||||
@@ -88,11 +88,11 @@ class ArchiveStorage:
|
||||
except ClientError as e:
|
||||
error_code = e.response.get("Error", {}).get("Code")
|
||||
if error_code == "404":
|
||||
raise ArchiveStorageNotConfiguredError(f"Archive bucket '{self.bucket}' does not exist")
|
||||
raise ArchiveStorageNotConfiguredError(f"Archive bucket '{self.bucket}' does not exist") from e
|
||||
elif error_code == "403":
|
||||
raise ArchiveStorageNotConfiguredError(f"Access denied to archive bucket '{self.bucket}'")
|
||||
raise ArchiveStorageNotConfiguredError(f"Access denied to archive bucket '{self.bucket}'") from e
|
||||
else:
|
||||
raise ArchiveStorageError(f"Failed to access archive bucket: {e}")
|
||||
raise ArchiveStorageError(f"Failed to access archive bucket: {e}") from e
|
||||
|
||||
def put_object(self, key: str, data: bytes) -> str:
|
||||
"""
|
||||
@@ -125,7 +125,7 @@ class ArchiveStorage:
|
||||
logger.debug("Uploaded object: %s (size=%d, checksum=%s)", key, len(data), checksum)
|
||||
return checksum
|
||||
except ClientError as e:
|
||||
raise ArchiveStorageError(f"Failed to upload object '{key}': {e}")
|
||||
raise ArchiveStorageError(f"Failed to upload object '{key}': {e}") from e
|
||||
|
||||
def get_object(self, key: str) -> bytes:
|
||||
"""
|
||||
@@ -254,7 +254,7 @@ class ArchiveStorage:
|
||||
ExpiresIn=expires_in,
|
||||
)
|
||||
except ClientError as e:
|
||||
raise ArchiveStorageError(f"Failed to generate pre-signed URL for '{key}': {e}")
|
||||
raise ArchiveStorageError(f"Failed to generate pre-signed URL for '{key}': {e}") from e
|
||||
|
||||
def list_objects(self, prefix: str) -> list[str]:
|
||||
"""
|
||||
@@ -274,7 +274,7 @@ class ArchiveStorage:
|
||||
for obj in page.get("Contents", []):
|
||||
keys.append(obj["Key"])
|
||||
except ClientError as e:
|
||||
raise ArchiveStorageError(f"Failed to list objects with prefix '{prefix}': {e}")
|
||||
raise ArchiveStorageError(f"Failed to list objects with prefix '{prefix}': {e}") from e
|
||||
|
||||
return keys
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def parse_time_range(
|
||||
try:
|
||||
dt = datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M").replace(second=0)
|
||||
except ValueError as e:
|
||||
raise ValueError(f"Invalid {label} time format: {e}")
|
||||
raise ValueError(f"Invalid {label} time format: {e}") from e
|
||||
|
||||
try:
|
||||
return tz.localize(dt, is_dst=None).astimezone(utc)
|
||||
|
||||
+6
-6
@@ -250,9 +250,9 @@ def uuid_value(value: str | UUID) -> str:
|
||||
try:
|
||||
uuid_obj = uuid.UUID(value)
|
||||
return str(uuid_obj)
|
||||
except ValueError:
|
||||
except ValueError as caught_error:
|
||||
error = f"{value} is not a valid uuid."
|
||||
raise ValueError(error)
|
||||
raise ValueError(error) from caught_error
|
||||
|
||||
|
||||
def normalize_uuid(value: str | UUID) -> str:
|
||||
@@ -314,9 +314,9 @@ def timestamp_value(timestamp):
|
||||
if int_timestamp < 0:
|
||||
raise ValueError
|
||||
return int_timestamp
|
||||
except ValueError:
|
||||
except ValueError as caught_error:
|
||||
error = f"{timestamp} is not a valid timestamp."
|
||||
raise ValueError(error)
|
||||
raise ValueError(error) from caught_error
|
||||
|
||||
|
||||
class StrLen:
|
||||
@@ -343,9 +343,9 @@ class DatetimeString:
|
||||
def __call__(self, value):
|
||||
try:
|
||||
datetime.strptime(value, self.format)
|
||||
except ValueError:
|
||||
except ValueError as caught_error:
|
||||
error = f"Invalid {self.argument}: {value}. {self.argument} must be conform to the format {self.format}"
|
||||
raise ValueError(error)
|
||||
raise ValueError(error) from caught_error
|
||||
|
||||
return value
|
||||
|
||||
|
||||
@@ -49,7 +49,7 @@ def parse_and_check_json_markdown(text: str, expected_keys: list[str]):
|
||||
try:
|
||||
json_obj = parse_json_markdown(text)
|
||||
except json.JSONDecodeError as e:
|
||||
raise OutputParserError(f"got invalid json object. error: {e}")
|
||||
raise OutputParserError(f"got invalid json object. error: {e}") from e
|
||||
|
||||
if isinstance(json_obj, list):
|
||||
if len(json_obj) == 1 and isinstance(json_obj[0], dict):
|
||||
|
||||
@@ -14,11 +14,11 @@ class PassportService:
|
||||
def verify(self, token):
|
||||
try:
|
||||
return jwt.decode(token, self.sk, algorithms=["HS256"])
|
||||
except jwt.ExpiredSignatureError:
|
||||
raise Unauthorized("Token has expired.")
|
||||
except jwt.InvalidSignatureError:
|
||||
raise Unauthorized("Invalid token signature.")
|
||||
except jwt.DecodeError:
|
||||
raise Unauthorized("Invalid token.")
|
||||
except jwt.PyJWTError: # Catch-all for other JWT errors
|
||||
raise Unauthorized("Invalid token.")
|
||||
except jwt.ExpiredSignatureError as caught_error:
|
||||
raise Unauthorized("Token has expired.") from caught_error
|
||||
except jwt.InvalidSignatureError as caught_error:
|
||||
raise Unauthorized("Invalid token signature.") from caught_error
|
||||
except jwt.DecodeError as caught_error:
|
||||
raise Unauthorized("Invalid token.") from caught_error
|
||||
except jwt.PyJWTError as caught_error: # Catch-all for other JWT errors
|
||||
raise Unauthorized("Invalid token.") from caught_error
|
||||
+2
-2
@@ -70,8 +70,8 @@ def get_decrypt_decoding(tenant_id: str) -> tuple[RSA.RsaKey, object]:
|
||||
if not private_key:
|
||||
try:
|
||||
private_key = storage.load(filepath)
|
||||
except FileNotFoundError:
|
||||
raise PrivkeyNotFoundError(f"Private key not found, tenant_id: {tenant_id}")
|
||||
except FileNotFoundError as caught_error:
|
||||
raise PrivkeyNotFoundError(f"Private key not found, tenant_id: {tenant_id}") from caught_error
|
||||
|
||||
redis_client.setex(cache_key, 120, private_key)
|
||||
|
||||
|
||||
@@ -97,7 +97,7 @@ def convert_12h_to_24h(time_str: str) -> tuple[int, int]:
|
||||
hour = int(time_parts[0])
|
||||
minute = int(time_parts[1])
|
||||
except ValueError as e:
|
||||
raise ValueError(f"Invalid time values: {e}")
|
||||
raise ValueError(f"Invalid time values: {e}") from e
|
||||
|
||||
if hour < 1 or hour > 12:
|
||||
raise ValueError(f"Invalid hour: {hour}. Must be between 1 and 12")
|
||||
|
||||
@@ -121,7 +121,7 @@ def open_zip_with_replacement_names(content: bytes) -> zipfile.ZipFile:
|
||||
if flags & _UTF8_FLAG:
|
||||
try:
|
||||
raw_name.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
except UnicodeDecodeError as caught_error:
|
||||
extra_start = name_start + name_size
|
||||
local_offset = (
|
||||
_local_header_offset(
|
||||
@@ -133,7 +133,7 @@ def open_zip_with_replacement_names(content: bytes) -> zipfile.ZipFile:
|
||||
+ directory.prefix_size
|
||||
)
|
||||
if local_offset < 0 or local_offset + _LOCAL_HEADER.size > directory.start:
|
||||
raise zipfile.BadZipFile("Invalid ZIP local header offset")
|
||||
raise zipfile.BadZipFile("Invalid ZIP local header offset") from caught_error
|
||||
local = _LOCAL_HEADER.unpack_from(content, local_offset)
|
||||
local_name_start = local_offset + _LOCAL_HEADER.size
|
||||
if (
|
||||
@@ -142,7 +142,7 @@ def open_zip_with_replacement_names(content: bytes) -> zipfile.ZipFile:
|
||||
or content[local_name_start : local_name_start + local[9]] != raw_name
|
||||
or not local[2] & _UTF8_FLAG
|
||||
):
|
||||
raise zipfile.BadZipFile("ZIP local and directory names differ")
|
||||
raise zipfile.BadZipFile("ZIP local and directory names differ") from caught_error
|
||||
struct.pack_into("<H", patched, cursor + 8, flags & ~_UTF8_FLAG)
|
||||
struct.pack_into("<H", patched, local_offset + 6, local[2] & ~_UTF8_FLAG)
|
||||
recovered[index] = raw_name.decode("utf-8", errors="replace")
|
||||
|
||||
@@ -355,8 +355,8 @@ class Workflow(Base): # bug
|
||||
|
||||
try:
|
||||
node_config: dict[str, Any] = next(filter(lambda node: node["id"] == node_id, nodes))
|
||||
except StopIteration:
|
||||
raise NodeNotFoundError(node_id)
|
||||
except StopIteration as caught_error:
|
||||
raise NodeNotFoundError(node_id) from caught_error
|
||||
return NodeConfigDictAdapter.validate_python(adapt_node_config_for_graph(node_config))
|
||||
|
||||
@staticmethod
|
||||
|
||||
@@ -121,7 +121,7 @@ class AliyunDataTrace(BaseTraceInstance):
|
||||
return self.trace_client.get_project_url()
|
||||
except Exception as e:
|
||||
logger.info("Aliyun get project url failed: %s", str(e), exc_info=True)
|
||||
raise ValueError(f"Aliyun get project url failed: {str(e)}")
|
||||
raise ValueError(f"Aliyun get project url failed: {str(e)}") from e
|
||||
|
||||
def _extract_app_id(self, trace_info: BaseTraceInfo) -> str:
|
||||
"""Extract app_id from trace_info, trying metadata first then message_data."""
|
||||
|
||||
Loaded 100 of 138 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user