LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
UN-2773 [FEAT] Add sharing functionality for API deployments (#1520)
Rahul Johny8480fad97ef3
diff --git a/backend/api_v2/api_deployment_views.py b/backend/api_v2/api_deployment_views.pyindex ac876548e..cd1ac0e5a 100644--- a/backend/api_v2/api_deployment_views.py+++ b/backend/api_v2/api_deployment_views.py@@ -5,7 +5,7 @@ from typing import Anyfrom configuration.models import Configurationfrom django.db.models import QuerySetfrom django.http import HttpResponse-from permissions.permission import IsOwner+from permissions.permission import IsOwner, IsOwnerOrSharedUserfrom prompt_studio.prompt_studio_registry_v2.models import PromptStudioRegistryfrom rest_framework import serializers, status, views, viewsetsfrom rest_framework.decorators import action@@ -28,8 +28,19 @@ from api_v2.serializers import (DeploymentResponseSerializer,ExecutionQuerySerializer,ExecutionRequestSerializer,+ SharedUserListSerializer,)+try:+ from plugins.notification.constants import ResourceType+ from plugins.notification.sharing_notification import SharingNotificationService++ NOTIFICATION_PLUGIN_AVAILABLE = True+ sharing_notification_service = SharingNotificationService()+except ImportError:+ NOTIFICATION_PLUGIN_AVAILABLE = False+ sharing_notification_service = None+logger = logging.getLogger(__name__)@@ -152,10 +163,13 @@ class DeploymentExecution(views.APIView):class APIDeploymentViewSet(viewsets.ModelViewSet):- permission_classes = [IsOwner]+ def get_permissions(self) -> list[Any]:+ if self.action in ["destroy", "partial_update", "update"]:+ return [IsOwner()]+ return [IsOwnerOrSharedUser()]def get_queryset(self) -> QuerySet | None:- queryset = APIDeployment.objects.filter(created_by=self.request.user)+ queryset = APIDeployment.objects.for_user(self.request.user)# Filter by workflow ID if providedworkflow_filter = self.request.query_params.get("workflow", None)@@ -252,3 +266,45 @@ class APIDeploymentViewSet(viewsets.ModelViewSet):f'attachment; filename="{instance.display_name}.json"')return response++ @action(detail=True, methods=["get"], permission_classes=[IsOwner])+ def list_of_shared_users(self, request: Request, pk: str | None = None) -> Response:+ """List users who have access to this API deployment."""+ instance = self.get_object()+ serializer = SharedUserListSerializer(instance)+ return Response(serializer.data)++ def partial_update(self, request: Request, *args: Any, **kwargs: Any) -> Response:+ """Override partial_update to handle sharing notifications."""+ # Get current instance and shared users+ instance = self.get_object()+ current_shared_users = set(instance.shared_users.all())++ # Perform the update+ response = super().partial_update(request, *args, **kwargs)++ # If successful and shared_users changed, send notifications+ if (+ response.status_code == 200+ and "shared_users" in request.data+ and NOTIFICATION_PLUGIN_AVAILABLE+ ):+ try:+ instance.refresh_from_db()+ new_shared_users = set(instance.shared_users.all())+ newly_shared_users = new_shared_users - current_shared_users++ if newly_shared_users:+ notification_service = SharingNotificationService()+ notification_service.send_sharing_notification(+ resource_type=ResourceType.API_DEPLOYMENT.value,+ resource_name=instance.display_name,+ resource_id=str(instance.id),+ shared_by=request.user,+ shared_to=list(newly_shared_users),+ resource_instance=instance,+ )+ except Exception as e:+ logger.exception(f"Failed to send sharing notification: {e}")++ return responsediff --git a/backend/api_v2/api_key_views.py b/backend/api_v2/api_key_views.pyindex b77d98826..67471dae4 100644--- a/backend/api_v2/api_key_views.py+++ b/backend/api_v2/api_key_views.py@@ -1,3 +1,4 @@+from permissions.permission import IsOwnerOrSharedUserfrom pipeline_v2.exceptions import PipelineNotFoundfrom pipeline_v2.pipeline_processor import PipelineProcessorfrom rest_framework import serializers, viewsets@@ -9,13 +10,12 @@ from api_v2.deployment_helper import DeploymentHelperfrom api_v2.exceptions import APINotFound, PathVariablesNotFoundfrom api_v2.key_helper import KeyHelperfrom api_v2.models import APIKey-from api_v2.permission import IsOwnerOrOrganizationMemberfrom api_v2.serializers import APIKeyListSerializer, APIKeySerializerclass APIKeyViewSet(viewsets.ModelViewSet):queryset = APIKey.objects.all()- permission_classes = [IsOwnerOrOrganizationMember]+ permission_classes = [IsOwnerOrSharedUser]def get_serializer_class(self) -> serializers.Serializer:if self.action in ["api_keys"]:diff --git a/backend/api_v2/migrations/0002_apideployment_shared_to_org_and_more.py b/backend/api_v2/migrations/0002_apideployment_shared_to_org_and_more.pynew file mode 100644index 000000000..5bd1a4f04--- /dev/null+++ b/backend/api_v2/migrations/0002_apideployment_shared_to_org_and_more.py@@ -0,0 +1,31 @@+# Generated by Django 4.2.1 on 2025-09-02 06:37++from django.conf import settings+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ migrations.swappable_dependency(settings.AUTH_USER_MODEL),+ ("api_v2", "0001_initial"),+ ]++ operations = [+ migrations.AddField(+ model_name="apideployment",+ name="shared_to_org",+ field=models.BooleanField(+ db_comment="Whether this API deployment is shared with the entire organization",+ default=False,+ ),+ ),+ migrations.AddField(+ model_name="apideployment",+ name="shared_users",+ field=models.ManyToManyField(+ blank=True,+ related_name="shared_api_deployments",+ to=settings.AUTH_USER_MODEL,+ ),+ ),+ ]diff --git a/backend/api_v2/models.py b/backend/api_v2/models.pyindex 0aeba5558..e4d67ec61 100644--- a/backend/api_v2/models.py+++ b/backend/api_v2/models.py@@ -20,7 +20,17 @@ API_ENDPOINT_MAX_LENGTH = 255class APIDeploymentModelManager(DefaultOrganizationManagerMixin, models.Manager):- pass+ def for_user(self, user):+ """Filter API deployments that the user can access:+ - API deployments created by the user+ - API deployments shared with the user+ """+ from django.db.models import Q++ return self.filter(+ Q(created_by=user) # Owned by user+ | Q(shared_users=user) # Shared with user+ ).distinct()class APIDeployment(DefaultOrganizationMixin, BaseModel):@@ -75,6 +85,14 @@ class APIDeployment(DefaultOrganizationMixin, BaseModel):blank=True,editable=False,)+ # Sharing fields+ shared_users = models.ManyToManyField(+ User, related_name="shared_api_deployments", blank=True+ )+ shared_to_org = models.BooleanField(+ default=False,+ db_comment="Whether this API deployment is shared with the entire organization",+ )# Managerobjects = APIDeploymentModelManager()diff --git a/backend/api_v2/serializers.py b/backend/api_v2/serializers.pyindex e7d1acabb..4f46784b6 100644--- a/backend/api_v2/serializers.py+++ b/backend/api_v2/serializers.py@@ -16,6 +16,7 @@ from rest_framework.serializers import (ListField,ModelSerializer,Serializer,+ SerializerMethodField,URLField,ValidationError,)@@ -391,6 +392,7 @@ class ExecutionQuerySerializer(Serializer):class APIDeploymentListSerializer(ModelSerializer):workflow_name = CharField(source="workflow.workflow_name", read_only=True)+ created_by_email = SerializerMethodField()class Meta:model = APIDeployment@@ -404,8 +406,13 @@ class APIDeploymentListSerializer(ModelSerializer):"api_endpoint","api_name","created_by",+ "created_by_email",]+ def get_created_by_email(self, obj):+ """Get the email of the creator."""+ return obj.created_by.email if obj.created_by else None+class APIKeyListSerializer(ModelSerializer):class Meta:@@ -437,3 +444,24 @@ class APIExecutionResponseSerializer(Serializer):status_api = CharField()error = CharField()result = JSONField()+++class SharedUserListSerializer(ModelSerializer):+ """Serializer for returning API deployment with shared user details."""++ shared_users = SerializerMethodField()+ created_by = SerializerMethodField()++ class Meta:+ model = APIDeployment+ fields = ["id", "display_name", "shared_users", "shared_to_org", "created_by"]++ def get_shared_users(self, obj):+ """Return list of shared users with id and email."""+ return [{"id": user.id, "email": user.email} for user in obj.shared_users.all()]++ def get_created_by(self, obj):+ """Return creator details."""+ if obj.created_by:+ return {"id": obj.created_by.id, "email": obj.created_by.email}+ return Nonediff --git a/backend/api_v2/urls.py b/backend/api_v2/urls.pyindex 57cf2a0a9..1e275ef9e 100644--- a/backend/api_v2/urls.py+++ b/backend/api_v2/urls.py@@ -28,6 +28,11 @@ by_prompt_studio_tool = APIDeploymentViewSet.as_view("get": APIDeploymentViewSet.by_prompt_studio_tool.__name__,})+list_shared_users = APIDeploymentViewSet.as_view(+ {+ "get": APIDeploymentViewSet.list_of_shared_users.__name__,+ }+)execute = DeploymentExecution.as_view()@@ -53,6 +58,11 @@ urlpatterns = format_suffix_patterns(deployment_details,name="api_deployment_details",),+ path(+ "deployment/<uuid:pk>/users/",+ list_shared_users,+ name="api_deployment_list_shared_users",+ ),path("deployment/by-prompt-studio-tool/",by_prompt_studio_tool,diff --git a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsxindex a211e07c1..99235ddca 100644--- a/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx+++ b/frontend/src/components/deployments/api-deployment/ApiDeployment.jsx@@ -8,6 +8,7 @@ import {CloudDownloadOutlined,FileSearchOutlined,NotificationOutlined,+ ShareAltOutlined,} from "@ant-design/icons";import { Button, Dropdown, Space, Switch, Tooltip, Typography } from "antd";import { useEffect, useState } from "react";@@ -24,6 +25,7 @@ import { DisplayCode } from "../display-code/DisplayCode";import { Layout } from "../layout/Layout";import { ManageKeys } from "../manage-keys/ManageKeys";import { PromptStudioModal } from "../../common/PromptStudioModal";+import { SharePermission } from "../../widgets/share-permission/SharePermission";import { apiDeploymentsService } from "./api-deployments-service";import { useExceptionHandler } from "../../../hooks/useExceptionHandler.jsx";import { LogsModal } from "../../pipelines-or-deployments/log-modal/LogsModal.jsx";@@ -61,6 +63,9 @@ function ApiDeployment() {const { getApiKeys, downloadPostmanCollection, copyUrl } =usePipelineHelper();const [openNotificationModal, setOpenNotificationModal] = useState(false);+ const [openShareModal, setOpenShareModal] = useState(false);+ const [allUsers, setAllUsers] = useState([]);+ const [isLoadingShare, setIsLoadingShare] = useState(false);const { count, isLoading, fetchCount } = usePromptStudioStore();const { getPromptStudioCount } = usePromptStudioService();@@ -141,6 +146,20 @@ function ApiDeployment() {),align: "left",},+ {+ title: "Owner",+ key: "created_by",+ render: (_, record) => {+ const currentUser = sessionDetails?.userId;+ const isOwner = record?.created_by === currentUser;+ return (+ <Space>+ {isOwner ? "You" : record?.created_by_email || "Unknown"}+ </Space>+ );+ },+ align: "left",+ },{title: "Enabled",key: "active",@@ -247,6 +266,61 @@ function ApiDeployment() {setOpenAddApiModal(true);};+ const handleShare = async () => {+ setIsLoadingShare(true);+ setOpenShareModal(true);+ // Fetch all users+ try {+ const [usersResponse, sharedUsersResponse] = await Promise.all([+ apiDeploymentsApiService.getAllUsers(),+ apiDeploymentsApiService.getSharedUsers(selectedRow.id),+ ]);++ const userList =+ usersResponse?.data?.members?.map((member) => ({+ id: member.id,+ email: member.email,+ })) || [];++ // Pass the complete user list - SharePermission component will handle filtering+ setAllUsers(userList);++ // Update selected row with shared user info for the SharePermission component+ const updatedSelectedRow = {+ ...selectedRow,+ ...sharedUsersResponse.data,+ };+ setSelectedRow(updatedSelectedRow);+ } catch (err) {+ setAlertDetails(+ handleException(err, `Unable to fetch sharing information`)+ );+ setOpenShareModal(false);+ } finally {+ setIsLoadingShare(false);+ }+ };++ const onShare = (sharedUsers, api, shareWithEveryone) => {+ setIsLoadingShare(true);+ apiDeploymentsApiService+ .updateSharing(selectedRow.id, sharedUsers, shareWithEveryone)+ .then(() => {+ setAlertDetails({+ type: "success",+ content: "Sharing permissions updated successfully",+ });+ setOpenShareModal(false);+ getApiDeploymentList(); // Refresh the list+ })+ .catch((err) => {+ setAlertDetails(handleException(err));+ })+ .finally(() => {+ setIsLoadingShare(false);+ });+ };+const actionItems = [// Configuration Section{@@ -292,6 +366,23 @@ function ApiDeployment() {},{key: "3",+ label: (+ <Space+ direction="horizontal"+ className="action-items"+ onClick={handleShare}+ >+ <div>+ <ShareAltOutlined />+ </div>+ <div>+ <Typography.Text>Share</Typography.Text>+ </div>+ </Space>+ ),+ },+ {+ key: "4",label: (<Spacedirection="horizontal"@@ -313,7 +404,7 @@ function ApiDeployment() {},// Operation Section{- key: "4",+ key: "5",label: (<Spacedirection="horizontal"@@ -346,7 +437,7 @@ function ApiDeployment() {},// Developer related Section{- key: "5",+ key: "6",label: (<Spacedirection="horizontal"@@ -363,7 +454,7 @@ function ApiDeployment() {),},{- key: "6",+ key: "7",label: (<Spacedirection="horizontal"@@ -387,7 +478,7 @@ function ApiDeployment() {},// Delete related section{- key: "7",+ key: "8",label: (<Spacedirection="horizontal"@@ -468,6 +559,16 @@ function ApiDeployment() {type={deploymentApiTypes.api}id={selectedRow?.id}/>+ <SharePermission+ open={openShareModal}+ setOpen={setOpenShareModal}+ adapter={selectedRow}+ permissionEdit={true}+ loading={isLoadingShare}+ allUsers={allUsers}+ onApply={onShare}+ isSharableToOrg={false}+ /></>);}diff --git a/frontend/src/components/deployments/api-deployment/api-deployments-service.js b/frontend/src/components/deployments/api-deployment/api-deployments-service.jsindex a2f6947c8..6fd9b752b 100644--- a/frontend/src/components/deployments/api-deployment/api-deployments-service.js+++ b/frontend/src/components/deployments/api-deployment/api-deployments-service.js@@ -96,6 +96,32 @@ function apiDeploymentsService() {};return axiosPrivate(options);},+ getSharedUsers: (id) => {+ options = {+ method: "GET",+ url: `${path}/api/deployment/${id}/users/`,+ };+ return axiosPrivate(options);+ },+ updateSharing: (id, sharedUsers, shareWithEveryone) => {+ options = {+ method: "PATCH",+ url: `${path}/api/deployment/${id}/`,+ headers: requestHeaders,+ data: {+ shared_users: sharedUsers,+ shared_to_org: shareWithEveryone,+ },+ };+ return axiosPrivate(options);+ },+ getAllUsers: () => {+ options = {+ method: "GET",+ url: `${path}/users/`,+ };+ return axiosPrivate(options);+ },};}