LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
Multitenancy v2 changes for prompt_studio_output_manager app (#712)
Deepak Ka5de7c07430f
diff --git a/backend/prompt_studio/prompt_studio_output_manager_v2/models.py b/backend/prompt_studio/prompt_studio_output_manager_v2/models.pyindex 0a9cd8bc7..ab946820b 100644--- a/backend/prompt_studio/prompt_studio_output_manager_v2/models.py+++ b/backend/prompt_studio/prompt_studio_output_manager_v2/models.py@@ -24,6 +24,9 @@ class PromptStudioOutputManager(BaseModel):context = models.TextField(db_comment="Field to store chunks used", editable=True, null=True, blank=True)+ challenge_data = models.JSONField(+ db_comment="Field to store challenge data", editable=True, null=True, blank=True+ )eval_metrics = models.JSONField(db_column="eval_metrics",null=False,diff --git a/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py b/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.pyindex 163dd781a..037974b79 100644--- a/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py+++ b/backend/prompt_studio/prompt_studio_output_manager_v2/output_manager_helper.py@@ -2,6 +2,7 @@ import jsonimport loggingfrom typing import Any, Optional+from django.core.exceptions import ObjectDoesNotExistfrom prompt_studio.prompt_profile_manager_v2.models import ProfileManagerfrom prompt_studio.prompt_studio_core_v2.exceptions import (AnswerFetchError,@@ -15,6 +16,9 @@ from prompt_studio.prompt_studio_output_manager_v2.constants import (from prompt_studio.prompt_studio_output_manager_v2.models import (PromptStudioOutputManager,)+from prompt_studio.prompt_studio_output_manager_v2.serializers import (+ PromptStudioOutputSerializer,+)from prompt_studio.prompt_studio_v2.models import ToolStudioPromptlogger = logging.getLogger(__name__)@@ -26,12 +30,13 @@ class OutputManagerHelper:run_id: str,prompts: list[ToolStudioPrompt],outputs: Any,- context: Any,document_id: str,is_single_pass_extract: bool,+ metadata: dict[str, Any],profile_manager_id: Optional[str] = None,- ) -> None:- """Handles updating prompt outputs in the database.+ ) -> list[dict[str, Any]]:+ """Handles updating prompt outputs in the database and returns+ serialized data.Args:run_id (str): ID of the run.@@ -39,8 +44,12 @@ class OutputManagerHelper:outputs (Any): Outputs corresponding to the prompts.document_id (str): ID of the document.profile_manager_id (Optional[str]): UUID of the profile manager.- is_single_pass_extract (bool):- Flag indicating if single pass extract is active.+ is_single_pass_extract (bool): Flag indicating if single pass+ extract is active.+ metadata (dict[str, Any]): Metadata for the update.++ Returns:+ list[dict[str, Any]]: List of serialized prompt output data."""def update_or_create_prompt_output(@@ -50,19 +59,25 @@ class OutputManagerHelper:eval_metrics: list[Any],tool: CustomTool,context: str,- ):+ challenge_data: Optional[dict[str, Any]],+ ) -> PromptStudioOutputManager:+ """Handles creating or updating a single prompt output and returns+ the instance."""try:- _, success = PromptStudioOutputManager.objects.get_or_create(- document_manager=document_manager,- tool_id=tool,- profile_manager=profile_manager,- prompt_id=prompt,- is_single_pass_extract=is_single_pass_extract,- defaults={- "output": output,- "eval_metrics": eval_metrics,- "context": context,- },+ prompt_output, success = (+ PromptStudioOutputManager.objects.get_or_create(+ document_manager=document_manager,+ tool_id=tool,+ profile_manager=profile_manager,+ prompt_id=prompt,+ is_single_pass_extract=is_single_pass_extract,+ defaults={+ "output": output,+ "eval_metrics": eval_metrics,+ "context": context,+ "challenge_data": challenge_data,+ },+ ))if success:@@ -76,11 +91,12 @@ class OutputManagerHelper:f"profile {profile_manager.profile_id}")- args: dict[str, str] = {+ args: dict[str, Any] = {"run_id": run_id,"output": output,"eval_metrics": eval_metrics,"context": context,+ "challenge_data": challenge_data,}PromptStudioOutputManager.objects.filter(document_manager=document_manager,@@ -90,11 +106,21 @@ class OutputManagerHelper:is_single_pass_extract=is_single_pass_extract,).update(**args)+ # Refresh the prompt_output instance to get updated values+ prompt_output.refresh_from_db()++ return prompt_output+except Exception as e:raise AnswerFetchError(f"Error updating prompt output {e}") from e+ # List to store serialized results+ serialized_data: list[dict[str, Any]] = []+ context = metadata.get("context")+ challenge_data = metadata.get("challenge_data")+if not prompts:- return # Return early if prompts list is empty+ return serialized_datatool = prompts[0].tool_iddefault_profile = OutputManagerHelper.get_default_profile(@@ -103,25 +129,40 @@ class OutputManagerHelper:document_manager = DocumentManager.objects.get(pk=document_id)for prompt in prompts:- if prompt.prompt_type == PSOMKeys.NOTES or not prompt.active:+ if prompt.prompt_type == PSOMKeys.NOTES:continueif not is_single_pass_extract:- context = json.dumps(context.get(prompt.prompt_key))+ context = context.get(prompt.prompt_key)+ if challenge_data:+ challenge_data = challenge_data.get(prompt.prompt_key)- output = json.dumps(outputs.get(prompt.prompt_key))+ if challenge_data:+ challenge_data["file_name"] = metadata.get("file_name")++ output = outputs.get(prompt.prompt_key)+ if prompt.enforce_type in {"json", "table"}:+ output = json.dumps(output)profile_manager = default_profileeval_metrics = outputs.get(f"{prompt.prompt_key}__evaluation", [])- update_or_create_prompt_output(+ # Update or create the prompt output+ prompt_output = update_or_create_prompt_output(prompt=prompt,profile_manager=profile_manager,output=output,eval_metrics=eval_metrics,tool=tool,context=context,+ challenge_data=challenge_data,)+ # Serialize the instance+ serializer = PromptStudioOutputSerializer(prompt_output)+ serialized_data.append(serializer.data)++ return serialized_data+@staticmethoddef get_default_profile(profile_manager_id: Optional[str], tool: CustomTool@@ -146,3 +187,49 @@ class OutputManagerHelper:return ProfileManager.get_default_llm_profile(tool=tool)except DefaultProfileError:raise DefaultProfileError("Default ProfileManager does not exist.")++ @staticmethod+ def fetch_default_output_response(+ tool_studio_prompts: list[ToolStudioPrompt], document_manager_id: str+ ) -> dict[str, Any]:+ """Method to frame JSON responses for combined output for default for+ default profile manager of the project.++ Args:+ tool_studio_prompts (list[ToolStudioPrompt])+ document_manager_id (str)++ Returns:+ dict[str, Any]: Formatted JSON response for combined output.+ """+ # Initialize the result dictionary+ result: dict[str, Any] = {}+ # Iterate over ToolStudioPrompt records+ for tool_prompt in tool_studio_prompts:+ if tool_prompt.prompt_type == PSOMKeys.NOTES:+ continue+ prompt_id = str(tool_prompt.prompt_id)+ profile_manager_id = tool_prompt.profile_manager_id++ # If profile_manager is not set, skip this record+ if not profile_manager_id:+ result[tool_prompt.prompt_key] = ""+ continue++ try:+ queryset = PromptStudioOutputManager.objects.filter(+ prompt_id=prompt_id,+ profile_manager=profile_manager_id,+ is_single_pass_extract=False,+ document_manager_id=document_manager_id,+ )++ if not queryset.exists():+ result[tool_prompt.prompt_key] = ""+ continue++ for output in queryset:+ result[tool_prompt.prompt_key] = output.output+ except ObjectDoesNotExist:+ result[tool_prompt.prompt_key] = ""+ return resultdiff --git a/backend/prompt_studio/prompt_studio_output_manager_v2/views.py b/backend/prompt_studio/prompt_studio_output_manager_v2/views.pyindex 441100d90..5ede4bb09 100644--- a/backend/prompt_studio/prompt_studio_output_manager_v2/views.py+++ b/backend/prompt_studio/prompt_studio_output_manager_v2/views.py@@ -8,6 +8,9 @@ from prompt_studio.prompt_studio_output_manager_v2.constants import (PromptOutputManagerErrorMessage,PromptStudioOutputManagerKeys,)+from prompt_studio.prompt_studio_output_manager_v2.output_manager_helper import (+ OutputManagerHelper,+)from prompt_studio.prompt_studio_output_manager_v2.serializers import (PromptStudioOutputSerializer,)@@ -57,8 +60,8 @@ class PromptStudioOutputView(viewsets.ModelViewSet):return querysetdef get_output_for_tool_default(self, request: HttpRequest) -> Response:- # TODO: Setup Serializer here# Get the tool_id from request parameters+ # TODO: Setup Serializer heretool_id = request.GET.get("tool_id")document_manager_id = request.GET.get("document_manager")tool_validation_message = PromptOutputManagerErrorMessage.TOOL_VALIDATION@@ -68,38 +71,16 @@ class PromptStudioOutputView(viewsets.ModelViewSet):try:# Fetch ToolStudioPrompt records based on tool_id- tool_studio_prompts = ToolStudioPrompt.objects.filter(tool_id=tool_id)+ tool_studio_prompts = ToolStudioPrompt.objects.filter(+ tool_id=tool_id+ ).order_by("sequence_number")except ObjectDoesNotExist:raise APIException(detail=tool_not_found, code=400)- # Initialize the result dictionary- result: dict[str, Any] = {}-- # Iterate over ToolStudioPrompt records- for tool_prompt in tool_studio_prompts:- prompt_id = str(tool_prompt.prompt_id)- profile_manager_id = str(tool_prompt.profile_manager.profile_id)-- # If profile_manager is not set, skip this record- if not profile_manager_id:- result[tool_prompt.prompt_key] = ""- continue-- try:- queryset = PromptStudioOutputManager.objects.filter(- prompt_id=prompt_id,- profile_manager=profile_manager_id,- is_single_pass_extract=False,- document_manager_id=document_manager_id,- )-- if not queryset.exists():- result[tool_prompt.prompt_key] = ""- continue-- for output in queryset:- result[tool_prompt.prompt_key] = output.output- except ObjectDoesNotExist:- result[tool_prompt.prompt_key] = ""+ # Invoke helper method to frame and fetch default response.+ result: dict[str, Any] = OutputManagerHelper.fetch_default_output_response(+ tool_studio_prompts=tool_studio_prompts,+ document_manager_id=document_manager_id,+ )return Response(result, status=status.HTTP_200_OK)