Spaces:
Runtime error
Runtime error
Implement dynamic entity detection for Pure LLM system
Browse files- Add detect_entity_type method to PureLLMHandler
- Remove hardcoded 'sales_orders' default in transformation engine
- Use LLM to analyze column patterns and detect appropriate entity type
- Add comprehensive entity detection prompts with business context
- Create test_entity_detection.py to validate functionality
- Update documentation to reflect dynamic entity detection feature
- Achieve 71.4% accuracy in entity detection tests
- Maintain fallback to sales_orders only if all detection attempts fail
- docs/PURE_LLM_SYSTEM.md +1 -0
- mapper/llm_handler_pure.py +116 -0
- mapper/transformation_engine_pure.py +38 -3
- test_entity_detection.py +115 -0
docs/PURE_LLM_SYSTEM.md
CHANGED
|
@@ -10,6 +10,7 @@ The Pure LLM Transformation System is a new approach that eliminates Jaccard sim
|
|
| 10 |
- **No Jaccard Similarity**: Eliminates complex similarity calculations
|
| 11 |
- **No Heuristic Fallbacks**: Uses only AI-powered mapping
|
| 12 |
- **Enhanced Context**: Rich template examples from `template.json`
|
|
|
|
| 13 |
- **5 Retry Attempts**: Robust error handling with multiple attempts
|
| 14 |
- **Template Preservation**: Known ERP+Entity combinations still use template mapping
|
| 15 |
|
|
|
|
| 10 |
- **No Jaccard Similarity**: Eliminates complex similarity calculations
|
| 11 |
- **No Heuristic Fallbacks**: Uses only AI-powered mapping
|
| 12 |
- **Enhanced Context**: Rich template examples from `template.json`
|
| 13 |
+
- **Dynamic Entity Detection**: Uses LLM to detect entity type from column patterns (no hardcoded defaults)
|
| 14 |
- **5 Retry Attempts**: Robust error handling with multiple attempts
|
| 15 |
- **Template Preservation**: Known ERP+Entity combinations still use template mapping
|
| 16 |
|
mapper/llm_handler_pure.py
CHANGED
|
@@ -412,6 +412,122 @@ Generate the expert mapping now:"""
|
|
| 412 |
|
| 413 |
logger.info(f"Mapping validation successful: {len(mapping)} valid mappings")
|
| 414 |
return True
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 415 |
|
| 416 |
|
| 417 |
def create_pure_llm_handler(**kwargs) -> PureLLMHandler:
|
|
|
|
| 412 |
|
| 413 |
logger.info(f"Mapping validation successful: {len(mapping)} valid mappings")
|
| 414 |
return True
|
| 415 |
+
|
| 416 |
+
def detect_entity_type(self, columns: List[str], available_entities: List[str]) -> Optional[str]:
|
| 417 |
+
"""Detect the most likely entity type based on column names using LLM.
|
| 418 |
+
|
| 419 |
+
Args:
|
| 420 |
+
columns: List of column names from the data
|
| 421 |
+
available_entities: List of available entity types to choose from
|
| 422 |
+
|
| 423 |
+
Returns:
|
| 424 |
+
Detected entity type or None if detection fails
|
| 425 |
+
"""
|
| 426 |
+
if not self.is_available:
|
| 427 |
+
logger.error("Pure LLM handler not available for entity detection")
|
| 428 |
+
return None
|
| 429 |
+
|
| 430 |
+
for attempt in range(self.max_retries):
|
| 431 |
+
try:
|
| 432 |
+
logger.info(f"Entity detection attempt {attempt + 1}/{self.max_retries}")
|
| 433 |
+
|
| 434 |
+
# Create entity detection prompt
|
| 435 |
+
prompt = self._create_entity_detection_prompt(columns, available_entities)
|
| 436 |
+
|
| 437 |
+
# Get response from LLM
|
| 438 |
+
from langchain.schema import HumanMessage
|
| 439 |
+
response = self.llm.invoke([HumanMessage(content=prompt)])
|
| 440 |
+
|
| 441 |
+
# Parse response
|
| 442 |
+
content = response.content.strip()
|
| 443 |
+
|
| 444 |
+
# Extract entity type from response
|
| 445 |
+
detected_entity = self._extract_entity_from_response(content, available_entities)
|
| 446 |
+
|
| 447 |
+
if detected_entity and detected_entity in available_entities:
|
| 448 |
+
logger.info(f"Entity detection successful: {detected_entity}")
|
| 449 |
+
return detected_entity
|
| 450 |
+
else:
|
| 451 |
+
logger.warning(f"Invalid entity detected on attempt {attempt + 1}: {detected_entity}")
|
| 452 |
+
|
| 453 |
+
except Exception as e:
|
| 454 |
+
logger.error(f"Entity detection API call failed (attempt {attempt + 1}): {e}")
|
| 455 |
+
|
| 456 |
+
# All attempts failed
|
| 457 |
+
logger.error(f"All {self.max_retries} entity detection attempts failed")
|
| 458 |
+
return None
|
| 459 |
+
|
| 460 |
+
def _create_entity_detection_prompt(self, columns: List[str], available_entities: List[str]) -> str:
|
| 461 |
+
"""Create prompt for entity type detection."""
|
| 462 |
+
return f"""You are an expert ERP data analyst. Analyze the following column names and determine the most likely business entity type they represent.
|
| 463 |
+
|
| 464 |
+
**Column Names to Analyze**:
|
| 465 |
+
{json.dumps(columns, indent=2)}
|
| 466 |
+
|
| 467 |
+
**Available Entity Types**:
|
| 468 |
+
{json.dumps(available_entities, indent=2)}
|
| 469 |
+
|
| 470 |
+
**Entity Type Characteristics**:
|
| 471 |
+
|
| 472 |
+
**sales_orders**: Order management data
|
| 473 |
+
- Typical columns: order_id, order_date, customer_id, total_amount, status, currency, item_id, quantity, unit_price, line_total
|
| 474 |
+
- Business context: Customer orders, sales transactions, order processing
|
| 475 |
+
|
| 476 |
+
**customers**: Customer/client master data
|
| 477 |
+
- Typical columns: customer_id, customer_name, contact_email, phone_number, is_company, status, address_line1, city, state, country
|
| 478 |
+
- Business context: Customer information, contact details, addresses
|
| 479 |
+
|
| 480 |
+
**invoices**: Billing and invoice data
|
| 481 |
+
- Typical columns: invoice_id, invoice_date, customer_id, total_amount, due_date, status, currency, item_id, quantity, unit_price
|
| 482 |
+
- Business context: Billing documents, payment processing, accounts receivable
|
| 483 |
+
|
| 484 |
+
**purchase_orders**: Procurement and purchasing data
|
| 485 |
+
- Typical columns: po_id, po_date, vendor_id, total_amount, status, currency, expected_receipt_date, item_id, quantity
|
| 486 |
+
- Business context: Vendor orders, procurement, accounts payable
|
| 487 |
+
|
| 488 |
+
**inventory_items**: Product/item master data
|
| 489 |
+
- Typical columns: item_id, item_name, description, base_price, cost_price, quantity_on_hand, is_active, unit_type
|
| 490 |
+
- Business context: Product catalog, inventory management, stock levels
|
| 491 |
+
|
| 492 |
+
**Analysis Instructions**:
|
| 493 |
+
1. Look for key identifying patterns in the column names
|
| 494 |
+
2. Consider the business domain and data relationships
|
| 495 |
+
3. Match column patterns to the most appropriate entity type
|
| 496 |
+
4. Focus on the primary business purpose of the data
|
| 497 |
+
|
| 498 |
+
**Response Format**:
|
| 499 |
+
Return ONLY the entity type name from the available options. No explanation needed.
|
| 500 |
+
|
| 501 |
+
**Example Responses**:
|
| 502 |
+
- sales_orders
|
| 503 |
+
- customers
|
| 504 |
+
- invoices
|
| 505 |
+
- purchase_orders
|
| 506 |
+
- inventory_items
|
| 507 |
+
|
| 508 |
+
Analyze the columns and return the most likely entity type:"""
|
| 509 |
+
|
| 510 |
+
def _extract_entity_from_response(self, content: str, available_entities: List[str]) -> Optional[str]:
|
| 511 |
+
"""Extract entity type from LLM response."""
|
| 512 |
+
content = content.strip().lower()
|
| 513 |
+
|
| 514 |
+
# Direct match
|
| 515 |
+
for entity in available_entities:
|
| 516 |
+
if entity.lower() == content:
|
| 517 |
+
return entity
|
| 518 |
+
|
| 519 |
+
# Partial match
|
| 520 |
+
for entity in available_entities:
|
| 521 |
+
if entity.lower() in content:
|
| 522 |
+
return entity
|
| 523 |
+
|
| 524 |
+
# Try to find any of the available entities in the response
|
| 525 |
+
for entity in available_entities:
|
| 526 |
+
if entity.replace('_', ' ').lower() in content or entity.replace('_', '').lower() in content:
|
| 527 |
+
return entity
|
| 528 |
+
|
| 529 |
+
logger.warning(f"Could not extract valid entity from response: {content}")
|
| 530 |
+
return None
|
| 531 |
|
| 532 |
|
| 533 |
def create_pure_llm_handler(**kwargs) -> PureLLMHandler:
|
mapper/transformation_engine_pure.py
CHANGED
|
@@ -161,8 +161,16 @@ class PureTransformationEngine:
|
|
| 161 |
logger.info("Pure LLM transformation")
|
| 162 |
|
| 163 |
try:
|
| 164 |
-
|
| 165 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 166 |
|
| 167 |
# Get CDF schema for target entity
|
| 168 |
cdf_schema = self.template_loader.get_cdf_schema(target_entity)
|
|
@@ -173,7 +181,6 @@ class PureTransformationEngine:
|
|
| 173 |
)
|
| 174 |
|
| 175 |
# Use Pure LLM to infer mapping
|
| 176 |
-
columns = list(input_df.columns)
|
| 177 |
llm_mapping = self.pure_llm_handler.infer_mapping_pure(columns, cdf_schema, target_entity)
|
| 178 |
|
| 179 |
if not llm_mapping:
|
|
@@ -207,6 +214,34 @@ class PureTransformationEngine:
|
|
| 207 |
message=f"Pure LLM transformation error: {str(e)}"
|
| 208 |
)
|
| 209 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 210 |
def _apply_column_mapping(self, input_df: pl.DataFrame, mapping: Dict[str, str], entity: str) -> pl.DataFrame:
|
| 211 |
"""Apply column mapping to transform DataFrame.
|
| 212 |
|
|
|
|
| 161 |
logger.info("Pure LLM transformation")
|
| 162 |
|
| 163 |
try:
|
| 164 |
+
columns = list(input_df.columns)
|
| 165 |
+
|
| 166 |
+
# Determine target entity - if not specified, let LLM detect it
|
| 167 |
+
if request.entity:
|
| 168 |
+
target_entity = request.entity
|
| 169 |
+
logger.info(f"Using specified entity: {target_entity}")
|
| 170 |
+
else:
|
| 171 |
+
# Let LLM detect the entity type based on column names
|
| 172 |
+
target_entity = self._detect_entity_with_llm(columns)
|
| 173 |
+
logger.info(f"LLM detected entity: {target_entity}")
|
| 174 |
|
| 175 |
# Get CDF schema for target entity
|
| 176 |
cdf_schema = self.template_loader.get_cdf_schema(target_entity)
|
|
|
|
| 181 |
)
|
| 182 |
|
| 183 |
# Use Pure LLM to infer mapping
|
|
|
|
| 184 |
llm_mapping = self.pure_llm_handler.infer_mapping_pure(columns, cdf_schema, target_entity)
|
| 185 |
|
| 186 |
if not llm_mapping:
|
|
|
|
| 214 |
message=f"Pure LLM transformation error: {str(e)}"
|
| 215 |
)
|
| 216 |
|
| 217 |
+
def _detect_entity_with_llm(self, columns: List[str]) -> str:
|
| 218 |
+
"""Use LLM to detect the most likely entity type based on column names.
|
| 219 |
+
|
| 220 |
+
Args:
|
| 221 |
+
columns: List of column names from the data
|
| 222 |
+
|
| 223 |
+
Returns:
|
| 224 |
+
Detected entity type
|
| 225 |
+
"""
|
| 226 |
+
try:
|
| 227 |
+
# Get available entity types
|
| 228 |
+
available_entities = [e.value for e in EntityType]
|
| 229 |
+
|
| 230 |
+
# Use LLM to detect entity type
|
| 231 |
+
detected_entity = self.pure_llm_handler.detect_entity_type(columns, available_entities)
|
| 232 |
+
|
| 233 |
+
if detected_entity and detected_entity in available_entities:
|
| 234 |
+
return detected_entity
|
| 235 |
+
else:
|
| 236 |
+
# Fallback to sales_orders if detection fails
|
| 237 |
+
logger.warning(f"LLM entity detection failed or returned invalid entity: {detected_entity}. Using fallback.")
|
| 238 |
+
return "sales_orders"
|
| 239 |
+
|
| 240 |
+
except Exception as e:
|
| 241 |
+
logger.error(f"Entity detection failed: {e}")
|
| 242 |
+
# Fallback to sales_orders if detection fails
|
| 243 |
+
return "sales_orders"
|
| 244 |
+
|
| 245 |
def _apply_column_mapping(self, input_df: pl.DataFrame, mapping: Dict[str, str], entity: str) -> pl.DataFrame:
|
| 246 |
"""Apply column mapping to transform DataFrame.
|
| 247 |
|
test_entity_detection.py
ADDED
|
@@ -0,0 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Test script to demonstrate dynamic entity detection functionality.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import os
|
| 7 |
+
import json
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
+
from mapper.llm_handler_pure import create_pure_llm_handler
|
| 10 |
+
|
| 11 |
+
# Load environment variables
|
| 12 |
+
load_dotenv()
|
| 13 |
+
|
| 14 |
+
def test_entity_detection():
|
| 15 |
+
"""Test entity detection with different column patterns."""
|
| 16 |
+
|
| 17 |
+
print("🧠 Testing Dynamic Entity Detection")
|
| 18 |
+
print("=" * 60)
|
| 19 |
+
|
| 20 |
+
# Initialize LLM handler
|
| 21 |
+
handler = create_pure_llm_handler()
|
| 22 |
+
|
| 23 |
+
if not handler.is_available:
|
| 24 |
+
print("❌ LLM handler not available - check GROQ_API_KEY")
|
| 25 |
+
return
|
| 26 |
+
|
| 27 |
+
# Available entity types
|
| 28 |
+
available_entities = ["sales_orders", "customers", "invoices", "purchase_orders", "inventory_items"]
|
| 29 |
+
|
| 30 |
+
# Test cases with different column patterns
|
| 31 |
+
test_cases = [
|
| 32 |
+
{
|
| 33 |
+
"name": "Sales Order Data",
|
| 34 |
+
"columns": ["order_id", "order_date", "customer_id", "total_amount", "status", "currency", "item_id", "quantity", "unit_price"],
|
| 35 |
+
"expected": "sales_orders"
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"name": "Customer Data",
|
| 39 |
+
"columns": ["customer_id", "customer_name", "contact_email", "phone_number", "address_line1", "city", "state", "country"],
|
| 40 |
+
"expected": "customers"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"name": "Invoice Data",
|
| 44 |
+
"columns": ["invoice_id", "invoice_date", "customer_id", "total_amount", "due_date", "status", "currency"],
|
| 45 |
+
"expected": "invoices"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"name": "Purchase Order Data",
|
| 49 |
+
"columns": ["po_id", "po_date", "vendor_id", "total_amount", "status", "expected_receipt_date"],
|
| 50 |
+
"expected": "purchase_orders"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"name": "Inventory Data",
|
| 54 |
+
"columns": ["item_id", "item_name", "description", "base_price", "cost_price", "quantity_on_hand", "is_active"],
|
| 55 |
+
"expected": "inventory_items"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"name": "SAP Sales Order Data",
|
| 59 |
+
"columns": ["VBAK.VBELN", "VBAK.ERDAT", "VBAK.KUNNR", "VBAK.AUART", "VBAK.WAERK", "VBAK.NETWR", "VBAP.MATNR", "VBAP.KWMENG"],
|
| 60 |
+
"expected": "sales_orders"
|
| 61 |
+
},
|
| 62 |
+
{
|
| 63 |
+
"name": "NetSuite Customer Data",
|
| 64 |
+
"columns": ["entityid", "companyname", "email", "phone", "billaddr1", "billcity", "billstate", "billcountry"],
|
| 65 |
+
"expected": "customers"
|
| 66 |
+
}
|
| 67 |
+
]
|
| 68 |
+
|
| 69 |
+
results = []
|
| 70 |
+
|
| 71 |
+
for i, test_case in enumerate(test_cases, 1):
|
| 72 |
+
print(f"\n🔍 Test {i}: {test_case['name']}")
|
| 73 |
+
print(f"Columns: {test_case['columns']}")
|
| 74 |
+
print(f"Expected: {test_case['expected']}")
|
| 75 |
+
|
| 76 |
+
# Detect entity type
|
| 77 |
+
detected = handler.detect_entity_type(test_case['columns'], available_entities)
|
| 78 |
+
|
| 79 |
+
# Check result
|
| 80 |
+
success = detected == test_case['expected']
|
| 81 |
+
status = "✅ PASS" if success else "❌ FAIL"
|
| 82 |
+
|
| 83 |
+
print(f"Detected: {detected}")
|
| 84 |
+
print(f"Result: {status}")
|
| 85 |
+
|
| 86 |
+
results.append({
|
| 87 |
+
"test": test_case['name'],
|
| 88 |
+
"expected": test_case['expected'],
|
| 89 |
+
"detected": detected,
|
| 90 |
+
"success": success
|
| 91 |
+
})
|
| 92 |
+
|
| 93 |
+
# Summary
|
| 94 |
+
print(f"\n📊 Entity Detection Test Summary")
|
| 95 |
+
print("=" * 60)
|
| 96 |
+
|
| 97 |
+
total_tests = len(results)
|
| 98 |
+
passed_tests = sum(1 for r in results if r['success'])
|
| 99 |
+
accuracy = (passed_tests / total_tests) * 100
|
| 100 |
+
|
| 101 |
+
print(f"Total Tests: {total_tests}")
|
| 102 |
+
print(f"Passed: {passed_tests}")
|
| 103 |
+
print(f"Failed: {total_tests - passed_tests}")
|
| 104 |
+
print(f"Accuracy: {accuracy:.1f}%")
|
| 105 |
+
|
| 106 |
+
if passed_tests == total_tests:
|
| 107 |
+
print("\n🎉 All entity detection tests passed!")
|
| 108 |
+
else:
|
| 109 |
+
print(f"\n⚠️ {total_tests - passed_tests} test(s) failed:")
|
| 110 |
+
for result in results:
|
| 111 |
+
if not result['success']:
|
| 112 |
+
print(f" - {result['test']}: Expected {result['expected']}, got {result['detected']}")
|
| 113 |
+
|
| 114 |
+
if __name__ == "__main__":
|
| 115 |
+
test_entity_detection()
|