|
| 1 | +""" |
| 2 | +Query complexity classifier for AutoThink. |
| 3 | +
|
| 4 | +This module provides functionality to classify queries as HIGH or LOW complexity |
| 5 | +using the adaptive-classifier model. |
| 6 | +""" |
| 7 | + |
| 8 | +import logging |
| 9 | +from typing import Dict, Any, Tuple, Optional, List, Union |
| 10 | +import os |
| 11 | +import sys |
| 12 | + |
| 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 |
| 73 | + predictions = self.classifier.predict(text) |
| 74 | + logger.debug(f"Classifier predictions: {predictions}") |
| 75 | + |
| 76 | + # Make sure predictions are in the expected format |
| 77 | + if isinstance(predictions, list) and all(isinstance(p, tuple) and len(p) == 2 for p in predictions): |
| 78 | + # Sort by confidence (assuming higher score = higher confidence) |
| 79 | + predictions.sort(key=lambda x: x[1], reverse=True) |
| 80 | + return predictions |
| 81 | + else: |
| 82 | + logger.warning(f"Unexpected prediction format: {predictions}") |
| 83 | + return self._fallback_classification(text) |
| 84 | + |
| 85 | + except Exception as e: |
| 86 | + logger.error(f"Error during classification: {e}") |
| 87 | + return self._fallback_classification(text) |
| 88 | + |
| 89 | + def _fallback_classification(self, text: str) -> List[Tuple[str, float]]: |
| 90 | + """ |
| 91 | + Simple heuristic classification when model isn't available. |
| 92 | + |
| 93 | + Args: |
| 94 | + text: The query text |
| 95 | + |
| 96 | + Returns: |
| 97 | + List of (label, score) tuples |
| 98 | + """ |
| 99 | + # Count key indicators of complexity |
| 100 | + complexity_indicators = [ |
| 101 | + "explain", "analyze", "compare", "evaluate", "synthesize", |
| 102 | + "how", "why", "complex", "detail", "thorough", "comprehensive", |
| 103 | + "step by step", "calculate", "prove", "justify", "multiple", |
| 104 | + "consequences", "implications", "differentiate", "frameworks" |
| 105 | + ] |
| 106 | + |
| 107 | + # Count mentions of complexity indicators |
| 108 | + count = sum(1 for indicator in complexity_indicators if indicator.lower() in text.lower()) |
| 109 | + |
| 110 | + # Calculate complexity probability based on count and text length |
| 111 | + text_length_factor = min(len(text) / 100, 2.0) # Cap at 2.0 |
| 112 | + indicator_factor = min(count / 3, 1.5) # Cap at 1.5 |
| 113 | + |
| 114 | + # Combined factor determines HIGH vs LOW |
| 115 | + complexity_score = text_length_factor * indicator_factor |
| 116 | + |
| 117 | + if complexity_score > 1.0: |
| 118 | + return [("HIGH", 0.7), ("LOW", 0.3)] |
| 119 | + else: |
| 120 | + return [("LOW", 0.8), ("HIGH", 0.2)] |
| 121 | + |
| 122 | + def is_high_complexity(self, text: str, threshold: float = 0.5) -> bool: |
| 123 | + """ |
| 124 | + Determine if a query is high complexity. |
| 125 | + |
| 126 | + Args: |
| 127 | + text: The query text |
| 128 | + threshold: Confidence threshold for HIGH classification |
| 129 | + |
| 130 | + Returns: |
| 131 | + Boolean indicating if the query is high complexity |
| 132 | + """ |
| 133 | + predictions = self.predict(text) |
| 134 | + |
| 135 | + for label, score in predictions: |
| 136 | + if label == "HIGH" and score >= threshold: |
| 137 | + return True |
| 138 | + |
| 139 | + return False |
| 140 | + |
| 141 | + def get_complexity_with_confidence(self, text: str) -> Tuple[str, float]: |
| 142 | + """ |
| 143 | + Get the complexity label and confidence score. |
| 144 | + |
| 145 | + Args: |
| 146 | + text: The query text |
| 147 | + |
| 148 | + Returns: |
| 149 | + Tuple of (complexity_label, confidence_score) |
| 150 | + """ |
| 151 | + predictions = self.predict(text) |
| 152 | + return predictions[0] # Return highest confidence prediction |
0 commit comments