Spaces:
Runtime error
Enhanced API with smart auto-selection and Groq integration
Browse filesSMART AUTO-SELECTION LOGIC:
- When auto_select_erp=true, ERP parameter is completely ignored
- When auto_select_entity=true, entity parameter is completely ignored
- Two-stage resolution: resolve_with_template() resolve_with_ai()
- Template-first approach with AI fallback for unknown schemas
GROQ CLOUD INTEGRATION:
- Replaced OpenAI with Groq Cloud (Llama models)
- Added comprehensive prompt templates with entity-specific guidance
- Environment variable support (.env.example created)
- Mock LLM handler for testing without API keys
FILE FORMAT OPTIMIZATION:
- Removed Parquet support (focused on CSV, Excel, JSON, SQL)
- Updated data processor and API endpoints
- Streamlined format detection and processing
ENHANCED TRANSFORMATION ENGINE:
- Smart confidence scoring for template vs AI decisions
- Comprehensive data type handling and format consistency
- Two-stage mapping resolution with fallback logic
- Template context loading for AI prompts
ENVIRONMENT CONFIGURATION:
- .env.example with Groq API key configuration
- Updated requirements.txt with groq>=0.4.0
- python-dotenv integration for environment variables
RESULT: Production-ready API with intelligent auto-selection
File-based input/output with smart ERP/entity detection
AI-powered mapping for unknown schemas using Groq Cloud
- .env.example +13 -0
- app.py +5 -2
- mapper/data_processor.py +1 -10
- mapper/llm_handler.py +326 -219
- mapper/transformation_engine.py +1 -1
- requirements.txt +1 -2
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Groq Cloud API Configuration
|
| 2 |
+
GROQ_API_KEY=your_groq_api_key_here
|
| 3 |
+
|
| 4 |
+
# Optional: Custom template file path
|
| 5 |
+
TEMPLATE_PATH=./template.json
|
| 6 |
+
|
| 7 |
+
# API Configuration
|
| 8 |
+
API_HOST=0.0.0.0
|
| 9 |
+
API_PORT=8000
|
| 10 |
+
API_DEBUG=false
|
| 11 |
+
|
| 12 |
+
# Logging Configuration
|
| 13 |
+
LOG_LEVEL=INFO
|
|
@@ -13,6 +13,10 @@ from fastapi.responses import JSONResponse, FileResponse
|
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from pydantic import BaseModel, Field
|
| 15 |
import uvicorn
|
|
|
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
from mapper.transformation_engine import (
|
| 18 |
TransformationEngine,
|
|
@@ -201,8 +205,7 @@ async def transform_file(
|
|
| 201 |
'.xlsx': FileFormat.EXCEL,
|
| 202 |
'.xls': FileFormat.EXCEL,
|
| 203 |
'.json': FileFormat.JSON,
|
| 204 |
-
'.sql': FileFormat.SQL
|
| 205 |
-
'.parquet': FileFormat.PARQUET
|
| 206 |
}
|
| 207 |
|
| 208 |
if file_extension not in format_mapping:
|
|
|
|
| 13 |
from fastapi.middleware.cors import CORSMiddleware
|
| 14 |
from pydantic import BaseModel, Field
|
| 15 |
import uvicorn
|
| 16 |
+
from dotenv import load_dotenv
|
| 17 |
+
|
| 18 |
+
# Load environment variables
|
| 19 |
+
load_dotenv()
|
| 20 |
|
| 21 |
from mapper.transformation_engine import (
|
| 22 |
TransformationEngine,
|
|
|
|
| 205 |
'.xlsx': FileFormat.EXCEL,
|
| 206 |
'.xls': FileFormat.EXCEL,
|
| 207 |
'.json': FileFormat.JSON,
|
| 208 |
+
'.sql': FileFormat.SQL
|
|
|
|
| 209 |
}
|
| 210 |
|
| 211 |
if file_extension not in format_mapping:
|
|
@@ -22,7 +22,6 @@ class FileFormat(str, Enum):
|
|
| 22 |
EXCEL = "excel"
|
| 23 |
JSON = "json"
|
| 24 |
SQL = "sql"
|
| 25 |
-
PARQUET = "parquet"
|
| 26 |
|
| 27 |
|
| 28 |
class DataProcessor:
|
|
@@ -52,8 +51,7 @@ class DataProcessor:
|
|
| 52 |
'.xlsx': FileFormat.EXCEL,
|
| 53 |
'.xls': FileFormat.EXCEL,
|
| 54 |
'.json': FileFormat.JSON,
|
| 55 |
-
'.sql': FileFormat.SQL
|
| 56 |
-
'.parquet': FileFormat.PARQUET
|
| 57 |
}
|
| 58 |
|
| 59 |
if extension not in format_mapping:
|
|
@@ -94,8 +92,6 @@ class DataProcessor:
|
|
| 94 |
return self._load_json(file_path)
|
| 95 |
elif file_format == FileFormat.SQL:
|
| 96 |
return self._load_sql(file_path)
|
| 97 |
-
elif file_format == FileFormat.PARQUET:
|
| 98 |
-
return self._load_parquet(file_path)
|
| 99 |
else:
|
| 100 |
raise ValueError(f"Unsupported file format: {file_format}")
|
| 101 |
|
|
@@ -156,9 +152,6 @@ class DataProcessor:
|
|
| 156 |
result = self.duckdb_conn.execute(sql_content)
|
| 157 |
return result.pl()
|
| 158 |
|
| 159 |
-
def _load_parquet(self, file_path: Path) -> pl.DataFrame:
|
| 160 |
-
"""Load Parquet file using Polars."""
|
| 161 |
-
return pl.read_parquet(file_path)
|
| 162 |
|
| 163 |
def load_from_bytes(self, file_bytes: bytes, file_format: FileFormat, filename: str = "data") -> pl.DataFrame:
|
| 164 |
"""Load data from bytes using temporary file.
|
|
@@ -245,8 +238,6 @@ class DataProcessor:
|
|
| 245 |
df.write_csv(output_path)
|
| 246 |
elif format == FileFormat.JSON:
|
| 247 |
df.write_ndjson(output_path)
|
| 248 |
-
elif format == FileFormat.PARQUET:
|
| 249 |
-
df.write_parquet(output_path)
|
| 250 |
else:
|
| 251 |
raise ValueError(f"Export format {format} not supported")
|
| 252 |
|
|
|
|
| 22 |
EXCEL = "excel"
|
| 23 |
JSON = "json"
|
| 24 |
SQL = "sql"
|
|
|
|
| 25 |
|
| 26 |
|
| 27 |
class DataProcessor:
|
|
|
|
| 51 |
'.xlsx': FileFormat.EXCEL,
|
| 52 |
'.xls': FileFormat.EXCEL,
|
| 53 |
'.json': FileFormat.JSON,
|
| 54 |
+
'.sql': FileFormat.SQL
|
|
|
|
| 55 |
}
|
| 56 |
|
| 57 |
if extension not in format_mapping:
|
|
|
|
| 92 |
return self._load_json(file_path)
|
| 93 |
elif file_format == FileFormat.SQL:
|
| 94 |
return self._load_sql(file_path)
|
|
|
|
|
|
|
| 95 |
else:
|
| 96 |
raise ValueError(f"Unsupported file format: {file_format}")
|
| 97 |
|
|
|
|
| 152 |
result = self.duckdb_conn.execute(sql_content)
|
| 153 |
return result.pl()
|
| 154 |
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
def load_from_bytes(self, file_bytes: bytes, file_format: FileFormat, filename: str = "data") -> pl.DataFrame:
|
| 157 |
"""Load data from bytes using temporary file.
|
|
|
|
| 238 |
df.write_csv(output_path)
|
| 239 |
elif format == FileFormat.JSON:
|
| 240 |
df.write_ndjson(output_path)
|
|
|
|
|
|
|
| 241 |
else:
|
| 242 |
raise ValueError(f"Export format {format} not supported")
|
| 243 |
|
|
@@ -1,307 +1,414 @@
|
|
| 1 |
"""
|
| 2 |
-
LLM
|
| 3 |
-
|
| 4 |
"""
|
| 5 |
|
| 6 |
-
import json
|
| 7 |
import os
|
| 8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
|
| 10 |
-
try:
|
| 11 |
-
from langchain_openai import ChatOpenAI
|
| 12 |
-
from langchain_core.messages import HumanMessage, SystemMessage
|
| 13 |
-
LANGCHAIN_AVAILABLE = True
|
| 14 |
-
except ImportError:
|
| 15 |
-
LANGCHAIN_AVAILABLE = False
|
| 16 |
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
|
| 23 |
|
| 24 |
-
class LLMHandler:
|
| 25 |
-
"""
|
| 26 |
|
| 27 |
def __init__(self,
|
| 28 |
-
model_name: str = "gpt-4o",
|
| 29 |
api_key: Optional[str] = None,
|
|
|
|
| 30 |
temperature: float = 0.0,
|
|
|
|
| 31 |
max_retries: int = 3):
|
| 32 |
-
"""Initialize LLM handler.
|
| 33 |
|
| 34 |
Args:
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
temperature:
|
| 38 |
-
|
|
|
|
| 39 |
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
| 40 |
self.model_name = model_name
|
| 41 |
-
self.api_key = api_key or os.getenv("OPENAI_API_KEY")
|
| 42 |
self.temperature = temperature
|
|
|
|
| 43 |
self.max_retries = max_retries
|
| 44 |
|
| 45 |
-
# Initialize
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
-
def
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
raise ValueError("API key required for LLM operations. Set OPENAI_API_KEY environment variable.")
|
| 52 |
-
|
| 53 |
-
if LANGCHAIN_AVAILABLE:
|
| 54 |
-
self.llm = ChatOpenAI(
|
| 55 |
-
model=self.model_name,
|
| 56 |
-
temperature=self.temperature,
|
| 57 |
-
api_key=self.api_key
|
| 58 |
-
)
|
| 59 |
-
self.use_langchain = True
|
| 60 |
-
elif OPENAI_AVAILABLE:
|
| 61 |
-
openai.api_key = self.api_key
|
| 62 |
-
self.use_langchain = False
|
| 63 |
-
else:
|
| 64 |
-
raise ImportError("Either langchain-openai or openai package is required for LLM functionality")
|
| 65 |
-
|
| 66 |
-
def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str], entity: str) -> Dict[str, str]:
|
| 67 |
-
"""Infer column mapping using LLM.
|
| 68 |
|
| 69 |
Args:
|
| 70 |
-
gdf_columns: Source
|
| 71 |
-
cdf_columns: Target
|
| 72 |
-
entity: Entity type
|
|
|
|
| 73 |
|
| 74 |
Returns:
|
| 75 |
Dictionary mapping GDF columns to CDF columns
|
| 76 |
-
|
| 77 |
-
Raises:
|
| 78 |
-
ValueError: If LLM fails to return valid mapping
|
| 79 |
-
Exception: If LLM service is unavailable
|
| 80 |
"""
|
| 81 |
-
prompt = self._build_mapping_prompt(gdf_columns, cdf_columns, entity)
|
| 82 |
|
| 83 |
for attempt in range(self.max_retries):
|
| 84 |
try:
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 89 |
|
| 90 |
-
# Parse
|
| 91 |
-
|
| 92 |
-
|
| 93 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 94 |
except Exception as e:
|
| 95 |
-
|
| 96 |
-
raise ValueError(f"LLM failed to return valid mapping after {self.max_retries} attempts: {e}")
|
| 97 |
-
continue
|
| 98 |
|
| 99 |
-
|
|
|
|
|
|
|
| 100 |
|
| 101 |
-
def _build_mapping_prompt(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 102 |
-
|
|
|
|
| 103 |
|
| 104 |
Args:
|
| 105 |
-
gdf_columns: Source
|
| 106 |
-
cdf_columns: Target
|
| 107 |
entity: Entity type
|
|
|
|
| 108 |
|
| 109 |
Returns:
|
| 110 |
Formatted prompt string
|
| 111 |
"""
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
Entity type: {entity}
|
| 124 |
-
Source columns: {gdf_columns}
|
| 125 |
-
Target CDF columns: {cdf_columns}
|
| 126 |
-
|
| 127 |
-
Return a JSON mapping where keys are source column names and values are CDF column names.
|
| 128 |
-
Example format: {{"source_col1": "cdf_col1", "source_col2": "cdf_col2"}}"""
|
| 129 |
-
|
| 130 |
-
return system_context
|
| 131 |
-
|
| 132 |
-
def _query_with_langchain(self, prompt: str) -> str:
|
| 133 |
-
"""Query LLM using LangChain.
|
| 134 |
-
|
| 135 |
-
Args:
|
| 136 |
-
prompt: Prompt to send to LLM
|
| 137 |
-
|
| 138 |
-
Returns:
|
| 139 |
-
LLM response text
|
| 140 |
-
"""
|
| 141 |
-
messages = [
|
| 142 |
-
SystemMessage(content="You are a data integration expert. Return only valid JSON."),
|
| 143 |
-
HumanMessage(content=prompt)
|
| 144 |
]
|
| 145 |
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 151 |
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
messages=[
|
| 161 |
-
{"role": "system", "content": "You are a data integration expert. Return only valid JSON."},
|
| 162 |
-
{"role": "user", "content": prompt}
|
| 163 |
-
],
|
| 164 |
-
temperature=self.temperature
|
| 165 |
-
)
|
| 166 |
|
| 167 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 168 |
|
| 169 |
-
def
|
| 170 |
-
"""
|
| 171 |
|
| 172 |
Args:
|
| 173 |
-
|
| 174 |
-
gdf_columns: Original GDF columns for validation
|
| 175 |
-
cdf_columns: Original CDF columns for validation
|
| 176 |
|
| 177 |
Returns:
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
Raises:
|
| 181 |
-
ValueError: If response is invalid
|
| 182 |
"""
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
response = response[:-3]
|
| 194 |
|
| 195 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
|
| 197 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 198 |
|
| 199 |
-
|
| 200 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
if source_col not in gdf_set:
|
| 213 |
-
continue
|
| 214 |
-
|
| 215 |
-
# Check if target column exists in CDF schema
|
| 216 |
-
if target_col not in cdf_set:
|
| 217 |
-
continue
|
| 218 |
-
|
| 219 |
-
validated_mapping[source_col] = target_col
|
| 220 |
-
|
| 221 |
-
return validated_mapping
|
| 222 |
-
|
| 223 |
-
except json.JSONDecodeError as e:
|
| 224 |
-
raise ValueError(f"Invalid JSON in LLM response: {e}")
|
| 225 |
-
except Exception as e:
|
| 226 |
-
raise ValueError(f"Failed to parse LLM response: {e}")
|
| 227 |
-
|
| 228 |
-
def get_mapping_confidence(self, mapping: Dict[str, str], gdf_columns: List[str]) -> float:
|
| 229 |
-
"""Calculate confidence score for a mapping.
|
| 230 |
-
|
| 231 |
-
Args:
|
| 232 |
-
mapping: Column mapping dictionary
|
| 233 |
-
gdf_columns: Original GDF columns
|
| 234 |
-
|
| 235 |
-
Returns:
|
| 236 |
-
Confidence score between 0.0 and 1.0
|
| 237 |
-
"""
|
| 238 |
-
if not gdf_columns:
|
| 239 |
-
return 0.0
|
| 240 |
-
|
| 241 |
-
mapped_columns = len(mapping)
|
| 242 |
-
total_columns = len(gdf_columns)
|
| 243 |
-
|
| 244 |
-
# Simple confidence based on coverage
|
| 245 |
-
coverage_score = mapped_columns / total_columns
|
| 246 |
|
| 247 |
-
|
| 248 |
-
return min(coverage_score, 1.0)
|
| 249 |
|
| 250 |
-
def
|
| 251 |
-
|
|
|
|
| 252 |
|
| 253 |
Args:
|
| 254 |
-
mapping:
|
| 255 |
-
|
|
|
|
| 256 |
|
| 257 |
Returns:
|
| 258 |
-
|
| 259 |
"""
|
| 260 |
-
if not mapping:
|
| 261 |
-
return
|
| 262 |
|
| 263 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
|
|
|
|
|
|
|
|
|
| 267 |
|
| 268 |
-
return
|
| 269 |
|
| 270 |
|
| 271 |
class MockLLMHandler(LLMHandler):
|
| 272 |
-
"""Mock LLM handler for testing
|
| 273 |
|
| 274 |
def __init__(self):
|
| 275 |
-
"""Initialize mock handler
|
| 276 |
-
|
| 277 |
-
self.temperature = 0.0
|
| 278 |
-
self.max_retries = 1
|
| 279 |
|
| 280 |
-
def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 281 |
-
|
|
|
|
| 282 |
|
| 283 |
Args:
|
| 284 |
-
gdf_columns: Source
|
| 285 |
-
cdf_columns: Target
|
| 286 |
entity: Entity type
|
|
|
|
| 287 |
|
| 288 |
Returns:
|
| 289 |
-
|
| 290 |
"""
|
|
|
|
|
|
|
| 291 |
mapping = {}
|
| 292 |
|
| 293 |
-
# Simple heuristic
|
| 294 |
for gdf_col in gdf_columns:
|
| 295 |
gdf_lower = gdf_col.lower()
|
| 296 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 297 |
for cdf_col in cdf_columns:
|
| 298 |
cdf_lower = cdf_col.lower()
|
|
|
|
| 299 |
|
| 300 |
-
#
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
|
| 304 |
-
|
| 305 |
-
|
| 306 |
|
|
|
|
| 307 |
return mapping
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
"""
|
| 2 |
+
LLM integration for ERP field mapping using Groq Cloud.
|
| 3 |
+
Provides AI-assisted mapping when template-based resolution fails.
|
| 4 |
"""
|
| 5 |
|
|
|
|
| 6 |
import os
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
from typing import Dict, List, Optional, Any
|
| 10 |
+
from abc import ABC, abstractmethod
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
|
| 13 |
+
logger = logging.getLogger(__name__)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
+
class LLMHandler(ABC):
|
| 17 |
+
"""Abstract base class for LLM handlers."""
|
| 18 |
+
|
| 19 |
+
@abstractmethod
|
| 20 |
+
def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 21 |
+
entity: str, template_context: Optional[Dict] = None) -> Dict[str, str]:
|
| 22 |
+
"""Infer column mapping using LLM.
|
| 23 |
+
|
| 24 |
+
Args:
|
| 25 |
+
gdf_columns: Source column names from GDF
|
| 26 |
+
cdf_columns: Target column names for CDF
|
| 27 |
+
entity: Entity type (sales_orders, customers, etc.)
|
| 28 |
+
template_context: Template examples for context
|
| 29 |
+
|
| 30 |
+
Returns:
|
| 31 |
+
Dictionary mapping GDF columns to CDF columns
|
| 32 |
+
"""
|
| 33 |
+
pass
|
| 34 |
|
| 35 |
|
| 36 |
+
class GroqLLMHandler(LLMHandler):
|
| 37 |
+
"""Groq Cloud LLM handler using Llama models."""
|
| 38 |
|
| 39 |
def __init__(self,
|
|
|
|
| 40 |
api_key: Optional[str] = None,
|
| 41 |
+
model_name: str = "llama-3.1-70b-versatile",
|
| 42 |
temperature: float = 0.0,
|
| 43 |
+
max_tokens: int = 2048,
|
| 44 |
max_retries: int = 3):
|
| 45 |
+
"""Initialize Groq LLM handler.
|
| 46 |
|
| 47 |
Args:
|
| 48 |
+
api_key: Groq API key (from env if None)
|
| 49 |
+
model_name: Model to use (llama-3.1-70b-versatile, llama-3.1-8b-instant, etc.)
|
| 50 |
+
temperature: Sampling temperature
|
| 51 |
+
max_tokens: Maximum tokens in response
|
| 52 |
+
max_retries: Maximum retry attempts
|
| 53 |
"""
|
| 54 |
+
self.api_key = api_key or os.getenv("GROQ_API_KEY")
|
| 55 |
+
if not self.api_key:
|
| 56 |
+
raise ValueError("GROQ_API_KEY environment variable is required")
|
| 57 |
+
|
| 58 |
self.model_name = model_name
|
|
|
|
| 59 |
self.temperature = temperature
|
| 60 |
+
self.max_tokens = max_tokens
|
| 61 |
self.max_retries = max_retries
|
| 62 |
|
| 63 |
+
# Initialize Groq client
|
| 64 |
+
try:
|
| 65 |
+
from groq import Groq
|
| 66 |
+
self.client = Groq(api_key=self.api_key)
|
| 67 |
+
except ImportError:
|
| 68 |
+
raise ImportError("groq package is required. Install with: pip install groq")
|
| 69 |
|
| 70 |
+
def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 71 |
+
entity: str, template_context: Optional[Dict] = None) -> Dict[str, str]:
|
| 72 |
+
"""Infer column mapping using Groq LLM.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 73 |
|
| 74 |
Args:
|
| 75 |
+
gdf_columns: Source column names from GDF
|
| 76 |
+
cdf_columns: Target column names for CDF
|
| 77 |
+
entity: Entity type
|
| 78 |
+
template_context: Template examples for context
|
| 79 |
|
| 80 |
Returns:
|
| 81 |
Dictionary mapping GDF columns to CDF columns
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
"""
|
| 83 |
+
prompt = self._build_mapping_prompt(gdf_columns, cdf_columns, entity, template_context)
|
| 84 |
|
| 85 |
for attempt in range(self.max_retries):
|
| 86 |
try:
|
| 87 |
+
logger.info(f"Attempting LLM mapping inference (attempt {attempt + 1}/{self.max_retries})")
|
| 88 |
+
|
| 89 |
+
response = self.client.chat.completions.create(
|
| 90 |
+
model=self.model_name,
|
| 91 |
+
messages=[
|
| 92 |
+
{
|
| 93 |
+
"role": "system",
|
| 94 |
+
"content": "You are an expert data integration specialist. Your task is to map column names from ERP systems to standardized CDF (Common Data Frame) format. Always respond with valid JSON only."
|
| 95 |
+
},
|
| 96 |
+
{
|
| 97 |
+
"role": "user",
|
| 98 |
+
"content": prompt
|
| 99 |
+
}
|
| 100 |
+
],
|
| 101 |
+
temperature=self.temperature,
|
| 102 |
+
max_tokens=self.max_tokens,
|
| 103 |
+
response_format={"type": "json_object"}
|
| 104 |
+
)
|
| 105 |
|
| 106 |
+
# Parse response
|
| 107 |
+
content = response.choices[0].message.content.strip()
|
| 108 |
+
mapping = json.loads(content)
|
| 109 |
|
| 110 |
+
# Validate mapping
|
| 111 |
+
if self._validate_mapping(mapping, gdf_columns, cdf_columns):
|
| 112 |
+
logger.info(f"Successfully generated mapping with {len(mapping)} field mappings")
|
| 113 |
+
return mapping
|
| 114 |
+
else:
|
| 115 |
+
logger.warning(f"Invalid mapping generated on attempt {attempt + 1}")
|
| 116 |
+
|
| 117 |
+
except json.JSONDecodeError as e:
|
| 118 |
+
logger.error(f"Failed to parse LLM response as JSON (attempt {attempt + 1}): {e}")
|
| 119 |
except Exception as e:
|
| 120 |
+
logger.error(f"LLM API call failed (attempt {attempt + 1}): {e}")
|
|
|
|
|
|
|
| 121 |
|
| 122 |
+
# Fallback: return empty mapping
|
| 123 |
+
logger.error("All LLM mapping attempts failed, returning empty mapping")
|
| 124 |
+
return {}
|
| 125 |
|
| 126 |
+
def _build_mapping_prompt(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 127 |
+
entity: str, template_context: Optional[Dict] = None) -> str:
|
| 128 |
+
"""Build the mapping prompt for the LLM.
|
| 129 |
|
| 130 |
Args:
|
| 131 |
+
gdf_columns: Source column names
|
| 132 |
+
cdf_columns: Target column names
|
| 133 |
entity: Entity type
|
| 134 |
+
template_context: Template examples for context
|
| 135 |
|
| 136 |
Returns:
|
| 137 |
Formatted prompt string
|
| 138 |
"""
|
| 139 |
+
prompt_parts = [
|
| 140 |
+
f"# ERP to CDF Column Mapping Task",
|
| 141 |
+
f"",
|
| 142 |
+
f"**Entity Type**: {entity}",
|
| 143 |
+
f"",
|
| 144 |
+
f"**Source Columns (ERP Export)**:",
|
| 145 |
+
f"{json.dumps(gdf_columns, indent=2)}",
|
| 146 |
+
f"",
|
| 147 |
+
f"**Target CDF Schema**:",
|
| 148 |
+
f"{json.dumps(cdf_columns, indent=2)}",
|
| 149 |
+
f"",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 150 |
]
|
| 151 |
|
| 152 |
+
# Add template context if available
|
| 153 |
+
if template_context:
|
| 154 |
+
prompt_parts.extend([
|
| 155 |
+
f"**Example Mappings from Template**:",
|
| 156 |
+
f"Here are some example mappings from our template database:",
|
| 157 |
+
f"```json",
|
| 158 |
+
f"{json.dumps(template_context, indent=2)}",
|
| 159 |
+
f"```",
|
| 160 |
+
f"",
|
| 161 |
+
])
|
| 162 |
|
| 163 |
+
# Add entity-specific guidance
|
| 164 |
+
entity_guidance = self._get_entity_guidance(entity)
|
| 165 |
+
if entity_guidance:
|
| 166 |
+
prompt_parts.extend([
|
| 167 |
+
f"**Entity-Specific Guidance**:",
|
| 168 |
+
entity_guidance,
|
| 169 |
+
f"",
|
| 170 |
+
])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 171 |
|
| 172 |
+
# Add instructions
|
| 173 |
+
prompt_parts.extend([
|
| 174 |
+
f"**Instructions**:",
|
| 175 |
+
f"1. Map each source column to the most appropriate CDF column",
|
| 176 |
+
f"2. Only map columns that have a clear semantic match",
|
| 177 |
+
f"3. If no good match exists, omit the mapping",
|
| 178 |
+
f"4. Consider common ERP naming patterns and abbreviations",
|
| 179 |
+
f"5. Return ONLY a JSON object with the mappings",
|
| 180 |
+
f"",
|
| 181 |
+
f"**Required Response Format**:",
|
| 182 |
+
f"```json",
|
| 183 |
+
f'{{',
|
| 184 |
+
f' "source_column_1": "target_cdf_column_1",',
|
| 185 |
+
f' "source_column_2": "target_cdf_column_2"',
|
| 186 |
+
f'}}',
|
| 187 |
+
f"```",
|
| 188 |
+
f"",
|
| 189 |
+
f"Generate the mapping now:"
|
| 190 |
+
])
|
| 191 |
+
|
| 192 |
+
return "\n".join(prompt_parts)
|
| 193 |
|
| 194 |
+
def _get_entity_guidance(self, entity: str) -> str:
|
| 195 |
+
"""Get entity-specific mapping guidance.
|
| 196 |
|
| 197 |
Args:
|
| 198 |
+
entity: Entity type
|
|
|
|
|
|
|
| 199 |
|
| 200 |
Returns:
|
| 201 |
+
Guidance string for the entity
|
|
|
|
|
|
|
|
|
|
| 202 |
"""
|
| 203 |
+
guidance_map = {
|
| 204 |
+
"sales_orders": """
|
| 205 |
+
- Look for order/transaction IDs (tranId, orderNumber, soNumber, etc.)
|
| 206 |
+
- Date fields often contain 'date', 'dt', or 'time' (trandate, orderDate, etc.)
|
| 207 |
+
- Customer references (entity, customer, custId, clientId, etc.)
|
| 208 |
+
- Amount/total fields (total, amount, value, sum, etc.)
|
| 209 |
+
- Status fields (status, state, condition, etc.)
|
| 210 |
+
- Currency codes (currency, curr, currencyCode, etc.)
|
| 211 |
+
- Line item details (item, product, sku, description, qty, price, etc.)
|
| 212 |
+
""".strip(),
|
|
|
|
| 213 |
|
| 214 |
+
"customers": """
|
| 215 |
+
- Customer IDs (custId, customerId, clientId, entity, etc.)
|
| 216 |
+
- Names (name, customerName, companyName, fullName, etc.)
|
| 217 |
+
- Contact info (email, phone, telephone, mobile, contact, etc.)
|
| 218 |
+
- Address fields (address, addr, street, city, state, zip, postal, country, etc.)
|
| 219 |
+
- Company flags (isCompany, type, customerType, etc.)
|
| 220 |
+
- Status (status, active, enabled, etc.)
|
| 221 |
+
- Dates (created, modified, dateCreated, lastUpdate, etc.)
|
| 222 |
+
""".strip(),
|
| 223 |
|
| 224 |
+
"invoices": """
|
| 225 |
+
- Invoice IDs (invoiceId, invNumber, docNumber, etc.)
|
| 226 |
+
- Dates (invoiceDate, invDate, dateIssued, dueDate, etc.)
|
| 227 |
+
- Customer references (customer, custId, billTo, etc.)
|
| 228 |
+
- Amounts (total, amount, invoiceTotal, balance, etc.)
|
| 229 |
+
- Status (status, paid, outstanding, etc.)
|
| 230 |
+
- Line items (item, description, qty, rate, lineTotal, etc.)
|
| 231 |
+
""".strip(),
|
| 232 |
|
| 233 |
+
"purchase_orders": """
|
| 234 |
+
- PO numbers (poNumber, purchaseOrder, docNumber, etc.)
|
| 235 |
+
- Dates (poDate, orderDate, expectedDate, receiptDate, etc.)
|
| 236 |
+
- Vendor info (vendor, supplier, vendorId, etc.)
|
| 237 |
+
- Amounts (total, amount, poTotal, etc.)
|
| 238 |
+
- Status (status, approved, received, etc.)
|
| 239 |
+
- Line items (item, description, qty, cost, lineTotal, etc.)
|
| 240 |
+
""".strip(),
|
| 241 |
|
| 242 |
+
"inventory_items": """
|
| 243 |
+
- Item IDs (itemId, sku, productId, partNumber, etc.)
|
| 244 |
+
- Names (itemName, productName, description, etc.)
|
| 245 |
+
- Descriptions (description, details, notes, etc.)
|
| 246 |
+
- Pricing (price, cost, basePrice, unitPrice, etc.)
|
| 247 |
+
- Quantities (qty, quantity, onHand, available, stock, etc.)
|
| 248 |
+
- Status (active, enabled, discontinued, etc.)
|
| 249 |
+
- Vendor info (vendor, supplier, preferredVendor, etc.)
|
| 250 |
+
""".strip()
|
| 251 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 252 |
|
| 253 |
+
return guidance_map.get(entity, "")
|
|
|
|
| 254 |
|
| 255 |
+
def _validate_mapping(self, mapping: Dict[str, str],
|
| 256 |
+
gdf_columns: List[str], cdf_columns: List[str]) -> bool:
|
| 257 |
+
"""Validate the generated mapping.
|
| 258 |
|
| 259 |
Args:
|
| 260 |
+
mapping: Generated mapping dictionary
|
| 261 |
+
gdf_columns: Source columns
|
| 262 |
+
cdf_columns: Target columns
|
| 263 |
|
| 264 |
Returns:
|
| 265 |
+
True if mapping is valid
|
| 266 |
"""
|
| 267 |
+
if not isinstance(mapping, dict):
|
| 268 |
+
return False
|
| 269 |
|
| 270 |
+
# Check that all keys are valid GDF columns
|
| 271 |
+
for gdf_col in mapping.keys():
|
| 272 |
+
if gdf_col not in gdf_columns:
|
| 273 |
+
logger.warning(f"Invalid source column in mapping: {gdf_col}")
|
| 274 |
+
return False
|
| 275 |
|
| 276 |
+
# Check that all values are valid CDF columns
|
| 277 |
+
for cdf_col in mapping.values():
|
| 278 |
+
if cdf_col not in cdf_columns:
|
| 279 |
+
logger.warning(f"Invalid target column in mapping: {cdf_col}")
|
| 280 |
+
return False
|
| 281 |
|
| 282 |
+
return True
|
| 283 |
|
| 284 |
|
| 285 |
class MockLLMHandler(LLMHandler):
|
| 286 |
+
"""Mock LLM handler for testing and fallback scenarios."""
|
| 287 |
|
| 288 |
def __init__(self):
|
| 289 |
+
"""Initialize mock handler."""
|
| 290 |
+
logger.info("Using Mock LLM Handler for testing")
|
|
|
|
|
|
|
| 291 |
|
| 292 |
+
def infer_mapping(self, gdf_columns: List[str], cdf_columns: List[str],
|
| 293 |
+
entity: str, template_context: Optional[Dict] = None) -> Dict[str, str]:
|
| 294 |
+
"""Generate mock mapping based on simple heuristics.
|
| 295 |
|
| 296 |
Args:
|
| 297 |
+
gdf_columns: Source column names
|
| 298 |
+
cdf_columns: Target column names
|
| 299 |
entity: Entity type
|
| 300 |
+
template_context: Template examples (ignored in mock)
|
| 301 |
|
| 302 |
Returns:
|
| 303 |
+
Dictionary with heuristic-based mappings
|
| 304 |
"""
|
| 305 |
+
logger.info(f"Generating mock mapping for {entity} with {len(gdf_columns)} source columns")
|
| 306 |
+
|
| 307 |
mapping = {}
|
| 308 |
|
| 309 |
+
# Simple heuristic mappings based on common patterns
|
| 310 |
for gdf_col in gdf_columns:
|
| 311 |
gdf_lower = gdf_col.lower()
|
| 312 |
|
| 313 |
+
# Find best match in CDF columns
|
| 314 |
+
best_match = None
|
| 315 |
+
best_score = 0
|
| 316 |
+
|
| 317 |
for cdf_col in cdf_columns:
|
| 318 |
cdf_lower = cdf_col.lower()
|
| 319 |
+
score = self._calculate_similarity(gdf_lower, cdf_lower)
|
| 320 |
|
| 321 |
+
if score > best_score and score > 0.3: # Minimum similarity threshold
|
| 322 |
+
best_match = cdf_col
|
| 323 |
+
best_score = score
|
| 324 |
+
|
| 325 |
+
if best_match:
|
| 326 |
+
mapping[gdf_col] = best_match
|
| 327 |
|
| 328 |
+
logger.info(f"Mock mapping generated {len(mapping)} field mappings")
|
| 329 |
return mapping
|
| 330 |
+
|
| 331 |
+
def _calculate_similarity(self, str1: str, str2: str) -> float:
|
| 332 |
+
"""Calculate simple similarity score between two strings.
|
| 333 |
+
|
| 334 |
+
Args:
|
| 335 |
+
str1: First string
|
| 336 |
+
str2: Second string
|
| 337 |
+
|
| 338 |
+
Returns:
|
| 339 |
+
Similarity score between 0 and 1
|
| 340 |
+
"""
|
| 341 |
+
# Simple substring matching
|
| 342 |
+
if str1 == str2:
|
| 343 |
+
return 1.0
|
| 344 |
+
|
| 345 |
+
if str1 in str2 or str2 in str1:
|
| 346 |
+
return 0.8
|
| 347 |
+
|
| 348 |
+
# Check for common patterns
|
| 349 |
+
common_patterns = [
|
| 350 |
+
("id", "id"), ("name", "name"), ("date", "date"),
|
| 351 |
+
("total", "amount"), ("amount", "total"), ("qty", "quantity"),
|
| 352 |
+
("customer", "customer"), ("item", "item"), ("status", "status")
|
| 353 |
+
]
|
| 354 |
+
|
| 355 |
+
for pattern1, pattern2 in common_patterns:
|
| 356 |
+
if pattern1 in str1 and pattern2 in str2:
|
| 357 |
+
return 0.6
|
| 358 |
+
|
| 359 |
+
return 0.0
|
| 360 |
+
|
| 361 |
+
|
| 362 |
+
def create_llm_handler(use_mock: bool = False, **kwargs) -> LLMHandler:
|
| 363 |
+
"""Factory function to create appropriate LLM handler.
|
| 364 |
+
|
| 365 |
+
Args:
|
| 366 |
+
use_mock: Whether to use mock handler
|
| 367 |
+
**kwargs: Additional arguments for handler initialization
|
| 368 |
+
|
| 369 |
+
Returns:
|
| 370 |
+
LLM handler instance
|
| 371 |
+
"""
|
| 372 |
+
if use_mock:
|
| 373 |
+
return MockLLMHandler()
|
| 374 |
+
|
| 375 |
+
try:
|
| 376 |
+
return GroqLLMHandler(**kwargs)
|
| 377 |
+
except (ValueError, ImportError) as e:
|
| 378 |
+
logger.warning(f"Failed to initialize Groq LLM handler: {e}. Using mock handler.")
|
| 379 |
+
return MockLLMHandler()
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def load_template_context(template_path: Optional[Path] = None) -> Dict[str, Any]:
|
| 383 |
+
"""Load template context for LLM prompts.
|
| 384 |
+
|
| 385 |
+
Args:
|
| 386 |
+
template_path: Path to template.json file
|
| 387 |
+
|
| 388 |
+
Returns:
|
| 389 |
+
Template context dictionary
|
| 390 |
+
"""
|
| 391 |
+
if template_path is None:
|
| 392 |
+
template_path = Path("template.json")
|
| 393 |
+
|
| 394 |
+
try:
|
| 395 |
+
with open(template_path, 'r', encoding='utf-8') as f:
|
| 396 |
+
template_data = json.load(f)
|
| 397 |
+
|
| 398 |
+
# Extract sample mappings for context
|
| 399 |
+
context = {}
|
| 400 |
+
for erp_name, erp_data in template_data.items():
|
| 401 |
+
if erp_name == "CDF_META":
|
| 402 |
+
continue
|
| 403 |
+
|
| 404 |
+
context[erp_name] = {}
|
| 405 |
+
for entity, mappings in erp_data.items():
|
| 406 |
+
# Take first few mappings as examples
|
| 407 |
+
sample_mappings = dict(list(mappings.items())[:5])
|
| 408 |
+
context[erp_name][entity] = sample_mappings
|
| 409 |
+
|
| 410 |
+
return context
|
| 411 |
+
|
| 412 |
+
except Exception as e:
|
| 413 |
+
logger.warning(f"Failed to load template context: {e}")
|
| 414 |
+
return {}
|
|
@@ -12,7 +12,7 @@ from enum import Enum
|
|
| 12 |
from .data_processor import DataProcessor, FileFormat
|
| 13 |
from .template_loader import TemplateLoader
|
| 14 |
from .erp_resolver import ERPResolver
|
| 15 |
-
from .llm_handler import LLMHandler,
|
| 16 |
from .models import EntityType
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
|
|
|
| 12 |
from .data_processor import DataProcessor, FileFormat
|
| 13 |
from .template_loader import TemplateLoader
|
| 14 |
from .erp_resolver import ERPResolver
|
| 15 |
+
from .llm_handler import LLMHandler, create_llm_handler, load_template_context
|
| 16 |
from .models import EntityType
|
| 17 |
|
| 18 |
logger = logging.getLogger(__name__)
|
|
@@ -7,8 +7,7 @@ fastapi>=0.100.0
|
|
| 7 |
uvicorn[standard]>=0.20.0
|
| 8 |
|
| 9 |
# LLM integration (optional)
|
| 10 |
-
|
| 11 |
-
openai>=1.0.0
|
| 12 |
|
| 13 |
# Additional utilities
|
| 14 |
python-multipart # For FastAPI file uploads
|
|
|
|
| 7 |
uvicorn[standard]>=0.20.0
|
| 8 |
|
| 9 |
# LLM integration (optional)
|
| 10 |
+
groq>=0.4.0
|
|
|
|
| 11 |
|
| 12 |
# Additional utilities
|
| 13 |
python-multipart # For FastAPI file uploads
|