Skip to content

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

UN-2444 [FEAT] Usage for Rent rolls (#1436)

harini-venkataraman437cba2531b2
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 52bf7dfd2..26ed5cebd 100644
--- a/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
+++ b/prompt-service/src/unstract/prompt_service/controllers/answer_prompt.py
@@ -209,30 +209,67 @@ def prompt_processor() -> Any:
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
+ app.logger.info("Starting rent roll extraction run...")
try:
- import asyncio
-
- # Get the extraction result
- extraction_result = asyncio.run(
- extractor.process(
- extractor_settings=output,
- extracted_data=extracted_data,
- llm_config=llm_adapter_config,
- schema=prompt_text,
- )
+ extraction_result = extractor.process(
+ extractor_settings=output,
+ extracted_data=extracted_data,
+ llm_config=llm_adapter_config,
+ schema=prompt_text,
)
# Update structured output with the extraction result
- # TODO: Add metrics
- # TODO: Add metadata
- structured_output[output[PSKeys.NAME]] = extraction_result
+ structured_output[output[PSKeys.NAME]] = extraction_result["data"]
response = {
PSKeys.OUTPUT: structured_output,
- PSKeys.METADATA: {},
- PSKeys.METRICS: {},
+ PSKeys.METADATA: extraction_result["metrics"],
+ PSKeys.METRICS: extraction_result["metrics"],
}
+
+ # Track token usage by sending to the audit service
+ try:
+ from unstract.sdk.utils.token_counter import TokenCounter
+
+ # Get metrics from the extraction result
+ metrics = extraction_result.get("metrics", {})
+
+ # Create token counter adapter from metrics
+ token_usage = metrics.get("token_usage") or {}
+ token_counter = TokenCounter(
+ input_tokens=token_usage.get("prompt_tokens"),
+ output_tokens=token_usage.get("completion_tokens"),
+ )
+
+ # Extract model name from llm config
+ # Extract model name from llm config
+ model_info = metrics.get("model_info") or {}
+ model_name = model_info.get("model_name")
+ provider = model_info.get("provider")
+
+ # Prepare usage data for audit
+ kwargs = {
+ "workflow_id": "", # Not applicable for rent rolls
+ "execution_id": "", # Not applicable for rent rolls
+ "adapter_instance_id": adapter_id,
+ "run_id": str(run_id),
+ "provider": provider,
+ "llm_usage_reason": "extraction",
+ }
+
+ # Push usage data to audit service
+ UsageHelper.push_usage_data(
+ event_type="extraction",
+ kwargs=kwargs,
+ platform_api_key=platform_key,
+ token_counter=token_counter,
+ model_name=model_name,
+ )
+ app.logger.info(
+ "Successfully pushed token usage data to audit service"
+ )
+ except Exception as e:
+ # Don't let usage tracking failures affect the main flow
+ app.logger.warning(f"Failed to track token usage: {str(e)}")
app.logger.info("Rent roll extraction completed successfully")
return response
except Exception as e:
diff --git a/prompt-service/src/unstract/prompt_service/helpers/usage.py b/prompt-service/src/unstract/prompt_service/helpers/usage.py
index 3e4d20e69..fe2ce415b 100644
--- a/prompt-service/src/unstract/prompt_service/helpers/usage.py
+++ b/prompt-service/src/unstract/prompt_service/helpers/usage.py
@@ -1,3 +1,5 @@
+import logging
+import traceback
from logging import Logger
from typing import Any
@@ -7,6 +9,9 @@ from unstract.prompt_service.constants import DBTableV2
from unstract.prompt_service.extensions import db, db_context
from unstract.prompt_service.utils.db_utils import DBUtils
from unstract.prompt_service.utils.env_loader import get_env_or_die
+from unstract.sdk.audit import Audit
+
+logger = logging.getLogger(__name__)
class UsageHelper:
@@ -80,3 +85,56 @@ class UsageHelper:
def _format_float_positional(value: float, precision: int = 10) -> str:
formatted: str = f"{value:.{precision}f}"
return formatted.rstrip("0").rstrip(".") if "." in formatted else formatted
+
+ @staticmethod
+ def push_usage_data(
+ event_type: str,
+ kwargs: dict[str, Any],
+ platform_api_key: str,
+ token_counter=None,
+ model_name: str = "",
+ ) -> bool:
+ """Push usage data to the audit service.
+
+ Args:
+ event_type: Type of usage event being recorded
+ kwargs: Additional data to include with the event
+ platform_api_key: API key for authentication with the audit service
+ token_counter: Token counter object with token usage metrics
+ model_name: Name of the model used (if applicable)
+
+ Returns:
+ bool: True if successful, False otherwise
+ Note:
+ This method handles all exceptions internally and returns False on failure
+ rather than propagating exceptions to the caller.
+ """
+ if not kwargs or not isinstance(kwargs, dict):
+ logger.error("Invalid kwargs provided to push_usage_data")
+ return False
+
+ if not platform_api_key or not isinstance(platform_api_key, str):
+ logger.error("Invalid platform_api_key provided to push_usage_data")
+ return False
+
+ try:
+ logger.debug(
+ f"Pushing usage data for event_type: {event_type}, model: {model_name}"
+ )
+
+ # Call the Audit SDK with the appropriate parameters
+ Audit().push_usage_data(
+ platform_api_key=platform_api_key,
+ token_counter=token_counter,
+ model_name=model_name,
+ event_type=event_type,
+ kwargs=kwargs,
+ )
+
+ logger.info(f"Successfully pushed usage data for {model_name}")
+ return True
+ except Exception as e:
+ logger.exception(
+ f"Error pushing usage data: {str(e)} - {traceback.format_exc()}"
+ )
+ return False
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
index f713c0f2e..4bf691421 100644
--- a/prompt-service/src/unstract/prompt_service/services/rentrolls_extractor/interface.py
+++ b/prompt-service/src/unstract/prompt_service/services/rentrolls_extractor/interface.py
@@ -2,7 +2,7 @@ import logging
import os
from typing import Any
-import aiohttp
+import requests
logger = logging.getLogger(__name__)
@@ -15,7 +15,7 @@ class RentRollExtractor:
logger.info("Initialized RentRollExtractor")
pass
- async def process(
+ def process(
self,
extractor_settings: dict[str, Any],
extracted_data: str,
@@ -49,24 +49,22 @@ class RentRollExtractor:
}
# Make HTTP call to rent roll service
- timeout = aiohttp.ClientTimeout(total=3600)
logger.info(f"Calling rent roll service at: {rentroll_url}")
- async with aiohttp.ClientSession(timeout=timeout) 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}"
- )
+ response = requests.post(rentroll_url, json=payload)
+
+ if response.status_code == 200:
+ result = response.json()
+
+ logger.info("Successfully received response from rent roll service")
+ return result
+ else:
+ error_text = response.text
+ logger.error(
+ f"Rent roll service returned status {response.status_code}: {error_text}"
+ )
+ raise Exception(
+ f"Rent roll service error: {response.status_code} - {error_text}"
+ )
except Exception as e:
logger.error(f"Error in rent roll extraction: {str(e)}", exc_info=True)
raise