""" Intent Engine - Optimized Ranking Module (Unified ONNX Version) This module implements improved constraint satisfaction and intent-aligned ranking using the shared ONNX embedding service for high performance. """ import hashlib import logging from dataclasses import dataclass from typing import Any from app.config.query_cache import get_ranking_cache from app.core.embedding_service import get_embedding_service from app.core.schema import ( Constraint, ConstraintType, DeclaredIntent, EthicalDimension, InferredIntent, SkillLevel, UniversalIntent, ) logger = logging.getLogger(__name__) @dataclass class SearchResult: """Represents a search result candidate with metadata""" id: str title: str description: str platform: str | None = None provider: str | None = None license: str | None = None price: float | None = None tags: list[str] | None = None qualityScore: float | None = 0.5 recency: str | None = None complexity: str | None = None compatibility: list[str] | None = None privacyRating: float | None = None opensource: bool | None = None @dataclass class RankedResult: """Represents a ranked result with alignment score and reasons""" result: SearchResult alignmentScore: float matchReasons: list[str] @dataclass class RankingRequest: """Request object for ranking API""" intent: UniversalIntent candidates: list[SearchResult] options: dict[str, Any] | None = None @dataclass class RankingResponse: """Response object for ranking API""" rankedResults: list[RankedResult] cache_hit: bool = False processing_time_ms: float = 0.0 class OptimizedConstraintSatisfactionEngine: """Improved constraint satisfaction with better performance""" def __init__(self): self.embedding_service = get_embedding_service() def satisfies_constraints( self, result: SearchResult, constraints: list[Constraint] ) -> bool: """Check if a result satisfies all hard constraints""" if not constraints: return True for constraint in constraints: if not constraint.hardFilter: continue if not self._satisfies_single_constraint(result, constraint): return False return True def _satisfies_single_constraint( self, result: SearchResult, constraint: Constraint ) -> bool: """Check if a result satisfies a single constraint""" dimension = constraint.dimension value = constraint.value constraint_type = constraint.type result_value = getattr(result, dimension, None) if constraint_type == ConstraintType.INCLUSION: if isinstance(value, str): if result_value is None: return False return result_value.lower() == value.lower() if isinstance(value, list): if result_value is None: return False result_lower = str(result_value).lower() return any(result_lower == str(v).lower() for v in value) elif constraint_type == ConstraintType.EXCLUSION: if isinstance(value, str): if result_value is None: return True return result_value.lower() != value.lower() if isinstance(value, list): if result_value is None: return True result_lower = str(result_value).lower() return all(result_lower != str(v).lower() for v in value) elif ( constraint_type == ConstraintType.RANGE and dimension == "price" and result_value is not None ): return self._check_price_range(result_value, value) return True def _check_price_range(self, price: float, range_spec: str) -> bool: """Check if price satisfies range specification""" range_spec = str(range_spec).lower().strip() if range_spec in {"budget", "free", "0"}: return price == 0 return True # Simplified for now class OptimizedIntentAlignmentEngine: """Improved intent alignment with better scoring using ONNX""" def __init__(self): self.embedding_service = get_embedding_service() def compute_intent_alignment( self, result: SearchResult, intent: UniversalIntent ) -> tuple[float, list[str]]: """Compute alignment score with improved weighting""" scores = [] reasons = [] declared = intent.declared or DeclaredIntent() inferred = intent.inferred or InferredIntent() # 1. Query-content alignment (semantic similarity) - 40% (Boosted) query_score, query_reasons = self._compute_query_content_alignment( result, intent, declared ) scores.append((query_score, 0.40)) reasons.extend(query_reasons) # 2. Use case alignment - 20% use_case_score, use_case_reasons = self._compute_use_case_alignment( result, intent, inferred ) scores.append((use_case_score, 0.20)) reasons.extend(use_case_reasons) # 3. Ethical signal alignment - 15% ethical_score, ethical_reasons = self._compute_ethical_alignment( result, intent, inferred ) scores.append((ethical_score, 0.15)) reasons.extend(ethical_reasons) # 4. Skill level alignment - 15% skill_score, skill_reasons = self._compute_skill_alignment( result, intent, declared ) scores.append((skill_score, 0.15)) reasons.extend(skill_reasons) # 5. Quality score - 10% quality_score = result.qualityScore or 0.5 scores.append((quality_score, 0.10)) # Calculate weighted average alignment_score = sum(score * weight for score, weight in scores) alignment_score = max(0.0, min(1.0, alignment_score)) return alignment_score, list(set(reasons)) def _compute_query_content_alignment( self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent ) -> tuple[float, list[str]]: """Compute semantic similarity between query and result using shared ONNX""" reasons = [] query = declared.query if declared else None if not query: return 0.5, reasons content = f"{result.title} {result.description}".strip() if not content: return 0.0, reasons # Get embeddings via shared ONNX service query_emb = self.embedding_service.encode_text(query) content_emb = self.embedding_service.encode_text(content) if query_emb is not None and content_emb is not None: similarity = self.embedding_service.cosine_similarity( query_emb, content_emb ) score = (similarity + 1) / 2 # Normalize to 0-1 if score > 0.7: reasons.append("high-semantic-match") elif score > 0.5: reasons.append("semantic-match") return score, reasons return 0.5, ["keyword-fallback"] def _compute_use_case_alignment( self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent ) -> tuple[float, list[str]]: """Compute use case alignment""" reasons = [] use_cases = inferred.useCases if inferred else [] if not use_cases or not result.tags: return 0.5, reasons score = 0.0 tag_text = " ".join(result.tags).lower() for use_case in use_cases: use_case_str = str(use_case.value).replace("_", " ") if use_case_str in tag_text: score += 1.0 reasons.append(f"use-case-{use_case.value}") score = min(1.0, score / len(use_cases)) if use_cases else 0.5 return score, reasons def _compute_ethical_alignment( self, result: SearchResult, intent: UniversalIntent, inferred: InferredIntent ) -> tuple[float, list[str]]: """Compute ethical signal alignment""" reasons = [] ethical_signals = inferred.ethicalSignals if inferred else [] if not ethical_signals: return 0.5, reasons score = 0.0 for signal in ethical_signals: if signal.dimension == EthicalDimension.PRIVACY: if result.privacyRating and result.privacyRating > 0.7: score += 1.0 reasons.append("privacy-aligned") elif signal.dimension == EthicalDimension.OPENNESS: if result.opensource: score += 1.0 reasons.append("open-source-aligned") score = min(1.0, score / len(ethical_signals)) if ethical_signals else 0.5 return score, reasons def _compute_skill_alignment( self, result: SearchResult, intent: UniversalIntent, declared: DeclaredIntent ) -> tuple[float, list[str]]: """Compute skill level alignment""" reasons = [] declared_skill = declared.skillLevel if declared else SkillLevel.INTERMEDIATE result_complexity = result.complexity if not result_complexity: return 0.5, reasons # Simple string match for complexity if result_complexity.lower() in str(declared_skill.name).lower(): return 1.0, ["exact-skill-match"] return 0.5, reasons class ResultDeduplicator: """Deduplicate results based on content similarity""" def __init__(self, similarity_threshold: float = 0.9): self.similarity_threshold = similarity_threshold self.embedding_service = get_embedding_service() def deduplicate(self, results: list[RankedResult]) -> list[RankedResult]: if not results: return results unique_results = [] seen_hashes = set() for result in results: # Fast hash-based deduplication content_hash = hashlib.md5( f"{result.result.title}".lower().encode() ).hexdigest() if content_hash not in seen_hashes: unique_results.append(result) seen_hashes.add(content_hash) return unique_results class OptimizedIntentRanker: """Main ranking class with ONNX optimizations""" def __init__(self): self.constraint_engine = OptimizedConstraintSatisfactionEngine() self.alignment_engine = OptimizedIntentAlignmentEngine() self.deduplicator = ResultDeduplicator() self.cache = get_ranking_cache() def rank_results(self, request: RankingRequest) -> RankingResponse: import time start_time = time.time() # Filter candidates filtered_candidates = self._filter_candidates(request) # Compute alignment scores ranked_results = [] for candidate in filtered_candidates: score, reasons = self.alignment_engine.compute_intent_alignment( candidate, request.intent ) ranked_results.append( RankedResult( result=candidate, alignmentScore=score, matchReasons=reasons ) ) # Deduplicate ranked_results = self.deduplicator.deduplicate(ranked_results) # Sort by score ranked_results.sort(key=lambda x: x.alignmentScore, reverse=True) processing_time = (time.time() - start_time) * 1000 return RankingResponse( rankedResults=ranked_results, cache_hit=False, processing_time_ms=processing_time, ) def _filter_candidates(self, request: RankingRequest) -> list[SearchResult]: if not request.intent.declared or not request.intent.declared.constraints: return request.candidates filtered = [] for candidate in request.candidates: if self.constraint_engine.satisfies_constraints( candidate, request.intent.declared.constraints ): filtered.append(candidate) return filtered # Global instance _ranker_instance = None def get_intent_ranker() -> OptimizedIntentRanker: global _ranker_instance if _ranker_instance is None: _ranker_instance = OptimizedIntentRanker() return _ranker_instance def rank_results(request: RankingRequest) -> RankingResponse: ranker = get_intent_ranker() return ranker.rank_results(request)