File size: 17,267 Bytes
d448413
be86e78
afba74c
d448413
 
 
afba74c
 
 
 
 
 
d448413
 
d16f985
be86e78
d448413
 
 
0b4afac
d448413
afba74c
d448413
be86e78
d448413
 
afba74c
0b4afac
afba74c
 
 
d448413
afba74c
d448413
 
afba74c
d448413
d16f985
d448413
be86e78
afba74c
d16f985
 
 
be86e78
 
 
 
 
 
 
 
 
 
 
 
d16f985
 
be86e78
d16f985
 
 
be86e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d448413
afba74c
 
be86e78
d448413
 
afba74c
 
 
 
d448413
 
 
 
d16f985
 
 
 
d448413
 
be86e78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
afba74c
be86e78
 
 
 
 
 
 
afba74c
d448413
be86e78
 
 
 
afba74c
be86e78
 
af079bc
be86e78
 
 
 
 
 
 
 
 
 
 
af079bc
 
 
 
 
 
 
 
 
 
afba74c
d448413
afba74c
 
 
 
 
 
 
 
 
af079bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d448413
be86e78
d448413
d16f985
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d448413
afba74c
 
d448413
 
afba74c
d448413
 
afba74c
d448413
afba74c
 
 
 
 
 
 
 
 
 
d448413
afba74c
 
 
 
 
 
 
 
 
d448413
afba74c
 
 
 
 
 
 
 
d448413
afba74c
 
 
 
 
 
 
 
d448413
afba74c
 
 
 
 
 
 
 
 
 
d448413
afba74c
d448413
afba74c
 
 
d448413
 
afba74c
 
 
d448413
 
afba74c
d448413
afba74c
 
d448413
afba74c
 
 
 
 
d448413
afba74c
 
 
 
 
d448413
afba74c
d448413
 
d16f985
 
afba74c
 
 
 
 
 
 
d16f985
afba74c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
"""
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 {}