LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
workflow manager workflow v2 delta changes (#689)
vishnuszipstacka7fb81493a69
diff --git a/backend/workflow_manager/workflow_v2/execution.py b/backend/workflow_manager/workflow_v2/execution.pyindex d8b9f85f7..58ada880f 100644--- a/backend/workflow_manager/workflow_v2/execution.py+++ b/backend/workflow_manager/workflow_v2/execution.py@@ -19,7 +19,6 @@ from workflow_manager.workflow_v2.enums import ExecutionStatusfrom workflow_manager.workflow_v2.exceptions import WorkflowExecutionErrorfrom workflow_manager.workflow_v2.models import Workflow, WorkflowExecutionfrom workflow_manager.workflow_v2.models.execution import EXECUTION_ERROR_LENGTH-from workflow_manager.workflow_v2.models.file_history import FileHistorylogger = logging.getLogger(__name__)@@ -57,7 +56,6 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):tool_instances=tool_instances_as_dto,platform_service_api_key=str(platform_key.key),ignore_processed_entities=False,- include_metadata=include_metadata,)if not workflow_execution:# Use pipline_id for pipelines / API deployment@@ -106,8 +104,9 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):self.compilation_result = self.compile_workflow(execution_id=self.execution_id)- @staticmethod+ @classmethoddef create_workflow_execution(+ cls,workflow_id: str,pipeline_id: Optional[str] = None,single_step: bool = False,@@ -116,6 +115,11 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):execution_id: Optional[str] = None,mode: tuple[str, str] = WorkflowExecution.Mode.INSTANT,) -> WorkflowExecution:+ # Validating with existing execution+ existing_execution = cls.get_execution_instance_by_id(execution_id)+ if existing_execution:+ return existing_execution+execution_method: tuple[str, str] = (WorkflowExecution.Method.SCHEDULEDif scheduled@@ -171,6 +175,26 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):)return execution+ @classmethod+ def get_execution_instance_by_id(+ cls, execution_id: str+ ) -> Optional[WorkflowExecution]:+ """Get execution by execution ID.++ Args:+ execution_id (str): UID of execution entity++ Returns:+ Optional[WorkflowExecution]: WorkflowExecution Entity+ """+ try:+ execution: WorkflowExecution = WorkflowExecution.objects.get(+ pk=execution_id+ )+ return execution+ except WorkflowExecution.DoesNotExist:+ return None+def build(self) -> None:if self.compilation_result["success"] is True:self.build_workflow()@@ -241,7 +265,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):)def publish_final_workflow_logs(- self, total_files: int, processed_files: int+ self, total_files: int, successful_files: int, failed_files: int) -> None:"""Publishes the final logs for the workflow.@@ -253,7 +277,8 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):LogState.SUCCESS, "Executed successfully", LogComponent.WORKFLOW)self.publish_log(- f"Execution completed for {processed_files} files out of {total_files}"+ f"Total files: {total_files}, "+ f"{successful_files} successfully executed and {failed_files} error(s)")def publish_initial_tool_execution_logs(@@ -280,34 +305,23 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):self,file_name: str,single_step: bool,- file_history: Optional[FileHistory] = None,- ) -> bool:+ ) -> tuple[bool, bool]:"""Executes the input file.Args:file_name (str): The name of the file to be executed.single_step (bool): Flag indicating whether to execute insingle step mode.- file_history (Optional[FileHistory], optional):- The file history object. Defaults to None.Returns:- bool: Flag indicating whether the file was executed.+ tuple[bool, bool]: Flag indicating whether the file was executed+ and skipped."""execution_type = ExecutionType.COMPLETE- is_executed = Falseif single_step:execution_type = ExecutionType.STEP- if not (file_history and file_history.is_completed()):- self.execute_uncached_input(file_name=file_name, single_step=single_step)- self.publish_log(f"Tool executed successfully for {file_name}")- is_executed = True- else:- self.publish_log(- f"Skipping file {file_name} as it is already processed."- "Clear the cache to process it again"- )+ self.execute_uncached_input(file_name=file_name, single_step=single_step)+ self.publish_log(f"Tool executed successfully for '{file_name}'")self._handle_execution_type(execution_type)- return is_executeddef execute_uncached_input(self, file_name: str, single_step: bool) -> None:"""Executes the uncached input file.@@ -370,11 +384,13 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):self.publish_log("Trying to fetch results from cache")@staticmethod- def update_execution_status(execution_id: str, status: ExecutionStatus) -> None:+ def update_execution_err(execution_id: str, err_msg: str = "") -> WorkflowExecution:try:execution = WorkflowExecution.objects.get(pk=execution_id)- execution.status = status.value+ execution.status = ExecutionStatus.ERROR.value+ execution.error_message = err_msg[:EXECUTION_ERROR_LENGTH]execution.save()+ return executionexcept WorkflowExecution.DoesNotExist:logger.error(f"execution doesn't exist {execution_id}")diff --git a/backend/workflow_manager/workflow_v2/utils.py b/backend/workflow_manager/workflow_v2/utils.pynew file mode 100644index 000000000..1c19fec69--- /dev/null+++ b/backend/workflow_manager/workflow_v2/utils.py@@ -0,0 +1,61 @@+from typing import Any++from workflow_manager.endpoint_v2.dto import FileHash+from workflow_manager.workflow_v2.models.workflow import Workflow+++class WorkflowUtil:+ """A utility class for managing workflow operations, particularly for+ selecting files for manual review and updating file destination based on+ review criteria."""++ @staticmethod+ def _mrq_files(+ percentage: float,+ n: int,+ ) -> Any:+ """Placeholder method for selecting a subset of files based on a given+ percentage.++ Args:+ percentage (float): The percentage of files to select.+ n (int): The total number of files.++ Returns:+ Any: The method is currently a placeholder and does not return a value.+ """+ pass++ @classmethod+ def get_q_no_list(cls, workflow: Workflow, total_files: int) -> Any:+ """Placeholder method for retrieving a list of files to be reviewed+ based on workflow rules.++ Args:+ workflow (Workflow): The workflow instance to be processed.+ total_files (int): The total number of files in the workflow.++ Returns:+ Any: The method is currently a placeholder and does not return a value.+ """+ pass++ @staticmethod+ def add_file_destination_filehash(+ index: int,+ q_file_no_list: Any,+ file_hash: FileHash,+ ) -> FileHash:+ """Updates the file destination in the FileHash object if the file+ index is marked for manual review.++ Args:+ index (int): The index of the file being processed.+ q_file_no_list (Any): A list or set of file indices marked for review.+ file_hash (FileHash): The FileHash object to be updated.++ Returns:+ FileHash: The potentially updated FileHash object with the file+ destination modified.+ """+ return file_hashdiff --git a/backend/workflow_manager/workflow_v2/workflow_helper.py b/backend/workflow_manager/workflow_v2/workflow_helper.pyindex 9a371051b..c94b2d576 100644--- a/backend/workflow_manager/workflow_v2/workflow_helper.py+++ b/backend/workflow_manager/workflow_v2/workflow_helper.py@@ -2,10 +2,10 @@ import jsonimport loggingimport osimport traceback-import uuidfrom typing import Any, Optionalfrom account_v2.constants import Common+from api.utils import APIDeploymentUtilsfrom api_v2.models import APIDeploymentfrom celery import current_taskfrom celery import exceptions as celery_exceptions@@ -25,6 +25,7 @@ from utils.constants import Accountfrom utils.local_context import StateStorefrom utils.user_context import UserContextfrom workflow_manager.endpoint_v2.destination import DestinationConnector+from workflow_manager.endpoint_v2.dto import FileHashfrom workflow_manager.endpoint_v2.source import SourceConnectorfrom workflow_manager.workflow_v2.constants import (CeleryConfigurations,@@ -44,6 +45,7 @@ from workflow_manager.workflow_v2.execution import WorkflowExecutionServiceHelpefrom workflow_manager.workflow_v2.file_history_helper import FileHistoryHelperfrom workflow_manager.workflow_v2.models.execution import WorkflowExecutionfrom workflow_manager.workflow_v2.models.workflow import Workflow+from workflow_manager.workflow_v2.utils import WorkflowUtillogger = logging.getLogger(__name__)@@ -89,7 +91,6 @@ class WorkflowHelper:scheduled: bool,execution_mode: tuple[str, str],workflow_execution: Optional[WorkflowExecution],- include_metadata: bool = False,) -> WorkflowExecutionServiceHelper:workflow_execution_service = WorkflowExecutionServiceHelper(organization_id=organization_id,@@ -100,7 +101,6 @@ class WorkflowHelper:scheduled=scheduled,mode=execution_mode,workflow_execution=workflow_execution,- include_metadata=include_metadata,)workflow_execution_service.build()return workflow_execution_service@@ -112,46 +112,64 @@ class WorkflowHelper:destination: DestinationConnector,execution_service: WorkflowExecutionServiceHelper,single_step: bool,- hash_values_of_files: dict[str, str] = {},+ hash_values_of_files: dict[str, FileHash] = {},) -> WorkflowExecution:- input_files = source.list_files_from_source()- total_files = len(input_files)- processed_files = 0- error_raised = 0+ input_files, total_files = source.list_files_from_source(hash_values_of_files)+ error_message = None+ successful_files = 0+ failed_files = 0execution_service.publish_initial_workflow_logs(total_files)execution_service.update_execution(ExecutionStatus.EXECUTING, increment_attempt=True)- for index, input_file in enumerate(input_files):+ if total_files > 0:+ q_file_no_list = WorkflowUtil.get_q_no_list(workflow, total_files)++ for index, (file_path, file_hash) in enumerate(input_files.items()):file_number = index + 1+ file_hash = WorkflowUtil.add_file_destination_filehash(+ file_number,+ q_file_no_list,+ file_hash,+ )try:- is_executed, error = WorkflowHelper.process_file(+ error = WorkflowHelper.process_file(current_file_idx=file_number,total_files=total_files,- input_file=input_file,+ input_file=file_hash.file_path,workflow=workflow,source=source,destination=destination,execution_service=execution_service,single_step=single_step,- hash_values_of_files=hash_values_of_files,+ file_hash=file_hash,)- if is_executed:- processed_files += 1if error:- error_raised += 1- except StopExecution as exception:+ failed_files += 1+ else:+ successful_files += 1+ except StopExecution as e:execution_service.update_execution(- ExecutionStatus.STOPPED, error=str(exception)+ ExecutionStatus.STOPPED, error=str(e))break- if error_raised and error_raised == total_files:- execution_service.update_execution(ExecutionStatus.ERROR)+ except Exception as e:+ failed_files += 1+ error_message = f"Error processing file '{file_path}'. {e}"+ execution_service.publish_log(+ message=error_message, level=LogLevel.ERROR+ )+ if failed_files and failed_files >= total_files:+ execution_service.update_execution(+ ExecutionStatus.ERROR, error=error_message+ )else:execution_service.update_execution(ExecutionStatus.COMPLETED)execution_service.publish_final_workflow_logs(- total_files=total_files, processed_files=processed_files+ total_files=total_files,+ successful_files=successful_files,+ failed_files=failed_files,)return execution_service.get_execution_instance()@@ -165,35 +183,26 @@ class WorkflowHelper:destination: DestinationConnector,execution_service: WorkflowExecutionServiceHelper,single_step: bool,- hash_values_of_files: dict[str, str],- ) -> tuple[bool, Optional[str]]:- file_history = None- error = None- is_executed = False- file_name, file_hash = source.add_file_to_volume(- input_file_path=input_file,- hash_values_of_files=hash_values_of_files,+ file_hash: FileHash,+ ) -> Optional[str]:+ error: Optional[str] = None+ file_name = source.add_file_to_volume(+ input_file_path=input_file, file_hash=file_hash)try:execution_service.initiate_tool_execution(current_file_idx, total_files, file_name, single_step)- file_history = FileHistoryHelper.get_file_history(- workflow=workflow, cache_key=file_hash- )- is_executed = execution_service.execute_input_file(- file_name=file_name,- single_step=single_step,- file_history=file_history,- )+ if not file_hash.is_executed:+ execution_service.execute_input_file(+ file_name=file_name,+ single_step=single_step,+ )except StopExecution:raiseexcept Exception as e:- execution_service.publish_log(- f"'Error processing file '{os.path.basename(input_file)}'. {str(e)}",- level=LogLevel.ERROR,- )- error = str(e)+ error = f"Error processing file '{os.path.basename(input_file)}'. {str(e)}"+ execution_service.publish_log(error, level=LogLevel.ERROR)execution_service.publish_update_log(LogState.RUNNING,f"Processing output for {file_name}",@@ -203,7 +212,6 @@ class WorkflowHelper:file_name=file_name,file_hash=file_hash,workflow=workflow,- file_history=file_history,error=error,input_file_path=input_file,)@@ -212,7 +220,7 @@ class WorkflowHelper:f"{file_name}'s output is processed successfully",LogComponent.DESTINATION,)- return is_executed, error+ return error@staticmethoddef validate_tool_instances_meta(@@ -228,14 +236,13 @@ class WorkflowHelper:@staticmethoddef run_workflow(workflow: Workflow,- hash_values_of_files: dict[str, str] = {},+ hash_values_of_files: dict[str, FileHash] = {},organization_id: Optional[str] = None,pipeline_id: Optional[str] = None,scheduled: bool = False,single_step: bool = False,workflow_execution: Optional[WorkflowExecution] = None,execution_mode: Optional[tuple[str, str]] = None,- include_metadata: bool = False,) -> ExecutionResponse:tool_instances: list[ToolInstance] = (ToolInstanceHelper.get_tool_instances_by_workflow(@@ -254,7 +261,6 @@ class WorkflowHelper:scheduled=scheduled,execution_mode=execution_mode,workflow_execution=workflow_execution,- include_metadata=include_metadata,)execution_id = execution_service.execution_idsource = SourceConnector(@@ -263,7 +269,11 @@ class WorkflowHelper:execution_id=execution_id,execution_service=execution_service,)- destination = DestinationConnector(workflow=workflow, execution_id=execution_id)+ destination = DestinationConnector(+ workflow=workflow,+ execution_id=execution_id,+ execution_service=execution_service,+ )# Validating endpointssource.validate()destination.validate()@@ -277,7 +287,6 @@ class WorkflowHelper:single_step=single_step,hash_values_of_files=hash_values_of_files,)- # TODO: Update through signalsWorkflowHelper._update_pipeline_status(pipeline_id=pipeline_id, workflow_execution=workflow_execution)@@ -290,6 +299,16 @@ class WorkflowHelper:mode=workflow_execution.execution_mode,result=destination.api_results,)+ except Exception as e:+ logger.error(f"Error executing workflow {workflow}: {e}")+ logger.error(f"Error {traceback.format_exc()}")+ workflow_execution = WorkflowExecutionServiceHelper.update_execution_err(+ execution_id, str(e)+ )+ WorkflowHelper._update_pipeline_status(+ pipeline_id=pipeline_id, workflow_execution=workflow_execution+ )+ raisefinally:destination.delete_execution_directory()@@ -302,15 +321,26 @@ class WorkflowHelper:# Update pipeline statusif workflow_execution.status != ExecutionStatus.ERROR.value:PipelineProcessor.update_pipeline(- pipeline_id, Pipeline.PipelineStatus.SUCCESS+ pipeline_id,+ Pipeline.PipelineStatus.SUCCESS,+ execution_id=workflow_execution.id,+ is_end=True,)else:PipelineProcessor.update_pipeline(- pipeline_id, Pipeline.PipelineStatus.FAILURE+ pipeline_id,+ Pipeline.PipelineStatus.FAILURE,+ execution_id=workflow_execution.id,+ error_message=workflow_execution.error_message,+ is_end=True,)# Expected exception since API deployments are not tracked in Pipelineexcept Pipeline.DoesNotExist:- pass+ api = APIDeploymentUtils.get_api_by_id(api_id=pipeline_id)+ if api:+ APIDeploymentUtils.send_notification(+ api=api, workflow_execution=workflow_execution+ )except Exception as e:logger.warning(f"Error updating pipeline {pipeline_id} status: {e}, "@@ -343,7 +373,7 @@ class WorkflowHelper:return ExecutionResponse(execution.workflow_id,execution_id,- task.status,+ execution.status,result=task.result,)@@ -351,10 +381,10 @@ class WorkflowHelper:def execute_workflow_async(workflow_id: str,execution_id: str,- hash_values_of_files: dict[str, str],+ hash_values_of_files: dict[str, FileHash],timeout: int = -1,pipeline_id: Optional[str] = None,- include_metadata: bool = False,+ queue: Optional[str] = None,) -> ExecutionResponse:"""Adding a workflow to the queue for execution.@@ -363,22 +393,34 @@ class WorkflowHelper:execution_id (str): Execution IDtimeout (int): Celery timeout (timeout -1 : async execution)pipeline_id (Optional[str], optional): Optional pipeline. Defaults to None.- include_metadata (bool): Whether to include metadata in the prompt outputReturns:ExecutionResponse: Existing status of execution"""try:+ file_hash_in_str = {+ key: value.to_json() for key, value in hash_values_of_files.items()+ }org_schema = UserContext.get_organization_identifier()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,- include_metadata=include_metadata,+ async_execution = WorkflowHelper.execute_bin.apply_async(+ args=[+ org_schema, # schema_name+ workflow_id, # workflow_id+ execution_id, # execution_id+ file_hash_in_str, # hash_values_of_files+ ],+ kwargs={+ "scheduled": False,+ "execution_mode": None,+ "pipeline_id": pipeline_id,+ "log_events_id": log_events_id,+ },+ queue=queue,+ )+ logger.info(+ f"Job '{async_execution}' has been enqueued for "+ f"execution_id '{execution_id}'")if timeout > -1:async_execution.wait(@@ -386,15 +428,16 @@ class WorkflowHelper:interval=CeleryConfigurations.INTERVAL,)task = AsyncResultData(async_result=async_execution)- logger.info(f"Job {async_execution} enqueued.")celery_result = task.to_dict()task_result = celery_result.get("result")- return ExecutionResponse(+ workflow_execution = WorkflowExecution.objects.get(id=execution_id)+ execution_response = ExecutionResponse(workflow_id,execution_id,- task.status,+ workflow_execution.status,result=task_result,)+ return execution_responseexcept celery_exceptions.TimeoutError:return ExecutionResponse(workflow_id,@@ -403,8 +446,8 @@ class WorkflowHelper:message=WorkflowMessages.CELERY_TIMEOUT_MESSAGE,)except Exception as error:- WorkflowExecutionServiceHelper.update_execution_status(- execution_id, ExecutionStatus.ERROR+ WorkflowExecutionServiceHelper.update_execution_err(+ execution_id, str(error))logger.error(f"Errors while job enqueueing {str(error)}")logger.error(f"Error {traceback.format_exc()}")@@ -429,11 +472,10 @@ class WorkflowHelper:schema_name: str,workflow_id: str,execution_id: str,- hash_values_of_files: dict[str, str],+ hash_values_of_files: dict[str, dict[str, Any]],scheduled: bool = False,execution_mode: Optional[tuple[str, str]] = None,pipeline_id: Optional[str] = None,- include_metadata: bool = False,**kwargs: dict[str, Any],) -> Optional[list[Any]]:"""Asynchronous Execution By celery.@@ -447,7 +489,6 @@ class WorkflowHelper:execution_mode (Optional[WorkflowExecution.Mode]): WorkflowExecution ModeDefaults to Nonepipeline_id (Optional[str], optional): Id of pipeline. Defaults to None- include_metadata (bool): Whether to include metadata in the prompt outputKwargs:log_events_id (str): Session ID of the user,@@ -468,7 +509,6 @@ class WorkflowHelper:scheduled=scheduled,execution_mode=execution_mode,pipeline_id=pipeline_id,- include_metadata=include_metadata,**kwargs,)@@ -482,7 +522,6 @@ class WorkflowHelper:scheduled: bool = False,execution_mode: Optional[tuple[str, str]] = None,pipeline_id: Optional[str] = None,- include_metadata: bool = False,**kwargs: dict[str, Any],) -> Optional[list[Any]]:"""Asynchronous Execution By celery.@@ -526,35 +565,80 @@ class WorkflowHelper:WorkflowExecutionServiceHelper.update_execution_task(execution_id=execution_id, task_id=task_id)- result = WorkflowHelper.run_workflow(- workflow=workflow,- organization_id=organization_id,- pipeline_id=pipeline_id,- scheduled=scheduled,- workflow_execution=workflow_execution,- execution_mode=execution_mode,- hash_values_of_files=hash_values_of_files,- include_metadata=include_metadata,- ).result- return result+ try:+ execution_response = WorkflowHelper.run_workflow(+ workflow=workflow,+ organization_id=organization_id,+ pipeline_id=pipeline_id,+ scheduled=scheduled,+ workflow_execution=workflow_execution,+ execution_mode=execution_mode,+ hash_values_of_files=hash_values_of_files,+ )+ except Exception as error:+ error_message = traceback.format_exc()+ logger.error(+ f"Error executing execution {workflow_execution}: {error_message}"+ )+ WorkflowExecutionServiceHelper.update_execution_err(+ execution_id, str(error)+ )+ raise+ return execution_response.result@staticmethoddef complete_execution(workflow: Workflow,execution_id: Optional[str] = None,pipeline_id: Optional[str] = None,- hash_values_of_files: dict[str, str] = {},- include_metadata: bool = False,+ execution_mode: Optional[WorkflowExecution] = WorkflowExecution.Mode.QUEUE,+ hash_values_of_files: dict[str, FileHash] = {},) -> ExecutionResponse:if pipeline_id:logger.info(f"Executing pipeline: {pipeline_id}")- response: ExecutionResponse = WorkflowHelper.execute_workflow_async(- workflow_id=workflow.id,- pipeline_id=pipeline_id,- execution_id=str(uuid.uuid4()),- hash_values_of_files=hash_values_of_files,+ # Create a new WorkflowExecution entity for each pipeline execution.+ # This ensures every pipeline run is tracked as a distinct execution.+ workflow_execution = (+ WorkflowExecutionServiceHelper.create_workflow_execution(+ workflow_id=workflow.id,+ single_step=False,+ pipeline_id=pipeline_id,+ mode=execution_mode,+ ))- return response+ execution_id = workflow_execution.id+ log_events_id = StateStore.get(Common.LOG_EVENTS_ID)+ org_schema = UserContext.get_organization_identifier()+ if execution_mode == WorkflowExecution.Mode.INSTANT:+ # Instant request from UX (Sync now in ETL and Workflow page)+ response: ExecutionResponse = WorkflowHelper.execute_workflow_async(+ workflow_id=workflow.id,+ pipeline_id=pipeline_id,+ execution_id=execution_id,+ hash_values_of_files=hash_values_of_files,+ )+ return response+ else:+ execution_result = WorkflowHelper.execute_bin(+ schema_name=org_schema,+ workflow_id=workflow.id,+ execution_id=workflow_execution.id,+ hash_values_of_files=hash_values_of_files,+ scheduled=True,+ execution_mode=execution_mode,+ pipeline_id=pipeline_id,+ log_events_id=log_events_id,+ )++ updated_execution = WorkflowExecution.objects.get(id=execution_id)+ execution_response = ExecutionResponse(+ workflow.id,+ execution_id,+ updated_execution.status,+ result=execution_result,+ )+ return execution_response+if execution_id is None:# Creating execution entity and returnreturn WorkflowHelper.create_and_make_execution_response(@@ -572,7 +656,6 @@ class WorkflowHelper:workflow=workflow,workflow_execution=workflow_execution,hash_values_of_files=hash_values_of_files,- include_metadata=include_metadata,)except WorkflowExecution.DoesNotExist:return WorkflowHelper.create_and_make_execution_response(