Skip to content

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

FIX: JSON Enforce Type (#293)

Tahier Hussainaad1fc7b9d1d
diff --git a/prompt-service/src/unstract/prompt_service/main.py b/prompt-service/src/unstract/prompt_service/main.py
index 1d16155a3..217ef8e48 100644
--- a/prompt-service/src/unstract/prompt_service/main.py
+++ b/prompt-service/src/unstract/prompt_service/main.py
@@ -1,5 +1,6 @@
import logging
from enum import Enum
+from json import JSONDecodeError
from typing import Any, Optional
import peewee
@@ -481,29 +482,25 @@ def prompt_processor() -> Any:
if assertion_failed or answer.lower() == "[]" or answer.lower() == "na":
structured_output[output[PSKeys.NAME]] = None
else:
- prompt = (
- f"Convert the following text:\n{answer} into valid JSON format."
- )
+ prompt = f"Convert the following text into valid JSON string: \
+ \n{answer}\n\n The JSON string should be able to be parsed \
+ into a Python dictionary. \
+ Output just the JSON string. No explanation is required. \
+ If you cannot extract the JSON string, output {{}}"
+
answer, usage = run_completion(
llm_helper,
llm_li,
prompt,
)
- # Remove any markdown code blocks
- lines = answer.split("\n")
- answer = ""
- for line in lines:
- if line.strip().startswith("```"):
- continue
- answer += line + "\n"
try:
structured_output[output[PSKeys.NAME]] = json.loads(answer)
- except Exception as e:
+ except JSONDecodeError as e:
app.logger.info(f"JSON format error : {answer}", LogLevel.ERROR)
app.logger.info(
f"Error parsing response (to json): {e}", LogLevel.ERROR
)
- structured_output[output[PSKeys.NAME]] = []
+ structured_output[output[PSKeys.NAME]] = {}
else:
structured_output[output[PSKeys.NAME]] = answer