LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
fix: Fixed log push for manual sync and status updates for pipeline (#381)
Chandrasekharan Mb95921663d50
diff --git a/backend/connector/connector_instance_helper.py b/backend/connector/connector_instance_helper.pyindex 65a378f26..e9c7ec7c7 100644--- a/backend/connector/connector_instance_helper.py+++ b/backend/connector/connector_instance_helper.py@@ -107,7 +107,7 @@ class ConnectorInstanceHelper:filter_params["connector_name"] = connector_nameconnector_instances = ConnectorInstance.objects.filter(**filter_params).all()- logger.info(f"Retrived connector instance values {connector_instances}")+ logger.debug(f"Retrieved connector instance values {connector_instances}")if values is not None:filtered_connector_instances = connector_instances.values(*values)logger.info(@@ -328,5 +328,4 @@ class ConnectorInstanceHelper:"workflow": workflow_id,}connector_instances = ConnectorInstance.objects.filter(**filter_params).all()- logger.info(f"Retrived connector instance values {connector_instances}")return list(connector_instances)diff --git a/backend/pipeline/exceptions.py b/backend/pipeline/exceptions.pyindex 0b9078ed2..8da26c481 100644--- a/backend/pipeline/exceptions.py+++ b/backend/pipeline/exceptions.py@@ -3,11 +3,6 @@ from typing import Optionalfrom rest_framework.exceptions import APIException-class PipelineSaveError(APIException):- status_code = 500- default_detail = "Error saving pipeline"--class WorkflowTriggerError(APIException):status_code = 400default_detail = "Error triggering workflow. Pipeline created"diff --git a/backend/pipeline/pipeline_processor.py b/backend/pipeline/pipeline_processor.pyindex e84280da6..707377577 100644--- a/backend/pipeline/pipeline_processor.py+++ b/backend/pipeline/pipeline_processor.py@@ -2,7 +2,7 @@ import loggingfrom typing import Optionalfrom django.utils import timezone-from pipeline.exceptions import InactivePipelineError, PipelineSaveError+from pipeline.exceptions import InactivePipelineErrorfrom pipeline.models import Pipelinelogger = logging.getLogger(__name__)@@ -18,7 +18,7 @@ class PipelineProcessor:"""pipeline: Pipeline = PipelineProcessor.fetch_pipeline(pipeline_id)pipeline.run_count = pipeline.run_count + 1- return PipelineProcessor.update_pipeline_status(+ return PipelineProcessor._update_pipeline_status(pipeline=pipeline,status=Pipeline.PipelineStatus.RESTARTING,is_end=False,@@ -38,7 +38,7 @@ class PipelineProcessor:return pipeline@staticmethod- def update_pipeline_status(+ def _update_pipeline_status(pipeline: Pipeline,status: tuple[str, str],is_end: bool,@@ -59,9 +59,23 @@ class PipelineProcessor:if is_active is not None:pipeline.active = is_active- try:- pipeline.save()- except Exception as exc:- logger.error(f"Error occured while saving pipeline : {exc}")- raise PipelineSaveError()+ pipeline.save()return pipeline++ @staticmethod+ def update_pipeline(+ pipeline_guid: Optional[str],+ status: tuple[str, str],+ is_active: Optional[bool] = None,+ ) -> None:+ if not pipeline_guid:+ return+ # Skip check if we are enabling an inactive pipeline+ check_active = not is_active+ pipeline: Pipeline = PipelineProcessor.fetch_pipeline(+ pipeline_id=pipeline_guid, check_active=check_active+ )+ PipelineProcessor._update_pipeline_status(+ pipeline=pipeline, is_end=True, status=status, is_active=is_active+ )+ logger.info(f"Updated pipeline {pipeline_guid} status: {status}")diff --git a/backend/scheduler/helper.py b/backend/scheduler/helper.pyindex 66a68da55..30c479b61 100644--- a/backend/scheduler/helper.py+++ b/backend/scheduler/helper.py@@ -92,7 +92,7 @@ class SchedulerHelper:delete_periodic_task(pipeline_id)except Exception as e:logger.error(f"Exception while removing job: {e}")- raise JobDeletionError+ raise JobDeletionError from e@staticmethoddef pause_job(pipeline_id: str) -> None:@@ -102,7 +102,7 @@ class SchedulerHelper:disable_task(pipeline_id)except Exception as e:logger.error(f"Exception while pausing job: {e}")- raise JobSchedulingError+ raise JobSchedulingError from e@staticmethoddef resume_job(pipeline_id: str) -> None:@@ -112,4 +112,4 @@ class SchedulerHelper:enable_task(pipeline_id)except Exception as e:logger.error(f"Exception while resuming job: {e}")- raise JobSchedulingError+ raise JobSchedulingError from ediff --git a/backend/scheduler/tasks.py b/backend/scheduler/tasks.pyindex 71673bc6b..e03dc3b28 100644--- a/backend/scheduler/tasks.py+++ b/backend/scheduler/tasks.py@@ -1,6 +1,6 @@import jsonimport logging-from typing import Any, Optional+from typing import Anyfrom account.models import Organizationfrom celery import shared_task@@ -45,25 +45,6 @@ def create_periodic_task()-def update_pipeline(- pipeline_guid: Optional[str],- status: tuple[str, str],- is_active: Optional[bool] = None,-) -> Any:- if not pipeline_guid:- return- check_active = True- if is_active is True:- check_active = False- pipeline: Pipeline = PipelineProcessor.fetch_pipeline(- pipeline_id=pipeline_guid, check_active=check_active- )- PipelineProcessor.update_pipeline_status(- pipeline=pipeline, is_end=True, status=status, is_active=is_active- )- logger.info(f"Updated pipeline status: {status}")--# TODO: Remove unused args with a migration@shared_taskdef execute_pipeline_task(@@ -85,16 +66,16 @@ def execute_pipeline_task(with tenant_context(tenant):workflow = Workflow.objects.get(id=workflow_id)logger.info(f"Executing workflow: {workflow}")- update_pipeline(pipepline_id, Pipeline.PipelineStatus.INPROGRESS)+ PipelineProcessor.update_pipeline(+ pipepline_id, Pipeline.PipelineStatus.INPROGRESS+ )execution_response = WorkflowHelper.complete_execution(workflow, execution_id, pipepline_id)logger.info(f"Execution response: {execution_response}")- update_pipeline(pipepline_id, Pipeline.PipelineStatus.SUCCESS)logger.info(f"Execution completed for pipeline: {name}")except Exception as e:logger.error(f"Failed to execute pipeline: {name}. Error: {e}")- update_pipeline(pipepline_id, Pipeline.PipelineStatus.FAILURE)def delete_periodic_task(task_name: str) -> None:@@ -105,8 +86,6 @@ def delete_periodic_task(task_name: str) -> None:logger.info(f"Deleted periodic task: {task_name}")except PeriodicTask.DoesNotExist:logger.error(f"Periodic task does not exist: {task_name}")- except Exception as e:- logger.error(f"Failed to delete periodic task: {e}")@shared_task@@ -114,7 +93,7 @@ def disable_task(task_name: str) -> None:task = PeriodicTask.objects.get(name=task_name)task.enabled = Falsetask.save()- update_pipeline(task_name, Pipeline.PipelineStatus.PAUSED, False)+ PipelineProcessor.update_pipeline(task_name, Pipeline.PipelineStatus.PAUSED, False)@shared_task@@ -122,4 +101,6 @@ def enable_task(task_name: str) -> None:task = PeriodicTask.objects.get(name=task_name)task.enabled = Truetask.save()- update_pipeline(task_name, Pipeline.PipelineStatus.RESTARTING, True)+ PipelineProcessor.update_pipeline(+ task_name, Pipeline.PipelineStatus.RESTARTING, True+ )diff --git a/backend/workflow_manager/workflow/execution.py b/backend/workflow_manager/workflow/execution.pyindex d969efcd2..9160deccb 100644--- a/backend/workflow_manager/workflow/execution.py+++ b/backend/workflow_manager/workflow/execution.py@@ -98,6 +98,11 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):self.project_settings = project_settingsself.pipeline_id = pipeline_idself.execution_id = str(workflow_execution.id)+ logger.info(+ f"Executing for Pipeline ID: {pipeline_id}, "+ f"workflow ID: {self.workflow_id}, execution ID: {self.execution_id}, "+ f"web socket messaging channel ID: {self.execution_log_id}"+ )self.compilation_result = self.compile_workflow(execution_id=self.execution_id)@@ -108,14 +113,13 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):raise InvalidAPIRequest("File shouldn't be empty")tool_instance.metadata[JsonSchemaKey.ROOT_FOLDER] = execution_path- # TODO: Review and remove log_guid if its unused@staticmethoddef create_workflow_execution(workflow_id: str,pipeline_id: Optional[str] = None,single_step: bool = False,scheduled: bool = False,- log_guid: Optional[str] = None,+ log_events_id: Optional[str] = None,execution_id: Optional[str] = None,mode: tuple[str, str] = WorkflowExecution.Mode.INSTANT,) -> WorkflowExecution:@@ -129,8 +133,8 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):if single_stepelse WorkflowExecution.Type.COMPLETE)- log_events_id = StateStore.get(Common.LOG_EVENTS_ID)execution_log_id = log_events_id if log_events_id else pipeline_id+ # TODO: Using objects.create() insteadworkflow_execution = WorkflowExecution(pipeline_id=pipeline_id,workflow_id=workflow_id,@@ -254,8 +258,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):LogState.SUCCESS, "Executed successfully", LogComponent.WORKFLOW)self.publish_log(- f"Execution completed successfully for the files {processed_files} "- f"out of {total_files}"+ f"Execution completed for {processed_files} files out of {total_files}")def publish_initial_tool_execution_logs(diff --git a/backend/workflow_manager/workflow/execution_log_utils.py b/backend/workflow_manager/workflow/execution_log_utils.pyindex f726bcf4b..f2e0420ac 100644--- a/backend/workflow_manager/workflow/execution_log_utils.py+++ b/backend/workflow_manager/workflow/execution_log_utils.py@@ -44,7 +44,7 @@ def consume_log_history(self):store_to_db(organization_id, logs)-def create_log_consumer_scheduler_if_not_exists():+def create_log_consumer_scheduler_if_not_exists() -> None:try:interval, _ = IntervalSchedule.objects.get_or_create(every=ExecutionLogConstants.CONSUMER_INTERVAL,diff --git a/backend/workflow_manager/workflow/models/execution.py b/backend/workflow_manager/workflow/models/execution.pyindex 1f70df3b1..8506d7e43 100644--- a/backend/workflow_manager/workflow/models/execution.py+++ b/backend/workflow_manager/workflow/models/execution.py@@ -52,6 +52,7 @@ class WorkflowExecution(BaseModel):execution_log_id = models.CharField(default="", editable=False, db_comment="Execution log events Id")+ # TODO: Restrict with an enumstatus = models.CharField(default="", db_comment="Current status of execution")error_message = models.CharField(max_length=EXECUTION_ERROR_LENGTH,diff --git a/backend/workflow_manager/workflow/views.py b/backend/workflow_manager/workflow/views.pyindex 1226a6171..7438890b8 100644--- a/backend/workflow_manager/workflow/views.py+++ b/backend/workflow_manager/workflow/views.py@@ -22,10 +22,7 @@ from workflow_manager.workflow.constants import WorkflowKeyfrom workflow_manager.workflow.dto import ExecutionResponsefrom workflow_manager.workflow.enums import SchemaEntity, SchemaTypefrom workflow_manager.workflow.exceptions import (- InvalidRequest,- MissingEnvException,WorkflowDoesNotExistError,- WorkflowExecutionError,WorkflowGenerationError,WorkflowRegenerationError,)@@ -46,14 +43,6 @@ from backend.constants import RequestKeylogger = logging.getLogger(__name__)-def update_pipeline(pipeline_guid: Optional[str], status: tuple[str, str]) -> Any:- if pipeline_guid:- pipeline: Pipeline = PipelineProcessor.fetch_pipeline(pipeline_id=pipeline_guid)- PipelineProcessor.update_pipeline_status(- pipeline=pipeline, is_end=True, status=status- )--def make_execution_response(response: ExecutionResponse) -> Any:return ExecuteWorkflowResponseSerializer(response).data@@ -207,20 +196,8 @@ class WorkflowViewSet(viewsets.ModelViewSet):make_execution_response(execution_response),status=status.HTTP_200_OK,)- except (InvalidRequest, WorkflowExecutionError) as exception:- logger.error(f"Error while executing workflow: {exception}")- update_pipeline(pipeline_guid, Pipeline.PipelineStatus.FAILURE)- raise exception- except MissingEnvException as exception:- logger.error(f"Error while executing workflow: {exception}")- update_pipeline(pipeline_guid, Pipeline.PipelineStatus.FAILURE)- return Response(- {"error": "Please check the logs for more details: " + str(exception)},- status=status.HTTP_400_BAD_REQUEST,- )except Exception as exception:logger.error(f"Error while executing workflow: {exception}")- update_pipeline(pipeline_guid, Pipeline.PipelineStatus.FAILURE)if file_objs and execution_id and workflow_id:DestinationConnector.delete_api_storage_dir(workflow_id=workflow_id, execution_id=execution_id@@ -245,7 +222,9 @@ class WorkflowViewSet(viewsets.ModelViewSet):)elif pipeline_guid:# pipeline execution- update_pipeline(pipeline_guid, Pipeline.PipelineStatus.INPROGRESS)+ PipelineProcessor.update_pipeline(+ pipeline_guid, Pipeline.PipelineStatus.INPROGRESS+ )execution_response = WorkflowHelper.complete_execution(workflow=workflow,execution_id=execution_id,diff --git a/backend/workflow_manager/workflow/workflow_helper.py b/backend/workflow_manager/workflow/workflow_helper.pyindex 4ac6364d5..e7eea7590 100644--- a/backend/workflow_manager/workflow/workflow_helper.py+++ b/backend/workflow_manager/workflow/workflow_helper.py@@ -5,6 +5,7 @@ import tracebackimport uuidfrom typing import Any, Optional+from account.constants import Commonfrom account.models import Organizationfrom api.models import APIDeploymentfrom celery import current_task@@ -14,6 +15,7 @@ from celery.result import AsyncResultfrom django.db import IntegrityError, connectionfrom django_tenants.utils import get_tenant_model, tenant_contextfrom pipeline.models import Pipeline+from pipeline.pipeline_processor import PipelineProcessorfrom rest_framework import serializersfrom tool_instance.constants import ToolInstanceKeyfrom tool_instance.models import ToolInstance@@ -21,6 +23,7 @@ from tool_instance.tool_instance_helper import ToolInstanceHelperfrom unstract.workflow_execution.enums import LogComponent, LogLevel, LogStatefrom unstract.workflow_execution.exceptions import StopExecutionfrom utils.cache_service import CacheService+from utils.local_context import StateStorefrom workflow_manager.endpoint.destination import DestinationConnectorfrom workflow_manager.endpoint.source import SourceConnectorfrom workflow_manager.workflow.constants import (@@ -272,14 +275,21 @@ class WorkflowHelper:single_step=single_step,hash_values_of_files=hash_values_of_files,)- log_id = str(execution_service.execution_log_id)- if log_id:- log_id = str(log_id)+ if pipeline_id:+ # Update pipeline status+ if updated_execution.status != ExecutionStatus.ERROR.value:+ PipelineProcessor.update_pipeline(+ pipeline_id, Pipeline.PipelineStatus.SUCCESS+ )+ else:+ PipelineProcessor.update_pipeline(+ pipeline_id, Pipeline.PipelineStatus.FAILURE+ )return ExecutionResponse(str(workflow.id),str(updated_execution.id),updated_execution.status,- log_id=log_id,+ log_id=str(execution_service.execution_log_id),error=updated_execution.error_message,mode=updated_execution.execution_mode,result=destination.api_results,@@ -339,12 +349,14 @@ class WorkflowHelper:"""try:org_schema = connection.tenant.schema_name+ log_events_id = StateStore.get(Common.LOG_EVENTS_ID)async_execution = WorkflowHelper.execute_bin.delay(org_schema,workflow_id,hash_values_of_files=hash_values_of_files,execution_id=execution_id,pipeline_id=pipeline_id,+ log_events_id=log_events_id,)if timeout > -1:async_execution.wait(@@ -399,6 +411,7 @@ class WorkflowHelper:scheduled: bool = False,execution_mode: Optional[tuple[str, str]] = None,pipeline_id: Optional[str] = None,+ **kwargs: dict[str, Any],) -> Optional[list[Any]]:"""Asynchronous Execution By celery.@@ -414,6 +427,10 @@ class WorkflowHelper:pipeline_id (Optional[str], optional): Id of pipeline.Defaults to None.+ Kwargs:+ log_events_id (str): Session ID of the user, helps establish+ WS connection for streaming logs to the FE+Returns:dict[str, list[Any]]: Returns a dict with result fromworkflow execution@@ -432,6 +449,7 @@ class WorkflowHelper:pipeline_id=pipeline_id,mode=WorkflowExecution.Mode.QUEUE,execution_id=execution_id,+ **kwargs, # type: ignore))except IntegrityError:@@ -565,11 +583,13 @@ class WorkflowHelper:single_step: bool = False,mode: tuple[str, str] = WorkflowExecution.Mode.INSTANT,) -> ExecutionResponse:+ log_events_id = StateStore.get(Common.LOG_EVENTS_ID)workflow_execution = WorkflowExecutionServiceHelper.create_workflow_execution(workflow_id=workflow_id,single_step=single_step,pipeline_id=pipeline_id,mode=mode,+ log_events_id=log_events_id,)return ExecutionResponse(workflow_execution.workflow_id,diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.pyindex cad6cd16a..263307d9f 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py@@ -217,8 +217,8 @@ class WorkflowExecutionService:logger.info(log_message)self.publish_log(log_message, step=actual_step)+ # TODO: Catch specific workflow execution error to avoid showing pythonic errorexcept Exception as error:- logger.info(f"Error while running tool {tool_uid}: {str(error)}")self.publish_log(str(error), LogLevel.ERROR, step=actual_step)self.publish_update_log(state=LogState.ERROR,