Intent Recognition System - Complete Documentation

๐ŸŽฏ System Overview

The Intent Recognition System is a multi-tenant, machine learning-powered platform designed to understand and classify user queries into predefined business intents. Built for enterprise use, it provides real-time intent matching with high accuracy, automatic pattern generation, and intelligent memory management.

Core Purpose

Transform natural language queries like "What time do you open?" into structured business intents like store_hours with confidence scores, enabling automated customer service, chatbots, FAQ systems, and voice assistants.


๐Ÿ—๏ธ System Architecture

High-Level Architecture

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚   Client Apps   โ”‚    โ”‚   Load Balancer โ”‚    โ”‚   Monitoring    โ”‚
โ”‚  (Web, Mobile,  โ”‚โ”€โ”€โ”€โ”€โ”‚   (Optional)    โ”‚โ”€โ”€โ”€โ”€โ”‚  (Grafana, etc) โ”‚
โ”‚   Chatbots)     โ”‚    โ”‚                 โ”‚    โ”‚                 โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
         โ”‚                       โ”‚                       โ”‚
         โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                 โ”‚
                    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                    โ”‚   Flask App     โ”‚
                    โ”‚  (Port 5000)    โ”‚
                    โ”‚                 โ”‚
                    โ”‚ โ€ข CRUD API      โ”‚
                    โ”‚ โ€ข Query API     โ”‚
                    โ”‚ โ€ข Cache Mgmt    โ”‚
                    โ”‚ โ€ข Rate Limiting โ”‚
                    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                             โ”‚
              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
              โ”‚              โ”‚              โ”‚
    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
    โ”‚ PostgreSQL  โ”‚ โ”‚   Redis     โ”‚ โ”‚ Background  โ”‚
    โ”‚ Database    โ”‚ โ”‚   Cache     โ”‚ โ”‚ Job Worker  โ”‚
    โ”‚             โ”‚ โ”‚             โ”‚ โ”‚             โ”‚
    โ”‚ โ€ข Intents   โ”‚ โ”‚ โ€ข Model     โ”‚ โ”‚ โ€ข Pattern   โ”‚
    โ”‚ โ€ข Patterns  โ”‚ โ”‚   Cache     โ”‚ โ”‚   Generationโ”‚
    โ”‚ โ€ข Metadata  โ”‚ โ”‚ โ€ข Queue     โ”‚ โ”‚ โ€ข OpenAI    โ”‚
    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Service Components

1. Flask Application (intent_app)

2. Background Job Worker (intent_background_job)

3. PostgreSQL Database (intent_postgres)

4. Redis Cache (intent_redis)


๐Ÿ”„ How The System Works

1. Intent Lifecycle Management

Intent Creation Flow

1. Client creates intent via POST /intents
   โ”œโ”€โ”€ Validates input data (customer_id, intent_key, description, etc.)
   โ”œโ”€โ”€ Stores intent in PostgreSQL with empty query_pattern
   โ”œโ”€โ”€ Caches intent data in Redis
   โ”œโ”€โ”€ Invalidates existing model cache for customer
   โ””โ”€โ”€ Queues pattern generation job

2. Background worker processes queue
   โ”œโ”€โ”€ Receives intent_id from Redis queue
   โ”œโ”€โ”€ Calls OpenAI API to generate query patterns
   โ”œโ”€โ”€ Updates database with generated patterns
   โ””โ”€โ”€ Triggers model retraining on next query

3. First query triggers model training
   โ”œโ”€โ”€ Loads all customer intents from database
   โ”œโ”€โ”€ Trains TF-IDF vectorizer + LogisticRegression model
   โ”œโ”€โ”€ Caches trained model in memory
   โ””โ”€โ”€ Returns query result

Query Processing Flow

1. Client sends query via POST /query
   โ”œโ”€โ”€ Validates query string and parameters
   โ”œโ”€โ”€ Checks rate limits
   โ””โ”€โ”€ Preprocesses query (tokenization, lemmatization)

2. Model loading/caching
   โ”œโ”€โ”€ Checks memory cache for customer model
   โ”œโ”€โ”€ If cached: Uses in-memory model (fast path ~60ms)
   โ”œโ”€โ”€ If not cached: Loads from disk and caches
   โ””โ”€โ”€ If no model exists: Trains new model

3. Intent matching
   โ”œโ”€โ”€ Vectorizes query using TF-IDF
   โ”œโ”€โ”€ Computes cosine similarity with all intent patterns
   โ”œโ”€โ”€ Finds best match above similarity threshold
   โ””โ”€โ”€ Returns intent details with confidence score

4. Response formatting
   โ”œโ”€โ”€ Formats result with intent metadata
   โ”œโ”€โ”€ Updates model cache access statistics
   โ””โ”€โ”€ Returns JSON response to client

2. Multi-Tenant Architecture

Customer Isolation

Scaling Strategy

Customer Growth Pattern:
โ”œโ”€โ”€ 1-10 customers: Single instance, shared resources
โ”œโ”€โ”€ 10-100 customers: Model caching essential, memory management
โ”œโ”€โ”€ 100-500 customers: Consider horizontal scaling
โ””โ”€โ”€ 500+ customers: Distributed architecture, shared base models

3. Machine Learning Pipeline

Training Process

For each customer:
1. Collect all intent patterns from database
2. Preprocess text:
   โ”œโ”€โ”€ Tokenization (NLTK word_tokenize)
   โ”œโ”€โ”€ Lowercasing and stopword removal
   โ”œโ”€โ”€ Lemmatization (WordNet)
   โ””โ”€โ”€ Clean text normalization

3. Feature extraction:
   โ”œโ”€โ”€ TF-IDF vectorization (max 1000 features)
   โ”œโ”€โ”€ English stopwords filtering
   โ””โ”€โ”€ Sparse matrix generation

4. Model training:
   โ”œโ”€โ”€ LogisticRegression (max_iter=1000)
   โ”œโ”€โ”€ Handle single-class edge case
   โ””โ”€โ”€ Cross-validation ready

5. Model persistence:
   โ”œโ”€โ”€ Save vectorizer and model to disk (joblib)
   โ”œโ”€โ”€ Cache in memory for fast access
   โ””โ”€โ”€ Track memory usage and metadata

Inference Process

For each query:
1. Preprocess query text (same pipeline as training)
2. Transform to TF-IDF vector using trained vectorizer
3. Compute cosine similarity with all intent patterns
4. Find maximum similarity score
5. Return intent if above threshold, else "no match"

4. Pattern Generation System

OpenAI Integration

Background Job Process:
1. Receive intent from queue (intent_id, info_blob, pattern_count)
2. Generate prompt for OpenAI:
   "Generate N questions showing intent to know things from: {info_blob}"
3. Call GPT-4o-mini API with retry logic
4. Parse response into individual patterns
5. Update database with generated patterns
6. Handle failures with exponential backoff

Queue Management

Redis Queue Architecture:
โ”œโ”€โ”€ pattern_generation_queue: New jobs
โ”œโ”€โ”€ pattern_generation_failed: Failed jobs
โ”œโ”€โ”€ BRPOP blocking: Real-time processing
โ”œโ”€โ”€ Retry logic: 3 attempts with backoff
โ””โ”€โ”€ Fallback polling: Every 5 minutes

5. Memory Management System

LRU Cache Implementation

ModelMemoryManager:
โ”œโ”€โ”€ OrderedDict for LRU ordering
โ”œโ”€โ”€ Memory estimation per model
โ”œโ”€โ”€ Automatic eviction when limits reached
โ”œโ”€โ”€ TTL-based expiration (24 hours default)
โ”œโ”€โ”€ Background cleanup thread (every 5 minutes)
โ””โ”€โ”€ Thread-safe operations with RLock

Cache Lifecycle

Model Caching Flow:
1. Model trained โ†’ Estimate memory usage โ†’ Cache if space available
2. Model accessed โ†’ Move to end of LRU โ†’ Update access count
3. Memory pressure โ†’ Evict LRU models โ†’ Force garbage collection
4. TTL expired โ†’ Remove stale models โ†’ Free memory
5. Intent updated โ†’ Invalidate cache โ†’ Force retrain on next query

๐Ÿ”ง Technical Implementation

Database Schema

CREATE TABLE intents (
    intent_id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    customer_id UUID NOT NULL,
    intent_key VARCHAR(255) NOT NULL,
    query_pattern TEXT[] DEFAULT '{}',
    description TEXT NOT NULL,
    info_blob TEXT NOT NULL,
    tags TEXT[] DEFAULT '{}',
    intent_query_pattern_count INTEGER DEFAULT 0,
    process_time TIMESTAMP,
    processing_error TEXT,
    last_processing_time TIMESTAMP,
    processing_attempts INTEGER DEFAULT 0,
    UNIQUE(customer_id, intent_key)
);

CREATE INDEX idx_intents_customer_id ON intents(customer_id);
CREATE INDEX idx_intents_tags ON intents USING GIN(tags);

API Endpoints

Intent Management

POST   /intents              # Create new intent
GET    /intents/{intent_id}  # Get intent details
PUT    /intents/{intent_id}  # Update intent
DELETE /intents/{intent_id}  # Delete intent
GET    /intents/customer/{customer_id}  # List customer intents

Query Processing

POST   /query               # Process query and return intent match

System Management

GET    /up                  # Health check
GET    /queue/status        # Queue monitoring
GET    /models/cache/status # Model cache statistics
POST   /models/cache/clear  # Clear model cache

Configuration Management

Environment Variables

# Database Configuration
DB_HOST=intent_postgres
DB_PORT=5432
DB_NAME=mydatabase
DB_USER=user
DB_PASSWORD=password

# Redis Configuration
REDIS_HOST=intent_redis
REDIS_PORT=6379

# OpenAI Configuration
OPENAI_API_KEY=sk-your-api-key-here

# Model Memory Management
MAX_CACHED_MODELS=10        # Maximum models in cache
MAX_MODEL_MEMORY_MB=500     # Memory limit in MB
MODEL_TTL_HOURS=24          # Cache expiration time

# Background Job Configuration
SLEEP_INTERVAL=10           # Queue polling interval

Docker Compose Services

services:
  app:
    environment:
      MAX_CACHED_MODELS: '10'
      MAX_MODEL_MEMORY_MB: '500'
      MODEL_TTL_HOURS: '24'

  background_job:
    environment:
      MAX_CACHED_MODELS: '5'
      MAX_MODEL_MEMORY_MB: '200'
      MODEL_TTL_HOURS: '12'

๐Ÿ“Š Performance Characteristics

Response Times

Scenario Response Time Notes
Cold Cache ~6000ms First query, model training required
Warm Cache ~60-70ms Model cached in memory
Cache Miss ~100-200ms Model loaded from disk
No Match ~60ms Fast similarity computation

Memory Usage

Component Memory Usage Scaling
Base Application ~60MB Fixed overhead
Per Model ~1-2MB Linear with customers
Cache Limit 500MB (app) Configurable
Background Job ~60MB Fixed overhead

Throughput

Metric Capacity Bottleneck
Queries/sec 50-100 Model inference
Concurrent Users 100+ Rate limiting
Pattern Generation 10/min OpenAI API limits
Model Training 1-2/sec CPU intensive

๐Ÿ”’ Security & Compliance

Data Protection

Authentication & Authorization

Current: Basic validation (customer_id in requests)
Recommended: JWT tokens, API keys, OAuth2 integration

Compliance Features


๐Ÿš€ Deployment & Operations

Container Architecture

Docker Compose Stack:
โ”œโ”€โ”€ intent_postgres (PostgreSQL 16)
โ”œโ”€โ”€ intent_redis (Redis 7 with AOF persistence)
โ”œโ”€โ”€ intent_app (Python 3.9 Flask application)
โ””โ”€โ”€ intent_background_job (Python 3.9 worker)

Health Monitoring

Health Checks:
โ”œโ”€โ”€ /up endpoint (application health)
โ”œโ”€โ”€ /queue/status (background job health)
โ”œโ”€โ”€ /models/cache/status (memory management)
โ”œโ”€โ”€ PostgreSQL health check (pg_isready)
โ””โ”€โ”€ Redis health check (ping)

Scaling Strategies

Vertical Scaling

Horizontal Scaling


๐ŸŽฏ Use Cases & Applications

Primary Use Cases

  1. Customer Service Chatbots
  2. Route queries to appropriate departments
  3. Provide instant FAQ responses
  4. Escalate complex issues to humans

  5. Voice Assistants

  6. Understand spoken commands
  7. Execute business-specific actions
  8. Provide voice-based customer support

  9. FAQ Systems

  10. Automatically categorize user questions
  11. Suggest relevant documentation
  12. Improve self-service capabilities

  13. Content Management

  14. Tag and categorize user-generated content
  15. Route support tickets automatically
  16. Analyze customer feedback themes

Industry Applications


๐Ÿ“ˆ Monitoring & Analytics

Key Metrics

Business Metrics:
โ”œโ”€โ”€ Intent match accuracy (similarity scores)
โ”œโ”€โ”€ Query volume per customer
โ”œโ”€โ”€ Most common intents
โ””โ”€โ”€ Customer engagement patterns

Technical Metrics:
โ”œโ”€โ”€ Response time percentiles (p50, p95, p99)
โ”œโ”€โ”€ Cache hit rates
โ”œโ”€โ”€ Memory usage trends
โ”œโ”€โ”€ Error rates and types
โ””โ”€โ”€ Background job processing times

Alerting Thresholds

alerts:
  high_response_time:
    threshold: "> 500ms p95"
    action: "Check model cache performance"

  low_cache_hit_rate:
    threshold: "< 80%"
    action: "Review TTL settings"

  high_memory_usage:
    threshold: "> 90%"
    action: "Clear cache or increase limits"

  queue_backlog:
    threshold: "> 100 items"
    action: "Scale background workers"

๐Ÿ”ฎ Future Roadmap

Short Term (1-3 months)

Medium Term (3-6 months)

Long Term (6+ months)


This documentation provides a comprehensive overview of how the Intent Recognition System works. Would you like me to expand on any particular section or create additional documentation for specific aspects like deployment, API reference, or troubleshooting?