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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
#!/usr/bin/env python3
"""
LLM Fallback Router for VoucherBot

This module implements an LLM-powered semantic router that serves as a fallback
for handling natural language queries that the regex-based router cannot process.

Key Features:
- Intent classification for housing search queries
- Parameter extraction with validation
- Robust error handling and JSON parsing
- Support for context-aware routing
- Comprehensive input validation
- Multilingual support for English, Spanish, Chinese, and Bengali
"""

import json
import re
import logging
from typing import Dict, Any, Optional, Union, List
from dataclasses import dataclass
from enum import Enum

# Set up logging
logger = logging.getLogger(__name__)

class IntentType(Enum):
    """Supported intent types for housing search queries."""
    SEARCH_LISTINGS = "SEARCH_LISTINGS"
    CHECK_VIOLATIONS = "CHECK_VIOLATIONS"
    ASK_VOUCHER_SUPPORT = "ASK_VOUCHER_SUPPORT"
    REFINE_SEARCH = "REFINE_SEARCH"
    FOLLOW_UP = "FOLLOW_UP"
    HELP_REQUEST = "HELP_REQUEST"
    UNKNOWN = "UNKNOWN"

# Custom Exceptions
class LLMFallbackRouterError(Exception):
    """Base exception for LLM Fallback Router errors."""
    pass

class InvalidInputError(LLMFallbackRouterError):
    """Raised when input validation fails."""
    pass

class InvalidLLMResponseError(LLMFallbackRouterError):
    """Raised when LLM response cannot be parsed or validated."""
    pass

class LLMProcessingError(LLMFallbackRouterError):
    """Raised when LLM processing fails."""
    pass

@dataclass
class RouterResponse:
    """Structured response from the LLM Fallback Router."""
    intent: str
    parameters: Dict[str, Any]
    reasoning: str
    
    def to_dict(self) -> Dict[str, Any]:
        """Convert to dictionary format."""
        return {
            "intent": self.intent,
            "parameters": self.parameters,
            "reasoning": self.reasoning
        }

class LLMFallbackRouter:
    """
    LLM-powered fallback semantic router for VoucherBot.
    
    This router handles natural language queries that cannot be processed
    by the regex-based primary router, including edge cases, ambiguous
    language, and multilingual inputs.
    
    Supports:
    - English (en)
    - Spanish (es) 
    - Chinese (zh)
    - Bengali (bn)
    """
    
    # Enhanced Borough normalization mapping with multilingual support
    BOROUGH_MAPPING = {
        # English
        "bk": "Brooklyn",
        "brooklyn": "Brooklyn",
        "si": "Staten Island",
        "staten island": "Staten Island",
        "staten_island": "Staten Island",
        "qns": "Queens",
        "queens": "Queens",
        "bx": "Bronx",
        "bronx": "Bronx",
        "mnh": "Manhattan",
        "manhattan": "Manhattan",
        "nyc": None,  # Too vague
        "city": "Manhattan",  # Common NYC reference
        
        # Spanish
        "bronx": "Bronx",
        "brooklyn": "Brooklyn", 
        "manhattan": "Manhattan",
        "queens": "Queens",
        "isla staten": "Staten Island",
        "staten": "Staten Island",
        
        # Chinese
        "布朗克斯": "Bronx",
        "布鲁克林": "Brooklyn",
        "曼哈顿": "Manhattan", 
        "皇后区": "Queens",
        "史泰登岛": "Staten Island",
        "布朗士": "Bronx",  # Alternative spelling
        "皇后": "Queens",    # Short form
        
        # Bengali
        "ব্রংক্স": "Bronx",
        "ব্রুকলিন": "Brooklyn",
        "ম্যানহাটান": "Manhattan",
        "কুইন্স": "Queens", 
        "স্ট্যাটেন আইল্যান্ড": "Staten Island",
        "ব্রনক্স": "Bronx",  # Alternative spelling
    }
    
    # Enhanced Voucher type normalization mapping with multilingual support
    VOUCHER_MAPPING = {
        # English
        "section 8": "Section 8",
        "section eight": "Section 8",
        "section-8": "Section 8",
        "s8": "Section 8",
        "sec 8": "Section 8",
        "cityfheps": "CityFHEPS",
        "city fheps": "CityFHEPS",
        "cityfeps": "CityFHEPS",  # Common misspelling
        "hasa": "HASA",
        "housing voucher": "Housing Voucher",
        "voucher": "Housing Voucher",
        "hpd": "HPD",
        "dss": "DSS",
        "hra": "HRA",
        
        # Spanish
        "sección 8": "Section 8",
        "seccion 8": "Section 8",
        "vale de vivienda": "Housing Voucher",
        "voucher de vivienda": "Housing Voucher",
        "cupón de vivienda": "Housing Voucher",
        
        # Chinese 
        "住房券": "Housing Voucher",
        "第八条": "Section 8",
        "住房补助": "Housing Voucher",
        "租房券": "Housing Voucher",
        
        # Bengali
        "ভাউচার": "Housing Voucher",
        "হাউজিং ভাউচার": "Housing Voucher",
        "আবাসন ভাউচার": "Housing Voucher",
        "সেকশন ৮": "Section 8",
    }
    
    def __init__(self, llm_client: Any, debug: bool = False, max_retries: int = 3):
        """
        Initialize the LLM Fallback Router.
        
        Args:
            llm_client: An instance of an LLM interface (e.g., OpenAI or smolAI)
            debug: Enable debug logging
            max_retries: Maximum number of retry attempts for LLM calls
        """
        self.llm_client = llm_client
        self.debug = debug
        self.max_retries = max_retries
        
        if debug:
            logger.setLevel(logging.DEBUG)
            logger.debug("LLMFallbackRouter initialized in debug mode")
    
    def detect_languages(self, message: str) -> List[str]:
        """
        Detect languages present in the message.
        
        Args:
            message: Input message to analyze
            
        Returns:
            List of detected language codes
        """
        detected = []
        
        # English: Latin letters and English-specific patterns
        if re.search(r'[a-zA-Z]', message):
            detected.append('en')
            
        # Spanish: Spanish-specific characters and patterns
        if re.search(r'[áéíóúñ¿¡ü]', message) or any(word in message.lower() for word in ['pero', 'español', 'hola', 'ayuda', 'necesito']):
            detected.append('es')
            
        # Chinese: Chinese characters (CJK Unified Ideographs)
        if re.search(r'[\u4e00-\u9fff]', message):
            detected.append('zh')
            
        # Bengali: Bengali script
        if re.search(r'[\u0980-\u09FF]', message):
            detected.append('bn')
            
        return detected if detected else ['en']  # Default to English
    
    def format_prompt(self, message: str, context: Optional[str] = None, language: str = "en") -> str:
        """
        Format the prompt for the LLM with the given message and context.
        
        Args:
            message: User's message to route
            context: Optional context from previous messages or search state
            language: Language code for the user interface (en, es, zh, bn)
            
        Returns:
            Formatted prompt string
        """
        # Detect languages in the message
        detected_languages = self.detect_languages(message)
        
        # Language-specific prompt instructions
        language_instructions = {
            "en": "The user interface is in English. Respond appropriately to English queries.",
            "es": "La interfaz de usuario está en español. El usuario puede escribir en español, responde apropiadamente.",
            "zh": "用户界面是中文的。用户可能会用中文写消息,请适当回应。",
            "bn": "ব্যবহারকারী ইন্টারফেস বাংলায়। ব্যবহারকারী বাংলায় বার্তা লিখতে পারেন, উপযুক্তভাবে সাড়া দিন।"
        }
        
        # Language-specific examples for better understanding
        language_examples = {
            "en": [
                {"message": "I need help finding an apartment", "intent": "HELP_REQUEST"},
                {"message": "Show me listings in Brooklyn", "intent": "SEARCH_LISTINGS"},
                {"message": "What vouchers do you accept?", "intent": "ASK_VOUCHER_SUPPORT"}
            ],
            "es": [
                {"message": "Necesito ayuda para encontrar apartamento", "intent": "HELP_REQUEST"},
                {"message": "Busco apartamento en Brooklyn", "intent": "SEARCH_LISTINGS"},
                {"message": "¿Qué tipos de voucher aceptan?", "intent": "ASK_VOUCHER_SUPPORT"}
            ],
            "zh": [
                {"message": "我需要帮助找房子", "intent": "HELP_REQUEST"},
                {"message": "在布鲁克林找两居室", "intent": "SEARCH_LISTINGS"},
                {"message": "你们接受什么类型的住房券?", "intent": "ASK_VOUCHER_SUPPORT"}
            ],
            "bn": [
                {"message": "ভাউচার নিয়ে সাহায্য চাই", "intent": "HELP_REQUEST"},
                {"message": "ব্রুকলিনে অ্যাপার্টমেন্ট খুঁজছি", "intent": "SEARCH_LISTINGS"},
                {"message": "কি ধরনের ভাউচার গ্রহণ করেন?", "intent": "ASK_VOUCHER_SUPPORT"}
            ]
        }
        
        language_note = language_instructions.get(language, language_instructions["en"])
        examples = language_examples.get(language, language_examples["en"])
        
        # Add detected languages note if message contains multiple languages
        if len(detected_languages) > 1:
            language_note += f" Note: This message contains multiple languages: {', '.join(detected_languages)}. Handle accordingly."
        
        examples_str = "\n".join([f'- "{ex["message"]}" → {ex["intent"]}' for ex in examples])
        
        # Build the prompt with proper escaping
        context_str = f'"{context}"' if context else "null"
        
        prompt = f"""You are a semantic router and parameter extraction engine for a housing chatbot designed to help users find voucher-friendly listings in New York City.

LANGUAGE CONTEXT: {language_note}

EXAMPLES FOR THIS LANGUAGE:
{examples_str}

Your job is to:
1. Classify the **intent** of the user's message.
2. Extract **relevant search parameters** (if any).
3. Generate a short explanation of your reasoning.

You will be given:
- `message`: the user's latest message (string)
- `context`: optionally, a prior message or search state (string or null)

Your response must be a valid JSON object with the following schema:

{{
  "intent": one of [
    "SEARCH_LISTINGS",         
    "CHECK_VIOLATIONS",        
    "ASK_VOUCHER_SUPPORT",     
    "REFINE_SEARCH",           
    "FOLLOW_UP",               
    "HELP_REQUEST",            
    "UNKNOWN"                  
  ],
  
  "parameters": {{
    "borough": (string or null),        
    "bedrooms": (integer or null),      
    "max_rent": (integer or null),      
    "voucher_type": (string or null)    
  }},

  "reasoning": (string)   
}}

Guidelines:
- Normalize borough abbreviations: "BK" → "Brooklyn", etc.
- Support multilingual borough names: "布鲁克林" → "Brooklyn", "ব্রুকলিন" → "Brooklyn"
- Normalize voucher types: "section eight" → "Section 8", "sección 8" → "Section 8" 
- Handle mixed language inputs appropriately
- If the message is vague, return "UNKNOWN" intent and explain why.
- Format JSON precisely.

Input:
- Message: "{message}"
- Context: {context_str}

Response:"""
        
        return prompt
    
    def _validate_input(self, message: str, context: Optional[str] = None) -> None:
        """
        Validate input parameters.
        
        Args:
            message: User message to validate
            context: Optional context to validate
            
        Raises:
            InvalidInputError: If validation fails
        """
        if not message or not message.strip():
            raise InvalidInputError("Message cannot be empty or whitespace-only")
        
        if len(message.strip()) > 1000:  # Reasonable length limit
            raise InvalidInputError("Message exceeds maximum length of 1000 characters")
        
        if context is not None and len(context) > 2000:  # Context can be longer
            raise InvalidInputError("Context exceeds maximum length of 2000 characters")
    
    def _normalize_parameters(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """
        Normalize extracted parameters to standard formats.
        
        Args:
            parameters: Raw parameters from LLM
            
        Returns:
            Normalized parameters
        """
        normalized = {}
        
        # Normalize borough
        if "borough" in parameters and parameters["borough"]:
            borough_lower = str(parameters["borough"]).lower().strip()
            normalized["borough"] = self.BOROUGH_MAPPING.get(borough_lower, parameters["borough"])
        else:
            normalized["borough"] = None
        
        # Normalize bedrooms
        if "bedrooms" in parameters and parameters["bedrooms"] is not None:
            try:
                bedrooms = int(parameters["bedrooms"])
                if 0 <= bedrooms <= 10:  # Reasonable range
                    normalized["bedrooms"] = bedrooms
                else:
                    normalized["bedrooms"] = None
            except (ValueError, TypeError):
                normalized["bedrooms"] = None
        else:
            normalized["bedrooms"] = None
        
        # Normalize max_rent
        if "max_rent" in parameters and parameters["max_rent"] is not None:
            try:
                max_rent = int(parameters["max_rent"])
                if 500 <= max_rent <= 15000:  # Reasonable range for NYC
                    normalized["max_rent"] = max_rent
                else:
                    normalized["max_rent"] = None
            except (ValueError, TypeError):
                normalized["max_rent"] = None
        else:
            normalized["max_rent"] = None
        
        # Normalize voucher_type
        if "voucher_type" in parameters and parameters["voucher_type"]:
            voucher_lower = str(parameters["voucher_type"]).lower().strip()
            normalized["voucher_type"] = self.VOUCHER_MAPPING.get(voucher_lower, parameters["voucher_type"])
        else:
            normalized["voucher_type"] = None
        
        return normalized
    
    def _validate_response(self, response_data: Dict[str, Any]) -> None:
        """
        Validate LLM response structure and content.
        
        Args:
            response_data: Parsed JSON response from LLM
            
        Raises:
            InvalidLLMResponseError: If response is invalid
        """
        # Check required fields
        required_fields = ["intent", "parameters", "reasoning"]
        for field in required_fields:
            if field not in response_data:
                raise InvalidLLMResponseError(f"Missing required field: {field}")
        
        # Validate intent
        intent = response_data["intent"]
        valid_intents = [intent_type.value for intent_type in IntentType]
        if intent not in valid_intents:
            raise InvalidLLMResponseError(f"Invalid intent: {intent}. Must be one of {valid_intents}")
        
        # Validate parameters structure
        parameters = response_data["parameters"]
        if not isinstance(parameters, dict):
            raise InvalidLLMResponseError("Parameters must be a dictionary")
        
        # Validate reasoning
        reasoning = response_data["reasoning"]
        if not isinstance(reasoning, str) or not reasoning.strip():
            raise InvalidLLMResponseError("Reasoning must be a non-empty string")
    
    def from_response(self, llm_response: str) -> RouterResponse:
        """
        Parse and validate LLM response into structured format.
        
        Args:
            llm_response: Raw response string from LLM
            
        Returns:
            RouterResponse object
            
        Raises:
            InvalidLLMResponseError: If response cannot be parsed or validated
        """
        try:
            # Try to extract JSON from response (in case LLM adds extra text)
            json_match = re.search(r'\{.*\}', llm_response.strip(), re.DOTALL)
            if json_match:
                json_str = json_match.group(0)
            else:
                json_str = llm_response.strip()
            
            # Parse JSON
            response_data = json.loads(json_str)
            
            # Validate structure
            self._validate_response(response_data)
            
            # Normalize parameters
            normalized_params = self._normalize_parameters(response_data["parameters"])
            
            return RouterResponse(
                intent=response_data["intent"],
                parameters=normalized_params,
                reasoning=response_data["reasoning"].strip()
            )
            
        except json.JSONDecodeError as e:
            logger.error(f"Failed to parse JSON response: {e}")
            logger.error(f"Raw response: {llm_response}")
            raise InvalidLLMResponseError(f"Invalid JSON in LLM response: {e}")
        except Exception as e:
            logger.error(f"Error processing LLM response: {e}")
            raise InvalidLLMResponseError(f"Error processing response: {e}")
    
    def route(self, message: str, context: Optional[str] = None, language: str = "en") -> Dict[str, Any]:
        """
        Route a user message using the LLM fallback router.
        
        Args:
            message: User's message to route
            context: Optional context from previous messages or search state
            language: Language code for the user interface (en, es, zh, bn)
            
        Returns:
            Dictionary with intent, parameters, and reasoning
            
        Raises:
            InvalidInputError: If input validation fails
            LLMProcessingError: If LLM processing fails
            InvalidLLMResponseError: If response parsing fails
        """
        # Validate input
        self._validate_input(message, context)
        
        if self.debug:
            logger.debug(f"Routing message: {message}")
            logger.debug(f"Context: {context}")
        
        # Format prompt
        prompt = self.format_prompt(message, context, language)
        
        # Call LLM with retries
        last_error = None
        for attempt in range(self.max_retries):
            try:
                if self.debug:
                    logger.debug(f"LLM call attempt {attempt + 1}/{self.max_retries}")
                
                # Call the LLM client
                # Note: This assumes the LLM client has a generate() or similar method
                # Adjust based on your specific LLM client interface
                if hasattr(self.llm_client, 'generate'):
                    llm_response = self.llm_client.generate(prompt)
                elif hasattr(self.llm_client, 'chat'):
                    llm_response = self.llm_client.chat(prompt)
                elif hasattr(self.llm_client, '__call__'):
                    llm_response = self.llm_client(prompt)
                else:
                    raise LLMProcessingError("LLM client does not have a recognized interface")
                
                if self.debug:
                    logger.debug(f"LLM response: {llm_response}")
                
                # Parse and validate response
                router_response = self.from_response(llm_response)
                
                if self.debug:
                    logger.debug(f"Parsed response: {router_response.to_dict()}")
                
                return router_response.to_dict()
                
            except InvalidLLMResponseError:
                # Don't retry for response parsing errors
                raise
            except Exception as e:
                last_error = e
                if self.debug:
                    logger.debug(f"Attempt {attempt + 1} failed: {e}")
                
                if attempt < self.max_retries - 1:
                    continue  # Retry
                else:
                    break  # Max retries reached
        
        # If we get here, all retries failed
        error_msg = f"LLM processing failed after {self.max_retries} attempts"
        if last_error:
            error_msg += f". Last error: {last_error}"
        
        logger.error(error_msg)
        raise LLMProcessingError(error_msg)

# Convenience functions for backward compatibility and easy testing
def create_fallback_router(llm_client: Any, debug: bool = False) -> LLMFallbackRouter:
    """
    Create a new LLMFallbackRouter instance.
    
    Args:
        llm_client: LLM client instance
        debug: Enable debug mode
        
    Returns:
        LLMFallbackRouter instance
    """
    return LLMFallbackRouter(llm_client, debug=debug)

def route_message(llm_client: Any, message: str, context: Optional[str] = None, language: str = "en") -> Dict[str, Any]:
    """
    Convenience function to route a single message.
    
    Args:
        llm_client: LLM client instance
        message: Message to route
        context: Optional context
        language: Language code for the user interface
        
    Returns:
        Routing result dictionary
    """
    router = LLMFallbackRouter(llm_client)
    return router.route(message, context, language)