Use Case

User Tracking

Monitor user behavior, analyze patterns, and optimize experiences while maintaining privacy compliance

Overview

Track and analyze how users interact with your AI-powered features to improve user experience, optimize costs, and understand usage patterns while respecting user privacy.

User Profiles

Build comprehensive user profiles with preferences and history

Real-time Analytics

Monitor user interactions and model usage in real-time

Privacy Compliant

GDPR-ready with consent management and data controls

Basic User Tracking

import requests

# Track user with custom properties
response = requests.post(
    "https://api.parrotrouter.com/v1/chat/completions",
    headers={
        "Authorization": "Bearer your-api-key",
        "X-User-ID": "user_123",  # Track specific user
        "X-User-Properties": json.dumps({
            "plan": "premium",
            "department": "engineering",
            "locale": "en-US"
        })
    },
    json={
        "model": "gpt-4",
        "messages": [{"role": "user", "content": "Hello"}],
        "metadata": {
            "session_id": "sess_abc123",
            "feature": "chat_support"
        }
    }
)

# Response includes tracking information
print(response.headers.get("X-Request-ID"))  # For analytics

Session Tracking

class SessionTracker:
    def __init__(self, api_key, user_id):
        self.api_key = api_key
        self.user_id = user_id
        self.session_id = str(uuid.uuid4())
        self.interactions = []
    
    def track_interaction(self, messages, response):
        interaction = {
            "timestamp": datetime.now().isoformat(),
            "messages": messages,
            "response": response.choices[0].message.content,
            "model": response.model,
            "tokens": response.usage.total_tokens,
            "latency": response.response_ms
        }
        self.interactions.append(interaction)
        
        # Send to analytics
        requests.post(
            "https://api.parrotrouter.com/v1/analytics/interactions",
            headers={"Authorization": f"Bearer {self.api_key}"},
            json={
                "user_id": self.user_id,
                "session_id": self.session_id,
                "interaction": interaction
            }
        )
    
    def end_session(self):
        # Send session summary
        summary = {
            "user_id": self.user_id,
            "session_id": self.session_id,
            "duration": len(self.interactions),
            "total_tokens": sum(i["tokens"] for i in self.interactions),
            "models_used": list(set(i["model"] for i in self.interactions))
        }
        
        requests.post(
            "https://api.parrotrouter.com/v1/analytics/sessions",
            headers={"Authorization": f"Bearer {self.api_key}"},
            json=summary
        )

User Journey Mapping

# Track user journey through conversion funnel
def track_funnel_event(user_id, event_name, properties=None):
    requests.post(
        "https://api.parrotrouter.com/v1/analytics/events",
        headers={"Authorization": "Bearer your-api-key"},
        json={
            "user_id": user_id,
            "event": event_name,
            "properties": properties or {},
            "timestamp": datetime.now().isoformat()
        }
    )

# Example: E-commerce assistant funnel
user_id = "user_123"

# Step 1: User asks about products
track_funnel_event(user_id, "product_inquiry", {
    "category": "electronics",
    "intent": "purchase"
})

# Step 2: AI provides recommendations
response = requests.post(
    "https://api.parrotrouter.com/v1/chat/completions",
    headers={
        "Authorization": "Bearer your-api-key",
        "X-User-ID": user_id
    },
    json={
        "model": "gpt-4",
        "messages": [{"role": "user", "content": "Show me laptops under $1000"}]
    }
)

track_funnel_event(user_id, "recommendations_viewed", {
    "count": 5,
    "model_used": "gpt-4"
})

# Step 3: User clicks on product
track_funnel_event(user_id, "product_clicked", {
    "product_id": "laptop_123",
    "price": 899
})

# Analyze funnel
funnel_stats = requests.get(
    f"https://api.parrotrouter.com/v1/analytics/funnels/ecommerce?user_id={user_id}",
    headers={"Authorization": "Bearer your-api-key"}
).json()

print(f"Conversion rate: {funnel_stats['conversion_rate']}%")

Privacy & Consent Management

# GDPR-compliant tracking with consent
def track_with_consent(user_id, consent_given=False):
    headers = {
        "Authorization": "Bearer your-api-key",
    }
    
    if consent_given:
        # Full tracking with user identification
        headers.update({
            "X-User-ID": user_id,
            "X-Tracking-Consent": "full"
        })
    else:
        # Anonymous tracking only
        headers["X-Tracking-Consent"] = "anonymous"
    
    return headers

# User data management
class PrivacyManager:
    def __init__(self, api_key):
        self.api_key = api_key
    
    def get_user_data(self, user_id):
        """GDPR: Right to access"""
        return requests.get(
            f"https://api.parrotrouter.com/v1/users/{user_id}/data",
            headers={"Authorization": f"Bearer {self.api_key}"}
        ).json()
    
    def delete_user_data(self, user_id):
        """GDPR: Right to deletion"""
        return requests.delete(
            f"https://api.parrotrouter.com/v1/users/{user_id}",
            headers={"Authorization": f"Bearer {self.api_key}"}
        )
    
    def update_consent(self, user_id, consent_settings):
        """Update tracking consent preferences"""
        return requests.put(
            f"https://api.parrotrouter.com/v1/users/{user_id}/consent",
            headers={"Authorization": f"Bearer {self.api_key}"},
            json=consent_settings
        )

Real-time User Analytics

# Get user insights and segments
def get_user_insights(user_id):
    response = requests.get(
        f"https://api.parrotrouter.com/v1/analytics/users/{user_id}/insights",
        headers={"Authorization": "Bearer your-api-key"}
    )
    return response.json()

insights = get_user_insights("user_123")

print(f"User segment: {insights['segment']}")
print(f"Lifetime value: $" + str(insights['ltv']))
print(f"Favorite models: {insights['preferred_models']}")
print(f"Usage pattern: {insights['usage_pattern']}")  # heavy, moderate, light
print(f"Churn risk: {insights['churn_probability']}%")

# Segment-based personalization
if insights['segment'] == 'power_user':
    model = "gpt-4"  # Give power users the best model
    max_tokens = 4000
elif insights['segment'] == 'cost_conscious':
    model = "gpt-3.5-turbo"  # Optimize for cost
    max_tokens = 1000
else:
    model = "gpt-3.5-turbo"  # Default
    max_tokens = 2000

# Track segment performance
segment_analytics = requests.get(
    "https://api.parrotrouter.com/v1/analytics/segments",
    headers={"Authorization": "Bearer your-api-key"},
    params={"period": "30d"}
).json()

for segment in segment_analytics['segments']:
    print(f"\nSegment: {segment['name']}")
    print(f"Users: {segment['user_count']}")
    print(f"Avg. monthly spend: $" + str(segment['avg_monthly_spend']))
    print(f"Retention rate: {segment['retention_rate']}%")

Best Practices

Privacy First

  • • Always obtain explicit consent before tracking
  • • Implement data minimization - only collect what you need
  • • Provide easy opt-out mechanisms
  • • Regular data purging policies

Actionable Analytics

  • • Track meaningful events tied to business outcomes
  • • Use cohort analysis for user retention
  • • A/B test different models and prompts
  • • Monitor cost per user segment

Performance Optimization

  • • Batch analytics events for efficiency
  • • Use sampling for high-volume tracking
  • • Implement client-side event queuing
  • • Set up real-time alerts for anomalies

Related Features