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: Enhanced WF logs and other minor fixes (#627)
Chandrasekharan M306614c7df42
diff --git a/backend/pipeline/models.py b/backend/pipeline/models.pyindex 7532885f4..8860d027a 100644--- a/backend/pipeline/models.py+++ b/backend/pipeline/models.py@@ -99,6 +99,7 @@ class Pipeline(BaseModel):def __str__(self) -> str:return (f"Pipeline({self.id}) ("+ f"name: {self.pipeline_name}, "f"cron string: {self.cron_string}, "f"is active: {self.active}, "f"is scheduled: {self.scheduled}"diff --git a/backend/pipeline/pipeline_processor.py b/backend/pipeline/pipeline_processor.pyindex 0bf5e491d..be1e19cc7 100644--- a/backend/pipeline/pipeline_processor.py+++ b/backend/pipeline/pipeline_processor.py@@ -99,6 +99,7 @@ class PipelineProcessor:is_active: Optional[bool] = None,execution_id: Optional[str] = None,error_message: Optional[str] = None,+ is_end: bool = False,) -> None:if not pipeline_guid:return@@ -108,7 +109,7 @@ class PipelineProcessor:pipeline_id=pipeline_guid, check_active=check_active)pipeline = PipelineProcessor._update_pipeline_status(- pipeline=pipeline, is_end=True, status=status, is_active=is_active+ pipeline=pipeline, is_end=is_end, status=status, is_active=is_active)PipelineProcessor._send_notification(pipeline=pipeline, execution_id=execution_id, error_message=error_messagediff --git a/backend/pipeline/serializers/crud.py b/backend/pipeline/serializers/crud.pyindex 51d3cda72..e14c909a3 100644--- a/backend/pipeline/serializers/crud.py+++ b/backend/pipeline/serializers/crud.py@@ -85,11 +85,14 @@ class PipelineSerializer(AuditSerializer):def create(self, validated_data: dict[str, Any]) -> Any:# TODO: Deduce pipeline type based on WF?- validated_data[PK.ACTIVE] = True # Add this as default instead?- validated_data[PK.SCHEDULED] = True+ validated_data[PK.ACTIVE] = Truereturn super().create(validated_data)def save(self, **kwargs: Any) -> Pipeline:+ if self.validated_data[PK.CRON_STRING]:+ self.validated_data[PK.SCHEDULED] = True+ else:+ self.validated_data[PK.SCHEDULED] = Falsepipeline: Pipeline = super().save(**kwargs)if pipeline.cron_string is None:SchedulerHelper.remove_job(pipeline_id=str(pipeline.id))diff --git a/backend/workflow_manager/endpoint/destination.py b/backend/workflow_manager/endpoint/destination.pyindex 61dd658ab..dad50241a 100644--- a/backend/workflow_manager/endpoint/destination.py+++ b/backend/workflow_manager/endpoint/destination.py@@ -186,7 +186,7 @@ class DestinationConnector(BaseConnector):self._push_data_to_queue(file_name, workflow, input_file_path)if self.execution_service:self.execution_service.publish_log(- message=f"File {file_name} processed successfully"+ message=f"File '{file_name}' processed successfully")if not file_history:FileHistoryHelper.create_file_history(diff --git a/backend/workflow_manager/endpoint/source.py b/backend/workflow_manager/endpoint/source.pyindex 3f06752ed..a31b9847a 100644--- a/backend/workflow_manager/endpoint/source.py+++ b/backend/workflow_manager/endpoint/source.py@@ -61,10 +61,18 @@ class SourceConnector(BaseConnector):organization_id: Optional[str] = None,execution_service: Optional[WorkflowExecutionServiceHelper] = None,) -> None:- """Initialize a SourceConnector object.+ """Create a SourceConnector.Args:- workflow (Workflow): _description_+ workflow (Workflow): Associated workflow instance+ execution_id (str): UUID of the current execution+ organization_id (Optional[str]): Organization ID. Defaults to None.+ execution_service (Optional[WorkflowExecutionServiceHelper]): Instance of+ WorkflowExecutionServiceHelper that helps with WF execution.+ Defaults to None. This is not used in case of execution by API.++ Raises:+ OrganizationIdNotFound: _description_"""organization_id = organization_id or connection.tenant.schema_nameif not organization_id:@@ -159,7 +167,11 @@ class SourceConnector(BaseConnector):# Process from root in case its user provided list is emptyif not folders_to_process:folders_to_process = ["/"]- logger.info(f"Folders to process: {folders_to_process}")+ patterns = self.valid_file_patterns(required_patterns=required_patterns)+ self.publish_user_sys_log(+ f"Matching for patterns '{', '.join(patterns)}' from "+ f"'{', '.join(folders_to_process)}'"+ )source_fs = self.get_fs_connector(settings=connector_settings, connector_id=connector.connector_id@@ -173,17 +185,18 @@ class SourceConnector(BaseConnector):input_directory = source_fs.get_connector_root_dir(input_dir=input_directory, root_path=root_dir_path)- is_directory = source_fs_fsspec.isdir(input_directory)+ if not source_fs_fsspec.isdir(input_directory):+ raise InvalidInputDirectory(dir=input_directory)except Exception as e:- raise InvalidInputDirectory(- detail=f"Error while validating path '{input_directory}': {str(e)}"- )- if not is_directory:- raise InvalidInputDirectory(dir=input_directory)+ msg = f"Error while validating path '{input_directory}'. {str(e)}"+ self.publish_user_sys_log(msg)+ if isinstance(e, InvalidInputDirectory):+ raise+ raise InvalidInputDirectory(detail=msg)total_files_to_process = 0total_matched_files = {}- patterns = self.valid_file_patterns(required_patterns=required_patterns)+for input_directory in folders_to_process:input_directory = source_fs.get_connector_root_dir(input_dir=input_directory, root_path=root_dir_path@@ -192,7 +205,9 @@ class SourceConnector(BaseConnector):matched_files, count = self._get_matched_files(source_fs_fsspec, input_directory, patterns, recursive, limit)- logger.info(f"Matched '{count}' files from '{input_directory}'")+ self.publish_user_sys_log(+ f"Matched '{count}' files from '{input_directory}'"+ )total_matched_files.update(matched_files)total_files_to_process += countself.publish_input_output_list_file_logs(@@ -200,6 +215,19 @@ class SourceConnector(BaseConnector):)return total_matched_files, total_files_to_process+ def publish_user_sys_log(self, msg: str) -> None:+ """Publishes log to the user and system.++ Pushes logs messages to the configured logger and to the+ websocket channel if the `execution_service` is configured.++ Args:+ msg (str): Message to log+ """+ logger.info(msg)+ if self.execution_service:+ self.execution_service.publish_log(msg)+def publish_input_output_list_file_logs(self, folders: list[str], matched_files: dict[str, FileHash], count: int) -> None:@@ -217,25 +245,25 @@ class SourceConnector(BaseConnector):)def publish_input_file_content(self, input_file_path: str, input_text: str) -> None:- if self.execution_service:- output_log_message = f"##Input text:\n\n```text\n{input_text}\n```\n\n"- input_log_message = (- "##Input file:\n\n```text\n"- f"{os.path.basename(input_file_path)}\n```\n\n"- )- self.execution_service.publish_update_log(- state=LogState.INPUT_UPDATE, message=input_log_message- )- self.execution_service.publish_update_log(- state=LogState.OUTPUT_UPDATE, message=output_log_message- )+ if not self.execution_service:+ return None+ output_log_message = f"##Input text:\n\n```text\n{input_text}\n```\n\n"+ input_log_message = (+ "##Input file:\n\n```text\n" f"{os.path.basename(input_file_path)}\n```\n\n"+ )+ self.execution_service.publish_update_log(+ state=LogState.INPUT_UPDATE, message=input_log_message+ )+ self.execution_service.publish_update_log(+ state=LogState.OUTPUT_UPDATE, message=output_log_message+ )def _matched_files_component_log(self, matched_files: dict[str, FileHash], count: int) -> str:output_log = "### Matched files \n```text\n\n\n"for file_path in islice(matched_files.keys(), 20):- output_log += f"{file_path}\n"+ output_log += f"- {file_path}\n"output_log += "```\n\n"output_log += f"""Total matched files: {count}\n\nPlease note that only the first 20 files are shown.\n\n"""@@ -303,7 +331,7 @@ class SourceConnector(BaseConnector):if file_history and file_history.is_completed():self.execution_service.publish_log(f"Skipping file {file_path} as it has already been processed. "- "Clear the cache to process it again."+ "Clear the file markers to process it again.")return Falsediff --git a/backend/workflow_manager/workflow/execution.py b/backend/workflow_manager/workflow/execution.pyindex 05cfd9007..b2a7676a9 100644--- a/backend/workflow_manager/workflow/execution.py+++ b/backend/workflow_manager/workflow/execution.py@@ -238,7 +238,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.@@ -250,7 +250,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} errored")def publish_initial_tool_execution_logs(@@ -292,7 +293,7 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):if single_step:execution_type = ExecutionType.STEPself.execute_uncached_input(file_name=file_name, single_step=single_step)- self.publish_log(f"Tool executed successfully for {file_name}")+ self.publish_log(f"Tool executed successfully for '{file_name}'")self._handle_execution_type(execution_type)def execute_uncached_input(self, file_name: str, single_step: bool) -> None:@@ -356,12 +357,13 @@ class WorkflowExecutionServiceHelper(WorkflowExecutionService):self.publish_log("Trying to fetch results from cache")@staticmethod- def update_execution_err(execution_id: str, err_msg: str = "") -> None:+ def update_execution_err(execution_id: str, err_msg: str = "") -> WorkflowExecution:try:execution = WorkflowExecution.objects.get(pk=execution_id)execution.status = ExecutionStatus.ERROR.valueexecution.error_message = err_msgexecution.save()+ return executionexcept WorkflowExecution.DoesNotExist:logger.error(f"execution doesn't exist {execution_id}")diff --git a/backend/workflow_manager/workflow/workflow_helper.py b/backend/workflow_manager/workflow/workflow_helper.pyindex f21bb3a37..55a160b41 100644--- a/backend/workflow_manager/workflow/workflow_helper.py+++ b/backend/workflow_manager/workflow/workflow_helper.py@@ -116,8 +116,8 @@ class WorkflowHelper:) -> WorkflowExecution:input_files, total_files = source.list_files_from_source(hash_values_of_files)error_message = None- processed_files = 0- error_raised = 0+ successful_files = 0+ failed_files = 0execution_service.publish_initial_workflow_logs(total_files)execution_service.update_execution(ExecutionStatus.EXECUTING, increment_attempt=True@@ -133,7 +133,7 @@ class WorkflowHelper:file_hash,)try:- is_executed, error = WorkflowHelper.process_file(+ error = WorkflowHelper.process_file(current_file_idx=file_number,total_files=total_files,input_file=file_hash.file_path,@@ -144,22 +144,22 @@ class WorkflowHelper:single_step=single_step,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- except Exception as error:- error_raised += 1- error_message = f"Error processing file {file_path}. {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 error_raised and error_raised >= total_files:+ if failed_files and failed_files >= total_files:execution_service.update_execution(ExecutionStatus.ERROR, error=error_message)@@ -167,7 +167,9 @@ class WorkflowHelper: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()@@ -182,9 +184,8 @@ class WorkflowHelper:execution_service: WorkflowExecutionServiceHelper,single_step: bool,file_hash: FileHash,- ) -> tuple[bool, Optional[str]]:- error = None- is_executed = False+ ) -> Optional[str]:+ error: Optional[str] = Nonefile_name = source.add_file_to_volume(input_file_path=input_file, file_hash=file_hash)@@ -219,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(@@ -301,17 +302,13 @@ class WorkflowHelper: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)- return ExecutionResponse(- str(workflow.id),- str(workflow_execution.id),- workflow_execution.status,- log_id=str(execution_service.execution_log_id),- error=workflow_execution.error_message or str(e),- mode=workflow_execution.execution_mode,- )+ raisefinally:destination.delete_execution_directory()@@ -327,6 +324,7 @@ class WorkflowHelper:pipeline_id,Pipeline.PipelineStatus.SUCCESS,execution_id=workflow_execution.id,+ is_end=True,)else:PipelineProcessor.update_pipeline(@@ -334,6 +332,7 @@ class WorkflowHelper: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:@@ -514,15 +513,23 @@ class WorkflowHelper:WorkflowExecutionServiceHelper.update_execution_task(execution_id=execution_id, task_id=task_id)- execution_response = WorkflowHelper.run_workflow(- workflow=workflow,- organization_id=schema_name,- pipeline_id=pipeline_id,- scheduled=scheduled,- workflow_execution=workflow_execution,- execution_mode=execution_mode,- hash_values_of_files=hash_values,- )+ try:+ execution_response = WorkflowHelper.run_workflow(+ workflow=workflow,+ organization_id=schema_name,+ pipeline_id=pipeline_id,+ scheduled=scheduled,+ workflow_execution=workflow_execution,+ execution_mode=execution_mode,+ hash_values_of_files=hash_values,+ )+ except Exception as e:+ return ExecutionResponse(+ workflow_id=workflow_id,+ execution_id=execution_id,+ execution_status=ExecutionStatus.ERROR.value,+ error=str(e),+ )return execution_response.result@staticmethoddiff --git a/tools/classifier/src/helper.py b/tools/classifier/src/helper.pyindex ed1722b46..d150a7bea 100644--- a/tools/classifier/src/helper.py+++ b/tools/classifier/src/helper.py@@ -101,12 +101,11 @@ class ClassifierHelper:str: page content"""self.tool.stream_log(- "Creating text extraction adapter " f"using adapter_id: {adapter_id}"+ f"Creating text extraction adapter using adapter_id: {adapter_id}")x2text = X2Text(tool=self.tool, adapter_instance_id=adapter_id)self.tool.stream_log("Text extraction adapter has been created successfully.")- self.tool.stream_log("Adapter created")try:extraction_result: TextExtractionResult = x2text.process(diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.pyindex a49021f98..1e9f67cff 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py@@ -199,9 +199,7 @@ class WorkflowExecutionService:message="Ready for execution",component=tool_instance_id,)- result = self.tool_utils.run_tool(- tool_sandbox=sandbox,- )+ result = self.tool_utils.run_tool(tool_sandbox=sandbox)if result and result.get("error"):raise ToolOutputNotFoundException(result.get("error"))if not self.validate_execution_result(step + 1):