LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows
Python ai-agentsdata-engineeringdocument-aigenerative-aiidpjson-extractionllmmcp-serverocrpdf-extractionprompt-engineeringstructured-output
feat: Backend - prompt service plumbing for error handling (#315)
Chandrasekharan M57d1470d7671
diff --git a/backend/prompt_studio/prompt_studio/exceptions.py b/backend/prompt_studio/prompt_studio/exceptions.pyindex 885ee092f..dd4140151 100644--- a/backend/prompt_studio/prompt_studio/exceptions.py+++ b/backend/prompt_studio/prompt_studio/exceptions.py@@ -6,11 +6,6 @@ class IndexingError(APIException):default_detail = "Error while indexing file"-class FilenameMissingError(APIException):- status_code = 400- default_detail = "No file selected to parse."--class AnswerFetchError(APIException):status_code = 400default_detail = "Error occured while fetching response for the prompt"diff --git a/backend/prompt_studio/prompt_studio_core/constants.py b/backend/prompt_studio/prompt_studio_core/constants.pyindex 806afd3e7..b1947ba31 100644--- a/backend/prompt_studio/prompt_studio_core/constants.py+++ b/backend/prompt_studio/prompt_studio_core/constants.py@@ -29,7 +29,6 @@ class ToolStudioPromptKeys:ID = "id"FILE_NAME = "file_name"FILE_HASH = "file_hash"- UNDEFINED = "undefined"TOOL_ID = "tool_id"NAME = "name"ACTIVE = "active"diff --git a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.pyindex 2b858bb11..7bca616e2 100644--- a/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py+++ b/backend/prompt_studio/prompt_studio_core/prompt_studio_helper.py@@ -24,13 +24,13 @@ from prompt_studio.prompt_studio_core.exceptions import ()from prompt_studio.prompt_studio_core.models import CustomToolfrom prompt_studio.prompt_studio_core.prompt_ide_base_tool import PromptIdeBaseTool+from prompt_studio.prompt_studio_document_manager.models import DocumentManagerfrom prompt_studio.prompt_studio_index_manager.prompt_studio_index_helper import ( # noqa: E501PromptStudioIndexHelper,)from prompt_studio.prompt_studio_output_manager.output_manager_helper import (OutputManagerHelper,)-from rest_framework.exceptions import APIExceptionfrom unstract.sdk.constants import LogLevelfrom unstract.sdk.exceptions import IndexingErrorfrom unstract.sdk.index import ToolIndex@@ -294,7 +294,6 @@ class PromptStudioHelper:@staticmethoddef prompt_responder(tool_id: str,- file_name: str,org_id: str,user_id: str,document_id: str,@@ -304,11 +303,11 @@ class PromptStudioHelper:service and returns the dict of response.Args:- id (Optional[str]): ID of the prompttool_id (str): ID of tool created in prompt studio- file_name (str): Name of the file uploadedorg_id (str): Organization IDuser_id (str): User's ID+ document_id (str): UUID of the document uploaded+ id (Optional[str]): ID of the promptRaises:PromptNotValid: If a prompt could not be queried from the DB@@ -317,13 +316,16 @@ class PromptStudioHelper:Returns:Any: Dictionary containing the response from prompt-service"""- file_path = FileManagerHelper.handle_sub_directory_for_tenants(+ document: DocumentManager = DocumentManager.objects.get(pk=document_id)+ doc_name: str = document.document_name++ doc_path = FileManagerHelper.handle_sub_directory_for_tenants(org_id=org_id,user_id=user_id,tool_id=tool_id,is_create=False,)- file_path = str(Path(file_path) / file_name)+ doc_path = str(Path(doc_path) / doc_name)if id:prompt_instance = PromptStudioHelper._fetch_prompt_from_id(id)@@ -333,7 +335,7 @@ class PromptStudioHelper:logger.info(f"[{tool_id}] Executing single prompt {id}")PromptStudioHelper._publish_log(- {"tool_id": tool_id, "prompt_id": id, "doc_name": file_name},+ {"tool_id": tool_id, "prompt_id": id, "doc_name": doc_name},LogLevels.INFO,LogLevels.RUN,"Executing single prompt",@@ -344,8 +346,8 @@ class PromptStudioHelper:tool: CustomTool = prompt_instance.tool_idif tool.summarize_as_source:- directory, filename = os.path.split(file_path)- file_path = os.path.join(+ directory, filename = os.path.split(doc_path)+ doc_path = os.path.join(directory,TSPKeys.SUMMARIZE,os.path.splitext(filename)[0] + ".txt",@@ -353,7 +355,7 @@ class PromptStudioHelper:logger.info(f"[{tool.tool_id}] Invoking prompt service for prompt {id}")PromptStudioHelper._publish_log(- {"tool_id": tool_id, "prompt_id": id, "doc_name": file_name},+ {"tool_id": tool_id, "prompt_id": id, "doc_name": doc_name},LogLevels.DEBUG,LogLevels.RUN,"Invoking prompt service",@@ -361,7 +363,8 @@ class PromptStudioHelper:try:response = PromptStudioHelper._fetch_response(- path=file_path,+ doc_path=doc_path,+ doc_name=doc_name,tool=tool,prompts=prompts,org_id=org_id,@@ -374,22 +377,17 @@ class PromptStudioHelper:document_id=document_id,is_single_pass_extract=False,)- except PermissionError as e:- raise e- except Exception as exc:+ except Exception as e:logger.error(- f"[{tool.tool_id}] Error while fetching response for prompt {id}: {exc}" # noqa: E501+ f"[{tool.tool_id}] Error while fetching response for prompt {id}: {e}" # noqa: E501)PromptStudioHelper._publish_log({"tool_id": tool_id, "prompt_id": id},LogLevels.ERROR,LogLevels.RUN,- "Failed to fetch prompt response",+ f"Failed to fetch prompt response. {e}",)- # TODO: Catch specific exceptions and remove this- if isinstance(exc, APIException):- raise exc- raise AnswerFetchError()+ raise elogger.info(f"[{tool.tool_id}] Response fetched successfully for prompt {id}" # noqa: E501@@ -422,7 +420,7 @@ class PromptStudioHelper:try:tool = prompts[0].tool_idresponse = PromptStudioHelper._fetch_single_pass_response(- file_path=file_path,+ file_path=doc_path,tool=tool,prompts=prompts,org_id=org_id,@@ -435,22 +433,6 @@ class PromptStudioHelper:document_id=document_id,is_single_pass_extract=True,)- except PermissionError as e:- raise e- except AnswerFetchError as e:- error_message = str(e)- logger.error(- "[%s] Error while fetching single pass response: %s",- tool_id,- error_message,- )- PromptStudioHelper._publish_log(- {"tool_id": tool_id, "prompt_id": str(id)},- LogLevels.ERROR,- LogLevels.RUN,- error_message,- )- raiseexcept Exception as e:logger.error(f"[{tool.tool_id}] Error while fetching single pass response: {e}" # noqa: E501@@ -459,9 +441,9 @@ class PromptStudioHelper:{"tool_id": tool_id, "prompt_id": str(id)},LogLevels.ERROR,LogLevels.RUN,- "Failed to fetch single pass response",+ f"Failed to fetch single pass response. {e}",)- raise AnswerFetchError()+ raise elogger.info(f"[{tool.tool_id}] Single pass response fetched successfully")PromptStudioHelper._publish_log(@@ -476,7 +458,8 @@ class PromptStudioHelper:@staticmethoddef _fetch_response(tool: CustomTool,- path: str,+ doc_path: str,+ doc_name: str,prompts: list[ToolStudioPrompt],org_id: str,document_id: str,@@ -484,12 +467,19 @@ class PromptStudioHelper:"""Utility function to invoke prompt service. Used internally.Args:- tool (CustomTool)- path (str)- prompt (dict)+ tool (CustomTool): CustomTool instance (prompt studio project)+ doc_path (str): Path to the document+ doc_name (str): Name of the document+ prompts (list[ToolStudioPrompt]): List of prompts to fetch responses for+ org_id (str): UUID of the organization+ document_id (str): UUID of the documentRaises:- AnswerFetchError+ DefaultProfileError: If no default profile is selected+ AnswerFetchError: Due to failures in prompt service++ Returns:+ Any: Output from LLM"""monitor_llm_instance: Optional[AdapterInstance] = tool.monitor_llmmonitor_llm: Optional[str] = None@@ -541,7 +531,7 @@ class PromptStudioHelper:raise DefaultProfileError()PromptStudioHelper.dynamic_indexer(profile_manager=prompt_profile_manager,- file_path=path,+ file_path=doc_path,tool_id=str(tool.tool_id),org_id=org_id,document_id=document_id,@@ -595,12 +585,12 @@ class PromptStudioHelper:tool_id = str(tool.tool_id)- file_hash = ToolUtils.get_hash_from_file(file_path=path)+ file_hash = ToolUtils.get_hash_from_file(file_path=doc_path)payload = {TSPKeys.OUTPUTS: outputs,TSPKeys.TOOL_ID: tool_id,- TSPKeys.FILE_NAME: path,+ TSPKeys.FILE_NAME: doc_name,TSPKeys.FILE_HASH: file_hash,Common.LOG_EVENTS_ID: StateStore.get(Common.LOG_EVENTS_ID),}@@ -616,7 +606,10 @@ class PromptStudioHelper:answer = responder.answer_prompt(payload)# TODO: Make use of dataclassesif answer["status"] == "ERROR":- raise AnswerFetchError()+ error_message = answer.get("error", None)+ raise AnswerFetchError(+ f"Error while fetching response for prompt. {error_message}"+ )output_response = json.loads(answer["structure_output"])return output_response@@ -796,6 +789,8 @@ class PromptStudioHelper:# TODO: Make use of dataclassesif answer["status"] == "ERROR":error_message = answer.get("error", None)- raise AnswerFetchError(error_message)+ raise AnswerFetchError(+ f"Error while fetching response for prompt. {error_message}"+ )output_response = json.loads(answer["structure_output"])return output_responsediff --git a/backend/prompt_studio/prompt_studio_core/views.py b/backend/prompt_studio/prompt_studio_core/views.pyindex 9b7ffee85..e98adf651 100644--- a/backend/prompt_studio/prompt_studio_core/views.py+++ b/backend/prompt_studio/prompt_studio_core/views.py@@ -14,7 +14,6 @@ from prompt_studio.prompt_profile_manager.constants import ProfileManagerErrorsfrom prompt_studio.prompt_profile_manager.models import ProfileManagerfrom prompt_studio.prompt_profile_manager.serializers import ProfileManagerSerializerfrom prompt_studio.prompt_studio.constants import ToolStudioPromptErrors-from prompt_studio.prompt_studio.exceptions import FilenameMissingErrorfrom prompt_studio.prompt_studio.serializers import ToolStudioPromptSerializerfrom prompt_studio.prompt_studio_core.constants import (FileViewTypes,@@ -249,17 +248,11 @@ class PromptStudioCoreView(viewsets.ModelViewSet):custom_tool = self.get_object()tool_id: str = str(custom_tool.tool_id)document_id: str = request.data.get(ToolStudioPromptKeys.DOCUMENT_ID)- document: DocumentManager = DocumentManager.objects.get(pk=document_id)- file_name: str = document.document_nameid: str = request.data.get(ToolStudioPromptKeys.ID)- if not file_name or file_name == ToolStudioPromptKeys.UNDEFINED:- logger.error("Mandatory field file_name is missing")- raise FilenameMissingError()response: dict[str, Any] = PromptStudioHelper.prompt_responder(id=id,tool_id=tool_id,- file_name=file_name,org_id=UserSessionUtils.get_organization_id(request),user_id=custom_tool.created_by.user_id,document_id=document_id,@@ -274,9 +267,6 @@ class PromptStudioCoreView(viewsets.ModelViewSet):request (HttpRequest): _description_pk (Any): Primary key of the CustomTool- Raises:- FilenameMissingError: _description_-Returns:Response"""@@ -285,15 +275,9 @@ class PromptStudioCoreView(viewsets.ModelViewSet):custom_tool = self.get_object()tool_id: str = str(custom_tool.tool_id)document_id: str = request.data.get(ToolStudioPromptKeys.DOCUMENT_ID)- document: DocumentManager = DocumentManager.objects.get(pk=document_id)- file_name: str = document.document_name- if not file_name or file_name == ToolStudioPromptKeys.UNDEFINED:- logger.error("Mandatory field file_name is missing")- raise FilenameMissingError()response: dict[str, Any] = PromptStudioHelper.prompt_responder(tool_id=tool_id,- file_name=file_name,org_id=UserSessionUtils.get_organization_id(request),user_id=custom_tool.created_by.user_id,document_id=document_id,diff --git a/prompt-service/src/unstract/prompt_service/exceptions.py b/prompt-service/src/unstract/prompt_service/exceptions.pynew file mode 100644index 000000000..ed75f438f--- /dev/null+++ b/prompt-service/src/unstract/prompt_service/exceptions.py@@ -0,0 +1,44 @@+from dataclasses import asdict, dataclass+from typing import Any, Optional++from werkzeug.exceptions import HTTPException++DEFAULT_ERR_MESSAGE = "Something went wrong"+++@dataclass+class ErrorResponse:+ """Represents error response from prompt service."""++ error: str = DEFAULT_ERR_MESSAGE+ name: str = "PromptServiceError"+ code: int = 500+ payload: Optional[Any] = None+++class APIError(HTTPException):+ code = 500++ def __init__(+ self,+ message: str = DEFAULT_ERR_MESSAGE,+ code: Optional[int] = None,+ payload: Any = None,+ ):+ super().__init__(description=message)+ self.message = message+ if code is not None:+ self.code = code+ self.payload = payload++ def to_dict(self):+ err = ErrorResponse(+ error=self.message,+ code=self.code,+ payload=self.payload,+ name=self.__class__.__name__,+ )+ return asdict(err)++ def __str__(self):+ return str(self.message)diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.pyindex f20ac130c..9624702ae 100644--- a/prompt-service/src/unstract/prompt_service/main.py+++ b/prompt-service/src/unstract/prompt_service/main.py@@ -1,20 +1,23 @@import logging+import tracebackfrom enum import Enumfrom json import JSONDecodeErrorfrom typing import Any, Optionalimport peewee-from flask import Flask, json, request+from flask import Flask, json, jsonify, requestfrom llama_index.core import VectorStoreIndexfrom llama_index.core.llms import LLMfrom llama_index.core.vector_stores import ExactMatchFilter, MetadataFiltersfrom unstract.prompt_service.authentication_middleware import AuthenticationMiddlewarefrom unstract.prompt_service.constants import PromptServiceContants as PSKeysfrom unstract.prompt_service.constants import RunLevel+from unstract.prompt_service.exceptions import APIError, ErrorResponsefrom unstract.prompt_service.helper import EnvLoader, plugin_loaderfrom unstract.prompt_service.prompt_ide_base_tool import PromptServiceBaseToolfrom unstract.sdk.constants import LogLevelfrom unstract.sdk.embedding import ToolEmbedding+from unstract.sdk.exceptions import SdkErrorfrom unstract.sdk.index import ToolIndexfrom unstract.sdk.llm import ToolLLMfrom unstract.sdk.utils.callback_manager import CallbackManager as UNCallbackManager@@ -170,13 +173,14 @@ def prompt_processor() -> Any:outputs = payload.get(PSKeys.OUTPUTS)tool_id: str = payload.get(PSKeys.TOOL_ID, "")file_hash = payload.get(PSKeys.FILE_HASH)+ doc_name = str(payload.get(PSKeys.FILE_NAME, ""))log_events_id: str = payload.get(PSKeys.LOG_EVENTS_ID, "")structured_output: dict[str, Any] = {}variable_names: list[str] = []_publish_log(log_events_id,- {"tool_id": tool_id},+ {"tool_id": tool_id, "doc_name": doc_name},LogLevel.DEBUG,RunLevel.RUN,"Preparing to execute all prompts",@@ -186,7 +190,7 @@ def prompt_processor() -> Any:variable_names.append(output[PSKeys.NAME])for output in outputs: # type:ignoreactive = output[PSKeys.ACTIVE]- name = output[PSKeys.NAME]+ prompt_name = output[PSKeys.NAME]promptx = output[PSKeys.PROMPT]chunk_size = output[PSKeys.CHUNK_SIZE]util = PromptServiceBaseTool(log_level=LogLevel.INFO, platform_key=platform_key)@@ -194,20 +198,20 @@ def prompt_processor() -> Any:adapter_instance_id = output[PSKeys.LLM]if active is False:- app.logger.info(f"[{tool_id}] Skipping inactive prompt: {name}")+ app.logger.info(f"[{tool_id}] Skipping inactive prompt: {prompt_name}")_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.INFO,RunLevel.RUN,"Skipping inactive prompt",)continue- app.logger.info(f"[{tool_id}] Executing prompt: {name}")+ app.logger.info(f"[{tool_id}] Executing prompt: {prompt_name}")_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.DEBUG,RunLevel.RUN,"Executing prompt",@@ -231,65 +235,40 @@ def prompt_processor() -> Any:)_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.DEBUG,RunLevel.RUN,"Retrieved document ID",)- llm_helper = ToolLLM(tool=util)- llm_li: Optional[LLM] = llm_helper.get_llm(- adapter_instance_id=adapter_instance_id- )- if llm_li is None:- msg = f"Couldn't fetch LLM {adapter_instance_id}"- app.logger.error(msg)- _publish_log(- log_events_id,- {"tool_id": tool_id, "prompt_key": name},- LogLevel.ERROR,- RunLevel.RUN,- "Failed due to LLM error",- )- result["error"] = msg- return result, 500- embedd_helper = ToolEmbedding(tool=util)- embedding_li = embedd_helper.get_embedding(- adapter_instance_id=output[PSKeys.EMBEDDING]- )- if embedding_li is None:- msg = f"Couldn't fetch embedding {output[PSKeys.EMBEDDING]}"- app.logger.error(msg)- _publish_log(- log_events_id,- {"tool_id": tool_id, "prompt_key": name},- LogLevel.ERROR,- RunLevel.RUN,- "Failed due to embedding error",+ try:+ llm_helper = ToolLLM(tool=util)+ llm_li: LLM = llm_helper.get_llm(adapter_instance_id=adapter_instance_id)+ embedd_helper = ToolEmbedding(tool=util)+ embedding_li = embedd_helper.get_embedding(+ adapter_instance_id=output[PSKeys.EMBEDDING])- result["error"] = msg- return result, 500- embedding_dimension = embedd_helper.get_embedding_length(embedding_li)+ embedding_dimension = embedd_helper.get_embedding_length(embedding_li)- vdb_helper = ToolVectorDB(- tool=util,- )- vector_db_li = vdb_helper.get_vector_db(- adapter_instance_id=output[PSKeys.VECTOR_DB],- embedding_dimension=embedding_dimension,- )- if vector_db_li is None:- msg = f"Couldn't fetch vector DB {output[PSKeys.VECTOR_DB]}"+ vdb_helper = ToolVectorDB(+ tool=util,+ )+ vector_db_li = vdb_helper.get_vector_db(+ adapter_instance_id=output[PSKeys.VECTOR_DB],+ embedding_dimension=embedding_dimension,+ )+ except SdkError as e:+ msg = f"Couldn't fetch adapter. {e}"app.logger.error(msg)- result["error"] = msg_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.ERROR,RunLevel.RUN,- "Failed due to vector db error",+ "Unable to obtain LLM / embedding / vectorDB",)- return result, 500+ return APIError(message=msg)+# Set up llm, embedding and callback manager to collect usage stats# for this contextUNCallbackManager.set_callback_manager(@@ -308,27 +287,27 @@ def prompt_processor() -> Any:doc_id=doc_id,)if context is None:- msg = (- "Couldn't fetch context from"- f" vector DB {output[PSKeys.VECTOR_DB]}"- )- app.logger.error(msg)- result["error"] = msg- # TODO: Try to fill doc_name also here+ # TODO: Obtain user set name for vector DB+ msg = "Couldn't fetch context from vector DB"+ app.logger.error(msg + f" {output[PSKeys.VECTOR_DB]}")_publish_log(log_events_id,- {"tool_id": tool_id},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.ERROR,RunLevel.RUN,- "Couldn't fetch context from vector DB",+ msg,)- return result, 500+ raise APIError(message=msg)assertion_failed = Falseanswer = "yes"_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.DEBUG,RunLevel.RUN,"Verifying assertion prompt",@@ -349,7 +328,7 @@ def prompt_processor() -> Any:app.logger.info("Assert failed.")_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.DEBUG,RunLevel.RUN,"Assertion failed",@@ -385,7 +364,11 @@ def prompt_processor() -> Any:answer = "NA"_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.INFO,RunLevel.RUN,"Retrieving context from adapter",@@ -407,7 +390,11 @@ def prompt_processor() -> Any:_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.DEBUG,RunLevel.RUN,"Retrieved context from adapter",@@ -415,7 +402,7 @@ def prompt_processor() -> Any:_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {"tool_id": tool_id, "prompt_key": prompt_name, "doc_name": doc_name},LogLevel.INFO,RunLevel.RUN,f"Processing prompt type: {output[PSKeys.TYPE]}",@@ -574,7 +561,11 @@ def prompt_processor() -> Any:if eval_plugin:_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.INFO,RunLevel.EVAL,"Evaluating response",@@ -598,7 +589,11 @@ def prompt_processor() -> Any:)_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.ERROR,RunLevel.EVAL,"Error while evaluation",@@ -606,7 +601,11 @@ def prompt_processor() -> Any:else:_publish_log(log_events_id,- {"tool_id": tool_id, "prompt_key": name},+ {+ "tool_id": tool_id,+ "prompt_key": prompt_name,+ "doc_name": doc_name,+ },LogLevel.DEBUG,RunLevel.EVAL,"Evaluation completed",@@ -618,7 +617,7 @@ def prompt_processor() -> Any:_publish_log(log_events_id,- {"tool_id": tool_id},+ {"tool_id": tool_id, "doc_name": doc_name},LogLevel.INFO,RunLevel.RUN,"Sanitizing null values",@@ -641,7 +640,7 @@ def prompt_processor() -> Any:_publish_log(log_events_id,- {"tool_id": tool_id},+ {"tool_id": tool_id, "doc_name": doc_name},LogLevel.INFO,RunLevel.RUN,"Execution complete",@@ -743,9 +742,11 @@ def run_completion(answer: str = completion[PSKeys.RESPONSE].textreturn answer+ # TODO: Catch and handle specific exception hereexcept Exception as e:- app.logger.info(f"Error completing prompt: {e}.")- raise e+ app.logger.info(f"Error fetching response for prompt: {e}.")+ # TODO: Publish this error as a FE update+ raise APIError(str(e)) from edef extract_variable(@@ -785,19 +786,62 @@ def enable_single_pass_extraction() -> None:enable_single_pass_extraction()+def log_exceptions(e: HTTPException):+ """Helper method to log exceptions.++ Args:+ e (HTTPException): Exception to log+ """+ code = 500+ if hasattr(e, "code"):+ code = e.code++ if code >= 500:+ message = "{method} {url} {status}\n\n{error}\n\n````{tb}````".format(+ method=request.method,+ url=request.url,+ status=code,+ error=str(e),+ tb=traceback.format_exc(),+ )+ else:+ message = "{method} {url} {status} {error}".format(+ method=request.method,+ url=request.url,+ status=code,+ error=str(e),+ )+ app.logger.error(message)++@app.errorhandler(HTTPException)-def handle_exception(e):+def handle_http_exception(e: HTTPException):"""Return JSON instead of HTML for HTTP errors."""- response = e.get_response()- response.data = json.dumps(- {- "code": e.code,- "name": e.name,- "error": e.description,- }- )- response.content_type = "application/json"- return response+ log_exceptions(e)+ if isinstance(e, APIError):+ return jsonify(e.to_dict()), e.code+ else:+ response = e.get_response()+ response.data = json.dumps(+ ErrorResponse(error=e.description, name=e.name, code=e.code)+ )+ response.content_type = "application/json"+ return response++[email protected](Exception)+def handle_uncaught_exception(e):+ """Handler for uncaught exceptions.++ Args:+ e (Exception): Any uncaught exception+ """+ # pass through HTTP errors+ if isinstance(e, HTTPException):+ return handle_http_exception(e)++ log_exceptions(e)+ return handle_http_exception(APIError())if __name__ == "__main__":diff --git a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.pyindex 584f70243..2c3448dd9 100644--- a/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py+++ b/unstract/workflow-execution/src/unstract/workflow_execution/workflow_execution.py@@ -204,7 +204,8 @@ class WorkflowExecutionService:)if not self.validate_execution_result(step + 1):raise ToolOutputNotFoundException(- f"Tool exception raised for tool {tool_uid}"+ f"Tool exception raised for tool {tool_uid}, "+ "check logs for more information")log_message = f"Step {actual_step} executed successfully"self.publish_update_log(