Skip to content

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

UN-2444 [FEAT] Temporary-Integration for Agentic table extractor service (#1390)

harini-venkataramanba94ea1c88d5
diff --git a/prompt-service/sample.env b/prompt-service/sample.env
index bacb6bf67..e26e6cbcd 100644
--- a/prompt-service/sample.env
+++ b/prompt-service/sample.env
@@ -59,3 +59,8 @@ ADAPTER_LLMW_POLL_INTERVAL=30
ADAPTER_LLMW_MAX_POLLS=1000
# Number of times to retry the /whisper-status API before failing the extraction
ADAPTER_LLMW_STATUS_RETRIES=5
+
+### Env for Rentroll Service ###
+# Rentroll Service
+RENTROLL_SERVICE_HOST=http://unstract-rentroll-service
+RENTROLL_SERVICE_PORT=5003
diff --git a/prompt-service/src/unstract/prompt_service/constants.py b/prompt-service/src/unstract/prompt_service/constants.py
index ef8c7108d..2035fb742 100644
--- a/prompt-service/src/unstract/prompt_service/constants.py
+++ b/prompt-service/src/unstract/prompt_service/constants.py
@@ -95,6 +95,7 @@ class PromptServiceConstants:
TOOL = "tool"
JSON_POSTAMBLE = "JSON_POSTAMBLE"
DEFAULT_JSON_POSTAMBLE = "Wrap the final JSON result inbetween ### like below example:\n###\n<FINAL_JSON_RESULT>\n###"
+ DOCUMENT_TYPE = "document_type"
class RunLevel(Enum):
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 30244c172..5a0b5d289 100644
--- a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
+++ b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
@@ -14,11 +14,16 @@ from unstract.prompt_service.helpers.plugin import PluginManager
from unstract.prompt_service.helpers.prompt_ide_base_tool import PromptServiceBaseTool
from unstract.prompt_service.helpers.usage import UsageHelper
from unstract.prompt_service.services.answer_prompt import AnswerPromptService
+from unstract.prompt_service.services.rentrolls_extractor.interface import (
+ RentRollExtractor,
+)
from unstract.prompt_service.services.retrieval import RetrievalService
from unstract.prompt_service.services.variable_replacement import (
VariableReplacementService,
)
+from unstract.prompt_service.utils.file_utils import FileUtils
from unstract.prompt_service.utils.log import publish_log
+from unstract.sdk.adapter import ToolAdapter
from unstract.sdk.adapters.llm.no_op.src.no_op_custom_llm import NoOpCustomLLM
from unstract.sdk.constants import LogLevel
from unstract.sdk.embedding import Embedding
@@ -172,6 +177,45 @@ def prompt_processor() -> Any:
raise APIError(message=msg)
if output[PSKeys.TYPE] == PSKeys.TABLE:
+ llm_config = (
+ ToolAdapter.get_adapter_config(util, output[PSKeys.LLM])
+ .get("adapter_metadata")
+ .to_dict()
+ )
+ table_settings = output[PSKeys.TABLE_SETTINGS]
+ document_type: str = table_settings.get(PSKeys.DOCUMENT_TYPE)
+ app.logger.info("Document type: %s", document_type)
+ if document_type == "rent_rolls":
+ # Create RentRollExtractor instance and process the extraction
+ extractor = RentRollExtractor()
+ fs_instance = FileUtils.get_fs_instance(execution_source=execution_source)
+ extracted_data = fs_instance.read(path=file_path, mode="r")
+ app.logger.info("Starting asyncio.run...")
+ # Call the process method asynchronously
+ try:
+ import asyncio
+
+ # Get the extraction result
+ extraction_result = asyncio.run(
+ extractor.process(
+ extractor_settings=output,
+ extracted_data=extracted_data,
+ llm_config=llm_config,
+ schema=prompt_text,
+ )
+ )
+
+ # Update structured output with the extraction result
+ # TODO: Add metrics
+ # TODO: Add metadata
+ response = {
+ PSKeys.OUTPUT: extraction_result,
+ }
+ app.logger.info("Rent roll extraction completed successfully")
+ return response
+ except Exception as e:
+ app.logger.error(f"Failed to process rent roll: {str(e)}")
+ # Continue with regular table extraction as fallback
try:
structured_output = AnswerPromptService.extract_table(
output=output,
diff --git a/prompt-service/src/unstract/prompt_service/services/rentrolls_extractor/interface.py b/prompt-service/src/unstract/prompt_service/services/rentrolls_extractor/interface.py
new file mode 100644
index 000000000..fdc215234
--- /dev/null
+++ b/prompt-service/src/unstract/prompt_service/services/rentrolls_extractor/interface.py
@@ -0,0 +1,71 @@
+import logging
+import os
+from typing import Any
+
+import aiohttp
+
+logger = logging.getLogger(__name__)
+
+
+class RentRollExtractor:
+ """Main class for rent roll extraction."""
+
+ def __init__(self):
+ """Initialize the rent roll extractor."""
+ logger.info("Initialized RentRollExtractor")
+ pass
+
+ async def process(
+ self,
+ extractor_settings: dict[str, Any],
+ extracted_data: str,
+ llm_config: dict[str, Any],
+ schema: str,
+ ) -> dict[str, Any]:
+ """Process the extraction with the given settings.
+
+ Args:
+ extractor_settings: Dictionary containing extraction settings.
+ extracted_data: Extracted data from the document.
+ llm_config: Dictionary containing LLM configuration.
+ schema: Schema for the extraction.
+
+ Returns:
+ Dict containing the extraction results.
+ """
+ logger.info("Starting rent roll extraction process")
+ try:
+ # Load environment variables for rent roll service
+ rentroll_host = os.environ.get("RENTROLL_SERVICE_HOST", "http://localhost")
+ rentroll_port = os.environ.get("RENTROLL_SERVICE_PORT", "5001")
+ rentroll_url = f"{rentroll_host}:{rentroll_port}/api/extract-rentrolls"
+
+ # Prepare the request payload
+ payload = {
+ "text": extracted_data,
+ "settings": extractor_settings,
+ "llm_config": llm_config,
+ "schema": schema,
+ }
+
+ # Make HTTP call to rent roll service
+ logger.info(f"Calling rent roll service at: {rentroll_url}")
+ async with aiohttp.ClientSession() as session:
+ async with session.post(rentroll_url, json=payload) as response:
+ if response.status == 200:
+ result = await response.json()
+ logger.info(
+ "Successfully received response from rent roll service"
+ )
+ return result
+ else:
+ error_text = await response.text()
+ logger.error(
+ f"Rent roll service returned status {response.status}: {error_text}"
+ )
+ raise Exception(
+ f"Rent roll service error: {response.status} - {error_text}"
+ )
+ except Exception as e:
+ logger.error(f"Error in rent roll extraction: {str(e)}", exc_info=True)
+ raise