Skip to content

LLM-Driven Extraction of Unstructured Data — Built for API Deployments & ETL Pipeline Workflows

[FIX] Revert JSON, Line-Item (#1298)

Deepak K597646087a54
diff --git a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
index c0fb39bbf..8faa7842c 100644
--- a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
+++ b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
@@ -206,6 +206,36 @@ def prompt_processor() -> Any:
"Error while extracting table for the prompt",
)
raise api_error
+ elif output[PSKeys.TYPE] == PSKeys.LINE_ITEM:
+ try:
+ structured_output = AnswerPromptService.extract_line_item(
+ tool_settings=tool_settings,
+ output=output,
+ structured_output=structured_output,
+ llm=llm,
+ file_path=file_path,
+ metadata=metadata,
+ execution_source=execution_source,
+ )
+ continue
+ except APIError as e:
+ app.logger.error(
+ "Failed to extract line-item for the prompt %s: %s",
+ output[PSKeys.NAME],
+ str(e),
+ )
+ publish_log(
+ log_events_id,
+ {
+ "tool_id": tool_id,
+ "prompt_key": prompt_name,
+ "doc_name": doc_name,
+ },
+ LogLevel.ERROR,
+ RunLevel.RUN,
+ "Error while extracting line-item for the prompt",
+ )
+ raise e
try:
answer = "NA"
diff --git a/prompt-service/src/unstract/prompt_service/services/answer_prompt.py b/prompt-service/src/unstract/prompt_service/services/answer_prompt.py
index 191195221..3c82b7643 100644
--- a/prompt-service/src/unstract/prompt_service/services/answer_prompt.py
+++ b/prompt-service/src/unstract/prompt_service/services/answer_prompt.py
@@ -1,3 +1,4 @@
+import json
from logging import Logger
from typing import Any
@@ -9,7 +10,6 @@ from unstract.prompt_service.constants import ExecutionSource, FileStorageKeys,
from unstract.prompt_service.constants import PromptServiceConstants as PSKeys
from unstract.prompt_service.exceptions import RateLimitError
from unstract.prompt_service.helpers.plugin import PluginManager
-from unstract.prompt_service.utils.file_utils import FileUtils
from unstract.prompt_service.utils.log import publish_log
from unstract.sdk.constants import LogLevel
from unstract.sdk.exceptions import RateLimitError as SdkRateLimitError
@@ -131,11 +131,7 @@ class AnswerPromptService:
PSKeys.HIGHLIGHT_DATA_PLUGIN
)
highlight_data = None
- if (
- highlight_data_plugin
- and enable_highlight
- and prompt_type.lower() != PSKeys.JSON
- ):
+ if highlight_data_plugin and enable_highlight:
fs_instance: FileStorage = FileStorage(FileStorageProvider.LOCAL)
if execution_source == ExecutionSource.IDE.value:
fs_instance = EnvHelper.get_storage(
@@ -154,7 +150,7 @@ class AnswerPromptService:
completion = llm.complete(
prompt=prompt,
process_text=highlight_data,
- extract_json=False,
+ extract_json=prompt_type.lower() != PSKeys.TEXT,
)
answer: str = completion[PSKeys.RESPONSE].text
highlight_data = completion.get(PSKeys.HIGHLIGHT_DATA, [])
@@ -238,28 +234,16 @@ class AnswerPromptService:
if answer.lower() == "na":
structured_output[prompt_key] = None
else:
- json_extraction_plugin = PluginManager().get_plugin("json-extraction")
- if json_extraction_plugin:
- answer = json_extraction_plugin["entrypoint_cls"](
- llm=llm,
- output=output,
- prompt=output[PSKeys.COMBINED_PROMPT],
- structured_output=structured_output,
- answer=answer,
- ).run()
- answer = AnswerPromptService.slice_from_first_bracket(answer)
- if enable_highlight:
- AnswerPromptService.handle_highlight(
- execution_source=execution_source,
- output=output,
- answer=answer,
- metadata=metadata,
- file_path=file_path,
- )
- parsed_data = repair_json(
- json_str=answer,
- return_objects=True,
- )
+ # Attempt parsing as-is (could be a valid object, array, or partial JSON)
+ a = repair_json(json_str=answer, return_objects=True)
+
+ # Attempt parsing with array wrap (useful for multiple comma-separated objects like {}, {}, {})
+ b = repair_json(json_str="[" + answer, return_objects=True)
+
+ # Heuristic: if wrapping only added '[' and ']', len(b) - len(a) == 2 → original was valid, use 'a'
+ # Otherwise, fallback to 'b' which likely fixed multiple items or invalid top-level structure
+ parsed_data = a if len(json.dumps(b)) - len(json.dumps(a)) == 2 else b
+
if isinstance(parsed_data, str):
err_msg = "Error parsing response (to json)\n" f"Candidate JSON: {answer}"
app.logger.info(err_msg, LogLevel.ERROR)
@@ -280,47 +264,62 @@ class AnswerPromptService:
structured_output[prompt_key] = parsed_data
@staticmethod
- def handle_highlight(
- execution_source: str,
+ def extract_line_item(
+ tool_settings: dict[str, Any],
output: dict[str, Any],
- answer: str,
- metadata: dict[str, Any] | None = None,
- file_path: str = "",
- ) -> None:
- """Handle highlight data from the LLM."""
- highlight_data_plugin = PluginManager().get_plugin("highlight-data")
- if highlight_data_plugin:
- highlight_response = highlight_data_plugin["entrypoint_cls"](
- file_path=file_path,
- fs_instance=FileUtils.get_fs_instance(execution_source=execution_source),
- ).run(None, True, answer)
- highlight_data = highlight_response.get(PSKeys.HIGHLIGHT_DATA, [])
- confidence_data = highlight_response.get(PSKeys.CONFIDENCE_DATA)
- line_numbers = highlight_response.get(PSKeys.LINE_NUMBERS, [])
- whisper_hash = highlight_response.get(PSKeys.WHISPER_HASH, "")
- prompt_key = output[PSKeys.NAME]
- if metadata is not None and prompt_key:
- if PSKeys.HIGHLIGHT_DATA not in metadata:
- metadata[PSKeys.HIGHLIGHT_DATA] = {}
- metadata[PSKeys.HIGHLIGHT_DATA][prompt_key] = highlight_data
+ structured_output: dict[str, Any],
+ llm: LLM,
+ file_path: str,
+ metadata: dict[str, str] | None,
+ execution_source: str,
+ ) -> dict[str, Any]:
+ line_item_extraction_plugin: dict[str, Any] = PluginManager().get_plugin(
+ "line-item-extraction"
+ )
+ if not line_item_extraction_plugin:
+ raise APIError(PSKeys.PAID_FEATURE_MSG)
- if PSKeys.LINE_NUMBERS not in metadata:
- metadata[PSKeys.LINE_NUMBERS] = {}
- metadata[PSKeys.LINE_NUMBERS][prompt_key] = line_numbers
+ extract_file_path = file_path
- metadata[PSKeys.WHISPER_HASH] = whisper_hash
+ # Read file content into context
+ fs_instance: FileStorage = FileStorage(FileStorageProvider.LOCAL)
+ if execution_source == ExecutionSource.IDE.value:
+ fs_instance = EnvHelper.get_storage(
+ storage_type=StorageType.PERMANENT,
+ env_name=FileStorageKeys.PERMANENT_REMOTE_STORAGE,
+ )
+ if execution_source == ExecutionSource.TOOL.value:
+ fs_instance = EnvHelper.get_storage(
+ storage_type=StorageType.SHARED_TEMPORARY,
+ env_name=FileStorageKeys.TEMPORARY_REMOTE_STORAGE,
+ )
- if confidence_data:
- if PSKeys.CONFIDENCE_DATA not in metadata:
- metadata[PSKeys.CONFIDENCE_DATA] = {}
- metadata[PSKeys.CONFIDENCE_DATA][prompt_key] = confidence_data
+ if not fs_instance.exists(extract_file_path):
+ raise FileNotFoundError(
+ f"The file at path '{extract_file_path}' does not exist."
+ )
+ context = fs_instance.read(path=extract_file_path, encoding="utf-8", mode="r")
- @staticmethod
- def slice_from_first_bracket(text: str) -> str:
- idx_brace = text.find("{")
- idx_bracket = text.find("[")
- indices = [i for i in [idx_brace, idx_bracket] if i != -1]
- if not indices:
- return text
- start = min(indices)
- return text[start:]
+ prompt = AnswerPromptService.construct_prompt(
+ preamble=tool_settings.get(PSKeys.PREAMBLE, ""),
+ prompt=output["promptx"],
+ postamble=tool_settings.get(PSKeys.POSTAMBLE, ""),
+ grammar_list=tool_settings.get(PSKeys.GRAMMAR, []),
+ context=context,
+ platform_postamble="",
+ )
+ try:
+ line_item_extraction = line_item_extraction_plugin["entrypoint_cls"](
+ llm=llm,
+ tool_settings=tool_settings,
+ output=output,
+ prompt=prompt,
+ structured_output=structured_output,
+ )
+ answer = line_item_extraction.run()
+ structured_output[output[PSKeys.NAME]] = answer
+ metadata[PSKeys.CONTEXT][output[PSKeys.NAME]] = [context]
+ return structured_output
+ except line_item_extraction_plugin["exception_cls"] as e:
+ msg = f"Couldn't extract table. {e}"
+ raise APIError(message=msg)