> ## Documentation Index
> Fetch the complete documentation index at: https://docs.orq.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Identity tracking for user analytics

> Monitor LLM usage per user or identity. Track individual AI interactions, costs, and patterns for personalization, billing, and user behavior analytics.

Associate requests with [Identity](/docs/analytics/identity) identifiers for user-level observability and analytics.

<Info>
  [Identities](/docs/analytics/identity) are orq.ai entities used to track project expenses, token usage, to learn more, see [Identity Tracking](/docs/proxy/identity-tracking).
</Info>

## Quick Start

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [{ role: "user", content: "How can I upgrade my account?" }],
    orq: {
      identity: {
        id: "user-12345",
        display_name: "John Smith",
        email: "[email protected]",
        metadata: {
          plan: "premium",
          signup_date: "2024-01-15",
        },
      },
    },
  });
  ```
</CodeGroup>

## Configuration

| Parameter      | Type      | Required | Description                                   |
| -------------- | --------- | -------- | --------------------------------------------- |
| `id`           | string    | Yes      | Unique identity identifier                    |
| `display_name` | string    | No       | Human-readable identity name                  |
| `email`        | string    | No       | Identity email address                        |
| `metadata`     | object    | No       | Custom key-value pairs for identity data      |
| `logo_url`     | string    | No       | URL to identity's profile image               |
| `tags`         | string\[] | No       | Classification tags for identity segmentation |

## Use Cases

| Scenario             | Identity ID Strategy      | Metadata Example                                |
| -------------------- | ------------------------- | ----------------------------------------------- |
| **User Analytics**   | `user-{userId}`           | `{"plan": "pro", "usage_tier": "high"}`         |
| **Customer Support** | `support-{ticketId}`      | `{"priority": "high", "issue_type": "billing"}` |
| **A/B Testing**      | `test-{userId}-{variant}` | `{"experiment": "pricing-v2", "variant": "b"}`  |
| **Multi-tenant**     | `tenant-{orgId}-{userId}` | `{"org": "acme-corp", "role": "admin"}`         |

## Implementation Examples

### User Session Tracking

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Track authenticated user interactions
  const userSession = {
    userId: "user-12345",
    userProfile: await getUserProfile(userId),
  };

  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [{ role: "user", content: "Show me my recent orders" }],
    orq: {
      identity: {
        id: userSession.userId,
        display_name: userSession.userProfile.fullName,
        email: userSession.userProfile.email,
        metadata: {
          plan: userSession.userProfile.subscriptionPlan,
          last_login: userSession.userProfile.lastLogin,
          total_orders: userSession.userProfile.orderCount,
        },
        tags: [
          "authenticated",
          `plan-${userSession.userProfile.subscriptionPlan}`,
        ],
      },
    },
  });
  ```
</CodeGroup>

### Support Ticket Integration

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Associate AI interactions with support tickets
  const supportContext = {
    ticketId: "TICKET-789",
    customerId: "customer-456",
    customerInfo: await getCustomerInfo(customerId),
  };

  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [{ role: "user", content: "I need help with my billing issue" }],
    orq: {
      identity: {
        id: `support-${supportContext.ticketId}`,
        display_name: supportContext.customerInfo.name,
        email: supportContext.customerInfo.email,
        metadata: {
          ticket_id: supportContext.ticketId,
          customer_tier: supportContext.customerInfo.tier,
          issue_category: "billing",
          created_at: new Date().toISOString(),
        },
        tags: [
          "support",
          "billing-issue",
          `tier-${supportContext.customerInfo.tier}`,
        ],
      },
    },
  });
  ```
</CodeGroup>

### Multi-Language Support

<CodeGroup>
  ```bash cURL theme={"theme":{"light":"github-light","dark":"github-dark"}}
  curl -X POST https://api.orq.ai/v3/router/chat/completions \
    -H "Authorization: Bearer $ORQ_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "openai/gpt-4o",
      "messages": [{"role": "user", "content": "I need technical assistance"}],
      "orq": {
        "identity": {
          "id": "enterprise-user-001",
          "display_name": "Alex Johnson",
          "email": "[email protected]",
          "metadata": {
            "company": "Enterprise Corp",
            "role": "technical_lead",
            "contract_tier": "enterprise"
          },
          "tags": ["enterprise", "technical"]
        }
      }
    }'
  ```

  ```python Python theme={"theme":{"light":"github-light","dark":"github-dark"}}
  import openai
  import json

  client = openai.OpenAI(
      api_key=os.environ["ORQ_API_KEY"],
      base_url="https://api.orq.ai/v3/router"
  )

  identity_data = {
      "id": "user-67890",
      "display_name": "Maria Garcia",
      "email": "[email protected]",
      "metadata": {
          "preferred_language": "es",
          "timezone": "America/Mexico_City",
          "subscription_status": "active"
      },
      "tags": ["spanish-speaker", "premium-user"]
  }

  response = client.chat.completions.create(
      model="openai/gpt-4o",
      messages=[{"role": "user", "content": "¿Cómo puedo cambiar mi plan?"}],
      extra_body={
          "orq": {
              "identity": identity_data
          }
      }
  )
  ```
</CodeGroup>

## Advanced Patterns

### Dynamic Identity Resolution

<CodeGroup>
  ```typescript TypeScript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  interface IdentityProfile {
    id: string;
    name: string;
    email: string;
    plan: "free" | "pro" | "enterprise";
    metadata?: Record<string, any>;
  }

  async function resolveIdentity(userId: string): Promise<IdentityProfile> {
    const user = await database.users.findById(userId);
    const subscription = await database.subscriptions.findByUserId(userId);

    return {
      id: `user-${userId}`,
      name: user.fullName,
      email: user.email,
      plan: subscription.plan,
      metadata: {
        signup_date: user.createdAt,
        last_active: user.lastActiveAt,
        feature_flags: user.featureFlags,
        usage_this_month: await getUsageMetrics(userId),
      },
    };
  }

  const identity = await resolveIdentity(currentUserId);

  const response = await openai.chat.completions.create({
    model: "openai/gpt-4o",
    messages: [{ role: "user", content: userMessage }],
    orq: { identity },
  });
  ```
</CodeGroup>

### Batch Identity Processing

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  const batchRequests = [
    { userId: "user1", message: "How do I reset my password?" },
    { userId: "user2", message: "What's my current usage?" },
    { userId: "user3", message: "Can I upgrade my plan?" },
  ];

  const responses = await Promise.all(
    batchRequests.map(async (req) => {
      const userProfile = await getUserProfile(req.userId);

      return openai.chat.completions.create({
        model: "openai/gpt-4o",
        messages: [{ role: "user", content: req.message }],
        orq: {
          identity: {
            id: req.userId,
            display_name: userProfile.name,
            email: userProfile.email,
            metadata: {
              request_batch: "batch-001",
              processed_at: new Date().toISOString(),
            },
            tags: ["batch-processing", `plan-${userProfile.plan}`],
          },
        },
      });
    }),
  );
  ```
</CodeGroup>

## Identity Analytics

### Usage Tracking

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Track feature usage per identity
  const trackFeatureUsage = async (identityId, feature, context = {}) => {
    const response = await openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{ role: "user", content: "Analyze my data" }],
      orq: {
        identity: {
          id: identityId,
          metadata: {
            feature_used: feature,
            usage_context: context,
            session_id: generateSessionId(),
            timestamp: new Date().toISOString(),
          },
          tags: ["feature-tracking", `feature-${feature}`],
        },
      },
    });

    return response;
  };

  // Usage
  await trackFeatureUsage("user-123", "data-analysis", {
    dataset_size: "large",
    complexity: "medium",
  });
  ```
</CodeGroup>

### Personalization Context

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Provide personalized responses based on identity data
  const getPersonalizedResponse = async (identityId, query) => {
    const identity = await getIdentityProfile(identityId);

    const systemPrompt = `
      You are assisting ${identity.display_name}, a ${identity.metadata.plan} plan user.
      Their preferences: ${JSON.stringify(identity.metadata.preferences)}
      Tailor your response to their experience level and subscription benefits.
    `;

    return await openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [
        { role: "system", content: systemPrompt },
        { role: "user", content: query },
      ],
      orq: {
        identity: {
          id: identityId,
          display_name: identity.display_name,
          email: identity.email,
          metadata: {
            ...identity.metadata,
            personalization_enabled: true,
          },
          tags: ["personalized", `plan-${identity.metadata.plan}`],
        },
      },
    });
  };
  ```
</CodeGroup>

## Performance Optimization

### Identity Data Caching

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Cache identity profiles to reduce database calls
  const identityCache = new Map();
  const CACHE_TTL = 5 * 60 * 1000; // 5 minutes

  async function getCachedIdentity(identityId) {
    const cached = identityCache.get(identityId);

    if (cached && Date.now() - cached.timestamp < CACHE_TTL) {
      return cached.data;
    }

    const identity = await fetchIdentityProfile(identityId);
    identityCache.set(identityId, {
      data: identity,
      timestamp: Date.now(),
    });

    return identity;
  }
  ```
</CodeGroup>

### Metadata Optimization

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Optimize metadata for frequently accessed fields
  const optimizeIdentityMetadata = (fullProfile) => {
    // Only include essential metadata to reduce payload size
    return {
      plan: fullProfile.subscription.plan,
      tier: fullProfile.subscription.tier,
      features: fullProfile.enabledFeatures.slice(0, 5), // Limit array size
      last_active: fullProfile.lastActiveAt,
    };
  };

  const identity = {
    id: userId,
    display_name: user.name,
    email: user.email,
    metadata: optimizeIdentityMetadata(userProfile),
    tags: [`plan-${userProfile.plan}`, "active-user"],
  };
  ```
</CodeGroup>

## Troubleshooting

| Issue                                   | Cause                          | Solution                                  |
| --------------------------------------- | ------------------------------ | ----------------------------------------- |
| **Identity not appearing in analytics** | Missing or invalid identity ID | Ensure identity.id is provided and unique |
| **Metadata not updating**               | Identity cache not refreshed   | Clear identity cache or reduce TTL        |
| **Performance degradation**             | Too much metadata per request  | Limit metadata to essential fields only   |
| **Duplicate identities**                | Inconsistent ID format         | Standardize identity ID generation        |

### Validation Examples

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Validate identity configuration
  function validateIdentity(identity) {
    const errors = [];

    if (!identity.id) {
      errors.push("Identity ID is required");
    }

    if (identity.id.length > 255) {
      errors.push("Identity ID too long (max 255 chars)");
    }

    if (identity.email && !isValidEmail(identity.email)) {
      errors.push("Invalid email format");
    }

    if (identity.metadata && Object.keys(identity.metadata).length > 20) {
      errors.push("Too many metadata fields (max 20)");
    }

    if (identity.tags && identity.tags.length > 10) {
      errors.push("Too many tags (max 10)");
    }

    return errors;
  }

  // Usage
  const identity = { id: "user-123", display_name: "John" };
  const errors = validateIdentity(identity);

  if (errors.length > 0) {
    throw new Error(`Identity validation failed: ${errors.join(", ")}`);
  }
  ```
</CodeGroup>

## Best Practices

1. **Consistent IDs**: Use predictable identity ID patterns across your application
2. **Essential Metadata**: Include only relevant metadata to minimize payload size
3. **Tag Strategy**: Use tags for filtering and segmentation, not detailed data
4. **Privacy Compliance**: Ensure identity data handling meets privacy requirements
5. **Performance**: Cache identity profiles to reduce database lookups
6. **Validation**: Always validate identity data before sending requests

## Limitations

| Limitation             | Description                          | Workaround                                  |
| ---------------------- | ------------------------------------ | ------------------------------------------- |
| **Identity ID Length** | Maximum 255 characters               | Use shorter, meaningful identifiers         |
| **Metadata Size**      | Recommended maximum 20 fields        | Group related data into nested objects      |
| **Tag Count**          | Maximum 10 tags per identity         | Use hierarchical tagging strategy           |
| **Email Validation**   | Basic format validation only         | Implement additional validation client-side |
| **Data Persistence**   | Identity data not stored permanently | Maintain identity profiles in your system   |

## Integration Examples

### CRM Integration

<CodeGroup>
  ```typescript Typescript theme={"theme":{"light":"github-light","dark":"github-dark"}}
  // Sync with CRM systems
  const syncWithCRM = async (identityId, interactions) => {
    const crmContact = await crm.contacts.get(identityId);

    const response = await openai.chat.completions.create({
      model: "openai/gpt-4o",
      messages: [{ role: "user", content: "Update my preferences" }],
      orq: {
        identity: {
          id: identityId,
          display_name: crmContact.name,
          email: crmContact.email,
          metadata: {
            crm_id: crmContact.id,
            lead_score: crmContact.leadScore,
            last_interaction: crmContact.lastInteraction,
            deal_stage: crmContact.currentDealStage,
          },
          tags: ["crm-synced", `stage-${crmContact.currentDealStage}`],
        },
      },
    });

    // Update CRM with AI interaction
    await crm.activities.create({
      contactId: crmContact.id,
      type: "ai_interaction",
      description: "AI assistant interaction",
      timestamp: new Date(),
    });

    return response;
  };
  ```
</CodeGroup>
