# Current System Architecture ## Request Flow Diagram ``` ┌─────────────────┐ │ User Request │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │ FastAPI │ │ Chat Endpoint │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │ Extract Search │ │ Terms (NLP) │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ ┌─────────────────┐ │ Phase 1: │◄──►│ Phase 2: │ │ Rule-Based │ │ AI-Enhanced │ │ Decision │ │ Decision │ └─────────┬───────┘ └─────────────────┘ │ ▼ ┌─────────┐ │Search? │──────────── No ────────────┐ └─────────┘ │ │ Yes │ ▼ │ ┌─────────────────┐ │ │ Phase 3: │ │ │ Universal Cache │ │ │ Check │ │ └─────────┬───────┘ │ │ │ ▼ │ ┌─────────┐ │ │Cache │──── Hit ──┐ │ │Hit? │ │ │ └─────────┘ │ │ │ Miss │ │ ▼ │ │ ┌─────────────────┐ │ │ │ Web Search │ │ │ │ Combined │ │ │ │ (Brave+DDG) │ │ │ └─────────┬───────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────┐ │ │ │ Store in Cache │ │ │ └─────────┬───────┘ │ │ │ │ │ ▼ │ │ ┌─────────────────┐ │ │ │ Format Results │◄──────┘ │ └─────────┬───────┘ │ │ │ ▼ │ ┌─────────────────┐◄──────────────────────┘ │ AI Response │ │ Generation │ │ (Gemini) │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │ Analytics │ │ Tracking │ └─────────┬───────┘ │ ▼ ┌─────────────────┐ │ JSON Response │ │ to Client │ └─────────────────┘ ``` ## Current Cache Implementation ``` ┌─────────────────────────────────────────────────────────────┐ │ Universal Search Cache │ │ │ │ ┌─────────────────┐ ┌─────────────────────────────────┐ │ │ │ Hash Table │ │ Cache Entry │ │ │ │ (OrderedDict) │ │ │ │ │ │ │ │ • search_results: List[Dict] │ │ │ │ MD5(terms) ──► │────┤ • search_query: str │ │ │ │ │ │ • search_terms: List[str] │ │ │ │ │ │ • timestamp: float │ │ │ │ │ │ • ttl: int │ │ │ │ │ │ • hit_count: int │ │ │ │ │ │ • last_accessed: float │ │ │ └─────────────────┘ └─────────────────────────────────┘ │ │ │ │ Lookup Strategy: │ │ 1. Exact Match: O(1) hash lookup │ │ 2. Semantic Search: O(n) spaCy similarity │ │ │ │ Max Size: 1000 entries │ │ Default TTL: 3600 seconds │ │ Memory: ~2-10MB per entry │ └─────────────────────────────────────────────────────────────┘ ``` ## Performance Characteristics | Operation | Time Complexity | Typical Duration | Resource Usage | |-----------|----------------|------------------|----------------| | **Exact Cache Hit** | O(1) | 1-5μs | RAM only | | **Semantic Cache Search** | O(n) | 10-500ms | CPU + RAM | | **Rule-Based Decision** | O(1) | 50-200ms | CPU intensive | | **AI-Based Decision** | O(1) | 200-500ms | Network + GPU | | **Web Search** | O(1) | 2-5s | Network + APIs | ## Current Limitations 1. **Decision-First Approach**: Always runs search decision logic before cache check 2. **Dual Lookup Complexity**: Two different cache lookup strategies 3. **Poor Semantic Scaling**: O(n) performance degrades with cache size 4. **Memory-Only**: Cache lost on server restart 5. **Session Complexity**: Removed but left complex patterns in codebase