LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
delta changes for pipeline v2 multitenancy (#686)
vishnuszipstack06f85ac7f42c
diff --git a/backend/pipeline_v2/deployment_helper.py b/backend/pipeline_v2/deployment_helper.pynew file mode 100644index 000000000..f50fd9b3c--- /dev/null+++ b/backend/pipeline_v2/deployment_helper.py@@ -0,0 +1,33 @@+import logging+from typing import Any++from api_v2.api_key_validator import BaseAPIKeyValidator+from api_v2.exceptions import InvalidAPIRequest+from api_v2.key_helper import KeyHelper+from pipeline_v2.exceptions import PipelineNotFound+from pipeline_v2.pipeline_processor import PipelineProcessor+from rest_framework.request import Request++logger = logging.getLogger(__name__)+++class DeploymentHelper(BaseAPIKeyValidator):+ @staticmethod+ def validate_parameters(request: Request, **kwargs: Any) -> None:+ """Validate pipeline_id for pipeline deployments."""+ pipeline_id = kwargs.get("pipeline_id") or request.data.get("pipeline_id")+ if not pipeline_id:+ raise InvalidAPIRequest("Missing params pipeline_id")++ @staticmethod+ def validate_and_process(+ self: Any, request: Request, func: Any, api_key: str, *args: Any, **kwargs: Any+ ) -> Any:+ """Fetch pipeline and validate API key."""+ pipeline_id = kwargs.get("pipeline_id") or request.data.get("pipeline_id")+ pipeline = PipelineProcessor.get_active_pipeline(pipeline_id=pipeline_id)+ if not pipeline:+ raise PipelineNotFound()+ KeyHelper.validate_api_key(api_key=api_key, instance=pipeline)+ kwargs["pipeline"] = pipeline+ return func(self, request, *args, **kwargs)diff --git a/backend/pipeline_v2/dto.py b/backend/pipeline_v2/dto.pynew file mode 100644index 000000000..3ed83bf30--- /dev/null+++ b/backend/pipeline_v2/dto.py@@ -0,0 +1,33 @@+from typing import Any, Optional+++class PipelineStatusPayload:+ def __init__(+ self,+ type: str,+ pipeline_id: str,+ pipeline_name: str,+ status: str,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ):+ self.type = type+ self.pipeline_id = pipeline_id+ self.pipeline_name = pipeline_name+ self.status = status+ self.execution_id = execution_id+ self.error_message = error_message++ def to_dict(self) -> dict[str, Any]:+ """Convert the payload DTO to a dictionary."""+ payload = {+ "type": self.type,+ "pipeline_id": str(self.pipeline_id),+ "pipeline_name": self.pipeline_name,+ "status": self.status,+ }+ if self.execution_id:+ payload["execution_id"] = str(self.execution_id)+ if self.error_message:+ payload["error_message"] = self.error_message+ return payloaddiff --git a/backend/pipeline_v2/exceptions.py b/backend/pipeline_v2/exceptions.pyindex 8da26c481..7d2885a98 100644--- a/backend/pipeline_v2/exceptions.py+++ b/backend/pipeline_v2/exceptions.py@@ -3,6 +3,11 @@ from typing import Optionalfrom rest_framework.exceptions import APIException+class NotFoundException(APIException):+ status_code = 404+ default_detail = "The requested resource was not found."++class WorkflowTriggerError(APIException):status_code = 400default_detail = "Error triggering workflow. Pipeline created"@@ -44,3 +49,7 @@ class MandatoryWorkflowId(APIException):class MandatoryCronSchedule(APIException):status_code = 400default_detail = "Cron schedule is mandatory"+++class PipelineNotFound(NotFoundException):+ default_detail = "Pipeline not found"diff --git a/backend/pipeline_v2/models.py b/backend/pipeline_v2/models.pyindex ccb90313a..856150439 100644--- a/backend/pipeline_v2/models.py+++ b/backend/pipeline_v2/models.py@@ -1,7 +1,8 @@import uuidfrom account_v2.models import User-from django.db import models+from django.conf import settings+from django.db import connection, modelsfrom utils.models.base_model import BaseModelfrom utils.models.organization_mixin import (DefaultOrganizationManagerMixin,@@ -37,22 +38,28 @@ class Pipeline(DefaultOrganizationMixin, BaseModel):PAUSED = "PAUSED", "Paused"id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)- pipeline_name = models.CharField(max_length=PIPELINE_NAME_LENGTH, default="")+ pipeline_name = models.CharField(+ max_length=PIPELINE_NAME_LENGTH, default="", unique=True+ )workflow = models.ForeignKey(Workflow,on_delete=models.CASCADE,- related_name="pipelines",+ related_name="pipeline_workflows",null=False,blank=False,)# Added as text field until a model for App is included.app_id = models.TextField(null=True, blank=True, max_length=APP_ID_LENGTH)- active = models.BooleanField(default=False) # TODO: Add dbcomment- scheduled = models.BooleanField(default=False) # TODO: Add dbcomment+ active = models.BooleanField(+ default=False, db_comment="Indicates whether the pipeline is active"+ )+ scheduled = models.BooleanField(+ default=False, db_comment="Indicates whether the pipeline is scheduled"+ )cron_string = models.TextField(db_comment="UNIX cron string",- null=False,- blank=False,+ null=True,+ blank=True,max_length=FieldLength.CRON_LENGTH,)pipeline_type = models.CharField(@@ -74,23 +81,37 @@ class Pipeline(DefaultOrganizationMixin, BaseModel):created_by = models.ForeignKey(User,on_delete=models.SET_NULL,- related_name="pipelines_created",+ related_name="created_pipeline",null=True,blank=True,)modified_by = models.ForeignKey(User,on_delete=models.SET_NULL,- related_name="pipelines_modified",+ related_name="modified_pipeline",null=True,blank=True,)- # Manager- objects = PipelineModelManager()+ @property+ def api_key_data(self):+ return {"pipeline": self.id, "description": f"API Key for {self.pipeline_name}"}++ @property+ def api_endpoint(self):+ org_schema = connection.get_tenant().schema_name+ deployment_endpoint = settings.API_DEPLOYMENT_PATH_PREFIX + "/pipeline/api"+ api_endpoint = f"{deployment_endpoint}/{org_schema}/{self.id}/"+ return api_endpointdef __str__(self) -> str:- return f"Pipeline({self.id})"+ 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}"+ )class Meta:verbose_name = "Pipeline"@@ -99,11 +120,7 @@ class Pipeline(DefaultOrganizationMixin, BaseModel):constraints = [models.UniqueConstraint(fields=["id", "pipeline_type"],- name="unique_pipeline_entity",- ),- models.UniqueConstraint(- fields=["pipeline_name", "organization"],- name="unique_pipeline_name",+ name="unique_pipeline",),]diff --git a/backend/pipeline_v2/notification.py b/backend/pipeline_v2/notification.pynew file mode 100644index 000000000..233a69097--- /dev/null+++ b/backend/pipeline_v2/notification.py@@ -0,0 +1,44 @@+import logging+from typing import Optional++from notification_v2.helper import NotificationHelper+from notification_v2.models import Notification+from pipeline_v2.dto import PipelineStatusPayload+from pipeline_v2.models import Pipeline++logger = logging.getLogger(__name__)+++class PipelineNotification:+ def __init__(+ self,+ pipeline: Pipeline,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ) -> None:+ self.notifications = Notification.objects.filter(+ pipeline=pipeline, is_active=True+ )+ self.pipeline = pipeline+ self.error_message = error_message+ self.execution_id = execution_id++ def send(self):+ if not self.notifications.count():+ logger.info(f"No notifications found for pipeline {self.pipeline}")+ return+ logger.info(+ f"Sending pipeline status notification for pipeline {self.pipeline}"+ )+ payload_dto = PipelineStatusPayload(+ type=self.pipeline.pipeline_type,+ pipeline_id=str(self.pipeline.id),+ pipeline_name=self.pipeline.pipeline_name,+ status=self.pipeline.last_run_status,+ execution_id=self.execution_id,+ error_message=self.error_message,+ )++ NotificationHelper.send_notification(+ notifications=self.notifications, payload=payload_dto.to_dict()+ )diff --git a/backend/pipeline_v2/piepline_api_execution_views.py b/backend/pipeline_v2/piepline_api_execution_views.pynew file mode 100644index 000000000..7b4bd14b8--- /dev/null+++ b/backend/pipeline_v2/piepline_api_execution_views.py@@ -0,0 +1,43 @@+import logging+from typing import Any++from pipeline_v2.deployment_helper import DeploymentHelper+from pipeline_v2.models import Pipeline+from rest_framework import status, views+from rest_framework.request import Request+from rest_framework.response import Response+from scheduler.tasks import execute_pipeline_task++logger = logging.getLogger(__name__)+++class PipelineApiExecution(views.APIView):+ def initialize_request(+ self, request: Request, *args: Any, **kwargs: Any+ ) -> Request:+ """To remove csrf request for public API.++ Args:+ request (Request): _description_++ Returns:+ Request: _description_+ """+ setattr(request, "csrf_processing_done", True)+ return super().initialize_request(request, *args, **kwargs)++ @DeploymentHelper.validate_api_key+ def post(+ self, request: Request, org_name: str, pipeline_id: str, pipeline: Pipeline+ ) -> Response:+ execute_pipeline_task.delay(+ workflow_id="",+ org_schema=org_name,+ execution_action="",+ execution_id="",+ pipepline_id=pipeline_id,+ with_logs=True,+ name=pipeline.pipeline_name,+ )+ logger.info(f"Triggered {pipeline} by API")+ return Response({"message": f"Triggered {pipeline}"}, status=status.HTTP_200_OK)diff --git a/backend/pipeline_v2/pipeline_processor.py b/backend/pipeline_v2/pipeline_processor.pyindex fa3328db2..a454a4d08 100644--- a/backend/pipeline_v2/pipeline_processor.py+++ b/backend/pipeline_v2/pipeline_processor.py@@ -4,6 +4,7 @@ from typing import Optionalfrom django.utils import timezonefrom pipeline_v2.exceptions import InactivePipelineErrorfrom pipeline_v2.models import Pipeline+from pipeline_v2.notification import PipelineNotificationlogger = logging.getLogger(__name__)@@ -27,6 +28,9 @@ class PipelineProcessor:@staticmethoddef fetch_pipeline(pipeline_id: str, check_active: bool = True) -> Pipeline:"""Retrieves and checks for an active pipeline.+ Args:+ pipeline_id (str): UUID of the pipeline+ check_active (bool): Whether to check if the pipeline is activeRaises:InactivePipelineError: If an active pipeline is not found@@ -37,6 +41,14 @@ class PipelineProcessor:raise InactivePipelineError(pipeline_name=pipeline.pipeline_name)return pipeline+ @classmethod+ def get_active_pipeline(cls, pipeline_id: str) -> Optional[Pipeline]:+ """Retrieves a list of active pipelines."""+ try:+ return cls.fetch_pipeline(pipeline_id, check_active=True)+ except Pipeline.DoesNotExist:+ return None+@staticmethoddef _update_pipeline_status(pipeline: Pipeline,@@ -62,11 +74,32 @@ class PipelineProcessor:pipeline.save()return pipeline+ @staticmethod+ def _send_notification(+ pipeline: Pipeline,+ execution_id: Optional[str] = None,+ error_message: Optional[str] = None,+ ) -> None:+ """Sends a notification for the pipeline.+ Args:+ pipeline (Pipeline): Pipeline to send notification for++ Returns:+ None+ """+ pipeline_notification = PipelineNotification(+ pipeline=pipeline, execution_id=execution_id, error_message=error_message+ )+ pipeline_notification.send()+@staticmethoddef update_pipeline(pipeline_guid: Optional[str],status: tuple[str, str],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@@ -75,7 +108,10 @@ class PipelineProcessor: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+ pipeline = PipelineProcessor._update_pipeline_status(+ pipeline=pipeline, is_end=is_end, status=status, is_active=is_active+ )+ PipelineProcessor._send_notification(+ pipeline=pipeline, execution_id=execution_id, error_message=error_message)logger.info(f"Updated pipeline {pipeline_guid} status: {status}")diff --git a/backend/pipeline_v2/public_api_urls.py b/backend/pipeline_v2/public_api_urls.pynew file mode 100644index 000000000..c6d9838c2--- /dev/null+++ b/backend/pipeline_v2/public_api_urls.py@@ -0,0 +1,15 @@+from django.urls import re_path+from pipeline_v2.piepline_api_execution_views import PipelineApiExecution+from rest_framework.urlpatterns import format_suffix_patterns++execute = PipelineApiExecution.as_view()++urlpatterns = format_suffix_patterns(+ [+ re_path(+ r"^api/(?P<org_name>[\w-]+)/(?P<pipeline_id>[\w-]+)/?$",+ execute,+ name="pipeline_api_deployment_execution",+ ),+ ]+)diff --git a/backend/pipeline_v2/serializers/crud.py b/backend/pipeline_v2/serializers/crud.pyindex ed3360b94..39420e7dd 100644--- a/backend/pipeline_v2/serializers/crud.py+++ b/backend/pipeline_v2/serializers/crud.py@@ -1,13 +1,17 @@import loggingfrom collections import OrderedDict-from typing import Any+from typing import Any, Optionalfrom connector_processor.connector_processor import ConnectorProcessorfrom connector_v2.connector_instance_helper import ConnectorInstanceHelperfrom connector_v2.models import ConnectorInstance+from croniter import croniter+from django.conf import settingsfrom pipeline_v2.constants import PipelineConstants as PCfrom pipeline_v2.constants import PipelineKey as PKfrom pipeline_v2.models import Pipeline+from rest_framework import serializers+from rest_framework.serializers import SerializerMethodFieldfrom scheduler.helper import SchedulerHelperfrom utils.serializer_utils import SerializerUtilsfrom workflow_manager.endpoint_v2.models import WorkflowEndpoint@@ -16,26 +20,94 @@ from backend.serializers import AuditSerializerfrom unstract.connectors.connectorkit import Connectorkitlogger = logging.getLogger(__name__)+DEPLOYMENT_ENDPOINT = settings.API_DEPLOYMENT_PATH_PREFIX + "/pipeline"class PipelineSerializer(AuditSerializer):+ api_endpoint = SerializerMethodField()+class Meta:model = Pipelinefields = "__all__"+ def validate_cron_string(self, value: Optional[str] = None) -> Optional[str]:+ """Validate the cron string provided in the serializer data.++ This method is called internally by the serializer to ensure that+ the cron string is well-formed and adheres to the correct format.+ If the cron string is valid, it is returned. If the string is None+ or empty, it returns None. If the string is invalid, a+ ValidationError is raised.++ Args:+ value (Optional[str], optional): The cron string to validate.+ Defaults to None.++ Raises:+ serializers.ValidationError: Raised if the cron string is+ not in a valid format.++ Returns:+ Optional[str]: The validated cron string if it is valid,+ otherwise None.+ """+ if value is None:+ return None+ cron_string = value.strip()+ # Check if the string is empty+ if not cron_string:+ return None++ # Validate the cron string+ try:+ croniter(cron_string)+ except Exception as error:+ logger.error(f"Invalid cron string '{cron_string}': {error}")+ raise serializers.ValidationError("Invalid cron string format.")++ # Check if the frequency is less than 1 hour+ cron_parts = cron_string.split()+ minute_field = cron_parts[0]+ if minute_field == "*" or any(char in minute_field for char in [",", "-", "/"]):+ raise serializers.ValidationError(+ "Cron schedule can not be more than once per hour. Please provide a "+ "cron schedule to run at an hourly or less frequent interval."+ )++ return cron_string++ def get_api_endpoint(self, instance: Pipeline):+ """Retrieve the API endpoint URL for a given Pipeline instance.++ This method is an internal serializer call that fetches the+ `api_endpoint` property from the provided Pipeline instance.++ Args:+ instance (Pipeline): The Pipeline instance for which the API+ endpoint URL is being retrieved.++ Returns:+ str: The API endpoint URL associated with the Pipeline instance.+ """+ return instance.api_endpoint+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 PK.CRON_STRING in self.validated_data:+ if self.validated_data[PK.CRON_STRING]:+ self.validated_data[PK.SCHEDULED] = True+ else:+ self.validated_data[PK.SCHEDULED] = Falsepipeline: Pipeline = super().save(**kwargs)- SchedulerHelper.add_job(- str(pipeline.pk),- cron_string=pipeline.cron_string,- )+ if pipeline.cron_string is None:+ SchedulerHelper.remove_job(pipeline_id=str(pipeline.id))+ else:+ SchedulerHelper.add_or_update_job(pipeline)return pipelinedef _get_name_and_icon(self, connectors: list[Any], connector_id: Any) -> Any:diff --git a/backend/pipeline_v2/urls.py b/backend/pipeline_v2/urls.pyindex d6950633d..5763fb17e 100644--- a/backend/pipeline_v2/urls.py+++ b/backend/pipeline_v2/urls.py@@ -24,6 +24,12 @@ pipeline_detail = PipelineViewSet.as_view(})+download_postman_collection = PipelineViewSet.as_view(+ {+ "get": PipelineViewSet.download_postman_collection.__name__,+ }+)+pipeline_execute = PipelineViewSet.as_view({"post": "execute"})@@ -37,5 +43,10 @@ urlpatterns = format_suffix_patterns(name=PipelineURL.EXECUTIONS,),path("pipeline/execute/", pipeline_execute, name=PipelineURL.EXECUTE),+ path(+ "pipeline/api/postman_collection/<uuid:pk>/",+ download_postman_collection,+ name="download_pipeline_postman_collection",+ ),])diff --git a/backend/pipeline_v2/views.py b/backend/pipeline_v2/views.pyindex 553b0179a..fecc23163 100644--- a/backend/pipeline_v2/views.py+++ b/backend/pipeline_v2/views.py@@ -1,9 +1,14 @@+import jsonimport logging-from typing import Any, Optional+from typing import Optionalfrom account_v2.custom_exceptions import DuplicateData+from api_v2.exceptions import NoActiveAPIKeyError+from api_v2.key_helper import KeyHelper+from api_v2.postman_collection.dto import PostmanCollectionfrom django.db import IntegrityErrorfrom django.db.models import QuerySet+from django.http import HttpResponsefrom permissions.permission import IsOwnerfrom pipeline_v2.constants import (PipelineConstants,@@ -18,8 +23,8 @@ from pipeline_v2.serializers.crud import PipelineSerializerfrom pipeline_v2.serializers.execute import (PipelineExecuteSerializer as ExecuteSerializer,)-from pipeline_v2.serializers.update import PipelineUpdateSerializerfrom rest_framework import serializers, status, viewsets+from rest_framework.decorators import actionfrom rest_framework.request import Requestfrom rest_framework.response import Responsefrom rest_framework.versioning import URLPathVersioning@@ -78,7 +83,9 @@ class PipelineViewSet(viewsets.ModelViewSet):serializer = self.get_serializer(data=request.data)serializer.is_valid(raise_exception=True)try:- serializer.save()+ pipeline_instance = serializer.save()+ # Create API key using the created instance+ KeyHelper.create_api_key(pipeline_instance)except IntegrityError:raise DuplicateData(f"{PipelineErrors.PIPELINE_EXISTS}, " f"{PipelineErrors.DUPLICATE_API}"@@ -90,29 +97,25 @@ class PipelineViewSet(viewsets.ModelViewSet):super().perform_destroy(instance)return SchedulerHelper.remove_job(pipeline_to_remove)- def partial_update(self, request: Request, pk: Any = None) -> Response:- serializer = PipelineUpdateSerializer(data=request.data)- if serializer.is_valid():- pipeline_id = serializer.validated_data.get("pipeline_id")- active = serializer.validated_data.get("active")- try:- if active:- SchedulerHelper.resume_job(pipeline_id)- else:- SchedulerHelper.pause_job(pipeline_id)- except Exception as e:- logger.error(f"Failed to update pipeline status: {e}")- return Response(- {"error": "Failed to update pipeline status"},- status=status.HTTP_500_INTERNAL_SERVER_ERROR,- )+ @action(detail=True, methods=["get"])+ def download_postman_collection(+ self, request: Request, pk: Optional[str] = None+ ) -> Response:+ """Downloads a Postman Collection of the API deployment instance."""+ instance: Pipeline = self.get_object()+ api_key_inst = instance.apikey_set.filter(is_active=True).first()+ if not api_key_inst:+ logger.error(f"No active API key set for pipeline {instance}")+ raise NoActiveAPIKeyError(deployment_name=instance.pipeline_name)- return Response(- {- "status": "success",- "message": f"Pipeline {pipeline_id} status updated",- },- status=status.HTTP_200_OK,- )- else:- return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)+ # Create a PostmanCollection for a Pipeline+ postman_collection = PostmanCollection.create(+ instance=instance, api_key=api_key_inst.api_key+ )+ response = HttpResponse(+ json.dumps(postman_collection.to_dict()), content_type="application/json"+ )+ response["Content-Disposition"] = (+ f'attachment; filename="{instance.pipeline_name}.json"'+ )+ return response