Skip to main content
Associate requests with Identity identifiers for user-level observability and analytics.
Identities are orq.ai entities used to track project expenses, token usage, to learn more, see Identity Tracking.

Quick Start

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",
      },
    },
  },
});

Configuration

ParameterTypeRequiredDescription
idstringYesUnique identity identifier
display_namestringNoHuman-readable identity name
emailstringNoIdentity email address
metadataobjectNoCustom key-value pairs for identity data
logo_urlstringNoURL to identity’s profile image
tagsstring[]NoClassification tags for identity segmentation

Use Cases

ScenarioIdentity ID StrategyMetadata Example
User Analyticsuser-{userId}{"plan": "pro", "usage_tier": "high"}
Customer Supportsupport-{ticketId}{"priority": "high", "issue_type": "billing"}
A/B Testingtest-{userId}-{variant}{"experiment": "pricing-v2", "variant": "b"}
Multi-tenanttenant-{orgId}-{userId}{"org": "acme-corp", "role": "admin"}

Implementation Examples

User Session Tracking

// 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}`,
      ],
    },
  },
});

Support Ticket Integration

// 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}`,
      ],
    },
  },
});

Multi-Language Support

curl -X POST https://api.orq.ai/v2/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"]
      }
    }
  }'

Advanced Patterns

Dynamic Identity Resolution

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 },
});

Batch Identity Processing

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}`],
        },
      },
    });
  }),
);

Identity Analytics

Usage Tracking

// 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",
});

Personalization Context

// 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}`],
      },
    },
  });
};

Performance Optimization

Identity Data Caching

// 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;
}

Metadata Optimization

// 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"],
};

Troubleshooting

IssueCauseSolution
Identity not appearing in analyticsMissing or invalid identity IDEnsure identity.id is provided and unique
Metadata not updatingIdentity cache not refreshedClear identity cache or reduce TTL
Performance degradationToo much metadata per requestLimit metadata to essential fields only
Duplicate identitiesInconsistent ID formatStandardize identity ID generation

Validation Examples

// 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(", ")}`);
}

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

LimitationDescriptionWorkaround
Identity ID LengthMaximum 255 charactersUse shorter, meaningful identifiers
Metadata SizeRecommended maximum 20 fieldsGroup related data into nested objects
Tag CountMaximum 10 tags per identityUse hierarchical tagging strategy
Email ValidationBasic format validation onlyImplement additional validation client-side
Data PersistenceIdentity data not stored permanentlyMaintain identity profiles in your system

Integration Examples

CRM Integration

// 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;
};