""" Pure LLM-based mapping handler with enhanced template context. Provides AI-assisted mapping using rich examples from template.json. """ import os import json import logging from typing import Dict, List, Optional, Any from pathlib import Path logger = logging.getLogger(__name__) class PureLLMHandler: """Pure LLM handler with enhanced template context for better mapping accuracy.""" def __init__(self, api_key: Optional[str] = None, model_name: str = "meta-llama/llama-4-maverick-17b-128e-instruct", temperature: float = 0.2, max_tokens: int = 2048, max_retries: int = 5): """Initialize Pure LLM handler with enhanced context. Args: api_key: Groq API key (from env if None) model_name: Model to use temperature: Sampling temperature (0.2 for consistent but creative mapping) max_tokens: Maximum tokens in response max_retries: Maximum retry attempts (5 as requested) """ self.api_key = api_key or os.getenv("GROQ_API_KEY") self.model_name = model_name self.temperature = temperature self.max_tokens = max_tokens self.max_retries = max_retries self.is_available = False # Load template context for enhanced prompts self.template_context = self._load_template_context() # Initialize LangChain components try: if not self.api_key: raise ValueError("GROQ_API_KEY environment variable is required") from langchain_groq import ChatGroq from langchain.prompts import PromptTemplate from langchain.schema import HumanMessage self.llm = ChatGroq( groq_api_key=self.api_key, model_name=self.model_name, temperature=self.temperature, max_tokens=self.max_tokens ) self.prompt_template = self._create_enhanced_prompt_template() self.is_available = True logger.info(f"Pure LLM handler initialized with model: {self.model_name}, retries: {self.max_retries}") except (ImportError, ValueError) as e: logger.warning(f"Pure LLM handler not available: {e}") self.is_available = False def _load_template_context(self) -> Dict[str, Any]: """Load template context from template.json for enhanced prompts.""" template_path = Path("template.json") try: with open(template_path, 'r', encoding='utf-8') as f: template_data = json.load(f) # Extract template mappings (exclude CDF_META) context = {} for erp_name, erp_data in template_data.items(): if erp_name == "CDF_META": continue context[erp_name] = erp_data logger.info(f"Loaded template context for {len(context)} ERP systems") return context except Exception as e: logger.warning(f"Failed to load template context: {e}") return {} def _create_enhanced_prompt_template(self): """Create enhanced prompt template with rich template context.""" from langchain.prompts import PromptTemplate template = """You are an expert ERP data integration specialist with deep knowledge of enterprise systems. Your task is to map column names from unknown ERP data to standardized CDF (Common Data Frame) format using your expertise and the provided template examples. # Pure LLM-Based ERP to CDF Column Mapping **Target Entity Type**: {entity} **Your Data Columns (Unknown ERP)**: {source_columns} **Target CDF Schema for {entity}**: {target_columns} **Template Examples from Known ERP Systems**: {template_examples} **Entity-Specific Mapping Guidance**: {entity_guidance} **Your Expert Instructions**: 1. Analyze the source column names and understand their business meaning 2. Use the template examples to understand common ERP naming patterns 3. Map each source column to the most semantically appropriate CDF column 4. Consider variations in naming conventions (abbreviations, prefixes, suffixes) 5. Only map columns where you have high confidence in the semantic match 6. If no good match exists for a source column, omit it from the mapping 7. Each CDF column should be mapped to at most one source column **Critical Requirements**: - Return ONLY a valid JSON object with the mappings - Use exact column names from the provided lists - Ensure semantic accuracy over quantity of mappings - Consider business context and ERP domain knowledge **Required Response Format**: ```json {{ "source_column_1": "target_cdf_column_1", "source_column_2": "target_cdf_column_2" }} ``` Generate the expert mapping now:""" return PromptTemplate( template=template, input_variables=[ "entity", "source_columns", "target_columns", "template_examples", "entity_guidance" ] ) def infer_mapping_pure(self, source_columns: List[str], cdf_columns: List[str], entity: str) -> Dict[str, str]: """Infer column mapping using pure LLM approach with enhanced template context. Args: source_columns: Source column names from unknown ERP cdf_columns: Target column names for CDF entity: Entity type Returns: Dictionary mapping source columns to CDF columns """ if not self.is_available: logger.error("Pure LLM handler not available") return {} for attempt in range(self.max_retries): try: logger.info(f"Pure LLM mapping inference attempt {attempt + 1}/{self.max_retries}") # Build enhanced template examples template_examples = self._build_template_examples(entity) # Get entity-specific guidance entity_guidance = self._get_entity_guidance(entity) # Format the enhanced prompt formatted_prompt = self.prompt_template.format( entity=entity, source_columns=json.dumps(source_columns, indent=2), target_columns=json.dumps(cdf_columns, indent=2), template_examples=template_examples, entity_guidance=entity_guidance ) # Get response from LLM from langchain.schema import HumanMessage response = self.llm.invoke([HumanMessage(content=formatted_prompt)]) # Parse response content = response.content.strip() # Extract and clean JSON mapping = self._extract_and_parse_json(content) # Validate mapping if self._validate_mapping(mapping, source_columns, cdf_columns): logger.info(f"Pure LLM mapping successful: {len(mapping)} field mappings") return mapping else: logger.warning(f"Invalid mapping generated on attempt {attempt + 1}") except Exception as e: logger.error(f"Pure LLM API call failed (attempt {attempt + 1}): {e}") # All attempts failed logger.error(f"All {self.max_retries} Pure LLM mapping attempts failed") return {} def _build_template_examples(self, entity: str) -> str: """Build rich template examples for the given entity.""" if not self.template_context: return "No template examples available." examples = [] # Select diverse ERP systems for examples priority_erps = ["NetSuite", "SAP ERP", "Oracle Fusion", "Microsoft Dynamics", "Workday"] for erp_name in priority_erps: if erp_name in self.template_context and entity in self.template_context[erp_name]: mapping = self.template_context[erp_name][entity] examples.append(f""" **{erp_name} {entity} mapping**: {json.dumps(mapping, indent=2)}""") # Add additional ERPs if we have less than 3 examples if len(examples) < 3: for erp_name, erp_data in self.template_context.items(): if erp_name not in priority_erps and entity in erp_data: mapping = erp_data[entity] examples.append(f""" **{erp_name} {entity} mapping**: {json.dumps(mapping, indent=2)}""") if len(examples) >= 5: # Limit to 5 examples break if not examples: return f"No template examples available for entity: {entity}" return "\n".join(examples) def _extract_and_parse_json(self, content: str) -> Dict[str, str]: """Extract and parse JSON from LLM response with multiple fallback methods.""" # Method 1: Extract from code blocks if "```json" in content: json_start = content.find("```json") + 7 json_end = content.find("```", json_start) if json_end != -1: content = content[json_start:json_end].strip() elif "```" in content: json_start = content.find("```") + 3 json_end = content.find("```", json_start) if json_end != -1: content = content[json_start:json_end].strip() # Method 2: Find JSON object boundaries json_start = content.find("{") json_end = content.rfind("}") + 1 if json_start != -1 and json_end > json_start: content = content[json_start:json_end] # Method 3: Clean up common issues content = content.replace("'", '"') # Single to double quotes content = content.replace('\n', ' ') # Remove newlines try: return json.loads(content) except json.JSONDecodeError as e: logger.error(f"JSON parsing failed: {e}") logger.error(f"Content: {repr(content)}") # Method 4: Regex extraction as fallback try: import re pattern = r'"([^"]+)"\s*:\s*"([^"]+)"' matches = re.findall(pattern, content) if matches: mapping = {} used_targets = set() for source, target in matches: if target not in used_targets: mapping[source] = target used_targets.add(target) return mapping except Exception as regex_error: logger.error(f"Regex fallback failed: {regex_error}") return {} def _get_entity_guidance(self, entity: str) -> str: """Get comprehensive entity-specific mapping guidance.""" guidance_map = { "sales_orders": """ **Sales Orders Mapping Patterns**: - **Order IDs**: Look for order numbers, transaction IDs, document numbers Common patterns: order_id, order_num, tranId, OrderNum, VBELN, so_nbr, OrderNo - **Dates**: Order dates, transaction dates, creation dates Common patterns: order_date, trandate, OrderDate, ERDAT, so_ord_date, odat - **Customer References**: Customer IDs, account numbers, entity references Common patterns: customer_id, entity, CustNum, KUNNR, so_cust, otbp - **Amounts**: Total amounts, order values, net amounts Common patterns: total_amount, total, OrderAmt, NETWR, so_total_amt, oamt - **Status**: Order status, document status, processing status Common patterns: status, OrderHeld, AUART, so_stat, stat - **Currency**: Currency codes, currency references Common patterns: currency, CurrencyCode, WAERK, so_curr, curr - **Line Items**: Item IDs, descriptions, quantities, prices Common patterns: item_id, description, quantity, unit_price, line_total """.strip(), "customers": """ **Customer Mapping Patterns**: - **Customer IDs**: Customer numbers, account IDs, entity IDs Common patterns: customer_id, CustNum, KUNNR, cm_addr, CustomerId - **Names**: Customer names, company names, party names Common patterns: customer_name, Name, NAME1, cm_name, CustomerName - **Contact Info**: Email addresses, phone numbers, contact details Common patterns: contact_email, phone_number, Email, TELF1, cm_phone - **Company Flags**: Organization type, party type, customer type Common patterns: is_company, PartyType, KTOKD, cm_type, CustomerType - **Status**: Customer status, blocked status, active status Common patterns: status, Blocked, SPERR, cm_sort, CustomerStatus - **Addresses**: Address lines, city, state, postal codes, country Common patterns: address_line1, city, state, postal_code, country - **Dates**: Creation dates, modification dates, established dates Common patterns: created_date, last_modified, ERDAT, AEDAT """.strip(), "invoices": """ **Invoice Mapping Patterns**: - **Invoice IDs**: Invoice numbers, document numbers, transaction IDs Common patterns: invoice_id, InvoiceNum, VBELN, ih_inv_nbr, InvoiceNo - **Dates**: Invoice dates, transaction dates, due dates Common patterns: invoice_date, due_date, InvoiceDate, FKDAT, ih_inv_date - **Customer References**: Customer IDs, bill-to customers, account numbers Common patterns: customer_id, CustNum, KUNAG, ih_cust, CustomerId - **Amounts**: Invoice amounts, total amounts, balance amounts Common patterns: total_amount, InvoiceAmt, NETWR, ih_amt, GrossAmount - **Status**: Invoice status, payment status, document status Common patterns: status, OpenInvoice, FKSTO, ih_stat, InvoiceStatus - **Line Items**: Item details, descriptions, quantities, prices Common patterns: item_id, description, quantity, unit_price, line_total """.strip(), "purchase_orders": """ **Purchase Order Mapping Patterns**: - **PO IDs**: Purchase order numbers, document numbers Common patterns: po_id, PONUM, EBELN, poh_nbr, OrderNo - **Dates**: Order dates, creation dates, delivery dates Common patterns: po_date, OrderDate, BEDAT, poh_ord_date, OrderDate - **Vendor References**: Vendor IDs, supplier IDs, vendor numbers Common patterns: vendor_id, VendorNum, LIFNR, poh_vend, SupplierId - **Amounts**: Total amounts, order amounts, net amounts Common patterns: total_amount, TotalOrder, NETWR, GrossAmount - **Status**: Order status, document status, approval status Common patterns: status, OpenOrder, BSTYP, poh_stat, OrderStatus - **Expected Dates**: Receipt dates, delivery dates, due dates Common patterns: expected_receipt_date, DueDate, EINDT, pod_due_date """.strip(), "inventory_items": """ **Inventory Item Mapping Patterns**: - **Item IDs**: Item numbers, part numbers, material numbers, SKUs Common patterns: item_id, PartNum, MATNR, pt_part, ItemId - **Names**: Item names, part descriptions, material descriptions Common patterns: item_name, PartDescription, MAKTX, pt_desc1, Name - **Descriptions**: Detailed descriptions, long descriptions Common patterns: description, SearchWord, pt_desc2, DetailedDescription - **Pricing**: Base prices, unit prices, list prices, costs Common patterns: base_price, cost_price, UnitPrice, STPRS, pt_price - **Quantities**: On-hand quantities, available quantities, stock levels Common patterns: quantity_on_hand, InventQtyAvail, LABST, QtyOnHand - **Status**: Active status, inactive flags, obsolete flags Common patterns: is_active, InActive, MSTAE, pt_status, Obsolete - **Vendor Info**: Preferred vendors, supplier references Common patterns: preferred_vendor_id, PrimPRec, LIFNR, pt_vend """.strip() } return guidance_map.get(entity, f"General mapping guidance for {entity} entity.") def _validate_mapping(self, mapping: Dict[str, str], source_columns: List[str], cdf_columns: List[str]) -> bool: """Validate the generated mapping with enhanced checks.""" if not isinstance(mapping, dict): logger.warning("Mapping is not a dictionary") return False if not mapping: logger.warning("Empty mapping generated") return False # Check source columns invalid_sources = [col for col in mapping.keys() if col not in source_columns] if invalid_sources: logger.warning(f"Invalid source columns in mapping: {invalid_sources}") return False # Check target columns invalid_targets = [col for col in mapping.values() if col not in cdf_columns] if invalid_targets: logger.warning(f"Invalid target columns in mapping: {invalid_targets}") return False # Check for duplicate target mappings target_counts = {} for target in mapping.values(): target_counts[target] = target_counts.get(target, 0) + 1 duplicates = [target for target, count in target_counts.items() if count > 1] if duplicates: logger.warning(f"Duplicate target mappings found: {duplicates}") return False logger.info(f"Mapping validation successful: {len(mapping)} valid mappings") return True def detect_entity_type(self, columns: List[str], available_entities: List[str]) -> Optional[str]: """Detect the most likely entity type based on column names using LLM. Args: columns: List of column names from the data available_entities: List of available entity types to choose from Returns: Detected entity type or None if detection fails """ if not self.is_available: logger.error("Pure LLM handler not available for entity detection") return None for attempt in range(self.max_retries): try: logger.info(f"Entity detection attempt {attempt + 1}/{self.max_retries}") # Create entity detection prompt prompt = self._create_entity_detection_prompt(columns, available_entities) # Get response from LLM from langchain.schema import HumanMessage response = self.llm.invoke([HumanMessage(content=prompt)]) # Parse response content = response.content.strip() # Extract entity type from response detected_entity = self._extract_entity_from_response(content, available_entities) if detected_entity and detected_entity in available_entities: logger.info(f"Entity detection successful: {detected_entity}") return detected_entity else: logger.warning(f"Invalid entity detected on attempt {attempt + 1}: {detected_entity}") except Exception as e: logger.error(f"Entity detection API call failed (attempt {attempt + 1}): {e}") # All attempts failed logger.error(f"All {self.max_retries} entity detection attempts failed") return None def _create_entity_detection_prompt(self, columns: List[str], available_entities: List[str]) -> str: """Create prompt for entity type detection.""" return f"""You are an expert ERP data analyst. Analyze the following column names and determine the most likely business entity type they represent. **Column Names to Analyze**: {json.dumps(columns, indent=2)} **Available Entity Types**: {json.dumps(available_entities, indent=2)} **Entity Type Characteristics**: **sales_orders**: Order management data - Typical columns: order_id, order_date, customer_id, total_amount, status, currency, item_id, quantity, unit_price, line_total - Business context: Customer orders, sales transactions, order processing **customers**: Customer/client master data - Typical columns: customer_id, customer_name, contact_email, phone_number, is_company, status, address_line1, city, state, country - Business context: Customer information, contact details, addresses **invoices**: Billing and invoice data - Typical columns: invoice_id, invoice_date, customer_id, total_amount, due_date, status, currency, item_id, quantity, unit_price - Business context: Billing documents, payment processing, accounts receivable **purchase_orders**: Procurement and purchasing data - Typical columns: po_id, po_date, vendor_id, total_amount, status, currency, expected_receipt_date, item_id, quantity - Business context: Vendor orders, procurement, accounts payable **inventory_items**: Product/item master data - Typical columns: item_id, item_name, description, base_price, cost_price, quantity_on_hand, is_active, unit_type - Business context: Product catalog, inventory management, stock levels **Analysis Instructions**: 1. Look for key identifying patterns in the column names 2. Consider the business domain and data relationships 3. Match column patterns to the most appropriate entity type 4. Focus on the primary business purpose of the data **Response Format**: Return ONLY the entity type name from the available options. No explanation needed. **Example Responses**: - sales_orders - customers - invoices - purchase_orders - inventory_items Analyze the columns and return the most likely entity type:""" def _extract_entity_from_response(self, content: str, available_entities: List[str]) -> Optional[str]: """Extract entity type from LLM response.""" content = content.strip().lower() # Direct match for entity in available_entities: if entity.lower() == content: return entity # Partial match for entity in available_entities: if entity.lower() in content: return entity # Try to find any of the available entities in the response for entity in available_entities: if entity.replace('_', ' ').lower() in content or entity.replace('_', '').lower() in content: return entity logger.warning(f"Could not extract valid entity from response: {content}") return None def create_pure_llm_handler(**kwargs) -> PureLLMHandler: """Factory function to create Pure LLM handler. Args: **kwargs: Additional arguments for handler initialization Returns: Pure LLM handler instance """ return PureLLMHandler(**kwargs)