Spaces:
Runtime error
Runtime error
Download mapper/llm_handler.py from CleanflowAI/cleanflowai: direct link, hf CLI and curl.
- Browser
- Download file 17.3 kB
-
https://huggingface.co/spaces/CleanflowAI/cleanflowai/resolve/main/mapper/llm_handler.py
- Command line
-
hf download hf://spaces/CleanflowAI/cleanflowai/mapper/llm_handler.py
-
curl -L -o llm_handler.py https://huggingface.co/spaces/CleanflowAI/cleanflowai/resolve/main/mapper/llm_handler.py
17.3 kB
| """ | |
| LLM integration for ERP field mapping using LangChain and Groq Cloud. | |
| Provides AI-assisted mapping when template-based resolution fails. | |
| """ | |
| import os | |
| import json | |
| import logging | |
| from typing import Dict, List, Optional, Any | |
| from pathlib import Path | |
| logger = logging.getLogger(__name__) | |
| class LLMHandler: | |
| """LangChain-based LLM handler using Groq Cloud with Llama models.""" | |
| def __init__(self, | |
| api_key: Optional[str] = None, | |
| model_name: str = "meta-llama/llama-4-maverick-17b-128e-instruct", | |
| temperature: float = 0.0, | |
| max_tokens: int = 2048, | |
| max_retries: int = 3): | |
| """Initialize LangChain Groq LLM handler. | |
| Args: | |
| api_key: Groq API key (from env if None) | |
| model_name: Model to use (meta-llama/llama-4-maverick-17b-128e-instruct, llama-3.1-70b-versatile, etc.) | |
| temperature: Sampling temperature | |
| max_tokens: Maximum tokens in response | |
| max_retries: Maximum retry attempts | |
| """ | |
| 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 | |
| # 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_prompt_template() | |
| self.is_available = True | |
| logger.info(f"LangChain Groq LLM handler initialized with model: {self.model_name}") | |
| except (ImportError, ValueError) as e: | |
| logger.warning(f"LangChain Groq LLM handler not available: {e}") | |
| self.is_available = False | |
| def _create_prompt_template(self): | |
| """Create LangChain prompt template for ERP mapping.""" | |
| from langchain.prompts import PromptTemplate | |
| template = """You are an expert data integration specialist. Your task is to map column names from ERP systems to standardized CDF (Common Data Frame) format. | |
| # ERP to CDF Column Mapping Task | |
| **Entity Type**: {entity} | |
| **Source Columns (ERP Export)**: | |
| {source_columns} | |
| **Target CDF Schema**: | |
| {target_columns} | |
| {template_context_section} | |
| {entity_guidance_section} | |
| **Instructions**: | |
| 1. Map each source column to the most appropriate CDF column | |
| 2. Only map columns that have a clear semantic match | |
| 3. If no good match exists, omit the mapping | |
| 4. Consider common ERP naming patterns and abbreviations | |
| 5. Return ONLY a valid JSON object with the mappings | |
| **Required Response Format**: | |
| ```json | |
| {{ | |
| "source_column_1": "target_cdf_column_1", | |
| "source_column_2": "target_cdf_column_2" | |
| }} | |
| ``` | |
| Generate the mapping now:""" | |
| return PromptTemplate( | |
| template=template, | |
| input_variables=[ | |
| "entity", | |
| "source_columns", | |
| "target_columns", | |
| "template_context_section", | |
| "entity_guidance_section" | |
| ] | |
| ) | |
| def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str], | |
| entity: str, template_context: Optional[Dict] = None) -> Dict[str, str]: | |
| """Infer column mapping using LangChain and Groq LLM. | |
| Args: | |
| gdf_columns: Source column names from GDF | |
| cdf_columns: Target column names for CDF | |
| entity: Entity type | |
| template_context: Template examples for context | |
| Returns: | |
| Dictionary mapping GDF columns to CDF columns | |
| """ | |
| if not self.is_available: | |
| logger.warning("LLM handler not available, returning heuristic mapping") | |
| return self._heuristic_mapping(gdf_columns, cdf_columns) | |
| for attempt in range(self.max_retries): | |
| try: | |
| logger.info(f"Attempting LangChain LLM mapping inference (attempt {attempt + 1}/{self.max_retries})") | |
| # Prepare template context section | |
| template_context_section = "" | |
| if template_context: | |
| template_context_section = f"""**Example Mappings from Template**: | |
| Here are some example mappings from our template database: | |
| ```json | |
| {json.dumps(template_context, indent=2)} | |
| ``` | |
| """ | |
| # Prepare entity guidance section | |
| entity_guidance = self._get_entity_guidance(entity) | |
| entity_guidance_section = "" | |
| if entity_guidance: | |
| entity_guidance_section = f"""**Entity-Specific Guidance**: | |
| {entity_guidance} | |
| """ | |
| # Format the prompt | |
| formatted_prompt = self.prompt_template.format( | |
| entity=entity, | |
| source_columns=json.dumps(gdf_columns, indent=2), | |
| target_columns=json.dumps(cdf_columns, indent=2), | |
| template_context_section=template_context_section, | |
| entity_guidance_section=entity_guidance_section | |
| ) | |
| # Get response from LLM | |
| from langchain.schema import HumanMessage | |
| response = self.llm.invoke([HumanMessage(content=formatted_prompt)]) | |
| # Parse response | |
| content = response.content.strip() | |
| # Extract JSON from response (handle code blocks and clean up) | |
| 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() | |
| # Find JSON object in response | |
| json_start = content.find("{") | |
| json_end = content.rfind("}") + 1 | |
| if json_start != -1 and json_end > json_start: | |
| content = content[json_start:json_end] | |
| # Clean up common JSON issues | |
| content = content.replace("'", '"') # Replace single quotes with double quotes | |
| content = content.replace('\n', ' ') # Remove newlines | |
| mapping = json.loads(content) | |
| # Validate mapping | |
| if self._validate_mapping(mapping, gdf_columns, cdf_columns): | |
| logger.info(f"Successfully generated mapping with {len(mapping)} field mappings") | |
| return mapping | |
| else: | |
| logger.warning(f"Invalid mapping generated on attempt {attempt + 1}") | |
| except json.JSONDecodeError as e: | |
| logger.error(f"Failed to parse LLM response as JSON (attempt {attempt + 1}): {e}") | |
| logger.error(f"Raw response content: {repr(content)}") | |
| # Try alternative parsing methods | |
| try: | |
| # Method 1: Use regex to extract key-value pairs | |
| import re | |
| pattern = r'"([^"]+)"\s*:\s*"([^"]+)"' | |
| matches = re.findall(pattern, content) | |
| if matches: | |
| # Remove duplicates by keeping only the first occurrence of each target column | |
| mapping = {} | |
| used_targets = set() | |
| for source, target in matches: | |
| if target not in used_targets: | |
| mapping[source] = target | |
| used_targets.add(target) | |
| else: | |
| logger.debug(f"Skipping duplicate target mapping: {source} -> {target}") | |
| if self._validate_mapping(mapping, gdf_columns, cdf_columns): | |
| logger.info(f"Successfully parsed mapping using regex with {len(mapping)} field mappings (removed duplicates)") | |
| return mapping | |
| # Method 2: Try to fix common JSON issues | |
| fixed_content = content | |
| # Fix trailing commas | |
| fixed_content = re.sub(r',\s*}', '}', fixed_content) | |
| fixed_content = re.sub(r',\s*]', ']', fixed_content) | |
| mapping = json.loads(fixed_content) | |
| if self._validate_mapping(mapping, gdf_columns, cdf_columns): | |
| logger.info(f"Successfully parsed mapping using fixed JSON with {len(mapping)} field mappings") | |
| return mapping | |
| except Exception as parse_error: | |
| logger.debug(f"Alternative parsing failed: {parse_error}") | |
| except Exception as e: | |
| logger.error(f"LangChain LLM API call failed (attempt {attempt + 1}): {e}") | |
| # Fallback: return heuristic mapping | |
| logger.error("All LangChain LLM mapping attempts failed, using heuristic fallback") | |
| return self._heuristic_mapping(gdf_columns, cdf_columns) | |
| def _heuristic_mapping(self, gdf_columns: List[str], cdf_columns: List[str]) -> Dict[str, str]: | |
| """Generate heuristic mapping based on simple patterns. | |
| Args: | |
| gdf_columns: Source column names | |
| cdf_columns: Target column names | |
| Returns: | |
| Dictionary with heuristic-based mappings | |
| """ | |
| logger.info(f"Generating heuristic mapping for {len(gdf_columns)} source columns") | |
| mapping = {} | |
| # Simple heuristic mappings based on common patterns | |
| for gdf_col in gdf_columns: | |
| gdf_lower = gdf_col.lower() | |
| # Find best match in CDF columns | |
| best_match = None | |
| best_score = 0 | |
| for cdf_col in cdf_columns: | |
| cdf_lower = cdf_col.lower() | |
| score = self._calculate_similarity(gdf_lower, cdf_lower) | |
| if score > best_score and score > 0.3: # Minimum similarity threshold | |
| best_match = cdf_col | |
| best_score = score | |
| if best_match: | |
| mapping[gdf_col] = best_match | |
| logger.info(f"Heuristic mapping generated {len(mapping)} field mappings") | |
| return mapping | |
| def _calculate_similarity(self, str1: str, str2: str) -> float: | |
| """Calculate simple similarity score between two strings. | |
| Args: | |
| str1: First string | |
| str2: Second string | |
| Returns: | |
| Similarity score between 0 and 1 | |
| """ | |
| # Simple substring matching | |
| if str1 == str2: | |
| return 1.0 | |
| if str1 in str2 or str2 in str1: | |
| return 0.8 | |
| # Check for common patterns | |
| common_patterns = [ | |
| ("id", "id"), ("name", "name"), ("date", "date"), | |
| ("total", "amount"), ("amount", "total"), ("qty", "quantity"), | |
| ("customer", "customer"), ("item", "item"), ("status", "status") | |
| ] | |
| for pattern1, pattern2 in common_patterns: | |
| if pattern1 in str1 and pattern2 in str2: | |
| return 0.6 | |
| return 0.0 | |
| def _get_entity_guidance(self, entity: str) -> str: | |
| """Get entity-specific mapping guidance. | |
| Args: | |
| entity: Entity type | |
| Returns: | |
| Guidance string for the entity | |
| """ | |
| guidance_map = { | |
| "sales_orders": """ | |
| - Look for order/transaction IDs (tranId, orderNumber, soNumber, etc.) | |
| - Date fields often contain 'date', 'dt', or 'time' (trandate, orderDate, etc.) | |
| - Customer references (entity, customer, custId, clientId, etc.) | |
| - Amount/total fields (total, amount, value, sum, etc.) | |
| - Status fields (status, state, condition, etc.) | |
| - Currency codes (currency, curr, currencyCode, etc.) | |
| - Line item details (item, product, sku, description, qty, price, etc.) | |
| """.strip(), | |
| "customers": """ | |
| - Customer IDs (custId, customerId, clientId, entity, etc.) | |
| - Names (name, customerName, companyName, fullName, etc.) | |
| - Contact info (email, phone, telephone, mobile, contact, etc.) | |
| - Address fields (address, addr, street, city, state, zip, postal, country, etc.) | |
| - Company flags (isCompany, type, customerType, etc.) | |
| - Status (status, active, enabled, etc.) | |
| - Dates (created, modified, dateCreated, lastUpdate, etc.) | |
| """.strip(), | |
| "invoices": """ | |
| - Invoice IDs (invoiceId, invNumber, docNumber, etc.) | |
| - Dates (invoiceDate, invDate, dateIssued, dueDate, etc.) | |
| - Customer references (customer, custId, billTo, etc.) | |
| - Amounts (total, amount, invoiceTotal, balance, etc.) | |
| - Status (status, paid, outstanding, etc.) | |
| - Line items (item, description, qty, rate, lineTotal, etc.) | |
| """.strip(), | |
| "purchase_orders": """ | |
| - PO numbers (poNumber, purchaseOrder, docNumber, etc.) | |
| - Dates (poDate, orderDate, expectedDate, receiptDate, etc.) | |
| - Vendor info (vendor, supplier, vendorId, etc.) | |
| - Amounts (total, amount, poTotal, etc.) | |
| - Status (status, approved, received, etc.) | |
| - Line items (item, description, qty, cost, lineTotal, etc.) | |
| """.strip(), | |
| "inventory_items": """ | |
| - Item IDs (itemId, sku, productId, partNumber, etc.) | |
| - Names (itemName, productName, description, etc.) | |
| - Descriptions (description, details, notes, etc.) | |
| - Pricing (price, cost, basePrice, unitPrice, etc.) | |
| - Quantities (qty, quantity, onHand, available, stock, etc.) | |
| - Status (active, enabled, discontinued, etc.) | |
| - Vendor info (vendor, supplier, preferredVendor, etc.) | |
| """.strip() | |
| } | |
| return guidance_map.get(entity, "") | |
| def _validate_mapping(self, mapping: Dict[str, str], | |
| gdf_columns: List[str], cdf_columns: List[str]) -> bool: | |
| """Validate the generated mapping. | |
| Args: | |
| mapping: Generated mapping dictionary | |
| gdf_columns: Source columns | |
| cdf_columns: Target columns | |
| Returns: | |
| True if mapping is valid | |
| """ | |
| if not isinstance(mapping, dict): | |
| return False | |
| # Check that all keys are valid GDF columns | |
| for gdf_col in mapping.keys(): | |
| if gdf_col not in gdf_columns: | |
| logger.warning(f"Invalid source column in mapping: {gdf_col}") | |
| return False | |
| # Check that all values are valid CDF columns | |
| for cdf_col in mapping.values(): | |
| if cdf_col not in cdf_columns: | |
| logger.warning(f"Invalid target column in mapping: {cdf_col}") | |
| return False | |
| return True | |
| def create_llm_handler(**kwargs) -> LLMHandler: | |
| """Factory function to create LLM handler. | |
| Args: | |
| **kwargs: Additional arguments for handler initialization | |
| Returns: | |
| LLM handler instance | |
| """ | |
| return LLMHandler(**kwargs) | |
| def load_template_context(template_path: Optional[Path] = None) -> Dict[str, Any]: | |
| """Load template context for LLM prompts. | |
| Args: | |
| template_path: Path to template.json file | |
| Returns: | |
| Template context dictionary | |
| """ | |
| if template_path is None: | |
| template_path = Path("template.json") | |
| try: | |
| with open(template_path, 'r', encoding='utf-8') as f: | |
| template_data = json.load(f) | |
| # Extract sample mappings for context | |
| context = {} | |
| for erp_name, erp_data in template_data.items(): | |
| if erp_name == "CDF_META": | |
| continue | |
| context[erp_name] = {} | |
| for entity, mappings in erp_data.items(): | |
| # Take first few mappings as examples | |
| sample_mappings = dict(list(mappings.items())[:5]) | |
| context[erp_name][entity] = sample_mappings | |
| return context | |
| except Exception as e: | |
| logger.warning(f"Failed to load template context: {e}") | |
| return {} | |