Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

UN-2603 [FEAT] Changes to support pushing from API to HITL (#1421)

Deepak K9e809aa1dcdc
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.py
index e13b211b4..dc307396e 100644
--- a/backend/api_v2/api_deployment_views.py
+++ b/backend/api_v2/api_deployment_views.py
@@ -65,6 +65,7 @@ class DeploymentExecution(views.APIView):
use_file_history = serializer.validated_data.get(ApiExecution.USE_FILE_HISTORY)
tag_names = serializer.validated_data.get(ApiExecution.TAGS)
llm_profile_id = serializer.validated_data.get(ApiExecution.LLM_PROFILE_ID)
+ hitl_queue_name = serializer.validated_data.get(ApiExecution.HITL_QUEUE_NAME)
response = DeploymentHelper.execute_workflow(
organization_name=org_name,
@@ -76,8 +77,10 @@ class DeploymentExecution(views.APIView):
use_file_history=use_file_history,
tag_names=tag_names,
llm_profile_id=llm_profile_id,
+ hitl_queue_name=hitl_queue_name,
)
if "error" in response and response["error"]:
+ logger.error("API deployment execution failed")
return Response(
{"message": response},
status=status.HTTP_422_UNPROCESSABLE_ENTITY,
diff --git a/backend/api_v2/constants.py b/backend/api_v2/constants.py
index 6e2017816..11e4ce41a 100644
--- a/backend/api_v2/constants.py
+++ b/backend/api_v2/constants.py
@@ -9,3 +9,4 @@ class ApiExecution:
EXECUTION_ID: str = "execution_id"
TAGS: str = "tags"
LLM_PROFILE_ID: str = "llm_profile_id"
+ HITL_QUEUE_NAME: str = "hitl_queue_name"
diff --git a/backend/api_v2/deployment_helper.py b/backend/api_v2/deployment_helper.py
index 6af12cef0..764e22e00 100644
--- a/backend/api_v2/deployment_helper.py
+++ b/backend/api_v2/deployment_helper.py
@@ -149,6 +149,7 @@ class DeploymentHelper(BaseAPIKeyValidator):
use_file_history: bool = False,
tag_names: list[str] = [],
llm_profile_id: str | None = None,
+ hitl_queue_name: str | None = None,
) -> ReturnDict:
"""Execute workflow by api.
@@ -160,12 +161,17 @@ class DeploymentHelper(BaseAPIKeyValidator):
processed files. Defaults to False
tag_names (list(str)): list of tag names
llm_profile_id (str, optional): LLM profile ID for overriding tool settings
+ hitl_queue_name (str, optional): Custom queue name for manual review
Returns:
ReturnDict: execution status/ result
"""
workflow_id = api.workflow.id
pipeline_id = api.id
+ if hitl_queue_name:
+ logger.info(
+ f"API execution with HITL: hitl_queue_name={hitl_queue_name}, api_name={api.api_name}"
+ )
tags = Tag.bulk_get_or_create(tag_names=tag_names)
workflow_execution = WorkflowExecutionServiceHelper.create_workflow_execution(
workflow_id=workflow_id,
@@ -193,6 +199,7 @@ class DeploymentHelper(BaseAPIKeyValidator):
queue=CeleryQueue.CELERY_API_DEPLOYMENTS,
use_file_history=use_file_history,
llm_profile_id=llm_profile_id,
+ hitl_queue_name=hitl_queue_name,
)
result.status_api = DeploymentHelper.construct_status_endpoint(
api_endpoint=api.api_endpoint, execution_id=execution_id
diff --git a/backend/api_v2/models.py b/backend/api_v2/models.py
index 6c3455f50..0aeba5558 100644
--- a/backend/api_v2/models.py
+++ b/backend/api_v2/models.py
@@ -87,16 +87,20 @@ class APIDeployment(DefaultOrganizationMixin, BaseModel):
return f"{self.id} - {self.display_name}"
def save(self, *args: Any, **kwargs: Any) -> None:
- """Save hook to update api_endpoint.
+ """Save hook to update api_endpoint and enforce constraints.
Custom save hook for updating the 'api_endpoint' based on
- 'api_name'. If the instance is being updated, it checks for
- changes in 'api_name' and adjusts 'api_endpoint'
- accordingly. If the instance is new, 'api_endpoint' is set
- based on 'api_name' and the current database schema.
+ 'api_name'. If the instance is being updated, it checks for
+ changes in 'api_name' and adjusts 'api_endpoint'
+ accordingly. If the instance is new, 'api_endpoint' is set
+ based on 'api_name' and the current database schema.
+
+ Also enforces one API deployment per workflow constraint for new deployments.
"""
+ organization_id = UserContext.get_organization_identifier()
+
+ # Update api_endpoint logic
if self.pk is not None:
- organization_id = UserContext.get_organization_identifier()
try:
original = APIDeployment.objects.get(pk=self.pk)
if original.api_name != self.api_name:
@@ -107,6 +111,10 @@ class APIDeployment(DefaultOrganizationMixin, BaseModel):
self.api_endpoint = (
f"{ApiExecution.PATH}/{organization_id}/{self.api_name}/"
)
+ else:
+ # New instance - set api_endpoint
+ self.api_endpoint = f"{ApiExecution.PATH}/{organization_id}/{self.api_name}/"
+
super().save(*args, **kwargs)
class Meta:
diff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.py
index e01c29258..763fb3e65 100644
--- a/backend/api_v2/serializers.py
+++ b/backend/api_v2/serializers.py
@@ -1,3 +1,4 @@
+import re
import uuid
from collections import OrderedDict
from typing import Any
@@ -56,6 +57,27 @@ class APIDeploymentSerializer(IntegrityErrorMixin, AuditSerializer):
api_name_validator(value)
return value
+ def validate(self, data):
+ """Validate that only one API deployment per workflow is allowed for new deployments."""
+ workflow = data.get("workflow")
+
+ # Only apply this validation for new deployments (not updates)
+ if workflow and not self.instance:
+ # Check if this workflow already has an active API deployment
+ existing_active_count = APIDeployment.objects.filter(
+ workflow=workflow, is_active=True
+ ).count()
+
+ # If there's already an active API deployment, prevent creating a new one
+ if existing_active_count > 0:
+ raise ValidationError(
+ {
+ "workflow": "This workflow already has an active API deployment. Only one API deployment per workflow is allowed."
+ }
+ )
+
+ return data
+
class APIKeySerializer(AuditSerializer):
class Meta:
@@ -117,6 +139,8 @@ class ExecutionRequestSerializer(TagParamsSerializer):
e.g:'tag1,tag2-name,tag3_name'
llm_profile_id (str): UUID of the LLM profile to override the default profile.
If not provided, the default profile will be used.
+ hitl_queue_name (str, optional): Document class name for manual review queue.
+ If not provided, uses API name as document class.
"""
MAX_FILES_ALLOWED = 32
@@ -128,6 +152,39 @@ class ExecutionRequestSerializer(TagParamsSerializer):
include_metrics = BooleanField(default=False)
use_file_history = BooleanField(default=False)
llm_profile_id = CharField(required=False, allow_null=True, allow_blank=True)
+ hitl_queue_name = CharField(required=False, allow_null=True, allow_blank=True)
+
+ def validate_hitl_queue_name(self, value: str | None) -> str | None:
+ """Validate queue name format: a-z0-9-_ with length and pattern restrictions."""
+ if not value:
+ return value
+
+ # Length validation
+ if len(value) < 3:
+ raise ValidationError("Queue name must be at least 3 characters long.")
+ if len(value) > 50:
+ raise ValidationError("Queue name cannot exceed 50 characters.")
+
+ # Check valid characters: a-z, 0-9, _, -
+ if not re.match(r"^[a-z0-9_-]+$", value):
+ raise ValidationError(
+ "Queue name can only contain lowercase letters, numbers, underscores, and hyphens."
+ )
+
+ # Check no starting/ending with _ or -
+ if value.startswith(("_", "-")) or value.endswith(("_", "-")):
+ raise ValidationError(
+ "Queue name cannot start or end with underscore or hyphen."
+ )
+
+ # Check no consecutive special characters
+ if re.search(r"[_-]{2,}", value):
+ raise ValidationError(
+ "Queue name cannot have repeating underscores or hyphens."
+ )
+
+ return value
+
files = ListField(
child=FileField(),
required=True,
diff --git a/backend/workflow_manager/endpoint_v2/destination.py b/backend/workflow_manager/endpoint_v2/destination.py
index 039dd1829..4b1233ec8 100644
--- a/backend/workflow_manager/endpoint_v2/destination.py
+++ b/backend/workflow_manager/endpoint_v2/destination.py
@@ -13,7 +13,6 @@ from workflow_manager.endpoint_v2.base_connector import BaseConnector
from workflow_manager.endpoint_v2.constants import (
ApiDeploymentResultStatus,
DestinationKey,
- QueueResultStatus,
)
from workflow_manager.endpoint_v2.database_utils import DatabaseUtils
from workflow_manager.endpoint_v2.dto import DestinationConfig, FileHash
@@ -25,7 +24,11 @@ from workflow_manager.endpoint_v2.exceptions import (
ToolOutputTypeMismatch,
)
from workflow_manager.endpoint_v2.models import WorkflowEndpoint
-from workflow_manager.endpoint_v2.queue_utils import QueueResult, QueueUtils
+from workflow_manager.endpoint_v2.queue_utils import (
+ QueueResult,
+ QueueResultStatus,
+ QueueUtils,
+)
from workflow_manager.utils.workflow_log import WorkflowLog
from workflow_manager.workflow_v2.models.file_history import FileHistory
from workflow_manager.workflow_v2.models.workflow import Workflow
@@ -59,6 +62,7 @@ class DestinationConnector(BaseConnector):
workflow_log: WorkflowLog,
use_file_history: bool,
file_execution_id: str | None = None,
+ hitl_queue_name: str | None = None,
) -> None:
"""Initialize a DestinationConnector object.
@@ -76,6 +80,7 @@ class DestinationConnector(BaseConnector):
)
self.workflow_log = workflow_log
self.use_file_history = use_file_history
+ self.hitl_queue_name = hitl_queue_name
self.workflow = workflow
def _get_endpoint_for_workflow(
@@ -153,7 +158,7 @@ class DestinationConnector(BaseConnector):
logger.error(f"Database connection failed: {str(e)}")
raise
- def _handle_hitl(
+ def _should_handle_hitl(
self,
file_name: str,
file_hash: FileHash,
@@ -161,7 +166,20 @@ class DestinationConnector(BaseConnector):
input_file_path: str,
file_execution_id: str,
) -> bool:
- """Handles HITL processing, returning True if data was pushed to the queue."""
+ """Determines if HITL processing should be performed, returning True if data was pushed to the queue."""
+ # Check if API deployment requested HITL override
+ if self.hitl_queue_name:
+ logger.info(f"API HITL override: pushing to queue for file {file_name}")
+ self._push_data_to_queue(
+ file_name=file_name,
+ workflow=workflow,
+ input_file_path=input_file_path,
+ file_execution_id=file_execution_id,
+ )
+ logger.info(f"Successfully pushed {file_name} to HITL queue")
+ return True
+
+ # Otherwise use existing workflow-based HITL logic
execution_result = self.get_tool_execution_result()
if WorkflowUtil.validate_db_rule(
execution_result, workflow, file_hash.file_destination
@@ -209,7 +227,7 @@ class DestinationConnector(BaseConnector):
if connection_type == WorkflowEndpoint.ConnectionType.FILESYSTEM:
self.copy_output_to_output_directory()
elif connection_type == WorkflowEndpoint.ConnectionType.DATABASE:
- if not self._handle_hitl(
+ if not self._should_handle_hitl(
file_name=file_name,
file_hash=file_hash,
workflow=workflow,
@@ -218,7 +236,19 @@ class DestinationConnector(BaseConnector):
):
self.insert_into_db(input_file_path=input_file_path)
elif connection_type == WorkflowEndpoint.ConnectionType.API:
- tool_execution_result = self.get_tool_execution_result(file_history)
+ logger.info(f"API connection type detected for file {file_name}")
+ # Check for HITL (Manual Review Queue) override for API deployments
+ if not self._should_handle_hitl(
+ file_name=file_name,
+ file_hash=file_hash,
+ workflow=workflow,
+ input_file_path=input_file_path,
+ file_execution_id=file_execution_id,
+ ):
+ logger.info(
+ f"No HITL override, getting tool execution result for {file_name}"
+ )
+ tool_execution_result = self.get_tool_execution_result(file_history)
elif connection_type == WorkflowEndpoint.ConnectionType.MANUALREVIEW:
self._push_data_to_queue(
file_name,
@@ -647,6 +677,7 @@ class DestinationConnector(BaseConnector):
workflow_id=self.workflow.id,
execution_id=self.execution_id,
use_file_history=self.use_file_history,
+ hitl_queue_name=self.hitl_queue_name,
)
@classmethod
@@ -661,6 +692,9 @@ class DestinationConnector(BaseConnector):
Returns:
DestinationConnector: New instance
"""
+ logger.info(
+ f"Creating DestinationConnector from config: hitl_queue_name={config.hitl_queue_name}"
+ )
# Reconstruct workflow
workflow = Workflow.objects.get(id=config.workflow_id)
@@ -671,10 +705,35 @@ class DestinationConnector(BaseConnector):
workflow_log=workflow_log,
use_file_history=config.use_file_history,
file_execution_id=config.file_execution_id,
+ hitl_queue_name=config.hitl_queue_name,
)
return destination
+ def _get_review_queue_name(self) -> str:
+ """Generate review queue name with optional HITL override for manual review processing.
+
+ Returns:
+ str: Queue name in the appropriate format:
+ - Custom HITL queue: review_queue_{org}_{workflow_id}:{hitl_queue_name}
+ - Standard queue: review_queue_{org}_{workflow_id}
+ """
+ logger.debug(f"Queue naming - hitl_queue_name={self.hitl_queue_name}")
+
+ # Base queue format: review_queue_{org}_{workflow_id}
+ base_queue_name = f"review_queue_{self.organization_id}_{str(self.workflow_id)}"
+
+ if self.hitl_queue_name:
+ # Custom HITL queue with user-specified name
+ q_name = f"{base_queue_name}:{self.hitl_queue_name}"
+ logger.debug(f"Using custom HITL queue: {q_name}")
+ else:
+ # Standard queue format for workflow-based processing
+ q_name = base_queue_name
+ logger.debug(f"Using standard queue name: {q_name}")
+
+ return q_name
+
def _push_to_queue(
self,
file_name: str,
@@ -708,6 +767,37 @@ class DestinationConnector(BaseConnector):
if not result:
return
connector: ConnectorInstance = self.source_endpoint.connector_instance
+
+ # For API deployments, use workflow execution storage instead of connector
+ if self.is_api:
+ logger.debug(
+ f"API deployment detected for {file_name}, using workflow execution file system"
+ )
+ # For API deployments, read file content from workflow execution storage
+ file_content_base64 = self._read_file_content_for_queue(
+ input_file_path, file_name
+ )
+
+ # Use common queue naming method
+ q_name = self._get_review_queue_name()
+ whisper_hash = meta_data.get("whisper-hash") if meta_data else None
+
+ queue_result = QueueResult(
+ file=file_name,
+ status=QueueResultStatus.SUCCESS,
+ result=result,
+ workflow_id=str(self.workflow_id),
+ file_content=file_content_base64,
+ whisper_hash=whisper_hash,
+ file_execution_id=file_execution_id,
+ ).to_dict()
+
+ queue_result_json = json.dumps(queue_result)
+ conn = QueueUtils.get_queue_inst()
+ conn.enqueue(queue_name=q_name, message=queue_result_json)
+ logger.info(f"Pushed {file_name} to queue {q_name} with file content")
+ return
+
connector_settings: dict[str, Any] = connector.connector_metadata
source_fs = self.get_fsspec(
@@ -718,7 +808,9 @@ class DestinationConnector(BaseConnector):
file_content = remote_file.read()
# Convert file content to a base64 encoded string
file_content_base64 = base64.b64encode(file_content).decode("utf-8")
- q_name = f"review_queue_{self.organization_id}_{workflow.id}"
+
+ # Use common queue naming method
+ q_name = self._get_review_queue_name()
if meta_data:
whisper_hash = meta_data.get("whisper-hash")
else:
@@ -737,3 +829,32 @@ class DestinationConnector(BaseConnector):
conn = QueueUtils.get_queue_inst()
# Enqueue the JSON string
conn.enqueue(queue_name=q_name, message=queue_result_json)
+ logger.info(f"Pushed {file_name} to queue {q_name} with file content")
+
+ def _read_file_content_for_queue(self, input_file_path: str, file_name: str) -> str:
+ """Read and encode file content for queue message.
+
+ Args:
+ input_file_path: Path to the file to read
+ file_name: Name of the file for logging purposes
+
+ Returns:
+ Base64 encoded file content
+
+ Raises:
+ APIException: If file cannot be read or doesn't exist
+ """
+ try:
+ file_system = FileSystem(FileStorageType.WORKFLOW_EXECUTION)
+ file_storage = file_system.get_file_storage()
+
+ if not file_storage.exists(input_file_path):
+ raise APIException(f"File not found: {input_file_path}")
+
+ file_bytes = file_storage.read(input_file_path, mode="rb")
+ if isinstance(file_bytes, str):
+ file_bytes = file_bytes.encode("utf-8")
+ return base64.b64encode(file_bytes).decode("utf-8")
+ except Exception as e:
+ logger.error(f"Failed to read file content for {file_name}: {e}")
+ raise APIException(f"Failed to read file content for queue: {e}")
diff --git a/backend/workflow_manager/endpoint_v2/dto.py b/backend/workflow_manager/endpoint_v2/dto.py
index a6bab30de..cbe990a3f 100644
--- a/backend/workflow_manager/endpoint_v2/dto.py
+++ b/backend/workflow_manager/endpoint_v2/dto.py
@@ -91,6 +91,7 @@ class DestinationConfig:
execution_id: str
use_file_history: bool
file_execution_id: str | None = None
+ hitl_queue_name: str | None = None
def to_json(self) -> dict[str, Any]:
"""Serialize the DestinationConfig instance to a JSON string."""
@@ -102,6 +103,7 @@ class DestinationConfig:
"execution_id": str(self.execution_id),
"use_file_history": self.use_file_history,
"file_execution_id": file_execution_id,
+ "hitl_queue_name": self.hitl_queue_name,
}
@staticmethod
@@ -111,6 +113,7 @@ class DestinationConfig:
data = json_str_or_dict
else:
data = json.loads(json_str_or_dict)
+
return DestinationConfig(**data)
diff --git a/backend/workflow_manager/endpoint_v2/queue_utils.py b/backend/workflow_manager/endpoint_v2/queue_utils.py
index bce45b765..f22e37300 100644
--- a/backend/workflow_manager/endpoint_v2/queue_utils.py
+++ b/backend/workflow_manager/endpoint_v2/queue_utils.py
@@ -45,7 +45,7 @@ class QueueResult:
return {
"file": self.file,
"whisper_hash": self.whisper_hash,
- "status": self.status,
+ "status": self.status.value,
"result": self.result,
"workflow_id": self.workflow_id,
"file_content": self.file_content,
diff --git a/backend/workflow_manager/workflow_v2/workflow_helper.py b/backend/workflow_manager/workflow_v2/workflow_helper.py
index a05a2dbad..b0b7ac2b6 100644
--- a/backend/workflow_manager/workflow_v2/workflow_helper.py
+++ b/backend/workflow_manager/workflow_v2/workflow_helper.py
@@ -68,6 +68,12 @@ from workflow_manager.workflow_v2.models.workflow import Workflow
logger = logging.getLogger(__name__)
+# Parameters to exclude when calling create_workflow_execution
+EXECUTION_EXCLUDED_PARAMS = {
+ "llm_profile_id",
+ "hitl_queue_name",
+}
+
class WorkflowHelper:
@staticmethod
@@ -251,6 +257,7 @@ class WorkflowHelper:
execution_mode: tuple[str, str] | None = None,
use_file_history: bool = True,
llm_profile_id: str | None = None,
+ hitl_queue_name: str | None = None,
) -> ExecutionResponse:
tool_instances: list[ToolInstance] = (
ToolInstanceHelper.get_tool_instances_by_workflow(
@@ -278,6 +285,7 @@ class WorkflowHelper:
execution_id=execution_id,
workflow_log=workflow_log,
use_file_history=use_file_history,
+ hitl_queue_name=hitl_queue_name,
)
try:
# Validating endpoints
@@ -422,6 +430,7 @@ class WorkflowHelper:
queue: str | None = None,
use_file_history: bool = True,
llm_profile_id: str | None = None,
+ hitl_queue_name: str | None = None,
) -> ExecutionResponse:
"""Adding a workflow to the queue for execution.
@@ -433,6 +442,7 @@ class WorkflowHelper:
queue (Optional[str]): Name of the celery queue to push into
use_file_history (bool): Use FileHistory table to return results on already
processed files. Defaults to True
+ hitl_queue_name (str | None): Name of the HITL queue to push files to
llm_profile_id (str, optional): LLM profile ID for overriding tool settings
Returns:
@@ -459,6 +469,7 @@ class WorkflowHelper:
"log_events_id": log_events_id,
"use_file_history": use_file_history,
"llm_profile_id": llm_profile_id,
+ "hitl_queue_name": hitl_queue_name,
},
queue=queue,
)
@@ -625,8 +636,10 @@ class WorkflowHelper:
workflow = Workflow.objects.get(id=workflow_id)
# TODO: Make use of WorkflowExecution.get_or_create()
try:
- # Filter out llm_profile_id from kwargs as create_workflow_execution doesn't accept it
- filtered_kwargs = {k: v for k, v in kwargs.items() if k != "llm_profile_id"}
+ # Filter out parameters that create_workflow_execution doesn't accept
+ filtered_kwargs = {
+ k: v for k, v in kwargs.items() if k not in EXECUTION_EXCLUDED_PARAMS
+ }
workflow_execution = WorkflowExecutionServiceHelper.create_workflow_execution(
workflow_id=workflow_id,
single_step=False,
@@ -643,6 +656,9 @@ class WorkflowHelper:
execution_id=execution_id, task_id=task_id
)
try:
+ logger.info(
+ f"Starting workflow execution: workflow_id={workflow_id}, execution_id={execution_id}, hitl_queue_name={kwargs.get('hitl_queue_name')}"
+ )
execution_response = WorkflowHelper.run_workflow(
workflow=workflow,
organization_id=organization_id,
@@ -653,6 +669,7 @@ class WorkflowHelper:
hash_values_of_files=hash_values,
use_file_history=use_file_history,
llm_profile_id=kwargs.get("llm_profile_id"),
+ hitl_queue_name=kwargs.get("hitl_queue_name"),
)
except Exception as error:
error_message = traceback.format_exc()
diff --git a/frontend/package.json b/frontend/package.json
index fcbc59f23..02540486b 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -59,7 +59,10 @@
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
- "eject": "react-scripts eject"
+ "eject": "react-scripts eject",
+ "lint": "eslint src/",
+ "lint:fix": "eslint src/ --fix",
+ "lint:changed": "git diff --name-only --diff-filter=ACMR | grep '\\.jsx\\?$' | xargs -r eslint || echo 'No JS/JSX files changed'"
},
"eslintConfig": {
"extends": [
diff --git a/frontend/src/components/agency/actions/Actions.jsx b/frontend/src/components/agency/actions/Actions.jsx
index bfde51b8d..4b61e1892 100644
--- a/frontend/src/components/agency/actions/Actions.jsx
+++ b/frontend/src/components/agency/actions/Actions.jsx
@@ -555,6 +555,7 @@ function Actions({ statusBarMsg, initializeWfComp, stepLoader }) {
isEdit={false}
workflowId={details?.id}
setDeploymentName={setDeploymentName}
+ workflowEndpointList={[]}
/>
)}
{openAddTaskModal && (
diff --git a/frontend/src/components/deployments/create-api-deployment-modal/CreateApiDeploymentModal.jsx b/frontend/src/components/deployments/create-api-deployment-modal/CreateApiDeploymentModal.jsx
index de990ab3f..2f62d05a3 100644
--- a/frontend/src/components/deployments/create-api-deployment-modal/CreateApiDeploymentModal.jsx
+++ b/frontend/src/components/deployments/create-api-deployment-modal/CreateApiDeploymentModal.jsx
@@ -130,7 +130,22 @@ const CreateApiDeploymentModal = ({
});
})
.catch((err) => {
- handleException(err, "", setBackendErrors);
+ if (err.response?.data) {
+ setBackendErrors(err.response.data);
+
+ // Show error notification
+ const errorData = err.response.data;
+ if (errorData.errors && errorData.errors.length > 0) {
+ setAlertDetails({
+ type: "error",
+ content: errorData.errors[0].detail || "Validation failed",
+ });
+ }
+ } else {
+ setAlertDetails(
+ handleException(err, "Failed to create API deployment")
+ );
+ }
})
.finally(() => {
setIsLoading(false);
@@ -153,7 +168,13 @@ const CreateApiDeploymentModal = ({
});
})
.catch((err) => {
- handleException(err, "", setBackendErrors);
+ if (err.response?.data) {
+ setBackendErrors(err.response.data);
+ } else {
+ setAlertDetails(
+ handleException(err, "Failed to update API deployment")
+ );
+ }
})
.finally(() => {
setIsLoading(false);
diff --git a/frontend/src/helpers/GetStaticData.js b/frontend/src/helpers/GetStaticData.js
index 421b0ab3a..af6e7a19d 100644
--- a/frontend/src/helpers/GetStaticData.js
+++ b/frontend/src/helpers/GetStaticData.js
@@ -401,8 +401,25 @@ const formattedDateTime = (ISOdateTime) => {
const getBackendErrorDetail = (attr, backendErrors) => {
if (backendErrors) {
- const error = backendErrors?.errors.find((error) => error?.attr === attr);
- return error ? error?.detail : null;
+ // Handle structured error response with errors array
+ if (backendErrors?.errors && Array.isArray(backendErrors.errors)) {
+ const error = backendErrors.errors.find((error) => error?.attr === attr);
+ return error ? error?.detail : null;
+ }
+
+ // Handle direct field errors (e.g., { api_name: ["error message"] })
+ if (backendErrors[attr]) {
+ return Array.isArray(backendErrors[attr])
+ ? backendErrors[attr].join(", ")
+ : backendErrors[attr];
+ }
+
+ // Handle nested errors in non_field_errors
+ if (backendErrors?.non_field_errors) {
+ return Array.isArray(backendErrors.non_field_errors)
+ ? backendErrors.non_field_errors.join(", ")
+ : backendErrors.non_field_errors;
+ }
}
return null;
};