Intent Recognition System - API Reference

📋 Overview

This document provides complete API reference for the Intent Recognition System. All endpoints return JSON responses and use standard HTTP status codes.

Base URL

http://localhost:5000

Authentication

Currently uses basic validation with customer_id in request bodies. Future versions will implement JWT tokens and API keys.

Rate Limiting

Content Type

All requests must include:

Content-Type: application/json

🔧 Intent Management API

Create Intent

Creates a new intent for a customer with automatic pattern generation.

Endpoint: POST /intents

Request Body:

{
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "intent_key": "store_hours",
  "description": "Customer wants to know store operating hours",
  "info_blob": "SuperMart grocery store is open Monday-Friday 8AM-10PM, Saturday-Sunday 9AM-9PM. We have extended holiday hours during Christmas and Thanksgiving.",
  "tags": ["hours", "schedule", "time"],
  "intent_query_pattern_count": 5
}

Request Parameters: | Field | Type | Required | Description | |-------|------|----------|-------------| | customer_id | UUID | ✅ | Unique customer identifier | | intent_key | String | ✅ | Unique intent identifier within customer | | description | String | ✅ | Human-readable intent description | | info_blob | String | ✅ | Context information for pattern generation | | tags | Array[String] | ❌ | Optional tags for categorization | | intent_query_pattern_count | Integer | ❌ | Number of patterns to generate (default: 0) |

Success Response: 201 Created

{
  "intent_id": "87654321-4321-4321-4321-210987654321",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "intent_key": "store_hours",
  "description": "Customer wants to know store operating hours",
  "info_blob": "SuperMart grocery store is open Monday-Friday 8AM-10PM...",
  "tags": ["hours", "schedule", "time"],
  "intent_query_pattern_count": 5,
  "query_pattern": [],
  "process_time": null,
  "processing_error": null,
  "last_processing_time": null,
  "processing_attempts": 0,
  "created_at": "2024-01-15T10:30:00Z"
}

Error Responses:

// 400 Bad Request - Invalid input
{
  "error": "Validation failed",
  "details": "customer_id is required"
}

// 409 Conflict - Duplicate intent_key
{
  "error": "Intent key already exists",
  "details": "Intent with key 'store_hours' already exists for this customer"
}

// 429 Too Many Requests - Rate limit exceeded
{
  "error": "Rate limit exceeded",
  "details": "50 per 1 hour",
  "retry_after": 3600
}

Get Intent by ID

Retrieves a specific intent by its unique identifier.

Endpoint: GET /intents/{intent_id}

Path Parameters: | Parameter | Type | Description | |-----------|------|-------------| | intent_id | UUID | Unique intent identifier |

Success Response: 200 OK

{
  "intent_id": "87654321-4321-4321-4321-210987654321",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "intent_key": "store_hours",
  "description": "Customer wants to know store operating hours",
  "info_blob": "SuperMart grocery store is open Monday-Friday 8AM-10PM...",
  "tags": ["hours", "schedule", "time"],
  "intent_query_pattern_count": 5,
  "query_pattern": [
    "What time do you open?",
    "When do you close?",
    "What are your hours?",
    "Are you open on weekends?",
    "What time does the store open?"
  ],
  "process_time": "2024-01-15T10:31:45Z",
  "processing_error": null,
  "last_processing_time": "2024-01-15T10:31:45Z",
  "processing_attempts": 1
}

Error Responses:

// 404 Not Found - Intent doesn't exist
{
  "error": "Intent not found",
  "details": "No intent found with ID: 87654321-4321-4321-4321-210987654321"
}

Update Intent

Updates an existing intent. Triggers model cache invalidation and retraining.

Endpoint: PUT /intents/{intent_id}

Path Parameters: | Parameter | Type | Description | |-----------|------|-------------| | intent_id | UUID | Unique intent identifier |

Request Body:

{
  "intent_key": "store_hours_updated",
  "description": "Updated description for store hours",
  "info_blob": "Updated info blob with new hours...",
  "tags": ["hours", "schedule", "time", "updated"],
  "intent_query_pattern_count": 7
}

Request Parameters: | Field | Type | Required | Description | |-------|------|----------|-------------| | intent_key | String | ❌ | Updated intent key | | description | String | ❌ | Updated description | | info_blob | String | ❌ | Updated context information | | tags | Array[String] | ❌ | Updated tags | | intent_query_pattern_count | Integer | ❌ | Updated pattern count |

Success Response: 200 OK

{
  "intent_id": "87654321-4321-4321-4321-210987654321",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "intent_key": "store_hours_updated",
  "description": "Updated description for store hours",
  "info_blob": "Updated info blob with new hours...",
  "tags": ["hours", "schedule", "time", "updated"],
  "intent_query_pattern_count": 7,
  "query_pattern": [
    "What time do you open?",
    "When do you close?",
    "What are your hours?"
  ],
  "process_time": "2024-01-15T10:31:45Z",
  "processing_error": null,
  "last_processing_time": "2024-01-15T10:31:45Z",
  "processing_attempts": 1,
  "updated_at": "2024-01-15T11:15:30Z"
}

Error Responses:

// 404 Not Found - Intent doesn't exist
{
  "error": "Intent not found",
  "details": "No intent found with ID: 87654321-4321-4321-4321-210987654321"
}

// 409 Conflict - Duplicate intent_key
{
  "error": "Intent key already exists",
  "details": "Intent with key 'store_hours_updated' already exists for this customer"
}

Delete Intent

Permanently deletes an intent and invalidates related model cache.

Endpoint: DELETE /intents/{intent_id}

Path Parameters: | Parameter | Type | Description | |-----------|------|-------------| | intent_id | UUID | Unique intent identifier |

Success Response: 200 OK

{
  "message": "Intent deleted successfully",
  "intent_id": "87654321-4321-4321-4321-210987654321"
}

Error Responses:

// 404 Not Found - Intent doesn't exist
{
  "error": "Intent not found",
  "details": "No intent found with ID: 87654321-4321-4321-4321-210987654321"
}

List Customer Intents

Retrieves all intents for a specific customer with optional filtering.

Endpoint: GET /intents/customer/{customer_id}

Path Parameters: | Parameter | Type | Description | |-----------|------|-------------| | customer_id | UUID | Unique customer identifier |

Query Parameters: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | tags | String | ❌ | Comma-separated tags to filter by | | limit | Integer | ❌ | Maximum number of results (default: 100) | | offset | Integer | ❌ | Number of results to skip (default: 0) | | include_patterns | Boolean | ❌ | Include query patterns in response (default: false) |

Example Request:

GET /intents/customer/12345678-1234-1234-1234-123456789abc?tags=hours,schedule&limit=10&include_patterns=true

Success Response: 200 OK

{
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "total_count": 25,
  "returned_count": 10,
  "offset": 0,
  "intents": [
    {
      "intent_id": "87654321-4321-4321-4321-210987654321",
      "intent_key": "store_hours",
      "description": "Customer wants to know store operating hours",
      "tags": ["hours", "schedule", "time"],
      "intent_query_pattern_count": 5,
      "query_pattern": [
        "What time do you open?",
        "When do you close?",
        "What are your hours?",
        "Are you open on weekends?",
        "What time does the store open?"
      ],
      "process_time": "2024-01-15T10:31:45Z",
      "processing_error": null,
      "last_processing_time": "2024-01-15T10:31:45Z",
      "processing_attempts": 1
    }
  ]
}

Error Responses:

// 404 Not Found - Customer has no intents
{
  "error": "No intents found",
  "details": "No intents found for customer: 12345678-1234-1234-1234-123456789abc"
}

🔍 Query Processing API

Process Query

Processes a natural language query and returns the best matching intent with confidence score.

Endpoint: POST /query

Request Body:

{
  "query": "What time do you open?",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "similarity_threshold": 0.3,
  "tags": ["hours", "schedule"],
  "max_results": 1
}

Request Parameters: | Field | Type | Required | Description | |-------|------|----------|-------------| | query | String | ✅ | Natural language query to process | | customer_id | UUID | ✅ | Customer identifier for intent matching | | similarity_threshold | Float | ❌ | Minimum similarity score (0.0-1.0, default: 0.3) | | tags | Array[String] | ❌ | Filter results by specific tags | | max_results | Integer | ❌ | Maximum number of results (default: 1) |

Success Response - Match Found: 200 OK

{
  "query": "What time do you open?",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "match_found": true,
  "similarity_score": 0.8547,
  "processing_time_ms": 67,
  "cache_hit": true,
  "intent": {
    "intent_id": "87654321-4321-4321-4321-210987654321",
    "intent_key": "store_hours",
    "description": "Customer wants to know store operating hours",
    "info_blob": "SuperMart grocery store is open Monday-Friday 8AM-10PM...",
    "tags": ["hours", "schedule", "time"],
    "matched_pattern": "What time do you open?"
  }
}

Success Response - No Match: 200 OK

{
  "query": "How do I build a rocket?",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "match_found": false,
  "similarity_score": 0.12,
  "processing_time_ms": 45,
  "cache_hit": true,
  "intent": null,
  "message": "No intent found above similarity threshold of 0.3"
}

Success Response - Multiple Results: 200 OK

{
  "query": "store hours",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "match_found": true,
  "results": [
    {
      "similarity_score": 0.8547,
      "intent": {
        "intent_id": "87654321-4321-4321-4321-210987654321",
        "intent_key": "store_hours",
        "description": "Customer wants to know store operating hours",
        "matched_pattern": "What are your hours?"
      }
    },
    {
      "similarity_score": 0.6234,
      "intent": {
        "intent_id": "11111111-2222-3333-4444-555555555555",
        "intent_key": "holiday_hours",
        "description": "Customer wants to know holiday operating hours",
        "matched_pattern": "What are your holiday hours?"
      }
    }
  ],
  "processing_time_ms": 72,
  "cache_hit": true
}

Error Responses:

// 400 Bad Request - Invalid input
{
  "error": "Validation failed",
  "details": "query is required and cannot be empty"
}

// 400 Bad Request - Invalid similarity threshold
{
  "error": "Invalid similarity_threshold",
  "details": "similarity_threshold must be between 0.0 and 1.0"
}

// 404 Not Found - Customer not found
{
  "error": "Customer not found",
  "details": "No intents found for customer: 12345678-1234-1234-1234-123456789abc"
}

// 500 Internal Server Error - Model training failed
{
  "error": "Model training failed",
  "details": "Unable to train model for customer due to insufficient data"
}

📊 System Management API

Health Check

Returns system health status.

Endpoint: GET /up

Success Response: 200 OK

{
  "status": "ok",
  "timestamp": "2024-01-15T12:00:00Z",
  "version": "1.0.0"
}

Queue Status

Returns background job queue status and metrics.

Endpoint: GET /queue/status

Success Response: 200 OK

{
  "queue_size": 5,
  "failed_queue_size": 1,
  "status": "healthy",
  "timestamp": "2024-01-15T12:00:00Z",
  "metrics": {
    "total_processed": 1247,
    "total_failed": 23,
    "success_rate": 0.9815,
    "average_processing_time_ms": 2340
  }
}

Status Values: - healthy: Queue size < 100 - busy: Queue size >= 100 - error: Unable to connect to queue

Error Responses:

// 500 Internal Server Error - Queue unavailable
{
  "error": "Unable to check queue status",
  "details": "Redis connection failed"
}

Model Cache Status

Returns model memory cache statistics and performance metrics.

Endpoint: GET /models/cache/status

Success Response: 200 OK

{
  "cache_stats": {
    "total_models": 8,
    "total_memory_mb": 15.7,
    "max_memory_mb": 500,
    "memory_usage_percent": 3.14,
    "cache_hits": 1543,
    "cache_misses": 89,
    "hit_rate": 0.9453,
    "oldest_model_age_hours": 18.5,
    "newest_model_age_minutes": 12.3
  },
  "status": "healthy",
  "timestamp": "2024-01-15T12:00:00Z"
}

Status Values: - healthy: Memory usage < 90% - high_memory: Memory usage >= 90% - error: Unable to check cache

Error Responses:

// 500 Internal Server Error - Cache unavailable
{
  "error": "Unable to check model cache status",
  "details": "Cache manager initialization failed"
}

Clear Model Cache

Manually clears all cached models to free memory.

Endpoint: POST /models/cache/clear

Success Response: 200 OK

{
  "message": "Model cache cleared successfully",
  "cleared_models": 8,
  "freed_memory_mb": 15.7,
  "timestamp": "2024-01-15T12:00:00Z"
}

Error Responses:

// 500 Internal Server Error - Clear failed
{
  "error": "Failed to clear model cache",
  "details": "Cache manager not available"
}

🔍 Advanced Search & Filtering

Search Intents by Content

Search intents by description, info_blob, or query patterns.

Endpoint: GET /intents/search

Query Parameters: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | customer_id | UUID | ✅ | Customer identifier | | q | String | ✅ | Search query | | fields | String | ❌ | Fields to search: description,info_blob,patterns (default: all) | | tags | String | ❌ | Comma-separated tags to filter by | | limit | Integer | ❌ | Maximum results (default: 20) | | offset | Integer | ❌ | Results to skip (default: 0) |

Example Request:

GET /intents/search?customer_id=12345678-1234-1234-1234-123456789abc&q=store%20hours&fields=description,patterns&limit=5

Success Response: 200 OK

{
  "query": "store hours",
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "total_count": 3,
  "returned_count": 3,
  "results": [
    {
      "intent_id": "87654321-4321-4321-4321-210987654321",
      "intent_key": "store_hours",
      "description": "Customer wants to know store operating hours",
      "tags": ["hours", "schedule", "time"],
      "relevance_score": 0.95,
      "matched_fields": ["description", "patterns"]
    }
  ]
}

Bulk Operations

Bulk Create Intents

Create multiple intents in a single request.

Endpoint: POST /intents/bulk

Request Body:

{
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "intents": [
    {
      "intent_key": "store_hours",
      "description": "Store operating hours",
      "info_blob": "Store hours information...",
      "tags": ["hours"],
      "intent_query_pattern_count": 3
    },
    {
      "intent_key": "return_policy",
      "description": "Product return policy",
      "info_blob": "Return policy information...",
      "tags": ["returns"],
      "intent_query_pattern_count": 5
    }
  ]
}

Success Response: 201 Created

{
  "customer_id": "12345678-1234-1234-1234-123456789abc",
  "total_requested": 2,
  "successful": 2,
  "failed": 0,
  "results": [
    {
      "intent_key": "store_hours",
      "intent_id": "87654321-4321-4321-4321-210987654321",
      "status": "created"
    },
    {
      "intent_key": "return_policy",
      "intent_id": "11111111-2222-3333-4444-555555555555",
      "status": "created"
    }
  ]
}

Bulk Delete Intents

Delete multiple intents by their IDs.

Endpoint: DELETE /intents/bulk

Request Body:

{
  "intent_ids": [
    "87654321-4321-4321-4321-210987654321",
    "11111111-2222-3333-4444-555555555555"
  ]
}

Success Response: 200 OK

{
  "total_requested": 2,
  "successful": 2,
  "failed": 0,
  "results": [
    {
      "intent_id": "87654321-4321-4321-4321-210987654321",
      "status": "deleted"
    },
    {
      "intent_id": "11111111-2222-3333-4444-555555555555",
      "status": "deleted"
    }
  ]
}

📈 Analytics & Reporting API

Query Analytics

Get analytics for query processing performance.

Endpoint: GET /analytics/queries

Query Parameters: | Parameter | Type | Required | Description | |-----------|------|----------|-------------| | customer_id | UUID | ❌ | Filter by customer | | start_date | String | ❌ | Start date (ISO 8601) | | end_date | String | ❌ | End date (ISO 8601) | | group_by | String | ❌ | Group by: hour, day, week (default: day) |

Success Response: 200 OK

{
  "period": {
    "start_date": "2024-01-01T00:00:00Z",
    "end_date": "2024-01-15T23:59:59Z"
  },
  "metrics": {
    "total_queries": 15420,
    "successful_matches": 13876,
    "no_matches": 1544,
    "match_rate": 0.8998,
    "average_response_time_ms": 78.5,
    "cache_hit_rate": 0.9234
  },
  "timeline": [
    {
      "date": "2024-01-01",
      "queries": 1024,
      "matches": 921,
      "avg_response_time_ms": 82.1
    }
  ]
}

Intent Performance

Get performance metrics for specific intents.

Endpoint: GET /analytics/intents/{intent_id}/performance

Success Response: 200 OK

{
  "intent_id": "87654321-4321-4321-4321-210987654321",
  "intent_key": "store_hours",
  "metrics": {
    "total_matches": 1247,
    "average_similarity_score": 0.7834,
    "most_common_queries": [
      {
        "query": "What time do you open?",
        "count": 342,
        "avg_similarity": 0.8956
      }
    ],
    "performance_trend": "improving"
  }
}

🚨 Error Handling

Standard HTTP Status Codes

Code Meaning Description
200 OK Request successful
201 Created Resource created successfully
400 Bad Request Invalid request data
401 Unauthorized Authentication required
403 Forbidden Access denied
404 Not Found Resource not found
409 Conflict Resource already exists
429 Too Many Requests Rate limit exceeded
500 Internal Server Error Server error
503 Service Unavailable Service temporarily unavailable

Error Response Format

All error responses follow this format:

{
  "error": "Brief error description",
  "details": "Detailed error message",
  "timestamp": "2024-01-15T12:00:00Z",
  "request_id": "req_123456789"
}

Rate Limiting Headers

Rate limit information is included in response headers:

X-RateLimit-Limit: 500
X-RateLimit-Remaining: 487
X-RateLimit-Reset: 1642248000

📝 Usage Examples

Complete Workflow Example

# 1. Create a new intent
curl -X POST http://localhost:5000/intents \
  -H "Content-Type: application/json" \
  -d '{
    "customer_id": "12345678-1234-1234-1234-123456789abc",
    "intent_key": "store_hours",
    "description": "Store operating hours",
    "info_blob": "SuperMart is open Mon-Fri 8AM-10PM, Sat-Sun 9AM-9PM",
    "intent_query_pattern_count": 5
  }'

# 2. Wait for pattern generation (check queue status)
curl http://localhost:5000/queue/status

# 3. Query the intent
curl -X POST http://localhost:5000/query \
  -H "Content-Type: application/json" \
  -d '{
    "query": "What time do you open?",
    "customer_id": "12345678-1234-1234-1234-123456789abc"
  }'

# 4. List all customer intents
curl "http://localhost:5000/intents/customer/12345678-1234-1234-1234-123456789abc"

# 5. Check model cache status
curl http://localhost:5000/models/cache/status

Python SDK Example

import requests
import json

class IntentAPI:
    def __init__(self, base_url="http://localhost:5000"):
        self.base_url = base_url
        self.session = requests.Session()
        self.session.headers.update({"Content-Type": "application/json"})

    def create_intent(self, customer_id, intent_key, description, info_blob, **kwargs):
        data = {
            "customer_id": customer_id,
            "intent_key": intent_key,
            "description": description,
            "info_blob": info_blob,
            **kwargs
        }
        response = self.session.post(f"{self.base_url}/intents", json=data)
        return response.json()

    def query_intent(self, query, customer_id, **kwargs):
        data = {
            "query": query,
            "customer_id": customer_id,
            **kwargs
        }
        response = self.session.post(f"{self.base_url}/query", json=data)
        return response.json()

    def get_customer_intents(self, customer_id, **params):
        response = self.session.get(
            f"{self.base_url}/intents/customer/{customer_id}",
            params=params
        )
        return response.json()

# Usage
api = IntentAPI()

# Create intent
result = api.create_intent(
    customer_id="12345678-1234-1234-1234-123456789abc",
    intent_key="store_hours",
    description="Store operating hours",
    info_blob="Store hours information...",
    intent_query_pattern_count=5
)

# Query intent
result = api.query_intent(
    query="What time do you open?",
    customer_id="12345678-1234-1234-1234-123456789abc"
)

This API reference provides complete documentation for all available endpoints. For additional support or feature requests, please refer to the main system documentation.