Classifies queries as HIGH or LOW complexity for token budget allocation. Uses the adaptive-classifier model for classification.
| 13 | logger = logging.getLogger(__name__) |
| 14 | |
| 15 | class ComplexityClassifier: |
| 16 | """ |
| 17 | Classifies queries as HIGH or LOW complexity for token budget allocation. |
| 18 | Uses the adaptive-classifier model for classification. |
| 19 | """ |
| 20 | |
| 21 | def __init__(self, model_name: str = "adaptive-classifier/llm-router"): |
| 22 | """ |
| 23 | Initialize the complexity classifier. |
| 24 | |
| 25 | Args: |
| 26 | model_name: HuggingFace model name or path for the classifier |
| 27 | """ |
| 28 | self.model_name = model_name |
| 29 | self.classifier = None |
| 30 | |
| 31 | # Load model |
| 32 | self._load_model() |
| 33 | |
| 34 | def _load_model(self): |
| 35 | """Load the classification model using adaptive-classifier library.""" |
| 36 | try: |
| 37 | # Check if adaptive-classifier is installed |
| 38 | try: |
| 39 | import adaptive_classifier |
| 40 | except ImportError: |
| 41 | logger.info("Installing adaptive-classifier library...") |
| 42 | os.system(f"{sys.executable} -m pip install adaptive-classifier") |
| 43 | import adaptive_classifier |
| 44 | |
| 45 | # Import the AdaptiveClassifier class |
| 46 | from adaptive_classifier import AdaptiveClassifier |
| 47 | |
| 48 | logger.info(f"Loading complexity classifier model: {self.model_name}") |
| 49 | self.classifier = AdaptiveClassifier.from_pretrained(self.model_name) |
| 50 | logger.info("Classifier loaded successfully") |
| 51 | |
| 52 | except Exception as e: |
| 53 | logger.error(f"Error loading complexity classifier: {e}") |
| 54 | # Fallback to basic classification if model fails to load |
| 55 | self.classifier = None |
| 56 | |
| 57 | def predict(self, text: str) -> List[Tuple[str, float]]: |
| 58 | """ |
| 59 | Predict the complexity label for a given text. |
| 60 | |
| 61 | Args: |
| 62 | text: The query text to classify |
| 63 | |
| 64 | Returns: |
| 65 | List of (label, score) tuples sorted by confidence |
| 66 | """ |
| 67 | if self.classifier is None: |
| 68 | logger.warning("Classifier not loaded. Using fallback classification.") |
| 69 | return self._fallback_classification(text) |
| 70 | |
| 71 | try: |
| 72 | # Make prediction using the AdaptiveClassifier |